-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuprintf.h
More file actions
4551 lines (3951 loc) · 166 KB
/
Copy pathuprintf.h
File metadata and controls
4551 lines (3951 loc) · 166 KB
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
// MIT License
//
// Copyright (c) 2024 Serhii Pievniev
//
// 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.
/*
uprintf v1.2.1
Documentation, examples and issues: https://github.com/spievniev/uprintf
Minimal example:
```
#define UPRINTF_IMPLEMENTATION
#include "uprintf.h"
typedef struct {
int i;
float f;
const char *str;
} S;
int main(void) {
S s = {1, 2.3F, "string"};
uprintf("structure: %S\n", &s);
return 0;
}
```
Building and running:
```
$ gcc -g2 example.c
$ ./a.out
structure: {
int i = 1
float f = 2.300000
const char *str = 0x559467793d83 ("string")
}
```
*/
// ====================== HEADER ==========================
#ifndef UPRINTF_H
#define UPRINTF_H
#ifdef __cplusplus
extern "C" {
#endif
void _upf_uprintf(const char *file, int line, const char *fmt, const char *args, ...);
#ifdef UPRINTF_TEST
extern int _upf_test_status;
#endif
#ifdef __cplusplus
} // extern "C"
#endif
// If variadic arguments are stringified directly, the macros will stringify to
// the macro name instead of being expanded. Passing them to another macro causes
// them to get expanded before stringification.
#define _upf_stringify_va_args(...) #__VA_ARGS__
// The noop instruction is required to prevent tail call optimization
// and keep the return PC within the scope of the caller function.
#define uprintf(fmt, ...) \
do { \
_upf_uprintf(__FILE__, __LINE__, fmt, _upf_stringify_va_args(__VA_ARGS__), __VA_ARGS__); \
__asm__ volatile("nop"); \
} while (0)
#endif // UPRINTF_H
// ================== IMPLEMENTATION ======================
#ifdef UPRINTF_IMPLEMENTATION
// ===================== OPTIONS ==========================
#ifndef UPRINTF_INDENTATION_WIDTH
#define UPRINTF_INDENTATION_WIDTH 4
#endif
#ifndef UPRINTF_MAX_DEPTH
#define UPRINTF_MAX_DEPTH 10
#endif
#ifndef UPRINTF_IGNORE_STRUCTS
#define UPRINTF_IGNORE_STRUCTS "FILE,pthread_mutex_t,pthread_cond_t"
#endif
#ifndef UPRINTF_ARRAY_COMPRESSION_THRESHOLD
#define UPRINTF_ARRAY_COMPRESSION_THRESHOLD 4
#endif
#ifndef UPRINTF_MAX_STRING_LENGTH
#define UPRINTF_MAX_STRING_LENGTH 200
#endif
// ===================== INCLUDES =========================
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <link.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
// ===================== BITNESS ==========================
#if UPRINTF_WORD_SIZE == 32 || UINTPTR_MAX == UINT32_MAX
#define _UPF_64BIT false
#elif UPRINTF_WORD_SIZE == 64 || UINTPTR_MAX == UINT64_MAX
#define _UPF_64BIT true
#else
#error Unknown or invalid word size, it must be 32 or 64 bits, it can be set using `#define UPRINTF_WORD_SIZE`
#endif
// ======================= ELF ============================
// Linker-generated entry to the dynamic section of ELF.
extern ElfW(Dyn) _DYNAMIC[];
#if _UPF_64BIT
#define _UPF_ELFW(x) ELF64_##x
#else
#define _UPF_ELFW(x) ELF32_##x
#endif
#if defined(__x86_64__)
#define _UPF_ELF_GLOB_DAT R_X86_64_GLOB_DAT
#elif defined(__i386__)
#define _UPF_ELF_GLOB_DAT R_386_GLOB_DAT
#elif defined(__aarch64__)
#define _UPF_ELF_GLOB_DAT R_AARCH64_GLOB_DAT
#elif defined(__arm__)
#define _UPF_ELF_GLOB_DAT R_ARM_GLOB_DAT
#elif defined(__riscv)
#define _UPF_ELF_GLOB_DAT R_RISCV_64
#elif defined(__powerpc64__)
#define _UPF_ELF_GLOB_DAT R_PPC64_GLOB_DAT
#elif defined(__powerpc__)
#define _UPF_ELF_GLOB_DAT R_PPC_GLOB_DAT
#elif defined(__s390x__)
#define _UPF_ELF_GLOB_DAT R_390_GLOB_DAT
#elif defined(__mips__)
#define _UPF_ELF_GLOB_DAT R_MIPS_GLOB_DAT
#elif defined(__sparc__)
#define _UPF_ELF_GLOB_DAT R_SPARC_GLOB_DAT
#else
#error "Unsupported architecture"
#endif
// ===================== dwarf.h ==========================
// dwarf.h's location is inconsistent and the package containing it may not be
// installed, so the library includes a partial implementation.
#define DW_UT_compile 0x01
#define DW_TAG_array_type 0x01
#define DW_TAG_class_type 0x02
#define DW_TAG_enumeration_type 0x04
#define DW_TAG_formal_parameter 0x05
#define DW_TAG_imported_declaration 0x08
#define DW_TAG_lexical_block 0x0b
#define DW_TAG_member 0x0d
#define DW_TAG_pointer_type 0x0f
#define DW_TAG_reference_type 0x10
#define DW_TAG_compile_unit 0x11
#define DW_TAG_structure_type 0x13
#define DW_TAG_subroutine_type 0x15
#define DW_TAG_typedef 0x16
#define DW_TAG_union_type 0x17
#define DW_TAG_unspecified_parameters 0x18
#define DW_TAG_inheritance 0x1c
#define DW_TAG_inlined_subroutine 0x1d
#define DW_TAG_ptr_to_member_type 0x1f
#define DW_TAG_subrange_type 0x21
#define DW_TAG_base_type 0x24
#define DW_TAG_const_type 0x26
#define DW_TAG_enumerator 0x28
#define DW_TAG_subprogram 0x2e
#define DW_TAG_variable 0x34
#define DW_TAG_volatile_type 0x35
#define DW_TAG_restrict_type 0x37
#define DW_TAG_namespace 0x39
#define DW_TAG_imported_module 0x3a
#define DW_TAG_rvalue_reference_type 0x42
#define DW_TAG_atomic_type 0x47
#define DW_TAG_call_site 0x48
#define DW_TAG_call_site_parameter 0x49
#define DW_FORM_addr 0x01
#define DW_FORM_block2 0x03
#define DW_FORM_block4 0x04
#define DW_FORM_data2 0x05
#define DW_FORM_data4 0x06
#define DW_FORM_data8 0x07
#define DW_FORM_string 0x08
#define DW_FORM_block 0x09
#define DW_FORM_block1 0x0a
#define DW_FORM_data1 0x0b
#define DW_FORM_flag 0x0c
#define DW_FORM_sdata 0x0d
#define DW_FORM_strp 0x0e
#define DW_FORM_udata 0x0f
#define DW_FORM_ref_addr 0x10
#define DW_FORM_ref1 0x11
#define DW_FORM_ref2 0x12
#define DW_FORM_ref4 0x13
#define DW_FORM_ref8 0x14
#define DW_FORM_ref_udata 0x15
#define DW_FORM_indirect 0x16
#define DW_FORM_sec_offset 0x17
#define DW_FORM_exprloc 0x18
#define DW_FORM_flag_present 0x19
#define DW_FORM_strx 0x1a
#define DW_FORM_addrx 0x1b
#define DW_FORM_ref_sup4 0x1c
#define DW_FORM_strp_sup 0x1d
#define DW_FORM_data16 0x1e
#define DW_FORM_line_strp 0x1f
#define DW_FORM_ref_sig8 0x20
#define DW_FORM_implicit_const 0x21
#define DW_FORM_loclistx 0x22
#define DW_FORM_rnglistx 0x23
#define DW_FORM_ref_sup8 0x24
#define DW_FORM_strx1 0x25
#define DW_FORM_strx2 0x26
#define DW_FORM_strx3 0x27
#define DW_FORM_strx4 0x28
#define DW_FORM_addrx1 0x29
#define DW_FORM_addrx2 0x2a
#define DW_FORM_addrx3 0x2b
#define DW_FORM_addrx4 0x2c
#define DW_AT_name 0x03
#define DW_AT_byte_size 0x0b
#define DW_AT_bit_offset 0x0c
#define DW_AT_bit_size 0x0d
#define DW_AT_low_pc 0x11
#define DW_AT_high_pc 0x12
#define DW_AT_language 0x13
#define DW_AT_import 0x18
#define DW_AT_const_value 0x1c
#define DW_AT_upper_bound 0x2f
#define DW_AT_abstract_origin 0x31
#define DW_AT_count 0x37
#define DW_AT_data_member_location 0x38
#define DW_AT_declaration 0x3c
#define DW_AT_encoding 0x3e
#define DW_AT_external 0x3f
#define DW_AT_specification 0x47
#define DW_AT_type 0x49
#define DW_AT_ranges 0x55
#define DW_AT_data_bit_offset 0x6b
#define DW_AT_linkage_name 0x6e
#define DW_AT_str_offsets_base 0x72
#define DW_AT_addr_base 0x73
#define DW_AT_rnglists_base 0x74
#define DW_AT_export_symbols 0x89
#define DW_ATE_address 0x01
#define DW_ATE_boolean 0x02
#define DW_ATE_complex_float 0x03
#define DW_ATE_float 0x04
#define DW_ATE_signed 0x05
#define DW_ATE_signed_char 0x06
#define DW_ATE_unsigned 0x07
#define DW_ATE_unsigned_char 0x08
#define DW_ATE_imaginary_float 0x09
#define DW_ATE_packed_decimal 0x0a
#define DW_ATE_numeric_string 0x0b
#define DW_ATE_edited 0x0c
#define DW_ATE_signed_fixed 0x0d
#define DW_ATE_unsigned_fixed 0x0e
#define DW_ATE_decimal_float 0x0f
#define DW_ATE_UTF 0x10
#define DW_ATE_UCS 0x11
#define DW_ATE_ASCII 0x12
#define DW_RLE_end_of_list 0x00
#define DW_RLE_base_addressx 0x01
#define DW_RLE_startx_endx 0x02
#define DW_RLE_startx_length 0x03
#define DW_RLE_offset_pair 0x04
#define DW_RLE_base_address 0x05
#define DW_RLE_start_end 0x06
#define DW_RLE_start_length 0x07
#define DW_LANG_C 0x0002
#define DW_LANG_C89 0x0001
#define DW_LANG_C99 0x000c
#define DW_LANG_C11 0x001d
#define DW_LANG_C17 0x002c
#define DW_LANG_C23 0x003e
#define DW_LANG_C_plus_plus 0x0004
#define DW_LANG_C_plus_plus_03 0x0019
#define DW_LANG_C_plus_plus_11 0x001a
#define DW_LANG_C_plus_plus_14 0x0021
#define DW_LANG_C_plus_plus_17 0x002a
#define DW_LANG_C_plus_plus_20 0x002b
#define DW_LANG_C_plus_plus_23 0x003a
// ===================== TESTING ==========================
#ifdef UPRINTF_TEST
#ifdef __cplusplus
extern "C" {
#endif
int _upf_test_status = EXIT_SUCCESS;
#ifdef __cplusplus
} // extern "C"
#endif
#define _UPF_SET_TEST_STATUS(status) _upf_test_status = status
#else // UPRINTF_TEST
#define _UPF_SET_TEST_STATUS(status) (void) status
#endif // UPRINTF_TEST
// ====================== ERRORS ==========================
#define _UPF_LOG(type, ...) \
do { \
fprintf(stderr, "(uprintf) [%s] ", type); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
} while (0)
#define _UPF_WARN(...) \
do { \
_UPF_LOG("WARNING", __VA_ARGS__); \
_UPF_SET_TEST_STATUS(EXIT_FAILURE); \
} while (0)
#define _UPF_ERROR(...) \
do { \
_UPF_LOG("ERROR", __VA_ARGS__); \
_UPF_SET_TEST_STATUS(EXIT_FAILURE); \
longjmp(_upf_state.error_jmp_buf, EXIT_FAILURE); \
} while (0)
#define _UPF_ASSERT(condition) \
do { \
if (!(condition)) _UPF_ERROR("Assert (%s) failed at %s:%d.", #condition, __FILE__, __LINE__); \
} while (0)
#define _UPF_OUT_OF_MEMORY() _UPF_ERROR("Process ran out of memory.")
// ======================= C++ ============================
#ifdef __cplusplus
// clang-format off
#define _UPF_ZERO_INIT {}
// clang-format on
#else
#define _UPF_ZERO_INIT {0}
#endif
#ifdef __cplusplus
namespace uprintf {
#endif
// ====================== TYPES ===========================
#define _UPF_VECTOR_TYPEDEF(name, type) \
typedef struct { \
uint32_t capacity; \
uint32_t length; \
type *data; \
} name
#define _UPF_MAP_TYPEDEF(name, key_t, value_t) \
typedef struct { \
uint32_t capacity; \
uint32_t size; \
struct { \
uint32_t hash; \
key_t key; \
value_t value; \
} *data; \
} name
_UPF_VECTOR_TYPEDEF(_upf_size_t_vec, size_t);
_UPF_VECTOR_TYPEDEF(_upf_cstr_vec, const char *);
typedef struct _upf_memory_region {
struct _upf_memory_region *prev;
size_t capacity;
size_t length;
uint8_t *data;
} _upf_memory_region;
typedef struct {
uint64_t name;
uint64_t form;
int64_t implicit_const;
} _upf_attr;
_UPF_VECTOR_TYPEDEF(_upf_attr_vec, _upf_attr);
typedef struct {
uint64_t tag;
bool has_children;
_upf_attr_vec attrs;
} _upf_abbrev;
_UPF_VECTOR_TYPEDEF(_upf_abbrev_vec, _upf_abbrev);
typedef enum {
_UPF_TK_STRUCT,
_UPF_TK_UNION,
_UPF_TK_ENUM,
_UPF_TK_ARRAY,
_UPF_TK_POINTER,
_UPF_TK_REFERENCE,
_UPF_TK_MEMBER_POINTER,
_UPF_TK_FUNCTION,
_UPF_TK_U1,
_UPF_TK_U2,
_UPF_TK_U4,
_UPF_TK_U8,
_UPF_TK_S1,
_UPF_TK_S2,
_UPF_TK_S4,
_UPF_TK_S8,
_UPF_TK_F4,
_UPF_TK_F8,
_UPF_TK_BOOL,
_UPF_TK_SCHAR,
_UPF_TK_UCHAR,
_UPF_TK_VOID,
_UPF_TK_UNKNOWN
} _upf_type_kind;
typedef struct {
const uint8_t *die;
const char *name;
} _upf_named_type;
_UPF_VECTOR_TYPEDEF(_upf_named_type_vec, _upf_named_type);
typedef struct {
const char *name;
const char *linkage_name;
const uint8_t *return_type_die;
const uint8_t *specification_die;
_upf_named_type_vec args;
bool is_variadic;
bool is_external;
uintptr_t pc;
} _upf_function;
_UPF_VECTOR_TYPEDEF(_upf_function_vec, _upf_function);
typedef struct {
// Number of inheritance levels from where the method originates.
int inheritance;
_upf_function function;
} _upf_method;
_UPF_VECTOR_TYPEDEF(_upf_method_vec, _upf_method);
typedef struct {
const char *name;
int64_t value;
} _upf_enum;
_UPF_VECTOR_TYPEDEF(_upf_enum_vec, _upf_enum);
#define _UPF_MOD_CONST 1 << 0
#define _UPF_MOD_VOLATILE 1 << 1
#define _UPF_MOD_RESTRICT 1 << 2
#define _UPF_MOD_ATOMIC 1 << 3
typedef struct _upf_type _upf_type;
_UPF_VECTOR_TYPEDEF(_upf_type_ptr_vec, struct _upf_type *);
typedef struct {
const char *name;
_upf_type *type;
size_t offset;
// Bit size is not zero only for bit field.
int bit_size;
// Number of inheritance levels from where the member originates.
int inheritance;
} _upf_member;
_UPF_VECTOR_TYPEDEF(_upf_member_vec, _upf_member);
struct _upf_type {
const char *name;
_upf_type_kind kind;
int modifiers;
size_t size;
union {
struct {
bool is_declaration;
_upf_member_vec members;
_upf_method_vec methods;
} cstruct;
struct {
_upf_type *underlying_type;
_upf_enum_vec enums;
} cenum;
struct {
_upf_type *element_type;
_upf_size_t_vec lengths;
} array;
struct {
_upf_type *type;
} pointer;
struct {
_upf_type *type;
bool is_rvalue;
} reference;
struct {
_upf_type *return_type;
_upf_type_ptr_vec arg_types;
bool is_variadic;
// Pointer to a function definition, if type was generated from it.
// NULL if the type is parsed from DWARF.
const _upf_function *function_ptr;
} function;
} as;
};
_UPF_VECTOR_TYPEDEF(_upf_type_vec, _upf_type *);
typedef struct {
uintptr_t start;
uintptr_t end;
} _upf_range;
_UPF_VECTOR_TYPEDEF(_upf_range_vec, _upf_range);
struct _upf_ns;
_UPF_VECTOR_TYPEDEF(_upf_ns_vec, struct _upf_ns *);
_UPF_MAP_TYPEDEF(_upf_name_type_map, const char *, const uint8_t *);
_UPF_MAP_TYPEDEF(_upf_name_function_map, const char *, _upf_function);
_UPF_MAP_TYPEDEF(_upf_name_ns_map, const char *, struct _upf_ns *);
typedef struct _upf_ns {
bool is_visited;
_upf_name_type_map vars;
_upf_name_type_map types;
_upf_name_function_map functions;
_upf_ns_vec imported_nss;
_upf_name_ns_map sub_nss;
} _upf_ns;
typedef struct _upf_ns_node {
_upf_ns *value;
struct _upf_ns_node *prev;
} _upf_ns_node;
typedef struct {
_upf_ns_node *head;
_upf_ns_node *tail;
} _upf_ns_queue;
struct _upf_scope;
_UPF_VECTOR_TYPEDEF(_upf_scope_vec, struct _upf_scope *);
typedef struct _upf_scope {
_upf_range_vec ranges;
_upf_scope_vec scopes;
_upf_name_type_map vars;
_upf_name_type_map types;
_upf_ns_vec nss;
} _upf_scope;
typedef struct {
bool is_cxx;
const uint8_t *base;
uint64_t base_address;
uint64_t addr_base;
uint64_t str_offsets_base;
uint64_t rnglists_base;
_upf_abbrev_vec abbrevs;
_upf_scope scope;
_upf_name_function_map extern_functions;
} _upf_cu;
_UPF_VECTOR_TYPEDEF(_upf_cu_vec, _upf_cu);
typedef struct {
const uint8_t *die;
_upf_ns_vec *nss;
} _upf_ns_import;
_UPF_VECTOR_TYPEDEF(_upf_ns_import_vec, _upf_ns_import);
_UPF_MAP_TYPEDEF(_upf_die_ns_map, const uint8_t *, _upf_ns *);
_UPF_MAP_TYPEDEF(_upf_die_nss_map, const uint8_t *, _upf_ns_vec);
_UPF_MAP_TYPEDEF(_upf_die_scope_map, const uint8_t *, _upf_scope *);
typedef struct {
_upf_cu *cu;
// All namespaces.
_upf_die_ns_map nss;
// Current namespaces.
_upf_ns_vec ns_stack;
// List of namespaces that need to be imported.
_upf_ns_import_vec ns_imports;
// List of declared functions that may be specified later.
_upf_die_nss_map declared_functions;
// List of specified functions that weren't declared yet.
_upf_die_scope_map specified_functions;
} _upf_parsing_info;
typedef enum {
_UPF_TT_UNKNOWN,
_UPF_TT_NUMBER,
_UPF_TT_STRING,
_UPF_TT_IDENTIFIER,
_UPF_TT_STRUCT,
_UPF_TT_ENUM,
_UPF_TT_TYPE_SPECIFIER,
_UPF_TT_TYPE_QUALIFIER,
_UPF_TT_ATOMIC,
_UPF_TT_GENERIC,
_UPF_TT_SIZEOF,
_UPF_TT_ALIGNOF,
_UPF_TT_OPEN_PAREN,
_UPF_TT_CLOSE_PAREN,
_UPF_TT_OPEN_BRACKET,
_UPF_TT_CLOSE_BRACKET,
_UPF_TT_OPEN_BRACE,
_UPF_TT_CLOSE_BRACE,
_UPF_TT_COMMA,
_UPF_TT_DOT,
_UPF_TT_DOT_STAR,
_UPF_TT_ARROW,
_UPF_TT_ARROW_STAR,
_UPF_TT_UNARY,
_UPF_TT_INCREMENT,
_UPF_TT_PLUS,
_UPF_TT_MINUS,
_UPF_TT_STAR,
_UPF_TT_LESS_THAN,
_UPF_TT_GREATER_THAN,
_UPF_TT_LOGICAL,
_UPF_TT_FACTOR,
_UPF_TT_AMPERSAND,
_UPF_TT_DOUBLE_AMPERSAND,
_UPF_TT_QUESTION,
_UPF_TT_COLON,
_UPF_TT_ASSIGNMENT,
_UPF_TT_CXX_CAST,
_UPF_TT_CXX_NEW,
_UPF_TT_CXX_SCOPE,
_UPF_TT_CXX_DECLTYPE,
_UPF_TT_CXX_NOEXCEPT,
_UPF_TT_CXX_TYPEID,
_UPF_TT_COUNT
} _upf_token_type;
typedef struct {
_upf_token_type type;
const char *string;
} _upf_token;
_UPF_VECTOR_TYPEDEF(_upf_token_vec, _upf_token);
// https://en.cppreference.com/w/c/language/operator_precedence.html
typedef enum {
_UPF_PREC_NONE = 0,
_UPF_PREC_ASSIGNMENT,
_UPF_PREC_TERNARY,
_UPF_PREC_LOGICAL,
_UPF_PREC_TERM,
_UPF_PREC_FACTOR,
_UPF_PREC_UNARY,
_UPF_PREC_POSTFIX
} _upf_parse_precedence;
typedef struct {
_upf_type *(*prefix)(void);
_upf_type *(*infix)(_upf_type *);
_upf_parse_precedence precedence;
} _upf_parse_rule;
typedef struct {
const void *data;
// Hashing `type` as pointer works because it is unique thanks to caching.
const _upf_type *type;
} _upf_struct_key;
typedef struct {
// Set if struct appears more than once.
bool is_repeating;
// Set if struct was printed.
bool is_visited;
// Set if struct was printed to reference later.
uint32_t id;
} _upf_struct_info;
_UPF_MAP_TYPEDEF(_upf_struct_info_map, _upf_struct_key, _upf_struct_info);
_UPF_MAP_TYPEDEF(_upf_pc_cstr_map, uintptr_t, const char *);
_UPF_MAP_TYPEDEF(_upf_die_type_map, const uint8_t *, _upf_type *);
// =================== GLOBAL STATE =======================
struct _upf_state {
_upf_memory_region *allocator;
_upf_cstr_vec ignored_structs;
bool is_init;
// Temporary global variable because expression cannot have the declaration.
uint32_t map_index;
// File loaded by dynamic linker (without debug info).
const uint8_t *base;
// mmap-ed file with debug info.
uint8_t *elf_file;
off_t elf_file_size;
// DWARF info
uint8_t offset_size;
uint8_t address_size;
// DWARF sections
const uint8_t *die;
size_t die_size;
const uint8_t *abbrev;
const char *str;
const char *line_str;
const uint8_t *str_offsets;
const uint8_t *addr;
const uint8_t *rnglists;
// parsed DWARF info
_upf_die_type_map type_map;
_upf_cu_vec cus;
_upf_pc_cstr_map extern_functions;
// sequential id for enumerating repeating structs
int struct_id;
// valid memory regions
_upf_range_vec addresses;
// bprintf
char *buffer;
char *ptr;
uint32_t size;
uint32_t free;
// error handling
jmp_buf error_jmp_buf;
const char *file_path;
int line;
// tokenizer
_upf_token_vec tokens;
uint32_t tokens_idx;
// parser
_upf_cu *current_cu;
_upf_scope_vec current_scopes;
};
static struct _upf_state _upf_state = _UPF_ZERO_INIT;
// ==================== ALLOCATOR =========================
#define _UPF_INITIAL_REGION_SIZE 65535 // 64kb
static _upf_memory_region *_upf_allocator_new_region(size_t capacity, _upf_memory_region *prev) {
_upf_memory_region *region = (_upf_memory_region *) malloc(sizeof(*region) + capacity * sizeof(*region->data));
if (region == NULL) _UPF_OUT_OF_MEMORY();
region->capacity = capacity;
region->length = 0;
region->prev = prev;
region->data = (uint8_t *) region + sizeof(*region);
return region;
}
static void *_upf_alloc(size_t size) {
if (_upf_state.allocator == NULL) {
size_t capacity = _UPF_INITIAL_REGION_SIZE;
if (size > capacity) capacity = size;
_upf_state.allocator = _upf_allocator_new_region(capacity, NULL);
}
// Align to pointer size.
int alignment = _upf_state.allocator->length % sizeof(void *);
if (alignment > 0) alignment = sizeof(void *) - alignment;
if (alignment + size > _upf_state.allocator->capacity - _upf_state.allocator->length) {
size_t new_capacity = _upf_state.allocator->capacity * 2;
if (size > new_capacity) new_capacity = size;
_upf_state.allocator = _upf_allocator_new_region(new_capacity, _upf_state.allocator);
alignment = 0;
}
void *memory = _upf_state.allocator->data + _upf_state.allocator->length + alignment;
_upf_state.allocator->length += alignment + size;
return memory;
}
static void _upf_free_allocator(void) {
_upf_memory_region *current = _upf_state.allocator;
while (current != NULL) {
_upf_memory_region *prev = current->prev;
free(current);
current = prev;
}
}
static char *_upf_new_string(const char *begin, const char *end) {
_UPF_ASSERT(begin != NULL && end != NULL && end >= begin);
size_t len = end - begin;
char *string = (char *) _upf_alloc(len + 1);
memcpy(string, begin, len);
string[len] = '\0';
return string;
}
static char *_upf_copy_string(const char *str) { return _upf_new_string(str, str + strlen(str)); }
// ====================== VECTOR ==========================
#define _UPF_INITIAL_VECTOR_CAPACITY 4
#ifdef __cplusplus
#define _UPF_VOID_CAST(T) (decltype(T))
#else
#define _UPF_VOID_CAST(T)
#endif
#define _UPF_VECTOR_PUSH(vec, element) \
do { \
if ((vec)->capacity == 0) { \
(vec)->capacity = _UPF_INITIAL_VECTOR_CAPACITY; \
uint32_t size = (vec)->capacity * sizeof(*(vec)->data); \
(vec)->data = _UPF_VOID_CAST((vec)->data) _upf_alloc(size); \
} else if ((vec)->capacity == (vec)->length) { \
uint32_t old_size = (vec)->capacity * sizeof(*(vec)->data); \
(vec)->capacity *= 2; \
void *new_data = _upf_alloc(old_size * 2); \
memcpy(new_data, (vec)->data, old_size); \
(vec)->data = _UPF_VOID_CAST((vec)->data) new_data; \
} \
(vec)->data[(vec)->length++] = element; \
} while (0)
#define _UPF_VECTOR_TOP(vec) (vec)->data[(vec)->length - 1]
// ===================== HASHMAP ==========================
#define _UPF_INITIAL_MAP_CAPACITY 6
#define _UPF_MAP_LOAD_FACTOR 0.75F
#define _UPF_OFFSET_OF(container_ptr, member_name) ((size_t) &((container_ptr)->member_name) - (size_t) (container_ptr))
// FNV-1a
static uint32_t _upf_hash(const void *data, size_t size) {
const uint8_t *bytes = (const uint8_t *) data;
uint32_t hash = 0x811c9dc5;
for (size_t i = 0; i < size; i++) {
hash ^= bytes[i];
hash *= 0x01000193;
}
return hash;
}
static void _upf_map_impl_init(uint8_t **data, uint32_t *capacity, size_t entry_size) {
if (*capacity > 0) return;
*capacity = _UPF_INITIAL_MAP_CAPACITY;
size_t size = *capacity * entry_size;
*data = (uint8_t *) _upf_alloc(size);
memset(*data, 0, size);
}
static uint32_t _upf_map_impl_hash_key(void *key, bool is_key_str, size_t key_size) {
uint32_t hash;
if (is_key_str) {
const char *str = *((const char **) key);
hash = _upf_hash(str, strlen(str));
} else {
hash = _upf_hash(key, key_size);
}
// Hash value 0 is reserved to mark unused entries.
if (hash == 0) hash++;
return hash;
}
static bool _upf_map_impl_keys_equal(const void *a, const void *b, bool is_key_str, uint32_t n) {
if (!is_key_str) return memcmp(a, b, n) == 0;
return strcmp(*((const char **) a), *((const char **) b)) == 0;
}
#define _UPF_MAP_GET_ENTRY(data, index, entry_size) (&(data)[(index) * (entry_size)])
#define _UPF_MAP_GET_HASH(data, index, entry_size) (*((uint32_t *) _UPF_MAP_GET_ENTRY(data, index, entry_size)))
// Find an element by the key, return whether it exists and write index to `result`.
static bool _upf_map_impl_find(
const uint8_t *data,
uint32_t capacity,
size_t entry_size,
void *key,
bool is_key_str,
size_t key_size,
size_t key_offset,
uint32_t *result
) {
if (capacity == 0) return false;
uint32_t index = _upf_map_impl_hash_key(key, is_key_str, key_size) % capacity;
while (_UPF_MAP_GET_HASH(data, index, entry_size) > 0) {
const uint8_t *current_key = &_UPF_MAP_GET_ENTRY(data, index, entry_size)[key_offset];
if (_upf_map_impl_keys_equal(key, current_key, is_key_str, key_size)) {
*result = index;
return true;
}
index = (index + 1) % capacity;
}
*result = index;
return false;
}
static void _upf_map_impl_set(
uint8_t **data,
uint32_t *size,
uint32_t *capacity,
size_t entry_size,
void *key,
bool is_key_str,
size_t key_size,
size_t key_offset,
void *value,
size_t value_size,
size_t value_offset
) {
_UPF_ASSERT(data != NULL && size != NULL && capacity != NULL && key != NULL && value != NULL);
if (*size >= *capacity * _UPF_MAP_LOAD_FACTOR) {
uint32_t new_capacity = *capacity * 2;
size_t size = new_capacity * entry_size;
uint8_t *new_data = (uint8_t *) _upf_alloc(size);
memset(new_data, 0, size);
// Rehash all the elements.
for (uint32_t i = 0; i < *capacity; i++) {
uint32_t hash = _UPF_MAP_GET_HASH(*data, i, entry_size);
if (hash == 0) continue;
uint32_t new_index = hash % new_capacity;
while (_UPF_MAP_GET_HASH(new_data, new_index, entry_size) > 0) new_index = (new_index + 1) % new_capacity;
memcpy(_UPF_MAP_GET_ENTRY(new_data, new_index, entry_size), _UPF_MAP_GET_ENTRY(*data, i, entry_size), entry_size);
}
*data = new_data;
*capacity = new_capacity;
}
uint32_t index;
bool exists = _upf_map_impl_find(*data, *capacity, entry_size, key, is_key_str, key_size, key_offset, &index);
if (!exists) *size = *size + 1;
uint8_t *new_entry = _UPF_MAP_GET_ENTRY(*data, index, entry_size);
uint32_t hash = _upf_map_impl_hash_key(key, is_key_str, key_size);
memcpy(new_entry, &hash, sizeof(hash));
memcpy(&new_entry[key_offset], key, key_size);
memcpy(&new_entry[value_offset], value, value_size);
}
#undef _UPF_MAP_GET_ENTRY
#undef _UPF_MAP_GET_HASH