-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathblocks.py
1682 lines (1449 loc) · 76 KB
/
blocks.py
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
# Copyright (c) 2024 Daniel Roethlisberger
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import binaryninja as binja
import sys
import traceback
from . import shinobi
from . import objctypes
# Had to disable is_valid due to spurious exceptions in Binary Ninja Core.
# https://github.com/Vector35/binaryninja-api/issues/6254
# https://github.com/droe/binja-blocks/issues/5
is_valid = None
#def is_valid(bv, arg=None):
# return bv.arch.name in (
# 'aarch64',
# 'x86_64',
# #'armv7',
# #'x86',
# )
_TYPE_ID_SOURCE = "binja-blocks"
_LOGGER_NAME = "Apple Blocks"
_OBJC_TYPE_SOURCE = """
struct objc_class {
};
typedef struct objc_class* Class;
struct objc_object {
Class isa;
};
typedef struct objc_object* id;
"""
_LIBCLOSURE_TYPE_SOURCE = """
enum Block_flags : uint32_t {
BLOCK_DEALLOCATING = 0x0001U, // runtime
// BLOCK_REFCOUNT_MASK = 0xfffeU, // runtime
// in-descriptor flags only
// BLOCK_GENERIC_HELPER_NONE = 0U << 14, // compiler
// BLOCK_GENERIC_HELPER_FROM_LAYOUT = 1U << 14, // compiler
// BLOCK_GENERIC_HELPER_INLINE = 2U << 14, // compiler
// BLOCK_GENERIC_HELPER_OUTOFLINE = 3U << 14, // compiler
// BLOCK_GENERIC_HELPER_MASK = 3U << 14, // compiler
BLOCK_GENERIC_HELPER_BIT0 = 1U << 14, // compiler
BLOCK_GENERIC_HELPER_BIT1 = 1U << 15, // compiler
BLOCK_INLINE_LAYOUT_STRING = 1U << 21, // compiler
BLOCK_SMALL_DESCRIPTOR = 1U << 22, // compiler
BLOCK_IS_NOESCAPE = 1U << 23, // compiler
BLOCK_NEEDS_FREE = 1U << 24, // runtime
BLOCK_HAS_COPY_DISPOSE = 1U << 25, // compiler
BLOCK_HAS_CTOR = 1U << 26, // compiler
BLOCK_IS_GC = 1U << 27, // runtime
BLOCK_IS_GLOBAL = 1U << 28, // compiler
BLOCK_USE_STRET = 1U << 29, // compiler
BLOCK_HAS_SIGNATURE = 1U << 30, // compiler
BLOCK_HAS_EXTENDED_LAYOUT = 1U << 31, // compiler
};
enum Block_byref_flags : uint32_t {
BLOCK_BYREF_DEALLOCATING = 0x0001U, // runtime
// BLOCK_BYREF_REFCOUNT_MASK = 0xfffeU, // runtime
BLOCK_BYREF_NEEDS_FREE = 1U << 24, // runtime
BLOCK_BYREF_HAS_COPY_DISPOSE = 1U << 25, // compiler
BLOCK_BYREF_IS_GC = 1U << 27, // runtime
// BLOCK_BYREF_LAYOUT_MASK = 7U << 28, // compiler
// BLOCK_BYREF_LAYOUT_EXTENDED = 1U << 28, // compiler
// BLOCK_BYREF_LAYOUT_NON_OBJECT = 2U << 28, // compiler
// BLOCK_BYREF_LAYOUT_STRONG = 3U << 28, // compiler
// BLOCK_BYREF_LAYOUT_WEAK = 4U << 28, // compiler
// BLOCK_BYREF_LAYOUT_UNRETAINED = 5U << 28, // compiler
BLOCK_BYREF_LAYOUT_BIT0 = 1U << 28, // compiler
BLOCK_BYREF_LAYOUT_BIT1 = 1U << 29, // compiler
BLOCK_BYREF_LAYOUT_BIT2 = 1U << 30, // compiler
};
typedef void(*BlockCopyFunction)(void *, const void *);
typedef void(*BlockDisposeFunction)(const void *);
typedef void(*BlockInvokeFunction)(void *, ...);
struct Block_byref_1 {
Class isa;
struct Block_byref_1 *forwarding;
volatile enum Block_byref_flags flags;
uint32_t size;
};
typedef void(*BlockByrefKeepFunction)(struct Block_byref*, struct Block_byref*);
typedef void(*BlockByrefDestroyFunction)(struct Block_byref *);
struct Block_byref_2 {
BlockByrefKeepFunction keep;
BlockByrefDestroyFunction destroy;
};
struct Block_byref_3 {
const char *layout;
};
struct Block_descriptor_1 {
enum Block_flags flags;
uint32_t reserved;
uint64_t size;
};
struct Block_descriptor_2 {
BlockCopyFunction copy;
BlockDisposeFunction dispose;
};
struct Block_descriptor_3 {
const char *signature;
const uint8_t *layout;
};
struct Block_literal {
Class isa;
volatile enum Block_flags flags;
uint32_t reserved;
BlockInvokeFunction invoke;
struct Block_descriptor_1 *descriptor;
};
"""
BLOCK_HAS_EXTENDED_LAYOUT = 0x80000000
BLOCK_HAS_SIGNATURE = 0x40000000
BLOCK_IS_GLOBAL = 0x10000000
BLOCK_HAS_COPY_DISPOSE = 0x02000000
BLOCK_SMALL_DESCRIPTOR = 0x00400000
BLOCK_GENERIC_HELPER_MASK = 0x0000C000
BLOCK_GENERIC_HELPER_NONE = 0x00000000
BLOCK_GENERIC_HELPER_FROM_LAYOUT = 0x00004000
BLOCK_GENERIC_HELPER_INLINE = 0x00008000
BLOCK_GENERIC_HELPER_OUTOFLINE = 0x0000C000
BLOCK_BYREF_HAS_COPY_DISPOSE = 0x02000000
BLOCK_BYREF_LAYOUT_MASK = 0x70000000
BLOCK_BYREF_LAYOUT_EXTENDED = 0x10000000
BLOCK_BYREF_LAYOUT_NON_OBJECT = 0x20000000
BLOCK_BYREF_LAYOUT_STRONG = 0x30000000
BLOCK_BYREF_LAYOUT_WEAK = 0x40000000
BLOCK_BYREF_LAYOUT_UNRETAINED = 0x50000000
BLOCK_LAYOUT_ESCAPE = 0x0
BLOCK_LAYOUT_NON_OBJECT_BYTES = 0x1
BLOCK_LAYOUT_NON_OBJECT_WORDS = 0x2
BLOCK_LAYOUT_STRONG = 0x3
BLOCK_LAYOUT_BYREF = 0x4
BLOCK_LAYOUT_WEAK = 0x5
BLOCK_LAYOUT_UNRETAINED = 0x6
BCK_DONE = 0x0
BCK_NON_OBJECT_BYTES = 0x1
BCK_NON_OBJECT_WORDS = 0x2
BCK_STRONG = 0x3
BCK_BLOCK = 0x4
BCK_BYREF = 0x5
BCK_WEAK = 0x6
def _get_custom_type_internal(bv, name, typestr, source, dependency=None):
assert (name is None) != (typestr is None)
def make_type():
if name is not None:
return bv.get_type_by_name(name)
else:
try:
return bv.x_parse_type(typestr)
except SyntaxError:
return None
type_ = make_type()
if type_ is not None:
return type_
if dependency is not None:
dependency()
types = bv.parse_types_from_string(source)
bv.define_types([(binja.Type.generate_auto_type_id(_TYPE_ID_SOURCE, k), k, v) for k, v in types.types.items()], None)
type_ = make_type()
assert type_ is not None
return type_
def _get_objc_type(bv, name):
"""
Get a type object for an Objective-C type that we ship stand-in
types for, by name. For a struct or an enum, this returns an
anonymous struct or enum, not a reference to the named type.
"""
return _get_custom_type_internal(bv, name, None, _OBJC_TYPE_SOURCE)
def _parse_objc_type(bv, typestr):
"""
Parse a type string containing Objective-C types that we ship
standin types for. When passed "struct Foo" or "enum Foo",
returns a reference to a named type, suitable for annotating
field members.
"""
return _get_custom_type_internal(bv, None, typestr, _OBJC_TYPE_SOURCE)
def _get_libclosure_type(bv, name):
"""
Get a type object for a libclosure type that we ship with
the plugin, by name. For a struct or an enum, this returns an
anonymous struct or enum, not a reference to the named type.
"""
return _get_custom_type_internal(bv, name, None, _LIBCLOSURE_TYPE_SOURCE,
lambda: _get_objc_type(bv, "Class"))
def _parse_libclosure_type(bv, typestr):
"""
Parse a type string containing libclosure types that we ship with
the plugin. When passed "struct Foo" or "enum Foo", returns a
reference to a named type, suitable for annotating field members.
"""
return _get_custom_type_internal(bv, None, typestr, _LIBCLOSURE_TYPE_SOURCE,
lambda: _get_objc_type(bv, "Class"))
def _define_ns_concrete_block_imports(bv):
"""
For some reason, Binary Ninja does not reliably define all external symbols.
Make sure __NSConcreteGlobalBlock and __NSConcreteStackBlock are defined
appropriately.
"""
objc_class_type = _parse_objc_type(bv, "Class")
for sym_name in ("__NSConcreteGlobalBlock", "__NSConcreteStackBlock"):
for sym_type in (binja.SymbolType.ExternalSymbol, binja.SymbolType.DataSymbol):
sym = bv.x_get_symbol_of_type(sym_name, sym_type)
if sym is None or sym.address == 0:
continue
bv.x_make_data_var(sym.address, objc_class_type)
break
def _blocks_plugin_logger(self):
"""
Get this plugin's logger for the view.
Create the logger if it does not exist yet.
Monkey-patching this in to avoid having to pass around
a separate logger with the same lifetime as the view.
"""
logger = getattr(self, '_x_blocks_plugin_logger', None)
if logger is None:
logger = self.create_logger(_LOGGER_NAME)
self._x_blocks_plugin_logger = logger
return logger
binja.BinaryView.x_blocks_plugin_logger = property(_blocks_plugin_logger)
class Layout:
"""
Represents a block literal or byref layout, describing the memory layout of
the imported variables included in the block literal or byref. In the case
of the block literals, these are variables the block closes over (captures).
"""
class Field:
"""
Represents a single field, or series of identical fields.
"""
def __init__(self, name_prefix, field_type, count=1, *, is_byref=False):
self.name_prefix = name_prefix
self.field_type = field_type
self.count = count
self.is_byref = is_byref
@classmethod
def from_generic_helper_info(cls, bv, generic_helper_type, generic_helper_info, generic_helper_info_bytecode):
"""
Always returns a layout instance, which may be empty if there is no
generic helper info available (generic_helper_type ==
BLOCK_GENERIC_HELPER_NONE).
"""
id_type = _parse_objc_type(bv, "id")
fields = []
if generic_helper_type == BLOCK_GENERIC_HELPER_INLINE:
assert generic_helper_info_bytecode is None
assert generic_helper_info is not None
assert isinstance(generic_helper_info, int)
assert (0xFFFFFFFFF00000FF & generic_helper_info) == 0
n_strong_ptrs = (generic_helper_info >> 8) & 0xf
n_block_ptrs = (generic_helper_info >> 12) & 0xf
n_byref_ptrs = (generic_helper_info >> 16) & 0xf
n_weak_ptrs = (generic_helper_info >> 20) & 0xf
if n_strong_ptrs > 0:
fields.append(Layout.Field("strong_ptr_", id_type, n_strong_ptrs))
if n_block_ptrs > 0:
fields.append(Layout.Field("block_ptr_", id_type, n_block_ptrs))
if n_byref_ptrs > 0:
fields.append(Layout.Field("byref_ptr_", id_type, n_byref_ptrs, is_byref=True))
if n_weak_ptrs > 0:
fields.append(Layout.Field("weak_ptr_", id_type, n_weak_ptrs))
elif generic_helper_type == BLOCK_GENERIC_HELPER_OUTOFLINE:
assert generic_helper_info_bytecode is not None
for op in generic_helper_info_bytecode[1:]:
opcode = (op & 0xf0) >> 4
oparg = (op & 0x0f)
if opcode == BCK_DONE:
break
elif opcode == BCK_NON_OBJECT_BYTES:
fields.append(Layout.Field("non_object_", bv.x_parse_type(f"uint8_t [{oparg}]")))
elif opcode == BCK_NON_OBJECT_WORDS:
fields.append(Layout.Field("non_object_", bv.x_parse_type("uint64_t"), oparg))
elif opcode == BCK_STRONG:
fields.append(Layout.Field("strong_ptr_", id_type, oparg))
elif opcode == BCK_BLOCK:
fields.append(Layout.Field("block_ptr_", id_type, oparg))
elif opcode == BCK_BYREF:
fields.append(Layout.Field("byref_ptr_", id_type, oparg, is_byref=True))
elif opcode == BCK_WEAK:
fields.append(Layout.Field("weak_ptr_", id_type, oparg))
else:
bv.x_blocks_plugin_logger.log_warn(f"Unknown out-of-line generic helper op {op:#04x}")
break
return cls(fields)
@classmethod
def from_layout(cls, bv, block_has_extended_layout, layout, layout_bytecode):
"""
Always returns a layout instance, which may be empty if there is no
layout information available (layout is None).
"""
id_type = _parse_objc_type(bv, "id")
fields = []
if layout is not None and block_has_extended_layout and layout != 0:
if layout < 0x1000:
# inline layout encoding
assert layout_bytecode is None
n_strong_ptrs = (layout >> 8) & 0xf
n_byref_ptrs = (layout >> 4) & 0xf
n_weak_ptrs = layout & 0xf
if n_strong_ptrs > 0:
fields.append(Layout.Field("strong_ptr_", id_type, n_strong_ptrs))
if n_byref_ptrs > 0:
fields.append(Layout.Field("byref_ptr_", id_type, n_byref_ptrs, is_byref=True))
if n_weak_ptrs > 0:
fields.append(Layout.Field("weak_ptr_", id_type, n_weak_ptrs))
else:
# out-of-line layout string
assert layout_bytecode is not None
for op in layout_bytecode:
opcode = (op & 0xf0) >> 4
oparg = (op & 0x0f)
if opcode == BLOCK_LAYOUT_ESCAPE:
break
elif opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES:
fields.append(Layout.Field("non_object_", bv.x_parse_type(f"uint8_t [{oparg}]")))
elif opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS:
fields.append(Layout.Field("non_object_", bv.x_parse_type("uint64_t"), oparg))
elif opcode == BLOCK_LAYOUT_STRONG:
fields.append(Layout.Field("strong_ptr_", id_type, oparg))
elif opcode == BLOCK_LAYOUT_BYREF:
fields.append(Layout.Field("byref_ptr_", id_type, oparg, is_byref=True))
elif opcode == BLOCK_LAYOUT_WEAK:
fields.append(Layout.Field("weak_ptr_", id_type, oparg))
elif opcode == BLOCK_LAYOUT_UNRETAINED:
fields.append(Layout.Field("unretained_ptr_", id_type, oparg))
else:
bv.x_blocks_plugin_logger.log_warn(f"Unknown out-of-line extended layout op {op:#04x}")
break
return cls(fields)
def __init__(self, fields):
self._fields = fields
@property
def byref_count(self):
return sum([f.count for f in self._fields if f.is_byref])
@property
def bytes_count(self):
return sum([f.count * f.field_type.width for f in self._fields])
def prefer_over(self, other):
"""
Prefer more byrefs.
If tied then prefer more bytes covered by fields.
"""
if self.byref_count < other.byref_count:
return False
if self.bytes_count < other.bytes_count:
return False
return True
def append_fields(self, struct):
byref_indexes = []
for field in self._fields:
for _ in range(field.count):
if field.is_byref:
byref_indexes.append(len(struct.members))
struct.append_with_offset_suffix(field.field_type, field.name_prefix)
return byref_indexes
class GeneratedStruct:
def __init__(self, bv, builder, name):
self._bv = bv
self.name = name
self.type_id = binja.Type.generate_auto_type_id(_TYPE_ID_SOURCE, self.name)
t = self._bv.get_type_by_name(self.name)
if t is not None:
self._bv.x_blocks_plugin_logger.log_debug(f"GeneratedStruct: Type with {name=} already exists, using existing type")
if self._bv.get_type_id(self.name) != self.type_id:
self._bv.x_blocks_plugin_logger.log_warn(f"GeneratedStruct: Loaded type_id {self._bv.get_type_id(self.name)} differs from computed type_id {self.type_id}")
self.builder = binja.StructureBuilder.create(t.members, packed=t.packed, width=t.width)
else:
self._bv.x_blocks_plugin_logger.log_debug(f"GeneratedStruct: Type with {name=} does not exist, defining new type")
self.builder = builder
bv.define_type(self.type_id, self.name, self.builder)
self.type_name = f"struct {self.name}"
self.type = bv.x_parse_type(self.type_name)
assert self.type is not None
@property
def pointer_to_type(self):
return binja.Type.pointer(self._bv.arch, self.type)
def update_member_type(self, member_name_or_index, new_member_type, if_type=None):
assert member_name_or_index is not None
if isinstance(member_name_or_index, str):
member_name = member_name_or_index
member_index = self.builder.index_by_name(member_name)
assert member_index is not None
elif isinstance(member_name_or_index, int):
member_index = member_name_or_index
member_name = self.builder.members[member_index].name
assert member_name is not None
else:
raise ValueError(f"member_name_or_index argument is of unexpected type {type(member_name_or_index).__name__}")
if if_type is not None:
if str(self.builder.members[member_index].type) != if_type:
return
self.builder.replace(member_index, new_member_type, member_name)
self._bv.define_type(self.type_id, self.name, self.builder)
self.type = self._bv.x_parse_type(self.type_name)
assert self.type is not None
class BlockLiteral:
class NotABlockLiteralError(Exception):
pass
class FailedToFindFieldsError(Exception):
pass
@classmethod
def from_data(cls, bv, bl_data_var, sym_addrs):
"""
Read block literal from data.
"""
is_stack_block = False
br = binja.BinaryReader(bv)
br.seek(bl_data_var.address)
isa = br.read64()
if isa is None:
raise BlockLiteral.NotABlockLiteralError("isa does not exist")
if isa not in sym_addrs:
raise BlockLiteral.NotABlockLiteralError("isa is not __NSConcreteGlobalBlock")
flags = br.read32()
if flags is None:
raise BlockLiteral.NotABlockLiteralError("flags does not exist")
if (flags & BLOCK_IS_GLOBAL) == 0:
raise BlockLiteral.NotABlockLiteralError(f"BLOCK_IS_GLOBAL ({BLOCK_IS_GLOBAL:#010x}) not set in flags")
reserved = br.read32()
if reserved is None:
raise BlockLiteral.NotABlockLiteralError("reserved does not exist")
invoke = br.read64()
if invoke is None:
raise BlockLiteral.NotABlockLiteralError("invoke does not exist")
if invoke == 0:
raise BlockLiteral.NotABlockLiteralError("invoke is NULL")
descriptor = br.read64()
if descriptor is None:
raise BlockLiteral.NotABlockLiteralError("descriptor does not exist")
if descriptor == 0:
raise BlockLiteral.NotABlockLiteralError("descriptor is NULL")
return cls(bv, is_stack_block, bl_data_var, isa, flags, reserved, invoke, descriptor)
@classmethod
def from_stack(cls, bv, bl_insn, bl_var, sym_addrs):
is_stack_block = True
bl_var.type = _parse_libclosure_type(bv, "struct Block_literal")
bl_insn = bv.x_reload_hlil_instruction(bl_insn,
lambda insn: \
isinstance(insn, binja.HighLevelILAssign) and \
isinstance(insn.dest, binja.HighLevelILStructField) and \
isinstance(insn.dest.src, binja.HighLevelILVar) and \
str(insn.dest.src.var.type) == 'struct Block_literal')
stack_var_id = bl_insn.dest.src.var.identifier
for insn in shinobi.yield_struct_field_assign_hlil_instructions_for_var_id(bl_insn.function, stack_var_id):
if insn.dest.member_index == 0:
if isinstance(insn.src, (binja.HighLevelILImport,
binja.HighLevelILConstPtr)) and \
insn.src.constant in sym_addrs:
isa = insn.src.constant
elif insn.dest.member_index == 1:
if isinstance(insn.src, (binja.HighLevelILConst,
binja.HighLevelILConstPtr)):
flags = insn.src.constant
elif insn.dest.member_index == 2:
if isinstance(insn.src, (binja.HighLevelILConst,
binja.HighLevelILConstPtr)):
reserved = insn.src.constant
else:
reserved = None
elif insn.dest.member_index == 3:
if isinstance(insn.src, (binja.HighLevelILConst,
binja.HighLevelILConstPtr)):
invoke = insn.src.constant
elif insn.dest.member_index == 4:
if isinstance(insn.src, (binja.HighLevelILConst,
binja.HighLevelILConstPtr)):
descriptor = insn.src.constant
else:
# We don't know if the members are assigned in-order,
# so we cannot rely on having descriptor and hence
# size available. As a result, do not attempt to pick
# up imported variables here. We'll need another pass
# for that later.
pass
local_vars = locals()
if all([vn in local_vars for vn in ('isa', 'flags', 'reserved', 'invoke', 'descriptor')]):
break
local_vars = locals()
missing_vars = list(filter(lambda vn: vn not in local_vars, ('isa', 'flags', 'reserved', 'invoke', 'descriptor')))
if len(missing_vars) > 0:
raise BlockLiteral.FailedToFindFieldsError(f"{', '.join(missing_vars)}; likely due to complex HLIL")
if invoke == 0:
raise BlockLiteral.NotABlockLiteralError("invoke is NULL")
if descriptor == 0:
raise BlockLiteral.NotABlockLiteralError("descriptor is NULL")
return cls(bv, is_stack_block, bl_insn, isa, flags, reserved, invoke, descriptor)
def __init__(self, bv, is_stack_block, insn_or_data_var, isa, flags, reserved, invoke, descriptor):
self._bv = bv
self.is_stack_block = is_stack_block
if self.is_stack_block:
self.insn = insn_or_data_var
self.data_var = None
self.address = self.insn.address
else:
self.insn = None
self.data_var = insn_or_data_var
self.address = self.data_var.address
self.isa = isa
self.flags = flags
self.reserved = reserved
self.invoke = invoke
self.descriptor = descriptor
assert self.invoke != 0
assert self.descriptor != 0
if self.is_stack_block:
assert (self.flags & BLOCK_IS_GLOBAL) == 0
else:
assert (self.flags & BLOCK_IS_GLOBAL) != 0
def __str__(self):
if self.is_stack_block:
block = f"Stack block"
else:
block = f"Global block"
return f"{block} at {self.address:x} with flags {self.flags:08x} invoke {self.invoke:x} descriptor {self.descriptor:x}"
def _warn(self, msg):
self._bv.x_blocks_plugin_logger.log_warn(f"Block literal at {self.address:x}: {msg}")
def annotate_literal(self, bd):
"""
Annotate the block literal.
"""
if self.is_stack_block:
assert isinstance(self.insn, binja.HighLevelILAssign)
assert isinstance(self.insn.dest, binja.HighLevelILStructField)
assert isinstance(self.insn.dest.src, binja.HighLevelILVar)
stack_var = self.insn.dest.src.var
stack_var_type_name = str(stack_var.type)
if stack_var_type_name.startswith("struct Block_literal_") and stack_var_type_name != bd.block_literal_struct.type_name:
# Stack var has already been annotated for initialization code
# at a different address, likely because multiple branches in
# the function place a block at the same stack address.
# Unfortunately, this seems to be a hypothetical situation
# right now, as Binja does not seem to handle different use of
# the same stack area by different branches gracefully.
self._warn(f"Stack var {stack_var.name} already annotated with type {stack_var_type_name}; may need to split the stack var")
return
if not stack_var.name.startswith("stack_block_"):
stack_var.name = f"stack_block_{stack_var.name}"
stack_var.type = bd.block_literal_struct.type_name
self.insn = self._bv.x_reload_hlil_instruction(self.insn,
lambda insn: \
isinstance(insn, binja.HighLevelILAssign) and \
isinstance(insn.dest, binja.HighLevelILStructField) and \
isinstance(insn.dest.src, binja.HighLevelILVar) and \
str(insn.dest.src.var.type).startswith('struct Block_literal_'))
else:
self.data_var.name = f"global_block_{self.address:x}"
self.data_var.type = bd.block_literal_struct.type_name
def annotate_invoke_function(self, bd):
"""
Annotate the invoke function.
"""
invoke_func = self._bv.get_function_at(self.invoke)
if invoke_func is not None:
# The signature type may be None if there was no signature field on
# the descriptor or if we failed to parse its ObjC type string.
invoke_func_type = bd.signature_type
if invoke_func_type is None and len(invoke_func.parameter_vars) == 0:
# If Binja did not pick up on any parameters, fall back to a vararg
# signature. We're not going to clobber any parameter types.
invoke_func_type = binja.Type.function(binja.Type.void(),
[bd.block_literal_struct.pointer_to_type],
variable_arguments=True)
if invoke_func_type is None:
# Finally fall back to surgically setting return and first argument
# types, leaving the other parameters undisturbed.
invoke_func.return_type = binja.Type.void()
invoke_func.parameter_vars[0].set_name_and_type_async("block", bd.block_literal_struct.pointer_to_type)
self._bv.update_analysis_and_wait()
else:
# Set function type.
# As of Binja 4.2, the setter for Function.type does not
# update_analysis_and_wait(), unlike the Variable.name and
# Variable.type setters that do. Also, the setter for
# Variable.name is not atomic; it will first copy the current
# type, then proceed to set both name and type on the variable.
# As a result, we need to update_analysis_and_wait() manually
# to avoid an easy-to-repro race condition where a subsequent
# assignment to Variable.name while the Function.type
# assignment is still in flight may clobber the type for the
# first parameter with the type it had before assigning the
# function type.
invoke_func.type = invoke_func_type
self._bv.update_analysis_and_wait()
if len(invoke_func.parameter_vars) >= 1:
invoke_func.parameter_vars[0].name = "block"
if invoke_func.name == f"sub_{invoke_func.start:x}":
invoke_func.name = f"sub_{invoke_func.start:x}_block_invoke"
def find_interesting_captures(self, bd):
"""
Find interesting captures of this block literal:
- Captured stack byrefs and their source variables
- Captures of self
"""
byref_captures = []
self_captures = []
if bd.imported_variables_size == 0:
return byref_captures, self_captures
byref_indexes_set = set(bd.byref_indexes)
for insn in shinobi.yield_struct_field_assign_hlil_instructions_for_var_id(self.insn.function, self.insn.dest.src.var.identifier):
if insn.dest.member_index is None:
# No field declared at offset insn.dest.offset. We could try
# to create fields automatically here, but let's leave it to
# the user for now.
continue
if insn.dest.member_index in byref_indexes_set and isinstance(insn.src, binja.HighLevelILAddressOf):
byref_captures.append((insn.dest.member_index, insn.src))
if isinstance(insn.src, binja.HighLevelILVar) and insn.src.var.name == "self":
self_captures.append((insn.dest.member_index, insn.src.var.type))
byref_captures_set = set([t[0] for t in byref_captures])
if len(byref_captures_set) != len(byref_indexes_set):
missing_indexes_set = byref_indexes_set - byref_captures_set
missing_indexes_str = ', '.join([str(idx) for idx in sorted(missing_indexes_set)])
self._warn(f"Failed to find byref capture for struct member indexes {missing_indexes_str}, review manually")
return byref_captures, self_captures
class BlockDescriptor:
class NotABlockDescriptorError(Exception):
pass
def __init__(self, bv, bl):
"""
Read block descriptor from data at bl.descriptor.
"""
assert bl.address is not None and bl.address != 0
assert bl.descriptor is not None and bl.descriptor != 0
assert bl.flags is not None and bl.flags != 0
self._bv = bv
self.address = bl.descriptor
self.block_address = bl.address
self.block_flags = bl.flags
if self.block_has_small_descriptor:
raise NotImplementedError("Block has small descriptor, see https://github.com/droe/binja-blocks/issues/19")
br = binja.BinaryReader(self._bv)
br.seek(self.address)
self.reserved = br.read64()
if self.reserved is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: reserved field does not exist")
# in-descriptor flags
if self.reserved != 0:
# u32 in_descriptor_flags
# u32 reserved
self.in_descriptor_flags = self.reserved & 0xFFFFFFFF
if self.in_descriptor_flags & 0xFFFF0000 != self.block_flags & 0xFFFF0000 & ~BLOCK_SMALL_DESCRIPTOR:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: block flags {self.block_flags:08x} inconsistent with in-descriptor flags {self.in_descriptor_flags:08x}")
else:
# u64 reserved
self.in_descriptor_flags = None
self.size = br.read64()
if self.size is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: size field does not exist")
if self.size < 0x20:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: size too small ({self.size} < 0x20)")
if self.block_has_copy_dispose:
self.copy = br.read64()
if self.copy is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: copy field does not exist")
self.dispose = br.read64()
if self.dispose is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: dispose field does not exist")
else:
self.copy = None
self.dispose = None
if self.block_has_signature:
self.signature = br.read64()
if self.signature is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: signature field does not exist")
if self.block_has_extended_layout or \
(self.generic_helper_type != BLOCK_GENERIC_HELPER_NONE) or \
(not self.block_has_copy_dispose) or \
self.block_is_global:
# Cases handled by reading and marking up a layout field:
# a) Descriptor with extended layout.
# b) Descriptor with generic helper type on in-descriptor flags that implies
# presence of layout field (generic helper from layout, inline, out-of-line).
# c) Descriptor without custom copy/dispose handlers.
# d) Old descriptor format without extended layout, e.g. "old GC layout",
# unsure of semantics, and unsure if relevant for 64-bit archs.
# e) ABI.2010.3.16 as per https://clang.llvm.org/docs/Block-ABI-Apple.html,
# i.e. signature field w/o layout field following, extended layout bit unset;
# unsure if this ever existed outside of spec documents.
# We'd want to handle this case differently if we had a way to recognise it.
self.layout = br.read64()
if self.layout is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: layout field does not exist")
if self.layout >= 0x1000:
# out-of-line layout string
self.layout_bytecode = self._bv.x_get_byte_string_at(self.layout)
if self.layout_bytecode is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: out-of-line layout string does not exist")
else:
# inline layout encoding
self.layout_bytecode = None
else:
# Cases handled by not reading and not marking up a layout field:
# f) Stack blocks without extended layout, without generic helper info,
# with custom copy/dispose handlers. These seem to sometimes get
# emitted without a layout field.
self.layout = None
self.layout_bytecode = None
if self.generic_helper_type in (BLOCK_GENERIC_HELPER_INLINE,
BLOCK_GENERIC_HELPER_OUTOFLINE):
br.seek(self.address - self._bv.arch.address_size)
assert self._bv.arch.address_size == 8
self.generic_helper_info = br.read64()
if self.generic_helper_info is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: generic_helper_info field does not exist")
if self.generic_helper_type == BLOCK_GENERIC_HELPER_OUTOFLINE:
assert self.generic_helper_info != 0
# min_len=1 to include the reserved byte in bytecode even if it's 0.
self.generic_helper_info_bytecode = self._bv.x_get_byte_string_at(self.generic_helper_info, min_len=1)
if self.generic_helper_info_bytecode is None:
raise BlockDescriptor.NotABlockDescriptorError(f"Block descriptor at {self.address:x}: out-of-line generic helper info string does not exist")
else:
self.generic_helper_info_bytecode = None
else:
self.generic_helper_info = None
self.generic_helper_info_bytecode = None
self.block_descriptor_struct = self._generate_block_descriptor_struct()
self.block_literal_struct, self.byref_indexes = self._generate_block_literal_struct()
# propagate struct type to descriptor pointer on block literal
self.block_literal_struct.update_member_type("descriptor", self.block_descriptor_struct.pointer_to_type, if_type="struct Block_descriptor_1*")
# We need the block literal struct before parsing the signature because
# we want to reference it for the block argument.
if self.block_has_signature and self.signature != 0:
self.signature_type = self._parse_signature(self._bv.get_ascii_string_at(self.signature, 0).raw)
else:
self.signature_type = None
# propagate invoke function signature to invoke pointer on block literal
if self.signature_type is not None:
self.block_literal_struct.update_member_type("invoke", binja.Type.pointer(self._bv.arch, self.signature_type), if_type="void (*)(void*, ...)")
def _parse_signature(self, signature_raw):
if signature_raw is None:
return None
def _type_for_ctype(ctype):
if ctype.endswith("!"):
fallback = 'id'
ctype = ctype.replace("!", "*")
elif ctype.endswith("*"):
fallback = 'void *'
else:
fallback = 'void'
try:
return self._bv.x_parse_type(ctype).with_confidence(254)
except SyntaxError:
# XXX if struct or union and we have member type info, create struct or union and retry
return self._bv.x_parse_type(fallback).with_confidence(200)
# This works well for most blocks, but because Binja does not
# seem to support [Apple's variant of] AArch64 calling
# conventions properly when things are passed in v registers or
# on the stack, signatures are sometimes wrong.
try:
ctypes = objctypes.ObjCEncodedTypes(signature_raw).ctypes
assert len(ctypes) > 0
types = list(map(_type_for_ctype, ctypes))
types[1] = self.block_literal_struct.pointer_to_type
return binja.Type.function(types[0], types[1:])
except NotImplementedError as e:
self._bv.x_blocks_plugin_logger.log_error(f"Failed to parse ObjC type encoding {signature_raw!r}: {type(e).__name__}: {e}")
return None
def _generate_block_descriptor_struct(self):
struct = binja.StructureBuilder.create()
if self.reserved == 0:
struct.append(self._bv.x_parse_type("uint64_t"), "reserved")
else:
assert self.in_descriptor_flags is not None
struct.append(_parse_libclosure_type(self._bv, "enum Block_flags"), "in_descriptor_flags")
struct.append(self._bv.x_parse_type("uint32_t"), "reserved")
assert struct.width == 8
struct.append(self._bv.x_parse_type("uint64_t"), "size")
if self.block_has_copy_dispose:
struct.append(_get_libclosure_type(self._bv, "BlockCopyFunction"), "copy")
struct.append(_get_libclosure_type(self._bv, "BlockDisposeFunction"), "dispose")
if self.block_has_signature:
struct.append(self._bv.x_parse_type("char const *"), "signature")
if self.layout is not None:
if self.layout < 0x1000:
# inline layout encoding
struct.append(self._bv.x_parse_type("uint64_t"), "layout")
else:
# out-of-line layout string
struct.append(self._bv.x_parse_type("uint8_t const *"), "layout")
else:
# Skip the layout field, see ctor for rationale.
pass
return GeneratedStruct(self._bv, struct, f"Block_descriptor_{self.address:x}")
def _generate_block_literal_struct(self):
# Packed because block layout bytecode can lead to misaligned words,
# which according to comments in LLVM source code seems intentional.
struct = binja.StructureBuilder.create(packed=True, width=self.size)
struct.append(_parse_objc_type(self._bv, "Class"), "isa")
struct.append(_parse_libclosure_type(self._bv, "enum Block_flags"), "flags")
struct.append(self._bv.x_parse_type("uint32_t"), "reserved")
struct.append(_get_libclosure_type(self._bv, "BlockInvokeFunction"), "invoke")
struct.append(binja.Type.pointer(self._bv.arch, _parse_libclosure_type(self._bv, "struct Block_descriptor_1")), "descriptor") # placeholder
if self.imported_variables_size > 0:
generic_helper_layout = Layout.from_generic_helper_info(self._bv, self.generic_helper_type, self.generic_helper_info, self.generic_helper_info_bytecode)
layout_layout = Layout.from_layout(self._bv, self.block_has_extended_layout, self.layout, self.layout_bytecode)
if generic_helper_layout.prefer_over(layout_layout):
self._bv.x_blocks_plugin_logger.log_debug("Preferring generic helper info over layout")
chosen_layout = generic_helper_layout
else:
self._bv.x_blocks_plugin_logger.log_debug("Preferring layout over generic helper info")
chosen_layout = layout_layout
byref_indexes = chosen_layout.append_fields(struct)
else:
byref_indexes = []
# A block descriptor can be used by 1..n block literals. Block
# literals sharing the same descriptor will have identical layout only
# as far as described in the invoke signature, and only as far as
# relevant to copy/dispose. Annotation with a single struct type
# shared by all block literals with the same descriptor has the benefit
# of blocks being passed around having the same type everywhere.
# However, as soon as one wants to propagate more specific types for
# captures, e.g. `struct Foo *` instead of merely `id`, then a single
# shared struct type works less well. Therefore, using a separate
# struct type for each block literal seems preferable.
#
# We still leave the struct generation in BlockDescriptor, since it is
# largely based on information not available in BlockLiteral without
# access to BlockDescriptor.
return GeneratedStruct(self._bv, struct, f"Block_literal_{self.block_address:x}"), byref_indexes
@property
def imported_variables_size(self):
return self.size - 0x20
@property
def block_has_copy_dispose(self):
return (self.block_flags & BLOCK_HAS_COPY_DISPOSE) != 0
@property
def block_has_signature(self):
return (self.block_flags & BLOCK_HAS_SIGNATURE) != 0
@property
def block_has_extended_layout(self):
return (self.block_flags & BLOCK_HAS_EXTENDED_LAYOUT) != 0
@property
def block_is_global(self):
return (self.block_flags & BLOCK_IS_GLOBAL) != 0
@property
def block_has_small_descriptor(self):
return (self.block_flags & BLOCK_SMALL_DESCRIPTOR) != 0
@property
def generic_helper_type(self):
if self.in_descriptor_flags is None:
return BLOCK_GENERIC_HELPER_NONE
return (self.in_descriptor_flags & BLOCK_GENERIC_HELPER_MASK)
def __str__(self):