forked from MacRuby/MacRuby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bridgesupport.cpp
1732 lines (1496 loc) · 46 KB
/
bridgesupport.cpp
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
/*
* MacRuby BridgeSupport implementation.
*
* This file is covered by the Ruby license. See COPYING for more details.
*
* Copyright (C) 2012-2013, The MacRuby Team. All rights reserved.
* Copyright (C) 2007-2011, Apple Inc. All rights reserved.
*/
#if MACRUBY_STATIC
# include <vector>
# include <map>
# include <string>
#else
# include <llvm/Module.h>
# include <llvm/DerivedTypes.h>
# include <llvm/Constants.h>
# include <llvm/CallingConv.h>
# include <llvm/Instructions.h>
# include <llvm/Intrinsics.h>
# include <llvm/Analysis/DebugInfo.h>
# if !defined(LLVM_TOT)
# include <llvm/Analysis/DIBuilder.h>
# endif
# include <llvm/ExecutionEngine/JIT.h>
# include <llvm/PassManager.h>
# include <llvm/Target/TargetData.h>
using namespace llvm;
#endif
#include "macruby_internal.h"
#include "ruby/node.h"
#include "vm.h"
#include "compiler.h"
#include "bridgesupport.h"
#include "objc.h"
#include "class.h"
#include <execinfo.h>
#include <dlfcn.h>
#include <sys/stat.h>
static ID boxed_ivar_type = 0;
static VALUE bs_const_magic_cookie = Qnil;
VALUE rb_cBoxed;
VALUE rb_cPointer;
typedef struct rb_vm_pointer {
VALUE type;
size_t type_size;
VALUE (*convert_to_rval)(void *);
void (*convert_to_ocval)(VALUE rval, void *);
void *val;
size_t len; // if 0, we don't know...
} rb_vm_pointer_t;
static inline ID
generate_const_name(char *name)
{
ID id;
if (islower(name[0])) {
name[0] = toupper(name[0]);
id = rb_intern(name);
name[0] = tolower(name[0]);
return id;
}
else {
return rb_intern(name);
}
}
extern "C"
VALUE
rb_vm_resolve_const_value(VALUE v, VALUE klass, ID id)
{
if (v == bs_const_magic_cookie) {
bs_element_constant_t *bs_const = GET_CORE()->find_bs_const(id);
if (bs_const == NULL) {
rb_bug("unresolved BridgeSupport constant `%s'",
rb_id2name(id));
}
void *sym = dlsym(RTLD_DEFAULT, bs_const->name);
if (sym == NULL) {
// The symbol can't be located, it's probably because the current
// program links against a different version of the framework.
rb_raise(rb_eRuntimeError, "can't locate symbol for constant %s",
rb_id2name(id));
}
if (bs_const->magic_cookie) {
// Constant is a magic cookie. We don't support these yet.
rb_raise(rb_eRuntimeError,
"magic-cookie constant %s is not supported yet",
rb_id2name(id));
}
void *convertor = GET_CORE()->gen_to_rval_convertor(bs_const->type);
v = ((VALUE (*)(void *))convertor)(sym);
CFMutableDictionaryRef iv_dict = rb_class_ivar_dict(rb_cObject);
assert(iv_dict != NULL);
CFDictionarySetValue(iv_dict, (const void *)id, (const void *)v);
}
return v;
}
bs_element_constant_t *
RoxorCore::find_bs_const(ID name)
{
std::map<ID, bs_element_constant_t *>::iterator iter =
bs_consts.find(name);
return iter == bs_consts.end() ? NULL : iter->second;
}
bs_element_method_t *
RoxorCore::find_bs_method(Class klass, SEL sel)
{
std::map<std::string, std::map<SEL, bs_element_method_t *> *> &map =
class_isMetaClass(klass) ? bs_classes_class_methods
: bs_classes_instance_methods;
do {
std::map<std::string,
std::map<SEL, bs_element_method_t *> *>::iterator iter =
map.find(class_getName(klass));
if (iter != map.end()) {
std::map<SEL, bs_element_method_t *> *map2 = iter->second;
std::map<SEL, bs_element_method_t *>::iterator iter2 =
map2->find(sel);
if (iter2 != map2->end()) {
return iter2->second;
}
}
klass = class_getSuperclass(klass);
}
while (klass != NULL);
return NULL;
}
rb_vm_bs_boxed_t *
RoxorCore::find_bs_boxed(std::string type)
{
std::map<std::string, rb_vm_bs_boxed_t *>::iterator iter =
bs_boxed.find(type);
if (iter == bs_boxed.end()) {
return NULL;
}
return iter->second;
}
rb_vm_bs_boxed_t *
RoxorCore::find_bs_struct(std::string type)
{
rb_vm_bs_boxed_t *boxed = find_bs_boxed(type);
if (boxed != NULL) {
if (boxed->is_struct()) {
return boxed;
}
return NULL;
}
#if MACRUBY_STATIC
return NULL;
#else
// Given structure type does not exist... but it may be an anonymous
// type (like {?=qq}) which is sometimes present in BridgeSupport files...
return register_anonymous_bs_struct(type.c_str());
#endif
}
rb_vm_bs_boxed_t *
RoxorCore::find_bs_opaque(std::string type)
{
rb_vm_bs_boxed_t *boxed = find_bs_boxed(type);
return boxed == NULL ? NULL : boxed->is_struct() ? NULL : boxed;
}
bs_element_cftype_t *
RoxorCore::find_bs_cftype(std::string type)
{
std::map<std::string, bs_element_cftype_t *>::iterator iter =
bs_cftypes.find(type);
return iter == bs_cftypes.end() ? NULL : iter->second;
}
std::string *
RoxorCore::find_bs_informal_protocol_method(SEL sel, bool class_method)
{
std::map<SEL, std::string *> &map = class_method
? bs_informal_protocol_cmethods : bs_informal_protocol_imethods;
std::map<SEL, std::string *>::iterator iter = map.find(sel);
return iter == map.end() ? NULL : iter->second;
}
bs_element_function_t *
RoxorCore::find_bs_function(std::string &name)
{
std::map<std::string, bs_element_function_t *>::iterator iter =
bs_funcs.find(name);
return iter == bs_funcs.end() ? NULL : iter->second;
}
static rb_vm_bs_boxed_t *
locate_bs_boxed(VALUE klass, const bool struct_only=false)
{
VALUE type = rb_attr_get(klass, boxed_ivar_type);
assert(type != Qnil);
rb_vm_bs_boxed_t *bs_boxed = GET_CORE()->find_bs_boxed(RSTRING_PTR(type));
assert(bs_boxed != NULL);
if (struct_only) {
assert(bs_boxed->is_struct());
}
return bs_boxed;
}
#if !defined(MACRUBY_STATIC)
extern "C"
void
rb_vm_check_arity(int given, int requested)
{
if (given != requested) {
rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)",
given, requested);
}
}
void
RoxorCompiler::compile_check_arity(Value *given, Value *requested)
{
if (checkArityFunc == NULL) {
// void rb_vm_check_arity(int given, int requested);
checkArityFunc = cast<Function>(module->getOrInsertFunction(
"rb_vm_check_arity",
VoidTy, Int32Ty, Int32Ty, NULL));
}
Value *args[] = {
given,
requested
};
compile_protected_call(checkArityFunc, args, args + 2);
}
extern "C"
void
rb_vm_set_struct(VALUE rcv, int field, VALUE val)
{
VALUE *data;
Data_Get_Struct(rcv, VALUE, data);
GC_WB(&data[field], val);
}
void
RoxorCompiler::compile_set_struct(Value *rcv, int field, Value *val)
{
if (setStructFunc == NULL) {
// void rb_vm_set_struct(VALUE rcv, int field, VALUE val);
setStructFunc = cast<Function>(module->getOrInsertFunction(
"rb_vm_set_struct",
VoidTy, RubyObjTy, Int32Ty, RubyObjTy, NULL));
}
Value *args[] = {
rcv,
ConstantInt::get(Int32Ty, field),
val
};
CallInst::Create(setStructFunc, args, args + 3, "", bb);
}
Function *
RoxorCompiler::compile_bs_struct_writer(rb_vm_bs_boxed_t *bs_boxed, int field)
{
// VALUE foo(VALUE self, SEL sel, VALUE val);
Function *f = cast<Function>(module->getOrInsertFunction("",
RubyObjTy, RubyObjTy, PtrTy, RubyObjTy, NULL));
Function::arg_iterator arg = f->arg_begin();
Value *self = arg++; // self
++arg; // sel
Value *val = arg++; // val
bb = BasicBlock::Create(context, "EntryBlock", f);
assert((unsigned)field < bs_boxed->as.s->fields_count);
const char *ftype = bs_boxed->as.s->fields[field].type;
const Type *llvm_type = convert_type(ftype);
Value *fval = new AllocaInst(llvm_type, "", bb);
val = compile_conversion_to_c(ftype, val, fval);
val = compile_conversion_to_ruby(ftype, llvm_type, val);
compile_set_struct(self, field, val);
ReturnInst::Create(context, val, bb);
return f;
}
Function *
RoxorCompiler::compile_bs_struct_new(rb_vm_bs_boxed_t *bs_boxed)
{
// VALUE foo(VALUE self, SEL sel, int argc, VALUE *argv);
Function *f = cast<Function>(module->getOrInsertFunction("",
RubyObjTy, RubyObjTy, PtrTy, Int32Ty, RubyObjPtrTy,
NULL));
Function::arg_iterator arg = f->arg_begin();
Value *klass = arg++; // self
++arg; // sel
Value *argc = arg++; // argc
Value *argv = arg++; // argv
bb = BasicBlock::Create(context, "EntryBlock", f);
BasicBlock *no_args_bb = BasicBlock::Create(context, "no_args", f);
BasicBlock *args_bb = BasicBlock::Create(context, "args", f);
Value *has_args = new ICmpInst(*bb, ICmpInst::ICMP_EQ, argc,
ConstantInt::get(Int32Ty, 0));
BranchInst::Create(no_args_bb, args_bb, has_args, bb);
// No arguments are given, let's create Ruby field objects based on a
// zero-filled memory slot.
bb = no_args_bb;
std::vector<Value *> fields;
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
const char *ftype = bs_boxed->as.s->fields[i].type;
const Type *llvm_type = convert_type(ftype);
Value *fval = new AllocaInst(llvm_type, "", bb);
const size_t type_size = GET_CORE()->get_sizeof(llvm_type);
Value *args[] = {
new BitCastInst(fval, PtrTy, "", bb), // start
ConstantInt::get(Int8Ty, 0), // value
ConstantInt::get(IntTy, type_size), // size
ConstantInt::get(Int32Ty, 0), // align
ConstantInt::get(Int1Ty, 0) // volatile
};
const Type *Tys[] = { args[0]->getType(), args[2]->getType() };
Function *memset_func = Intrinsic::getDeclaration(module,
Intrinsic::memset, Tys, 2);
assert(memset_func != NULL);
CallInst::Create(memset_func, args, args + 5, "", bb);
fval = new LoadInst(fval, "", bb);
fval = compile_conversion_to_ruby(ftype, llvm_type, fval);
fields.push_back(fval);
}
ReturnInst::Create(context, compile_new_struct(klass, fields), bb);
// Arguments are given. Need to check given arity, then convert the given
// Ruby values into the requested struct field types.
bb = args_bb;
fields.clear();
compile_check_arity(argc,
ConstantInt::get(Int32Ty, bs_boxed->as.s->fields_count));
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
const char *ftype = bs_boxed->as.s->fields[i].type;
const Type *llvm_type = convert_type(ftype);
Value *fval = new AllocaInst(llvm_type, "", bb);
Value *index = ConstantInt::get(Int32Ty, i);
Value *arg = GetElementPtrInst::Create(argv, index, "", bb);
arg = new LoadInst(arg, "", bb);
compile_conversion_to_c(ftype, arg, fval);
arg = new LoadInst(fval, "", bb);
arg = compile_conversion_to_ruby(ftype, llvm_type, arg);
fields.push_back(arg);
}
ReturnInst::Create(context, compile_new_struct(klass, fields), bb);
return f;
}
static VALUE
rb_vm_struct_fake_new(VALUE rcv, SEL sel, int argc, VALUE *argv)
{
// Generate the real #new method.
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(rcv, true);
GET_CORE()->lock();
Function *f = RoxorCompiler::shared->compile_bs_struct_new(bs_boxed);
IMP imp = GET_CORE()->compile(f);
GET_CORE()->unlock();
// Replace the fake method with the new one in the runtime.
rb_objc_define_method(*(VALUE *)rcv, "new", (void *)imp, -1);
// Call the new method.
return ((VALUE (*)(VALUE, SEL, int, VALUE *))imp)(rcv, sel, argc, argv);
}
static VALUE
rb_vm_struct_fake_set(VALUE rcv, SEL sel, VALUE val)
{
// Locate the given field.
char buf[100];
const char *selname = sel_getName(sel);
size_t s = strlcpy(buf, selname, sizeof buf);
if (buf[s - 1] == ':') {
s--;
}
assert(buf[s - 1] == '=');
buf[s - 1] = '\0';
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(CLASS_OF(rcv), true);
int field = -1;
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
const char *fname = bs_boxed->as.s->fields[i].name;
if (strcmp(fname, buf) == 0) {
field = i;
break;
}
}
assert(field != -1);
// Generate the new setter method.
GET_CORE()->lock();
Function *f = RoxorCompiler::shared->compile_bs_struct_writer(
bs_boxed, field);
IMP imp = GET_CORE()->compile(f);
GET_CORE()->unlock();
// Replace the fake method with the new one in the runtime.
buf[s - 1] = '=';
buf[s] = '\0';
rb_objc_define_method(*(VALUE *)rcv, buf, (void *)imp, 1);
// Call the new method.
return ((VALUE (*)(VALUE, SEL, VALUE))imp)(rcv, sel, val);
}
// Readers are statically generated.
#include "bs_struct_readers.c"
static VALUE
rb_vm_boxed_equal(VALUE rcv, SEL sel, VALUE val)
{
if (rcv == val) {
return Qtrue;
}
VALUE klass = CLASS_OF(rcv);
if (!rb_obj_is_kind_of(val, klass)) {
return Qfalse;
}
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(klass);
VALUE *rcv_data; Data_Get_Struct(rcv, VALUE, rcv_data);
VALUE *val_data; Data_Get_Struct(val, VALUE, val_data);
if (bs_boxed->bs_type == BS_ELEMENT_STRUCT) {
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
if (!rb_equal(rcv_data[i], val_data[i])) {
return Qfalse;
}
}
return Qtrue;
}
return rcv_data == val_data ? Qtrue : Qfalse;
}
static VALUE
rb_vm_struct_inspect(VALUE rcv, SEL sel)
{
VALUE str = rb_str_new2("#<");
rb_str_cat2(str, rb_obj_classname(rcv));
VALUE *rcv_data;
Data_Get_Struct(rcv, VALUE, rcv_data);
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(CLASS_OF(rcv), true);
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
rb_str_cat2(str, " ");
rb_str_cat2(str, bs_boxed->as.s->fields[i].name);
rb_str_cat2(str, "=");
rb_str_append(str, rb_inspect(rcv_data[i]));
}
rb_str_cat2(str, ">");
return str;
}
static VALUE
rb_vm_struct_to_a(VALUE rcv, SEL sel)
{
VALUE ary = rb_ary_new();
VALUE *rcv_data;
Data_Get_Struct(rcv, VALUE, rcv_data);
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(CLASS_OF(rcv), true);
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
rb_ary_push(ary, rcv_data[i]);
}
return ary;
}
static VALUE
rb_vm_struct_aref(VALUE rcv, SEL sel, VALUE index)
{
const long idx = NUM2LONG(index);
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(CLASS_OF(rcv), true);
if (idx < 0 || (unsigned long)idx >= bs_boxed->as.s->fields_count) {
rb_raise(rb_eArgError, "given index %ld out of bounds", idx);
}
VALUE *rcv_data;
Data_Get_Struct(rcv, VALUE, rcv_data);
return rcv_data[idx];
}
static VALUE
rb_vm_struct_aset(VALUE rcv, SEL sel, VALUE index, VALUE val)
{
const long idx = NUM2LONG(index);
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(CLASS_OF(rcv), true);
if (idx < 0 || (unsigned long)idx >= bs_boxed->as.s->fields_count) {
rb_raise(rb_eArgError, "given index %ld out of bounds", idx);
}
char buf[100];
snprintf(buf, sizeof buf, "%s=:", bs_boxed->as.s->fields[idx].name);
return rb_vm_call(rcv, sel_registerName(buf), 1, &val);
}
static VALUE
rb_vm_struct_dup(VALUE rcv, SEL sel)
{
VALUE klass = CLASS_OF(rcv);
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(klass, true);
VALUE *rcv_data;
Data_Get_Struct(rcv, VALUE, rcv_data);
VALUE *new_data = (VALUE *)xmalloc(
bs_boxed->as.s->fields_count * sizeof(VALUE));
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
VALUE field = rcv_data[i];
// Numeric values cannot be duplicated.
if (!rb_obj_is_kind_of(field, rb_cNumeric)) {
field = rb_send_dup(field);
}
GC_WB(&new_data[i], field);
}
return Data_Wrap_Struct(klass, NULL, NULL, new_data);
}
static VALUE
rb_boxed_fields(VALUE rcv, SEL sel)
{
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(rcv);
VALUE ary = rb_ary_new();
if (bs_boxed->bs_type == BS_ELEMENT_STRUCT) {
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
VALUE field = ID2SYM(rb_intern(bs_boxed->as.s->fields[i].name));
rb_ary_push(ary, field);
}
}
return ary;
}
static VALUE
rb_boxed_size(VALUE rcv, SEL sel)
{
rb_vm_bs_boxed_t *bs_boxed = locate_bs_boxed(rcv);
if (bs_boxed->bs_type == BS_ELEMENT_STRUCT) {
return LONG2NUM(GET_CORE()->get_sizeof(bs_boxed->as.s->type));
}
return Qnil;
}
static VALUE
rb_vm_opaque_new(VALUE rcv, SEL sel)
{
// XXX instead of doing this, we should perhaps simply delete the new
// method on the class...
rb_raise(rb_eRuntimeError, "can't allocate opaque type `%s'",
rb_class2name(rcv));
}
bool
RoxorCore::register_bs_boxed(bs_element_type_t type, void *value)
{
std::string octype(((bs_element_opaque_t *)value)->type);
std::map<std::string, rb_vm_bs_boxed_t *>::iterator iter =
bs_boxed.find(octype);
if (iter != bs_boxed.end()) {
// A boxed class of this type already exists, so let's create an
// alias to it.
rb_vm_bs_boxed_t *boxed = iter->second;
const ID name = rb_intern(((bs_element_opaque_t *)value)->name);
rb_const_set(rb_cObject, name, boxed->klass);
return false;
}
rb_vm_bs_boxed_t *boxed = (rb_vm_bs_boxed_t *)malloc(
sizeof(rb_vm_bs_boxed_t));
assert(boxed != NULL);
boxed->bs_type = type;
boxed->as.v = value;
boxed->type = NULL; // lazy
boxed->klass = rb_define_class(((bs_element_opaque_t *)value)->name,
rb_cBoxed);
rb_ivar_set(boxed->klass, boxed_ivar_type, rb_str_new2(octype.c_str()));
if (type == BS_ELEMENT_STRUCT && !boxed->as.s->opaque) {
// Define the fake #new method.
rb_objc_define_method(*(VALUE *)boxed->klass, "new",
(void *)rb_vm_struct_fake_new, -1);
// Define accessors.
assert(boxed->as.s->fields_count <= BS_STRUCT_MAX_FIELDS);
for (unsigned i = 0; i < boxed->as.s->fields_count; i++) {
// Readers.
rb_objc_define_method(boxed->klass, boxed->as.s->fields[i].name,
(void *)struct_readers[i], 0);
// Writers.
char buf[100];
snprintf(buf, sizeof buf, "%s=", boxed->as.s->fields[i].name);
rb_objc_define_method(boxed->klass, buf,
(void *)rb_vm_struct_fake_set, 1);
}
// Define other utility methods.
rb_objc_define_method(*(VALUE *)boxed->klass, "fields",
(void *)rb_boxed_fields, 0);
rb_objc_define_method(*(VALUE *)boxed->klass, "size",
(void *)rb_boxed_size, 0);
rb_objc_define_method(boxed->klass, "dup",
(void *)rb_vm_struct_dup, 0);
rb_objc_define_method(boxed->klass, "clone",
(void *)rb_vm_struct_dup, 0);
rb_objc_define_method(boxed->klass, "inspect",
(void *)rb_vm_struct_inspect, 0);
rb_objc_define_method(boxed->klass, "to_a",
(void *)rb_vm_struct_to_a, 0);
rb_objc_define_method(boxed->klass, "[]",
(void *)rb_vm_struct_aref, 1);
rb_objc_define_method(boxed->klass, "[]=",
(void *)rb_vm_struct_aset, 2);
}
else {
// Opaque methods.
rb_objc_define_method(*(VALUE *)boxed->klass, "new",
(void *)rb_vm_opaque_new, -1);
}
// Common methods.
rb_objc_define_method(boxed->klass, "==", (void *)rb_vm_boxed_equal, 1);
bs_boxed[octype] = boxed;
return true;
}
rb_vm_bs_boxed_t *
RoxorCore::register_anonymous_bs_struct(const char *type)
{
const size_t type_len = strlen(type);
assert(type_len > 0);
if (type_len < 3 || type[0] != _C_STRUCT_B || type[1] != '?'
|| type[2] != '=') {
// Does not look like an anonymous struct...
return NULL;
}
// Prepare the list of field types.
const size_t buf_len = type_len + 1;
char *buf = (char *)malloc(buf_len);
assert(buf != NULL);
std::vector<std::string> s_types;
const char *p = &type[3];
while (*p != _C_STRUCT_E) {
p = GetFirstType(p, buf, buf_len);
assert(*p != '\0');
s_types.push_back(buf);
}
free(buf);
// Prepare the BridgeSupport structure.
bs_element_struct_t *bs_struct = (bs_element_struct_t *)
malloc(sizeof(bs_element_struct_t));
assert(bs_struct != NULL);
bs_struct->name = (char *)"?";
bs_struct->type = strdup(type);
bs_struct->fields_count = s_types.size();
assert(bs_struct->fields_count > 0);
bs_struct->fields = (bs_element_struct_field_t *)
malloc(sizeof(bs_element_struct_field_t) * bs_struct->fields_count);
assert(bs_struct->fields != NULL);
for (unsigned i = 0; i < bs_struct->fields_count; i++) {
bs_element_struct_field_t *field = &bs_struct->fields[i];
field->name = (char *)"?";
field->type = strdup(s_types.at(i).c_str());
}
bs_struct->opaque = false;
// Prepare the boxed structure.
rb_vm_bs_boxed_t *boxed = (rb_vm_bs_boxed_t *)
malloc(sizeof(rb_vm_bs_boxed_t));
assert(boxed != NULL);
boxed->bs_type = BS_ELEMENT_STRUCT;
boxed->as.s = bs_struct;
boxed->type = NULL; // Lazy
boxed->klass = rb_cBoxed; // This type has no class
// Register it to the runtime.
bs_boxed[type] = boxed;
return boxed;
}
static inline long
rebuild_new_struct_ary(const StructType *type, VALUE orig, VALUE new_ary)
{
long n = 0;
for (StructType::element_iterator iter = type->element_begin();
iter != type->element_end();
++iter) {
const Type *ftype = *iter;
if (ftype->getTypeID() == Type::StructTyID) {
const long n2 = rebuild_new_struct_ary(cast<StructType>(ftype), orig, new_ary);
VALUE tmp = rb_ary_new();
for (long i = 0; i < n2; i++) {
if (RARRAY_LEN(orig) == 0) {
return 0;
}
rb_ary_push(tmp, rb_ary_shift(orig));
}
rb_ary_push(new_ary, tmp);
}
n++;
}
return n;
}
extern "C"
void
rb_vm_get_struct_fields(VALUE rval, VALUE *buf, rb_vm_bs_boxed_t *bs_boxed)
{
if (TYPE(rval) == T_ARRAY) {
unsigned n = RARRAY_LEN(rval);
if (n < bs_boxed->as.s->fields_count) {
rb_raise(rb_eArgError,
"not enough elements in array `%s' to create " \
"structure `%s' (%d for %d)",
RSTRING_PTR(rb_inspect(rval)), bs_boxed->as.s->name, n,
bs_boxed->as.s->fields_count);
}
if (n > bs_boxed->as.s->fields_count) {
VALUE new_rval = rb_ary_new();
VALUE orig = rval;
rval = rb_ary_dup(rval);
rebuild_new_struct_ary(cast<StructType>(bs_boxed->type), rval,
new_rval);
n = RARRAY_LEN(new_rval);
if (RARRAY_LEN(rval) != 0 || n != bs_boxed->as.s->fields_count) {
rb_raise(rb_eArgError,
"too much elements in array `%s' to create " \
"structure `%s' (%ld for %d)",
RSTRING_PTR(rb_inspect(orig)),
bs_boxed->as.s->name, RARRAY_LEN(orig),
bs_boxed->as.s->fields_count);
}
rval = new_rval;
}
for (unsigned i = 0; i < n; i++) {
buf[i] = RARRAY_AT(rval, i);
}
}
else if (CLASS_OF(rval) == rb_cRange &&
(strcmp(bs_boxed->as.s->name, "NSRange") == 0 ||
strcmp(bs_boxed->as.s->name, "CFRange") == 0)) {
VALUE b, e;
int exclusive;
rb_range_values(rval, &b, &e, &exclusive);
int begin = NUM2INT(b);
int end = NUM2INT(e);
if (begin < 0 || end < 0) {
// We don't know what the max length of the range will be, so we
// can't count backwards.
rb_raise(rb_eArgError,
"negative values are not allowed in ranges " \
"that are converted to %s structures: `%s'. " \
"Use `Range#relative_to(max)' to expand them.",
bs_boxed->as.s->name,
RSTRING_PTR(rb_inspect(rval)));
}
int length = exclusive ? end-begin : end-begin+1;
buf[0] = INT2NUM(begin);
buf[1] = INT2NUM(length);
}
else {
if (!rb_obj_is_kind_of(rval, bs_boxed->klass)) {
rb_raise(rb_eTypeError,
"expected instance of `%s', got `%s' (%s)",
rb_class2name(bs_boxed->klass),
RSTRING_PTR(rb_inspect(rval)),
rb_obj_classname(rval));
}
if (bs_boxed->klass == rb_cBoxed) {
// An anonymous type...
// Let's check that the given boxed object matches the types.
rb_vm_bs_boxed_t *rval_bs_boxed =
locate_bs_boxed(CLASS_OF(rval), true);
assert(rval_bs_boxed != NULL);
if (rval_bs_boxed->as.s->fields_count
!= bs_boxed->as.s->fields_count) {
rb_raise(rb_eTypeError,
"expected instance of Boxed with %d fields, got %d",
bs_boxed->as.s->fields_count,
rval_bs_boxed->as.s->fields_count);
}
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
if (strcmp(bs_boxed->as.s->fields[i].type,
rval_bs_boxed->as.s->fields[i].type) != 0) {
rb_raise(rb_eTypeError,
"field %d of given instance of `%s' does not match " \
"the type expected (%s, got %s)",
i,
rb_class2name(bs_boxed->klass),
bs_boxed->as.s->fields[i].type,
rval_bs_boxed->as.s->fields[i].type);
}
}
}
VALUE *data;
Data_Get_Struct(rval, VALUE, data);
for (unsigned i = 0; i < bs_boxed->as.s->fields_count; i++) {
buf[i] = data[i];
}
}
}
static const char *convert_ffi_type(VALUE type,
bool raise_exception_if_unknown);
static void
rb_pointer_init_type(rb_vm_pointer_t *ptr, VALUE type)
{
const char *type_str = StringValuePtr(type);
// LLVM doesn't allow to get a pointer to Type::VoidTy, and for convenience
// reasons we map a pointer to void as a pointer to unsigned char.
if (*type_str == 'v') {
type_str = "C";
type = rb_str_new2(type_str);
}
GC_WB(&ptr->type, type);
RoxorCore *core = GET_CORE();
ptr->type_size = core->get_sizeof(type_str);
assert(ptr->type_size > 0);
ptr->convert_to_rval =
(VALUE (*)(void *))core->gen_to_rval_convertor(type_str);
ptr->convert_to_ocval =
(void (*)(VALUE, void *))core->gen_to_ocval_convertor(type_str);
}
extern "C"
VALUE
rb_pointer_new(const char *type_str, void *val, size_t len)
{
rb_vm_pointer_t *ptr = (rb_vm_pointer_t *)xmalloc(sizeof(rb_vm_pointer_t));
rb_pointer_init_type(ptr, rb_str_new2(type_str));
GC_WB(&ptr->val, val);
ptr->len = len;
return Data_Wrap_Struct(rb_cPointer, NULL, NULL, ptr);
}
static VALUE
rb_pointer_s_new(VALUE rcv, SEL sel, int argc, VALUE *argv)
{
VALUE type, len;
rb_scan_args(argc, argv, "11", &type, &len);
size_t rlen = 1;
if (!NIL_P(len)) {
const long n = FIX2LONG(len);
if (n <= 0) {
rb_raise(rb_eArgError, "given len must be greater than 0");
}
rlen = (size_t)n;
}
const char *type_str = convert_ffi_type(type, false);
// There's no such thing as void type in ruby
if (*type_str == 'v') {
rb_raise(rb_eTypeError, "Void pointer is not allowed");
}
return rb_pointer_new(type_str,
xmalloc(GET_CORE()->get_sizeof(type_str) * rlen), rlen);
}
static VALUE
rb_pointer_s_magic_cookie(VALUE rcv, SEL sel, VALUE val)
{
long magic_cookie = NUM2LONG(val);
rb_vm_pointer_t *ptr = (rb_vm_pointer_t *)xmalloc(sizeof(rb_vm_pointer_t));
GC_WB(&ptr->type, rb_str_new2("^v"));
ptr->type_size = sizeof(void *);
ptr->convert_to_rval = NULL;
ptr->convert_to_ocval = NULL;
ptr->val = (void *)magic_cookie;
ptr->len = 1;
return Data_Wrap_Struct(rb_cPointer, NULL, NULL, ptr);
}
static void
check_no_magic_cookie(rb_vm_pointer_t *ptr)
{
if (ptr->convert_to_rval == NULL || ptr->convert_to_ocval == NULL) {
rb_raise(rb_eArgError, "cannot access magic cookie pointers");
}
}
static inline void *
pointer_val(rb_vm_pointer_t *ptr, VALUE idx)
{
const long i = NUM2LONG(idx);
if (i < 0) {
rb_raise(rb_eArgError, "index must not be negative");
}
if (ptr->len > 0 && (size_t)i >= ptr->len) {
rb_raise(rb_eArgError, "index %ld out of bounds (%ld)", i, ptr->len);
}
return (void *)((char *)ptr->val + (i * ptr->type_size));
}
static VALUE
rb_pointer_aref(VALUE rcv, SEL sel, VALUE idx)
{
rb_vm_pointer_t *ptr;
Data_Get_Struct(rcv, rb_vm_pointer_t, ptr);
check_no_magic_cookie(ptr);
return ptr->convert_to_rval(pointer_val(ptr, idx));
}
static VALUE
rb_pointer_value(VALUE rcv, SEL sel)
{
return rb_pointer_aref(rcv, 0, INT2FIX(0));
}
static VALUE
rb_pointer_aset(VALUE rcv, SEL sel, VALUE idx, VALUE val)
{
rb_vm_pointer_t *ptr;
Data_Get_Struct(rcv, rb_vm_pointer_t, ptr);
check_no_magic_cookie(ptr);
ptr->convert_to_ocval(val, pointer_val(ptr, idx));
return val;
}
static VALUE