-
Notifications
You must be signed in to change notification settings - Fork 3
/
object.c
1656 lines (1480 loc) · 48.7 KB
/
object.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* Copyright (c) 2017, Yuxuan Shui <[email protected]> */
#include <deai/builtins/log.h>
#include <deai/callable.h>
#include <deai/error.h>
#include <deai/helper.h>
#include <deai/object.h>
#include <deai/type.h>
#include <assert.h>
#include <ev.h>
#include <inttypes.h>
#include <stdalign.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/mman.h>
#include "di_internal.h"
#include "utils.h"
#define HANDLER_PREFIX "handler_object_"
struct di_signal {
di_object;
int nhandlers;
};
// This is essentially a fat weak reference, from object to its listeners.
struct di_listener {
struct di_weak_object *listen_handle;
struct list_head siblings;
};
static di_object_internal dead_weakly_referenced_object = {
.ref_count = 0,
.weak_ref_count = 1, // Keep this object from being freed
};
struct di_weak_object *const dead_weak_ref =
(struct di_weak_object *)&dead_weakly_referenced_object;
const void *null_ptr = NULL;
// clang-format off
static_assert(sizeof(di_object) == sizeof(di_object_internal),
"di_object size mismatch");
static_assert(alignof(di_object) == alignof(di_object_internal),
"di_object alignment mismatch");
// clang-format on
static const char error_type[] = "deai:Error";
di_string di_error_to_string(di_object *err) {
di_string func = DI_STRING_INIT, file = DI_STRING_INIT;
int line = -1;
di_rawget_borrowed(err, "func", func);
di_rawget_borrowed(err, "file", file);
di_rawget_borrowed(err, "line", line);
scoped_di_array parts_arr = {
.arr = tmalloc(di_string, 5),
.elem_type = DI_TYPE_STRING,
};
di_string *parts = parts_arr.arr;
di_object *source = NULL;
di_rawget_borrowed(err, "source", source);
unsigned pos = 0;
if (source != NULL) {
parts[pos++] = di_error_to_string(source);
parts[pos++] = di_string_dup(
"\nWhile handling the above error, the following error occurred:\n");
}
if (func.length || file.length || line > 0) {
if (func.length == 0) {
func = di_string_borrow_literal("<unknown>");
}
if (file.length == 0) {
file = di_string_borrow_literal("??");
}
parts[pos++] = di_string_printf("error caught in \"%.*s\" (%.*s:%d): ", (int)func.length,
func.data, (int)file.length, file.data, line);
} else {
parts[pos++] = di_string_dup("error caught: ");
}
if (di_rawgetxt(err, di_string_borrow_literal("error"), DI_TYPE_STRING,
(di_value *)&parts[pos]) != 0) {
parts[pos] = di_string_dup("<unknown error>");
}
pos++;
if (di_rawgetxt(err, di_string_borrow_literal("detail"), DI_TYPE_STRING,
(di_value *)&parts[pos]) != 0) {
parts[pos] = di_string_dup("(no detail)");
}
pos++;
#ifdef ENABLE_STACK_TRACE
di_array ips = {0}, procs = {0}, names = {0};
if (di_rawget_borrowed(err, "stack_ips", ips) == 0 &&
di_rawget_borrowed(err, "stack_procs", procs) == 0 &&
di_rawget_borrowed(err, "stack_proc_names", names) == 0) {
auto ctx = stack_trace_annotate_prepare();
uint64_t *ips_arr = ips.arr, *procs_arr = procs.arr;
di_string *names_arr = names.arr;
parts = realloc(parts_arr.arr, sizeof(di_string) * (pos + ips.length + 1));
if (!parts) {
goto stack_trace_out;
}
parts_arr.arr = parts;
parts[pos++] = di_string_dup("\nstack traceback:");
for (size_t i = 0; i < ips.length; i++) {
if (ctx) {
scoped_di_string annotated = stack_trace_annotate(ctx, ips_arr[i]);
parts[i + pos] = di_string_printf("%10zu: %#16" PRIx64 " %.*s", i, ips_arr[i],
(int)annotated.length, annotated.data);
} else {
auto offsets = procs_arr[i] != 0 ? ips_arr[i] - procs_arr[i] : 0;
auto proc_name = names_arr[i];
if (proc_name.length == 0) {
proc_name = di_string_borrow_literal("<unknown>");
}
if (offsets) {
parts[i + pos] =
di_string_printf("%10zu: %#16" PRIx64 "(%.*s+%#lx)", i, ips_arr[i],
(int)proc_name.length, proc_name.data, offsets);
} else {
parts[i + pos] =
di_string_printf("%10zu%#16" PRIx64 "(%.*s)", i, ips_arr[i],
(int)proc_name.length, proc_name.data);
}
}
}
pos += ips.length;
if (ctx) {
stack_trace_annotate_end(ctx);
}
}
stack_trace_out:
#endif
parts_arr.length = pos;
di_string ret = di_string_join(parts_arr, di_string_borrow_literal("\n"));
return ret;
}
di_object *
di_new_error_from_string(const char *file, int line, const char *func, di_string message) {
auto err = di_new_object_with_type(di_object);
di_set_type(err, error_type);
#ifdef ENABLE_STACK_TRACE
auto frame_count = stack_trace_frame_count();
di_array ips = {
.arr = tmalloc(uint64_t, frame_count),
.elem_type = DI_TYPE_UINT,
};
di_array procs = {
.arr = tmalloc(uint64_t, frame_count),
.elem_type = DI_TYPE_UINT,
};
di_array names = {
.arr = tmalloc(di_string, frame_count),
.elem_type = DI_TYPE_STRING,
};
frame_count = stack_trace_get(0, frame_count, ips.arr, procs.arr, names.arr);
uint64_t *procs_arr = procs.arr;
for (unsigned int i = 0; i < frame_count; i++) {
if (procs_arr[i] != (uintptr_t)di_new_error_from_string &&
procs_arr[i] != (uintptr_t)di_new_error2) {
if (i > 0) {
for (unsigned int j = 0; j < i; j++) {
di_free_string(((di_string *)names.arr)[j]);
}
memmove(ips.arr, ips.arr + i * sizeof(uint64_t),
(frame_count - i) * sizeof(uint64_t));
memmove(procs.arr, procs.arr + i * sizeof(uint64_t),
(frame_count - i) * sizeof(uint64_t));
memmove(names.arr, names.arr + i * sizeof(di_string),
(frame_count - i) * sizeof(di_string));
}
ips.length = frame_count - i;
procs.length = frame_count - i;
names.length = frame_count - i;
break;
}
}
di_member(err, "stack_ips", ips);
di_member(err, "stack_procs", procs);
di_member(err, "stack_proc_names", names);
#endif
di_method(err, "__to_string", di_error_to_string);
di_member(err, "error", message);
if (file) {
di_member_clone(err, "file", di_string_borrow(file));
}
if (line >= 0) {
di_member(err, "line", line);
}
if (func) {
di_member_clone(err, "func", di_string_borrow(func));
}
return err;
}
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
di_object *di_new_error2(const char *file, int line, const char *func, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
di_string msg;
int ret = vasprintf((char **)&msg.data, fmt, ap);
if (ret < 0) {
msg = di_string_dup(fmt);
} else {
msg.length = strlen(msg.data);
}
return di_new_error_from_string(file, line, func, msg);
}
bool di_is_error(di_object *obj) {
return di_check_type(obj, error_type);
}
static int di_call_internal(di_object *self, di_object *method_, di_type *rt,
di_value *ret, di_tuple args, bool *called) {
auto method = (di_object_internal *)method_;
*called = false;
if (!method->call) {
return -EINVAL;
}
di_tuple real_args;
real_args.length = args.length + 1;
assert(real_args.length <= MAX_NARGS);
/* Push the object itself as the first argument */
real_args.elements = alloca(sizeof(struct di_variant) * real_args.length);
memcpy(&real_args.elements[1], args.elements, sizeof(struct di_variant) * args.length);
real_args.elements[0].type = DI_TYPE_OBJECT;
real_args.elements[0].value = (di_value *)&self;
int rc = method->call(method_, rt, ret, real_args);
*called = true;
di_unref_object(method_);
return rc;
}
int di_callx(di_object *self, di_string name, di_type *rt, di_value *ret, di_tuple args,
bool *called) {
di_object *val;
*called = 0;
int rc = di_getxt(self, name, DI_TYPE_OBJECT, (di_value *)&val, NULL);
if (rc != 0) {
return rc;
}
return di_call_internal(self, val, rt, ret, args, called);
};
/// Call "<prefix>_<name>" with "<prefix>" as fallback
///
/// @param[out] found whether a handler is found
static int call_handler_with_fallback(di_object *nonnull o, const char *nonnull prefix,
di_string name, struct di_variant arg,
di_type *nullable rtype, di_value *nullable ret,
di_object *nullable *nullable error, bool *found) {
*found = false;
scoped_di_string buf = di_string_printf("%s_%.*s", prefix, (int)name.length, name.data);
di_type rtype2 = DI_LAST_TYPE;
di_value ret2 = {0};
struct di_variant args[3] = {
{.type = DI_TYPE_OBJECT, .value = (di_value *)&o},
{.type = arg.type, .value = arg.value},
};
di_tuple tmp = {
// There is a trick here.
// DI_LAST_TYPE is used to signify that the argument "doesn't exist". Unlike
// DI_TYPE_NIL, which would mean there is one argument, whose type is nil.
// This is not a convention. Generally speaking, DI_LAST_TYPE should never
// appear in argument lists.
.length = arg.type != DI_LAST_TYPE ? 2 : 1,
.elements = args,
};
di_object *handler = NULL;
int rc = -ENOENT;
if (di_rawget_borrowed2(o, buf, handler) == 0) {
*found = true;
if (error != NULL) {
rc = di_call_object_catch(handler, &rtype2, &ret2, tmp, error);
} else {
rc = di_call_object(handler, &rtype2, &ret2, tmp);
}
}
if (rc != 0 && di_rawget_borrowed(o, prefix, handler) == 0) {
*found = true;
tmp.length++;
if (tmp.length > 2) {
args[2] = args[1];
}
args[1] = (struct di_variant){
.type = DI_TYPE_STRING,
.value = (di_value[]){{.string = name}},
};
if (error != NULL) {
rc = di_call_object_catch(handler, &rtype2, &ret2, tmp, error);
} else {
rc = di_call_object(handler, &rtype2, &ret2, tmp);
}
}
if (rc == 0) {
if (ret && rtype) {
*rtype = rtype2;
*ret = ret2;
} else {
di_free_value(rtype2, &ret2);
}
}
return rc;
}
int di_setx(di_object *o, di_string prop, di_type type, const void *val,
di_object *nullable *nullable error) {
// If a setter is present, we just call that and we are done.
bool handler_found;
int rc = call_handler_with_fallback(o, "__set", prop,
(struct di_variant){(di_value *)val, type}, NULL,
NULL, error, &handler_found);
if (handler_found) {
return rc;
}
// Call the deleter if present
rc = call_handler_with_fallback(o, "__delete", prop, (struct di_variant){NULL, DI_LAST_TYPE},
NULL, NULL, error, &handler_found);
if (handler_found && rc != 0) {
return rc;
}
// Finally, replace the value
auto mem = di_lookup(o, prop);
if (mem) {
// the old member still exists, we need to drop the old value
di_free_value(mem->type, mem->data);
mem->data = realloc(mem->data, di_sizeof_type(type));
mem->type = type;
di_copy_value(mem->type, mem->data, val);
return 0;
}
return di_add_member_clone(o, prop, type, val);
}
int di_refrawgetx(di_object *o, di_string prop, di_type *type, di_value **ret) {
auto m = di_lookup(o, prop);
// nil type is treated as non-existent
if (!m) {
return -ENOENT;
}
assert(di_sizeof_type(m->type) != 0);
*type = m->type;
*ret = m->data;
return 0;
}
int di_rawgetx(di_object *o, di_string prop, di_type *type, di_value *ret) {
di_value *tmp = NULL;
int rc = di_refrawgetx(o, prop, type, &tmp);
if (rc != 0) {
return rc;
}
di_copy_value(*type, ret, tmp);
return 0;
}
/// A di_call_fn that does nothing.
int di_noop(di_object *o, di_type *rt, di_value *r, di_tuple args) {
return 0;
}
/// Decide if `val` contains DI_LAST_TYPE, and if so, free `val`.
/// Ordinary `di_free_value` cannot free value of DI_LAST_TYPE, this function should only
/// be used when calling getter functions.
static bool di_free_last_type(di_type type, di_value *val) {
bool ret = false;
if (type == DI_LAST_TYPE) {
return true;
}
if (type == DI_TYPE_VARIANT) {
// In case of a variant, we need to check the inner type.
ret = di_free_last_type(val->variant.type, val->variant.value);
if (ret) {
free(val->variant.value);
}
}
return ret;
}
int di_getx(di_object *o, di_string prop, di_type *type, di_value *ret,
di_object *nullable *nullable error) {
int rc = di_rawgetx(o, prop, type, ret);
if (rc == 0) {
return 0;
}
bool handler_found;
rc = call_handler_with_fallback(o, "__get", prop, (struct di_variant){NULL, DI_LAST_TYPE},
type, ret, error, &handler_found);
if (rc != 0) {
return rc;
}
if (error && *error) {
return 0;
}
if (di_free_last_type(*type, ret)) {
return -ENOENT;
}
return 0;
}
int di_getxt(di_object *o, di_string prop, di_type rtype, di_value *ret,
di_object *nullable *nullable error) {
di_value ret2;
di_type rt;
int rc = di_getx(o, prop, &rt, &ret2, error);
if (rc != 0) {
return rc;
}
rc = di_type_conversion(rt, &ret2, rtype, ret, 0);
return rc;
};
int di_rawgetxt(di_object *o, di_string prop, di_type rtype, di_value *ret) {
di_value ret2;
di_type rt;
int rc = di_rawgetx(o, prop, &rt, &ret2);
if (rc != 0) {
return rc;
}
rc = di_type_conversion(rt, &ret2, rtype, ret, 0);
return rc;
};
int di_set_type(di_object *o, const char *type) {
return di_rawsetx(o, di_string_borrow_literal("__type"), DI_TYPE_STRING_LITERAL, &type);
}
const char *di_get_type(di_object *o) {
const char *ret;
int rc = di_rawgetxt(o, di_string_borrow_literal("__type"), DI_TYPE_STRING_LITERAL,
(di_value *)&ret);
if (rc != 0) {
if (rc == -ENOENT) {
return "deai:object";
}
return ERR_PTR(rc);
}
return ret;
}
bool di_check_type(di_object *o, const char *tyname) {
const char *ot = di_get_type(o);
if (IS_ERR_OR_NULL(ot)) {
return false;
}
return strcmp(ot, tyname) == 0;
}
#ifdef TRACK_OBJECTS
thread_local struct list_head all_objects;
struct di_ref_tracked_object *ref_tracked;
#endif
/// Objects that has been unreferenced since last mark and sweep.
thread_local struct list_head unreferred_objects;
thread_local bool collecting_garbage = false;
void di_init_object(di_object *obj_) {
di_object_internal *obj = (di_object_internal *)obj_;
obj->ref_count = 1;
// non-zero strong references will implicitly hold a weak refrence. that reference
// is only dropped when the object destruction finishes. this is to avoid the
// case where the last weak reference to the object is dropped during object
// destruction, thus cause the object to be freed in the middle of destruction.
obj->weak_ref_count = 1;
obj->destroyed = 0;
#ifdef TRACK_OBJECTS
list_add(&obj->siblings, &all_objects);
#endif
INIT_LIST_HEAD(&obj->unreferred_siblings);
}
di_object *di_new_object(size_t sz, size_t alignment) {
if (sz < sizeof(di_object)) {
return NULL;
}
if (alignment < alignof(di_object)) {
return NULL;
}
di_object_internal *obj;
DI_CHECK_OK(posix_memalign((void **)&obj, alignment, sz));
memset(obj, 0, sz);
di_init_object((di_object *)obj);
return (di_object *)obj;
}
struct di_module *di_new_module_with_size(di_object *di, size_t size) {
if (size < sizeof(struct di_module)) {
return NULL;
}
struct di_module *pm = (void *)di_new_object(size, alignof(max_align_t));
di_set_type((void *)pm, "deai:module");
di_member_clone(pm, DEAI_MEMBER_NAME_RAW, di);
return (void *)pm;
}
struct di_module *di_new_module(di_object *di) {
return di_new_module_with_size(di, sizeof(struct di_module));
}
static di_variant di_remove_member_raw_impl(di_object_internal *obj, struct di_member *m) {
HASH_DEL(*(struct di_member **)&obj->members, m);
auto ret = (di_variant){.type = m->type, .value = m->data};
di_free_string(m->name);
free(m);
return ret;
}
int di_remove_member_raw(di_object *obj, di_string name, di_variant *ret) {
auto m = di_lookup(obj, name);
if (!m) {
return -ENOENT;
}
*ret = di_remove_member_raw_impl((void *)obj, m);
return 0;
}
int di_delete_member_raw(di_object *obj, di_string name) {
auto m = di_lookup(obj, name);
if (!m) {
return -ENOENT;
}
di_free_variant(di_remove_member_raw_impl((di_object_internal *)obj, (void *)m));
return 0;
}
int di_delete_member(di_object *obj, di_string name, di_object *nullable *nullable error) {
bool handler_found;
int rc2 = call_handler_with_fallback(obj, "__delete", name,
(struct di_variant){NULL, DI_LAST_TYPE}, NULL,
NULL, error, &handler_found);
if (handler_found) {
return rc2;
}
return di_delete_member_raw(obj, name);
}
static void di_finalize_object_inner(di_object_internal *obj) {
#ifdef TRACK_OBJECTS
di_log_va(log_module, DI_LOG_DEBUG, "Finalizing object %p", obj);
#endif
// Call dtor before removing members and signals, so the dtor can still make use
// of whatever is stored in the object, and emit more signals.
// But this also means signal and member deleters won't be called for them.
if (obj->dtor) {
auto tmp = obj->dtor;
// Never call dtor more than once
obj->dtor = NULL;
tmp((di_object *)obj);
}
struct di_member *m = (void *)obj->members;
while (m) {
auto next_m = m->hh.next;
#if 0
scopedp(char) *dbg = di_value_to_string(m->type, m->data);
fprintf(stderr, "removing member %.*s (%s)\n", (int)m->name.length,
m->name.data, dbg);
#endif
di_free_variant(di_remove_member_raw_impl(obj, m));
m = next_m;
}
}
void di_finalize_object(di_object *_obj) {
di_finalize_object_inner((di_object_internal *)_obj);
}
static inline void di_decrement_weak_ref_count(di_object_internal *obj) {
obj->weak_ref_count--;
if (obj->weak_ref_count == 0) {
assert(obj->ref_count == 0);
#ifdef TRACK_OBJECTS
list_del(&obj->siblings);
fprintf(stderr, "freeing object %p\n", obj);
#endif
free(obj);
}
}
// Try to never call destroy twice on something. Although it's fine to do so
static void di_destroy_object(di_object *_obj) {
auto obj = (di_object_internal *)_obj;
assert(obj->ref_count == 0);
if (obj->destroyed) {
di_log_va(log_module, DI_LOG_WARN, "warning: destroy object multiple times\n");
}
obj->destroyed = 1;
di_finalize_object_inner(obj);
di_decrement_weak_ref_count(obj);
}
#if 0
static inline __attribute__((always_inline)) void print_caller(int depth) {
unw_context_t ctx;
unw_cursor_t cursor;
unw_getcontext(&ctx);
unw_init_local(&cursor, &ctx);
for (int i = 0; i < depth && unw_step(&cursor) > 0; i++) {
if (i) {
printf(", ");
}
unw_word_t ip, off;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
char buf[256];
if (unw_get_proc_name(&cursor, buf, sizeof(buf), &off) == 0) {
printf("%s+%#08lx", buf, off);
} else {
printf("%#08lx", ip);
}
}
printf("\n");
}
#endif
di_object *di_ref_object(di_object *_obj) {
auto obj = (di_object_internal *)_obj;
obj->ref_count++;
#ifdef TRACK_OBJECTS
struct di_ref_tracked_object *t = NULL;
HASH_FIND_PTR(ref_tracked, (void **)&_obj, t);
if (t != NULL) {
di_log_va(log_module, DI_LOG_DEBUG, "%p is referenced (%ld)\n", _obj, obj->ref_count);
print_stack_trace(0, 10);
}
#endif
return _obj;
}
struct di_weak_object *di_weakly_ref_object(di_object *_obj) {
auto obj = (di_object_internal *)_obj;
obj->weak_ref_count++;
return (struct di_weak_object *)obj;
}
di_object *nullable di_upgrade_weak_ref(struct di_weak_object *weak) {
assert(weak != PTR_POISON);
auto obj = (di_object_internal *)weak;
// Garbage collector cannot call user code when mark == 1
assert(obj->mark == 0 || obj->mark == 2 || obj->mark == 3);
// If mark == 2 or 3, the object is scheduled for destruction. If we allow
// upgrades of weak reference to it, then user might "revive" it by, e.g. adding
// it to roots. Yet the garbage collector will still finalize the object, causing
// surprising behavior. So we forbid upgrades of weak references in the case.
if (obj->ref_count > 0 && obj->destroyed == 0 && obj->mark != 2 && obj->mark != 3) {
return di_ref_object((di_object *)obj);
}
return NULL;
}
void di_drop_weak_ref(struct di_weak_object **weak) {
assert(*weak != PTR_POISON);
auto obj = (di_object_internal *)*weak;
di_decrement_weak_ref_count(obj);
*weak = PTR_POISON;
}
void di_unref_object(di_object *_obj) {
auto obj = (di_object_internal *)_obj;
assert(obj->ref_count > 0);
assert(!obj->destroyed);
obj->ref_count--;
#ifdef TRACK_OBJECTS
struct di_ref_tracked_object *t = NULL;
HASH_FIND_PTR(ref_tracked, (void **)&_obj, t);
if (t != NULL) {
di_log_va(log_module, DI_LOG_DEBUG, "%p is unreferenced (%ld)\n", _obj, obj->ref_count);
print_stack_trace(0, 10);
}
#endif
assert(obj->mark == 0 || obj->mark == 2 || obj->mark == 3);
if (obj->ref_count == 0) {
list_del_init(&obj->unreferred_siblings);
di_destroy_object(_obj);
} else if (list_empty(&obj->unreferred_siblings) && obj->mark == 0) {
if (unreferred_objects.next == NULL) {
INIT_LIST_HEAD(&unreferred_objects);
}
list_add(&obj->unreferred_siblings, &unreferred_objects);
}
// if obj->mark == 3 or 2, then the object is scheduled for destruction, we don't need
// to add it to `unreferred_objects` list. It is unnecessary and will cause use-after-free.
}
size_t di_min_return_size(size_t in) {
if (in < sizeof(ffi_arg)) {
return sizeof(ffi_arg);
}
return in;
}
static int check_new_member(di_object_internal *obj, struct di_member *m) {
struct di_member *om = NULL;
if (!m->name.data) {
return -EINVAL;
}
HASH_FIND(hh, obj->members, m->name.data, m->name.length, om);
if (om) {
return -EEXIST;
}
return 0;
}
static int di_insert_member(di_object_internal *obj, struct di_member *m) {
int ret = check_new_member(obj, (void *)m);
if (ret != 0) {
return ret;
}
HASH_ADD_KEYPTR(hh, obj->members, m->name.data, m->name.length, m);
return 0;
}
static struct di_member *
di_add_member(di_object_internal *o, di_string name, di_type t, void *v) {
if (!name.data) {
return ERR_PTR(-EINVAL);
}
auto m = tmalloc(struct di_member, 1);
m->type = t;
m->data = v;
m->name = di_clone_string(name);
int ret = di_insert_member(o, m);
if (ret != 0) {
di_free_value(t, v);
free(v);
di_free_string(m->name);
free(m);
return ERR_PTR(ret);
}
return m;
}
static struct di_member *
di_add_member_clone2(di_object *o, di_string name, di_type t, const void *value) {
if (di_sizeof_type(t) == 0) {
return ERR_PTR(-EINVAL);
}
void *copy = calloc(1, di_sizeof_type(t));
di_copy_value(t, copy, value);
return di_add_member((di_object_internal *)o, name, t, copy);
}
int di_add_member_clone(di_object *o, di_string name, di_type t, const void *value) {
auto ret = di_add_member_clone2(o, name, t, value);
if (IS_ERR(ret)) {
return (int)PTR_ERR(ret);
}
return 0;
}
int di_add_member_clonev(di_object *o, di_string name, di_type t, ...) {
if (di_sizeof_type(t) == 0) {
return -EINVAL;
}
di_value nv;
va_list ap;
va_start(ap, t);
va_arg_with_di_type(ap, t, &nv);
va_end(ap);
return di_add_member_clone(o, name, t, &nv);
}
struct di_member *di_add_member_move2(di_object *o, di_string name, di_type *t, void *addr) {
auto sz = di_sizeof_type(*t);
if (sz == 0) {
return ERR_PTR(-EINVAL);
}
di_type tt = *t;
void *taddr = malloc(sz);
memcpy(taddr, addr, sz);
*t = DI_TYPE_NIL;
memset(addr, 0, sz);
return di_add_member((di_object_internal *)o, name, tt, taddr);
}
int di_add_member_move(di_object *o, di_string name, di_type *t, void *addr) {
auto ret = di_add_member_move2(o, name, t, addr);
if (IS_ERR(ret)) {
return (int)PTR_ERR(ret);
}
return 0;
}
struct di_member *di_lookup(di_object *_obj, di_string name) {
if (name.data == NULL) {
return NULL;
}
auto obj = (di_object_internal *)_obj;
struct di_member *ret = NULL;
HASH_FIND(hh, obj->members, name.data, name.length, ret);
return (void *)ret;
}
di_tuple di_object_next_member(di_object *obj, di_string name) {
di_object *next = NULL;
if (di_rawget_borrowed(obj, "__next", next) == 0) {
di_variant ret = DI_VARIANT_INIT;
di_tuple args = {
.length = 2,
.elements =
(struct di_variant[]){
{.type = DI_TYPE_OBJECT, .value = (di_value *)&obj},
{.type = DI_TYPE_STRING, .value = (di_value *)&name},
},
};
di_value inner;
ret.value = &inner;
if (((di_object_internal *)next)->call(next, &ret.type, ret.value, args) != 0) {
return DI_TUPLE_INIT;
}
if (ret.type != DI_TYPE_TUPLE) {
di_free_value(ret.type, &inner);
return DI_TUPLE_INIT;
}
if (inner.tuple.length != 2 || inner.tuple.elements[0].type != DI_TYPE_STRING) {
di_free_tuple(inner.tuple);
return DI_TUPLE_INIT;
}
return inner.tuple;
}
di_tuple ret = DI_TUPLE_INIT;
struct di_member *m = NULL, *next_m = NULL;
if (name.data == NULL) {
HASH_ITER (hh, ((di_object_internal *)obj)->members, m, next_m) {
if (di_string_starts_with(m->name, "__")) {
continue;
}
break;
}
} else {
m = di_lookup(obj, name);
m = m == NULL ? NULL : m->hh.next;
while (m != NULL && di_string_starts_with(m->name, "__")) {
m = m->hh.next;
}
}
if (m == NULL) {
return ret;
}
ret.length = 2;
ret.elements = tmalloc(struct di_variant, 2);
ret.elements[0] = di_alloc_variant(di_clone_string(m->name));
ret.elements[1].type = m->type;
ret.elements[1].value = malloc(di_sizeof_type(m->type));
di_copy_value(m->type, ret.elements[1].value, m->data);
return ret;
}
/// Return an array of strings of all raw member names
di_array di_get_all_member_names_raw(di_object *obj_) {
auto obj = (di_object_internal *)obj_;
di_array ret = {
.arr = NULL,
.elem_type = DI_TYPE_STRING,
.length = HASH_COUNT(obj->members),
};
di_string *arr = ret.arr = tmalloc(di_string, ret.length);
int cnt = 0;
struct di_member *i, *ni;
HASH_ITER (hh, obj->members, i, ni) {
di_copy_value(DI_TYPE_STRING, &arr[cnt], &i->name);
cnt += 1;
}
assert(cnt == ret.length);
return ret;
}
bool di_foreach_member_raw(di_object *obj_, di_member_cb cb, void *user_data) {
auto obj = (di_object_internal *)obj_;
struct di_member *i, *ni;
HASH_ITER (hh, obj->members, i, ni) {
if (cb(i->name, i->type, i->data, user_data)) {
return true;
}
}
return false;
}
/// Restriction for destructors:
///
/// 1. They shouldn't assume any other member of `obj` is still valid.
void di_set_object_dtor(di_object *nonnull obj, di_dtor_fn nullable dtor) {
auto internal = (di_object_internal *)obj;
internal->dtor = dtor;
}
void di_set_object_call(di_object *nonnull obj, di_call_fn nullable call) {
auto internal = (di_object_internal *)obj;
internal->call = call;
}
bool di_is_object_callable(di_object *nonnull obj) {
auto internal = (di_object_internal *)obj;
return internal->call != NULL;
}
void di_free_tuple(di_tuple t) {
for (int i = 0; i < t.length; i++) {
di_free_value(DI_TYPE_VARIANT, (di_value *)&t.elements[i]);
}
free(t.elements);
}
void di_free_array(di_array arr) {
if (arr.length == 0) {
DI_CHECK(arr.arr == NULL);
return;
}
size_t step = di_sizeof_type(arr.elem_type);
for (int i = 0; i < arr.length; i++) {
di_free_value(arr.elem_type, arr.arr + step * i);
}
free(arr.arr);
}
void di_free_value(di_type t, di_value *value_ptr) {
if (t == DI_TYPE_NIL) {
return;
}
// If t != DI_TYPE_UINT, then `ptr_` cannot be NULL
di_value *nonnull val = value_ptr;
di_object *nonnull obj;
switch (t) {
case DI_TYPE_ARRAY:
di_free_array(val->array);
break;
case DI_TYPE_TUPLE:
di_free_tuple(val->tuple);
break;
case DI_TYPE_STRING:
di_free_string(val->string);
break;
case DI_TYPE_OBJECT:
case DI_TYPE_EMPTY_OBJECT:
obj = val->object;
di_unref_object(obj);
break;
case DI_TYPE_WEAK_OBJECT:
di_drop_weak_ref(&val->weak_object);
break;
case DI_TYPE_VARIANT:
di_free_value(val->variant.type, val->variant.value);
free(val->variant.value);