summaryrefslogtreecommitdiff
path: root/bxgen.c
blob: 1514508f7699cdb8f43031415105fbdfddca038b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
#if 0
SRC=${0##*/}
BIN=${SRC%.*}
gcc                                                   \
  -Wno-old-style-declaration                          \
  -Wno-missing-field-initializers -Wno-missing-braces \
  -Wall -Wextra -Werror -pedantic                     \
  -O0 -fsanitize=undefined,address,leak -mshstk       \
  -o $BIN.tmp $SRC &&                                 \
  ./$BIN.tmp $@ && rm $BIN.tmp
exit $?
#endif

//  ================================================================
//
//    bxgen.c
//    Binary executable code generation - compiler backend
//
//  Qualities
//
//  - Single source file (for now)
//  - Simple and flexible API
//  - No external dependencies
//  - No configuration required
//  - No dynamic memory management
//  - Easy cross-compilation
//  - Platform-independent host
//
//  Inspirations
//
//  - Cuik    https://github.com/RealNeGate/Cuik
//  - tinycc  https://repo.or.cz/w/tinycc.git
//  - QBE     https://c9x.me/compile/
//
//  To-Do list
//
//  - ELF + x86_64 executable
//  - x86_64 object file
//  - Linking libraries
//  - String table for names and arrays
//  - Proper error handling
//  - Proper prefixes for identifiers
//  - Effective entity allocation
//  - Implicit procedure prototypes
//  - Implicit exit after ret from entry point
//  - Static single-assignment
//  - Sea of Nodes
//  - Optimization layers
//  - Multithreading
//  - Memory reallocation when necessary
//  - JIT
//  - COFF, PE, OMF, Mach-O
//  - i386, RISC-V, ARM, WebAssembly
//  - Built-in standard library
//
//  Bugs
//
//  - ...
//
//  Done features
//
//  - ELF header
//  - IO static dispatch
//
//  ================================================================
//
//    Compilation options
//
//  ================================================================

//#define DISABLE_IMPLEMENTATION
//#define DISABLE_HELPERS
//#define DISABLE_TESTING

//  ================================================================
//
//    Basic declarations
//
//  ================================================================

typedef signed char        i8;
typedef signed short       i16;
typedef signed int         i32;
typedef signed long long   i64;
typedef unsigned char      u8;
typedef unsigned short     u16;
typedef unsigned int       u32;
typedef unsigned long long u64;
typedef float              f32;
typedef double             f64;
typedef signed char        b8;  // 8-bit boolean
typedef int                b32; // 32-bit boolean
typedef int                s32; // 32-bit status code
typedef char               c8;  // 8-bit character

//  ================================================================
//
//    IR data declarations
//
//  ================================================================

enum {
  //  For indices
  UNDEFINED = -1,

  //  Formats
  //

  FORMAT_ELF  = 1,
  FORMAT_COFF,
  FORMAT_PE,
  FORMAT_OMF,
  FORMAT_MATCH_O,

  //  Architecture
  //

  ARCH_RISC_V = 64,
  ARCH_I386,
  ARCH_X86_64,
  ARCH_ARM,

  //  Sea of Nodes flow type
  //

  FLOW_DATA = 0,
  FLOW_CONTROL,

  //  Semantic node operations
  //

  DATA_I64 = 0,
  CTRL_CALL,
  CTRL_RET,

  //  Calling conventions

  CONV_CDECL = 0,
  CONV_STDCALL,
  CONV_FASTCALL,
  CONV_THISCALL,

  //  Primitive data types
  //

  TYPE_I32 = 0,

  //  Unit types
  //

  UNIT_CODE = 0,
  UNIT_LIBRARY_OBJECT,
  UNIT_LIBRARY_STATIC,
  UNIT_LIBRARY_DYNAMIC,

  //  Entity types
  //

  ENTITY_NODE = 0,
  ENTITY_PROC,
  ENTITY_UNIT,

  //  Limits
  //

  MAX_LITERAL_SIZE = 400,
  MAX_NAME_SIZE    = 80,
  MAX_PROC_COUNT   = 40,
  MAX_NODE_COUNT   = 60,
  MAX_LINK_COUNT   = 20,
  MAX_ARG_COUNT    = 20,
  MAX_ENTITY_COUNT = 16384,

  //  IO dispatch operations
  //

  IO_OPEN_READ = 0,
  IO_OPEN_WRITE,
  IO_CLOSE,
  IO_SEEK,
  IO_READ,
  IO_WRITE,
  IO_CHMOD_EXE,

  IO_SEEK_CURSOR = 0,
  IO_SEEK_BEGIN,
  IO_SEEK_END,
};

typedef struct {
  i16 size;
  i16 type;
  i64 node;
} Var;

typedef struct {
  i16 val_count;
  Var vals[MAX_ARG_COUNT];
} Ret;

typedef struct {
  //    NOTE
  //    We may call a local procedure by it's id,
  //    or a global procedure by name.

  i16 convention; // can be implicitly retrieved from the procedure
  i64 target_proc;
  i64 target_name_size;
  c8  target_name[MAX_NAME_SIZE]; // TODO use string table
  i64 arg_count;
  Var args[MAX_ARG_COUNT];
} Call;

//  A semantic node is an operation with optional data
//  and possible references to other nodes.

typedef struct {
  i16 op;
  i64 index_in_proc;
  union {
    u8   lit_bytes[MAX_LITERAL_SIZE]; // byte array literal
    i64  lit_int;                     // integer literal
    Ret  ret;
    Call call;
  };
} Node;

//  A procedure is a collection of semantic nodes
//  and has a string name.

typedef struct {
  i16 convention;
  i64 name_size;
  c8  name[MAX_NAME_SIZE]; // TODO use string table
  i64 node_count;
  i64 nodes[MAX_NODE_COUNT];
  i64 ret_index;
  i64 unit;
  i64 index_in_unit;
} Proc;

//  A compilation unit is a collection of procedures.
//

typedef struct {
  i16 type;
  i64 entry_point_index;
  i64 name_size;
  c8  name[MAX_NAME_SIZE]; // TODO use string table
  i64 proc_count;
  i64 procs[MAX_PROC_COUNT];
  i64 link_count;
  i64 links[MAX_LINK_COUNT];
} Unit;

//  An entity can be any of:
//  - `Node`
//  - `Proc`
//  - `Unit`
//
//  Every entity can be referenced by it's unique index
//  in the entity pool.

typedef struct {
  b8  is_enabled;
  i16 type;
  union {
    Node node;
    Proc proc;
    Unit unit;
  };
} Entity;

//  Pool, a collection of all entities.
//
//    NOTE
//    We use one single large memory block for *everything*.

typedef struct {
  i64     entity_count;
  i64     capacity;
  Entity *entities;
} Pool;

//  ================================================================
//
//    API declarations
//
//  ================================================================

#ifdef __cplusplus
extern "C" {
#endif

i64  pool_add(Pool *pool, Entity data);
void pool_remove(Pool *pool, i64 entity, i16 type);

i64  node_init(Pool *pool, Node data);
void node_destroy(Pool *pool, i64 node);
i64  node_data_i64(Pool *pool, i64 value);
i64  node_ctrl_call(Pool *pool, i16 convention, i64 target_proc, i64 arg_count, Var *args);
i64  node_ctrl_call_by_name(Pool *pool, i16 convention, i64 name_size, c8 *name, i64 arg_count, Var *args);
i64  node_ctrl_ret(Pool *pool, i64 value_count, Var *values);

i64  proc_init(Pool *pool);
void proc_destroy(Pool *pool, i64 proc);
void proc_set_convention(Pool *pool, i64 proc, i16 convention);
void proc_set_name(Pool *pool, i64 proc, i64 name_size, c8 *name);
void proc_node_add(Pool *pool, i64 proc, i64 node);
void proc_node_remove(Pool *pool, i64 proc, i64 node);

i64  unit_init(Pool *pool, i16 type);
void unit_destroy(Pool *pool, i64 unit);
void unit_proc_add(Pool *pool, i64 unit, i64 proc);
void unit_proc_remove(Pool *pool, i64 unit, i64 proc);
void unit_link_add(Pool *pool, i64 unit, i64 link_unit);
void unit_link_remove(Pool *pool, i64 unit, i64 link_unit);
void unit_set_name(Pool *pool, i64 unit, i64 name_size, c8 *name);
void unit_set_entry_point(Pool *pool, i64 unit, i64 entry_point_proc);
void unit_write(Pool *pool, i64 unit, u16 target, i64 io_id, void *io_user_data);

i64  io_open_read(i64 name_size, c8 *name, void *user_data);
i64  io_open_write(i64 name_size, c8 *name, void *user_data);
void io_close(i64 f, void *user_data);
b8   io_seek(i64 f, i64 offset, u16 origin, void *user_data);
i64  io_read(i64 f, i64 size, void *data, void *user_data);
i64  io_write(i64 f, i64 size, void *data, void *user_data);
void io_chmod_exe(i64 f, void *user_data);

void bx_assert(b8 condition, c8 const *message, u32 line, c8 const *file);
void io_dispatch(i16 op, i64 *id, i64 *size, void *data, void *user_data);

#ifndef DISABLE_HELPERS
i64  n_i64(i64 value);
i64  n_call(i16 convention, i64 target_proc, i64 arg_count, Var *args);
i64  n_call_by_name(i16 convention, c8 *name, i64 arg_count, Var *args);
i64  n_ret(i64 val_count, Var *vals);
i64  p_new(c8 *name);
void p_add(i64 proc, i64 node);
i64  u_new();
void u_add(i64 unit, i64 proc);
void u_entry_point(i64 unit, i64 proc);
void u_elf_x86_64(i64 unit, c8 *output_file_name);
void l_code(i64 unit, i64 link_unit);
void l_object(i64 unit, c8 *object_library);
void l_static(i64 unit, c8 *static_library);
#endif

#ifdef __cplusplus
}
#endif

//  ================================================================
//
//    Main features implementation
//
//  ================================================================

#ifndef DISABLE_IMPLEMENTATION

#ifdef __cplusplus
#error Implementation code should be compiled with a C compiler!
#endif

//  Utils
//

#ifndef NULL
#define NULL ((void *) 0)
#endif

#define BX_ASSERT(condition) \
  bx_assert((condition), #condition, __LINE__, __FILE__)

static void bx_memcpy(void *dst, void const *src, i64 size) {
  BX_ASSERT(dst != NULL);
  BX_ASSERT(src != NULL);
  BX_ASSERT(size > 0);

  for (i64 i = 0; i < size; ++i)
    ((u8 *)dst)[i] = ((u8 const *)src)[i];
}

static b8 bx_str_eq(c8 const *a, c8 const *b) {
  BX_ASSERT(a != NULL);
  BX_ASSERT(b != NULL);

  while (*a == *b && *a != '\0' && *b != '\0') {
    ++a;
    ++b;
  }

  return *a == '\0' && *b == '\0';
}

static c8 *bx_find_char(c8 *s, c8 c) {
  BX_ASSERT(s != NULL);

  while (*s != '\0' && *s != c)
    ++s;

  return *s == c ? s : NULL;
}

//  IR building procs
//

i64 pool_add(Pool *pool, Entity data) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entity_count < pool->capacity);

  i64 id             = pool->entity_count++;
  data.is_enabled    = 1,
  pool->entities[id] = data;

  return id;
}

void pool_remove(Pool *pool, i64 entity, i16 type) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[entity].is_enabled);
  BX_ASSERT(pool->entities[entity].type == type);

  pool->entities[entity].is_enabled = 1;
}

i64 node_init(Pool *pool, Node data) {
  data.index_in_proc = UNDEFINED;

  return pool_add(pool, (Entity) {
    .type = ENTITY_NODE,
    .node = data,
  });
}

void node_destroy(Pool *pool, i64 node) {
  pool_remove(pool, node, ENTITY_NODE);
}

i64 node_data_i64(Pool *pool, i64 value) {
  return node_init(pool, (Node) {
    .op      = DATA_I64,
    .lit_int = value,
  });
}

i64 node_ctrl_call(Pool *pool, i16 convention, i64 target_proc, i64 arg_count, Var *args) {
  BX_ASSERT(arg_count <= MAX_ARG_COUNT);

  Call call = {
    .convention  = convention,
    .target_proc = target_proc,
    .arg_count   = arg_count,
  };

  if (arg_count > 0)
    bx_memcpy(call.args, args, arg_count * sizeof *args);

  return node_init(pool, (Node) {
    .op   = CTRL_CALL,
    .call = call,
  });
}

i64 node_ctrl_call_by_name(Pool *pool, i16 convention, i64 name_size, c8 *name, i64 arg_count, Var *args) {
  BX_ASSERT(arg_count <= MAX_ARG_COUNT);

  Call call = {
    .convention       = convention,
    .target_name_size = name_size,
    .arg_count        = arg_count,
  };

  if (name_size > 0)
    bx_memcpy(call.target_name, name, name_size);
  if (arg_count > 0)
    bx_memcpy(call.args, args, arg_count * sizeof *args);

  return node_init(pool, (Node) {
    .op   = CTRL_CALL,
    .call = call,
  });
}

i64 node_ctrl_ret(Pool *pool, i64 value_count, Var *values) {
  BX_ASSERT(value_count <= MAX_ARG_COUNT);

  Ret ret = { .val_count = value_count, };

  if (value_count > 0)
    bx_memcpy(ret.vals, values, value_count * sizeof *values);

  return node_init(pool, (Node) {
    .op  = CTRL_RET,
    .ret = ret,
  });
}

i64 proc_init(Pool *pool) {
  return pool_add(pool, (Entity) {
    .type = ENTITY_PROC,
    .proc = (Proc) {
      .ret_index     = UNDEFINED,
      .index_in_unit = UNDEFINED,
    },
  });
}

void proc_destroy(Pool *pool, i64 proc) {
  pool_remove(pool, proc, ENTITY_PROC);
}

void proc_set_convention(Pool *pool, i64 proc, i16 convention) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[proc].is_enabled);
  BX_ASSERT(pool->entities[proc].type == ENTITY_PROC);

  pool->entities[proc].proc.convention = convention;
}

void proc_set_name(Pool *pool, i64 proc, i64 name_size, c8 *name) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[proc].is_enabled);
  BX_ASSERT(pool->entities[proc].type == ENTITY_PROC);

  BX_ASSERT(name_size <= MAX_NAME_SIZE);
  BX_ASSERT(name_size >= 0);

  Proc *p    = &pool->entities[proc].proc;
  p->name_size = name_size;

  if (name_size > 0)
    bx_memcpy(p->name, name, name_size);
}

void proc_node_add(Pool *pool, i64 proc, i64 node) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[proc].is_enabled);
  BX_ASSERT(pool->entities[proc].type == ENTITY_PROC);
  BX_ASSERT(pool->entities[node].is_enabled);
  BX_ASSERT(pool->entities[node].type == ENTITY_NODE);

  Proc *p = &pool->entities[proc].proc;
  Node *n = &pool->entities[node].node;

  BX_ASSERT(n->index_in_proc == UNDEFINED);

  i64 index = p->node_count;

  if (n->op == CTRL_RET)
  {
    //  Only one return node is allowed.
    //

    BX_ASSERT(p->ret_index == UNDEFINED);
    p->ret_index = index;
  }

  BX_ASSERT(index < MAX_NODE_COUNT);

  n->index_in_proc = index;
  p->nodes[index]  = node;
  ++p->node_count;
}

void proc_node_remove(Pool *pool, i64 proc, i64 node) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[proc].is_enabled);
  BX_ASSERT(pool->entities[proc].type == ENTITY_PROC);
  BX_ASSERT(pool->entities[node].type == ENTITY_NODE);

  Proc *p = &pool->entities[proc].proc;
  Node *n = &pool->entities[node].node;

  BX_ASSERT(n->index_in_proc != UNDEFINED);
  BX_ASSERT(p->nodes[n->index_in_proc] == node);

  if (n->op == CTRL_RET) {
    BX_ASSERT(p->ret_index != UNDEFINED);
    p->ret_index = UNDEFINED;
  }

  p->nodes[n->index_in_proc] = UNDEFINED;
  n->index_in_proc           = UNDEFINED;
}

i64 unit_init(Pool *pool, i16 type) {
  return pool_add(pool, (Entity) {
    .type = ENTITY_UNIT,
    .unit = (Unit) {
      .type              = type,
      .entry_point_index = UNDEFINED,
    }
  });
}

void unit_destroy(Pool *pool, i64 unit) {
  pool_remove(pool, unit, ENTITY_UNIT);
}

void unit_proc_add(Pool *pool, i64 unit, i64 proc) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[unit].is_enabled);
  BX_ASSERT(pool->entities[unit].type == ENTITY_UNIT);
  BX_ASSERT(pool->entities[proc].is_enabled);
  BX_ASSERT(pool->entities[proc].type == ENTITY_PROC);

  Unit *u = &pool->entities[unit].unit;
  Proc *p = &pool->entities[proc].proc;

  BX_ASSERT(p->index_in_unit == UNDEFINED);

  i64 index = u->proc_count;

  BX_ASSERT(index < MAX_PROC_COUNT);

  p->index_in_unit = index;
  u->procs[index]  = proc;
  ++u->proc_count;
}

void unit_proc_remove(Pool *pool, i64 unit, i64 proc) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[unit].is_enabled);
  BX_ASSERT(pool->entities[unit].type == ENTITY_UNIT);
  BX_ASSERT(pool->entities[proc].type == ENTITY_PROC);

  Unit *u = &pool->entities[unit].unit;
  Proc *p = &pool->entities[proc].proc;

  BX_ASSERT(p->index_in_unit != UNDEFINED);
  BX_ASSERT(u->procs[p->index_in_unit] == proc);

  if (u->entry_point_index == p->index_in_unit)
    u->entry_point_index = UNDEFINED;

  u->procs[p->index_in_unit] = UNDEFINED;
  p->index_in_unit           = UNDEFINED;
}

void unit_link_add(Pool *pool, i64 unit, i64 link_unit) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[unit].is_enabled);
  BX_ASSERT(pool->entities[unit].type == ENTITY_UNIT);
  BX_ASSERT(pool->entities[link_unit].is_enabled);
  BX_ASSERT(pool->entities[link_unit].type == ENTITY_UNIT);

  Unit *u = &pool->entities[unit].unit;

  for (i64 i = 0; i < u->link_count; ++i)
    if (u->links[i] == link_unit)
      return;

  BX_ASSERT(u->link_count < MAX_LINK_COUNT);
  u->links[u->link_count++] = link_unit;
}

void unit_link_remove(Pool *pool, i64 unit, i64 link_unit) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[unit].is_enabled);
  BX_ASSERT(pool->entities[unit].type == ENTITY_UNIT);
  BX_ASSERT(pool->entities[link_unit].type == ENTITY_UNIT);

  Unit *u = &pool->entities[unit].unit;

  for (i64 i = 0; i < u->link_count; ++i)
    if (u->links[i] == link_unit) {
      u->links[i] = UNDEFINED;
      return;
    }

  BX_ASSERT(0);
}

void unit_set_name(Pool *pool, i64 unit, i64 name_size, c8 *name) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[unit].is_enabled);
  BX_ASSERT(pool->entities[unit].type == ENTITY_UNIT);

  BX_ASSERT(name_size <= MAX_NAME_SIZE);
  BX_ASSERT(name_size >= 0);

  Unit *u    = &pool->entities[unit].unit;
  u->name_size = name_size;

  if (name_size > 0)
    bx_memcpy(u->name, name, name_size);
}

void unit_set_entry_point(Pool *pool, i64 unit, i64 entry_point_proc) {
  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[unit].is_enabled);
  BX_ASSERT(pool->entities[unit].type == ENTITY_UNIT);

  Unit *u = &pool->entities[unit].unit;

  if (entry_point_proc == UNDEFINED) {
    u->entry_point_index = UNDEFINED;
    return;
  }

  BX_ASSERT(pool->entities[entry_point_proc].is_enabled);
  BX_ASSERT(pool->entities[entry_point_proc].type == ENTITY_PROC);

  Proc *p = &pool->entities[entry_point_proc].proc;

  BX_ASSERT(p->index_in_unit != UNDEFINED);
  BX_ASSERT(u->procs[p->index_in_unit] == entry_point_proc);

  pool->entities[unit].unit.entry_point_index = p->index_in_unit;
}

//  Code generation proc
//

#include <stdio.h>  // TEMP
#include <stdlib.h> // TEMP

enum {
  MAX_SECTION_SIZE   = 1024 * 1024 * 10,
  MAX_INPUT_SIZE     = 1024 * 1024 * 100,
  MAX_RELOCATIONS    = 1024 * 10,
  MAX_INPUT_SECTIONS = 1024 * 10,
};

typedef struct {
  i64 memory_address;
  i64 file_offset;
  i64 size;
  u8  bytes[MAX_SECTION_SIZE];
} Section;

typedef struct {
  i64 src_section;
  i64 src_file_offset;
  i64 src_size;
  i64 dst_section;
  i64 dst_memory_address;
} Relocation;

typedef struct {
  i64 object_index;
  i64 section_index;
  i64 file_offset;
  i64 size;
} Input_Section_Info;

typedef struct {
  Section            exec;
  Section            read_only;
  Section            read_write;
  Section            zero_init;
  i64                relocs_size;
  Relocation         relocs[MAX_RELOCATIONS];
  i64                input_raw_size;
  u8                 input_raw[MAX_INPUT_SIZE];
  i64                input_sections_size;
  Input_Section_Info input_sections[MAX_INPUT_SECTIONS];
} Binary_Output;

void unit_write(Pool *pool, i64 unit, u16 target, i64 io_out, void *io_user_data) {
  //  Docs
  //
  //  AR         https://man.freebsd.org/cgi/man.cgi?query=ar&sektion=5
  //  ELF        https://man7.org/linux/man-pages/man5/elf.5.html
  //
  //  LLVM impl  https://github.com/llvm/llvm-project/blob/main/lld/ELF/Driver.cpp#L2822
  //             https://github.com/llvm/llvm-project/blob/main/lld/ELF/Writer.cpp#L304
  //             https://github.com/llvm/llvm-project/blob/main/lld/ELF/OutputSections.cpp#L469

  BX_ASSERT(pool != NULL && pool->entities != NULL);
  BX_ASSERT(pool->entities[unit].is_enabled);
  BX_ASSERT(pool->entities[unit].unit.entry_point_index != UNDEFINED);
  BX_ASSERT(target == (FORMAT_ELF | ARCH_X86_64));

  //  ELF config
  //

  u8  elf_class   = 2;  // elf64
  u8  elf_data    = 1;  // 2's complement, little endian
  u8  elf_ver     = 1;  // current version
  u8  elf_abi     = 0;  // SysV
  u8  elf_abi_ver = 0;  // ABI version
  u16 elf_machine = 62; // x86_64

  #define WRITE(x, n)     io_write( io_out, n,                              x,                    io_user_data )
  #define WRITE_V(...)    io_write( io_out, sizeof((u8[]) {__VA_ARGS__}),  (u8[])  {__VA_ARGS__}, io_user_data )
  #define WRITE_DUP(x, n) io_write( io_out, n,                             (u8[n]) {         0 }, io_user_data )
  #define WRITE_2(x)      io_write( io_out, 2,                            &(u16)   {         x }, io_user_data )
  #define WRITE_4(x)      io_write( io_out, 4,                            &(u32)   {         x }, io_user_data )
  #define WRITE_8(x)      io_write( io_out, 8,                            &(u64)   {         x }, io_user_data )

  u16 ehs   = 64;
  u16 shs   = 0;
  u16 phs   = 56;
  u64 align = 8;

  u8 code[16] = {
    0xb8,             // mov rax
    0x3c, 0, 0, 0,    // 60            // exit
    0x48, 0x31, 0xff, // xor rdx, rdx  // rdx = 0
    0x0f, 0x05,       // syscall
  };

  u64 code_offset  = ehs + phs;
  u64 code_size    = sizeof code;
  u64 entry_offset = 0;

  u64 base_address = 0x400000; // x86_64 base address
  u64 code_address = base_address + code_offset;
  u64 entry        = code_address + entry_offset;

  BX_ASSERT((code_offset % align) == 0);
  BX_ASSERT((code_size % align) == 0);

  //  ELF header
  //

  WRITE_V( 0x7f, 'E', 'L', 'F' ); // magic

  WRITE_V( elf_class   );
  WRITE_V( elf_data    );
  WRITE_V( elf_ver     );
  WRITE_V( elf_abi     );
  WRITE_V( elf_abi_ver );

  WRITE_DUP(0, 7); // padding

  WRITE_2(           2 ); // executable
  WRITE_2( elf_machine );
  WRITE_4(           1 ); // current version
  WRITE_8( entry       ); // entry point address
  WRITE_8( ehs         ); // program header offset
  WRITE_8(           0 ); // section header offset
  WRITE_4(           0 ); // flags
  WRITE_2( ehs         ); // ELF header size
  WRITE_2( phs         ); // program header size
  WRITE_2(           1 ); // program header count
  WRITE_2( shs         ); // section header size
  WRITE_2(           0 ); // section header count
  WRITE_2(           0 ); // string table section header index

  //  Program header
  //

  WRITE_4(            1 ); // type   (PT_LOAD)
  WRITE_4(            5 ); // flags  (PF_X | PF_R)
  WRITE_8( code_offset  ); // offset
  WRITE_8( code_address ); // virtual address
  WRITE_8( code_address ); // phisical address
  WRITE_8( code_size    ); // size in file
  WRITE_8( code_size    ); // size in memory
  WRITE_8(            8 ); // align

  //  Code
  //

  for (i64 i = code_offset - ehs - phs; i > 0; --i)
    WRITE_V( 0 );

  WRITE( code, code_size );

  #undef WRITE_V
  #undef WRITE_DUP
  #undef WRITE_32
  #undef WRITE_64

  #undef WRITE

  //  Read dependencies
  //
  {
    Unit *u = &pool->entities[unit].unit;

    for (i64 i = 0; i < u->link_count; ++i) {
      if (u->links[i] == UNDEFINED)
        continue;

      i64   index = u->links[i];
      Unit *l     = &pool->entities[index].unit;

      BX_ASSERT(pool->entities[index].is_enabled);
      BX_ASSERT(l->type == UNIT_LIBRARY_STATIC);
      BX_ASSERT(l->name_size > 0 && l->name_size <= MAX_NAME_SIZE);

      i64 f = io_open_read(l->name_size, l->name, io_user_data);

      c8 buf0_[MAX_NAME_SIZE + 1] = { 0 };
      bx_memcpy(buf0_, l->name, l->name_size);
      printf("\nReading `%s` library...\n\n", buf0_);

      i64 n = 0, current_offset = 0;

      //  ================================================================
      //
      //  Read AR library

      u8 magic[8];

      n = io_read(f, sizeof magic, magic, io_user_data); if (n == 0) continue;
      current_offset += n;

      BX_ASSERT(magic[0] == '!');
      BX_ASSERT(magic[1] == '<');
      BX_ASSERT(magic[2] == 'a');
      BX_ASSERT(magic[3] == 'r');
      BX_ASSERT(magic[4] == 'c');
      BX_ASSERT(magic[5] == 'h');
      BX_ASSERT(magic[6] == '>');
      BX_ASSERT(magic[7] == '\n');

      u32 static offsets[10000]      = { 0 };
      c8  static symbols[10000][256] = { 0 };
      b8  static found[10000]        = { 0 };
      i64        num_symbols         = 0;

      for (;;) {
        c8 id[17]        = { 0 };
        c8 timestamp[13] = { 0 };
        c8 owner[7]      = { 0 };
        c8 group[7]      = { 0 };
        c8 mode[9]       = { 0 };
        c8 size[11]      = { 0 };
        c8 end[2]        = { 0 };

        i64 file_offset = current_offset;

        n = io_read(f, (sizeof id)        - 1, id,        io_user_data); if (n == 0) break; current_offset += n;
        n = io_read(f, (sizeof timestamp) - 1, timestamp, io_user_data); if (n == 0) break; current_offset += n;
        n = io_read(f, (sizeof owner)     - 1, owner,     io_user_data); if (n == 0) break; current_offset += n;
        n = io_read(f, (sizeof group)     - 1, group,     io_user_data); if (n == 0) break; current_offset += n;
        n = io_read(f, (sizeof mode)      - 1, mode,      io_user_data); if (n == 0) break; current_offset += n;
        n = io_read(f, (sizeof size)      - 1, size,      io_user_data); if (n == 0) break; current_offset += n;
        n = io_read(f,  sizeof end,            end,       io_user_data); if (n == 0) break; current_offset += n;

        BX_ASSERT(end[0] == '\x60');
        BX_ASSERT(end[1] == '\x0a');

        if (bx_str_eq(id, "/               ")) {
          //  AR symbol table
          //

          u32 count_be;
          n = io_read(f, 4, &count_be, io_user_data); if (n == 0) break;
          current_offset += n;

          num_symbols =
            (( count_be        & 0xffu) << 24) |
            (((count_be >>  8) & 0xffu) << 16) |
            (((count_be >> 16) & 0xffu) <<  8) |
             ((count_be >> 24) & 0xffu);

          printf("Symbol table - %lld symbols.\n\n", num_symbols);
          BX_ASSERT(num_symbols <= (i64) (sizeof offsets / sizeof *offsets));

          for (u32 j = 0; j < num_symbols; ++j) {
            u32 offset_be;
            n = io_read(f, 4, &offset_be, io_user_data); if (n == 0) break;
            current_offset += n;

            offsets[j] =
              (( offset_be        & 0xffu) << 24) |
              (((offset_be >>  8) & 0xffu) << 16) |
              (((offset_be >> 16) & 0xffu) <<  8) |
               ((offset_be >> 24) & 0xffu);
          }
          if (n == 0) break;

          i64 byte_count = 0;

          for (u32 j = 0; j < num_symbols; ++j) {
            i64 symbol_size = 0;
            for (;; ++symbol_size) {
              c8 c;
              n = io_read(f, 1, &c, io_user_data); if (n == 0) break;
              current_offset += n;
              ++byte_count;
              if (c == '\0')
                break;
              BX_ASSERT(symbol_size < 256);
              if (symbol_size < 256)
                symbols[j][symbol_size] = c;
            }
            if (n == 0) break;
          }
          if (n == 0) break;

          if ((byte_count & 1) == 1) {
            //  align
            io_seek(f, 1, IO_SEEK_CURSOR, io_user_data);
            current_offset += 1;
          }
        } else if (bx_str_eq(id, "//              ")) {
          //  String table
          //

          i64 byte_count = atoi(size);
          if ((byte_count & 1) == 1)
            ++byte_count; // align

          b8 has_line = 0;

          while (byte_count > 0) {
            c8 c;
            n = io_read(f, 1, &c, io_user_data); if (n == 0) break;
            current_offset += n;
            byte_count -= n;
            if (c == '\0') {
              if (has_line) {
                printf("\n");
                has_line = 0;
              }
            } else {
              if (c == '/') {
                if (!has_line)
                  printf("<EMPTY>");
              } else
                printf("%c", c);
              has_line = 1;
            }
          }
        } else {
          if (bx_find_char(id, '/') != NULL)
            *bx_find_char(id, '/') = '\0';
          if (bx_find_char(size, ' ') != NULL)
            *bx_find_char(size, ' ') = '\0';

          printf("%08llx  %-16s - %5s bytes\n\n",
                 file_offset,
                 id,
                 size);

          //  Search for symbols pointing to the current file
          //
          {
            b8 symbol_found = 0;
            for (i64 symbol_index = 0; symbol_index < num_symbols; ++symbol_index)
              if (offsets[symbol_index] == file_offset) {
                printf("  %-50s\n",
                       symbols[symbol_index]);
                found[symbol_index] = 1;
                symbol_found        = 1;
              }
            if (!symbol_found)
              printf("  <SYMBOLS NOT FOUND>\n");
          }

          //  ================================================================
          //
          //  Decode ELF object file

          i64 byte_count = atoi(size);
          if ((byte_count & 1) == 1)
            ++byte_count; // align

          i64 begin_offset = current_offset;

          u8 buf[16];
          n = io_read(f, sizeof buf, buf, io_user_data); if (n == 0) break;
          current_offset += n;
          byte_count -= n;

          BX_ASSERT(buf[0] == 0x7f);
          BX_ASSERT(buf[1] == 'E');
          BX_ASSERT(buf[2] == 'L');
          BX_ASSERT(buf[3] == 'F');

          BX_ASSERT(buf[4] == elf_class);
          BX_ASSERT(buf[5] == elf_data);
          BX_ASSERT(buf[6] == elf_ver);
          BX_ASSERT(buf[7] == 0 || buf[7] == 3); // SysV or Linux
          BX_ASSERT(buf[8] == elf_abi_ver);

          #define READ(x) do {         \
            n = io_read(f, sizeof (x), \
                        &(x),          \
                        io_user_data); \
            current_offset += n;       \
            byte_count -= n;           \
          } while (0)

          u64 section_header_offset;
          u16 section_count;
          u16 strings_index;
          u64 strings_offset;

          u64 symbol_names_offset;
          u32 symbol_names_size;
          b8  symbol_names_found = 0;

          //  ELF header
          //
          {
            u16 type;
            u16 machine;
            u32 ver;
            u64 entry;
            u64 program_header_offset;
            u32 flags;
            u16 elf_header_size;
            u16 program_header_size;
            u16 program_header_count;
            u16 section_header_size;

            READ(type);
            READ(machine);
            READ(ver);
            READ(entry);
            READ(program_header_offset);
            READ(section_header_offset);
            READ(flags);
            READ(elf_header_size);
            READ(program_header_size);
            READ(program_header_count);
            READ(section_header_size);
            READ(section_count);
            READ(strings_index);

            BX_ASSERT(type == 1); // relocatable
            BX_ASSERT(machine == elf_machine);
            BX_ASSERT(ver == 1); // current version
            BX_ASSERT(entry == 0);
            BX_ASSERT(program_header_offset == 0);
            BX_ASSERT(flags == 0);
            BX_ASSERT(elf_header_size == 64);
            BX_ASSERT(program_header_size == 0);
            BX_ASSERT(program_header_count == 0);
            BX_ASSERT(section_header_size == 64);

            u64 section_offset = section_header_offset - (current_offset - begin_offset);

            io_seek(f, section_offset, IO_SEEK_CURSOR, io_user_data);
            byte_count     -= section_offset;
            current_offset += section_offset;

            //  Find offset to the section name string table data
            //
            {
              i64 prev_offset = current_offset;
              io_seek(f,
                      begin_offset + section_header_offset + strings_index * 64 + 24,
                      IO_SEEK_BEGIN, io_user_data);

              n = io_read(f, 8, &strings_offset, io_user_data); if (n == 0) break;

              io_seek(f, prev_offset, IO_SEEK_BEGIN, io_user_data);
              current_offset = prev_offset;
            }

            //  Find offset to the symbol string table data
            //
            {
              i64 prev_offset     = current_offset;
              i64 prev_byte_count = byte_count;

              for (u16 i = 0; i < section_count; ++i) {
                io_seek(f,
                        begin_offset + section_header_offset + i * 64,
                        IO_SEEK_BEGIN, io_user_data);
                u32 name;
                u64 offset;
                u32 size;

                READ(name);
                io_seek(f, 20, IO_SEEK_CURSOR, io_user_data);
                READ(offset);
                READ(size);

                //  Search for the name in the string table
                //

                io_seek(f,
                        begin_offset + strings_offset + name,
                        IO_SEEK_BEGIN, io_user_data);

                c8 buf[8];
                n = io_read(f, sizeof buf, buf, io_user_data); if (n == 0) break;

                if (!bx_str_eq(buf, ".strtab"))
                  continue;

                symbol_names_offset = offset;
                symbol_names_size   = size;
                symbol_names_found  = 1;
                break;
              }

              io_seek(f, prev_offset, IO_SEEK_BEGIN, io_user_data);
              current_offset = prev_offset;
              byte_count     = prev_byte_count;
            }
          }

          for (u16 i = 0; i < section_count; ++i) {
            u32 name;
            u32 type;
            u64 flags;
            u64 addr;
            u64 offset;
            u64 size;
            u32 link;
            u32 info;
            u64 addralign;
            u64 entsize;

            READ(name);
            READ(type);
            READ(flags);
            READ(addr);
            READ(offset);
            READ(size);
            READ(link);
            READ(info);
            READ(addralign);
            READ(entsize);

            if (type == 0) {
              printf("\n");
              continue;
            }

            if (type == 2 || type == 4 || type == 9) // sym/rela/rel
              printf("%s", "\x1b[32m");
            else if ((flags & 2) != 0) // alloc
              printf("%s", "\x1b[34m");
            else if (type == 3) // string table
              printf("%s", "\x1b[33m");
            else
              printf("%s", "\x1b[31m");

            //  NOTE
            //  Only alloc (flags & 2) sections should be written to the output binary.

            //  Search for the name in the string table
            //
            {
              i64 prev_offset = current_offset;
              io_seek(f,
                      begin_offset + strings_offset + name,
                      IO_SEEK_BEGIN, io_user_data);

              i32 padding = 50;

              printf("  ");

              for (;; --padding) {
                c8 c;
                n = io_read(f, 1, &c, io_user_data); if (n == 0) break;
                if (c == '\0')
                  break;
                printf("%c", c);
              }

              if (padding > 0)
                printf("%*s", padding, "");

              io_seek(f, prev_offset, IO_SEEK_BEGIN, io_user_data);
              current_offset = prev_offset;
            }

            printf("%s", "\x1b[37m");

            printf(
              "%-10s",
              type >= 1 && type <= 9 ?
                (c8 const *[]) {
                  "Program",
                  "Symbols",
                  "Strings",
                  "Rel add",
                  "Hash",
                  "Dynamic",
                  "Note",
                  "Zeros",
                  "Rel",
                }[type - 1] :
              type == 17 ?
                  "Group"   :
                  ""
            );

            if ((flags & 2) == 2)
              printf("R");
            else
              printf("_");
            if ((flags & 1) == 1)
              printf("W");
            else
              printf("_");
            if ((flags & 4) == 4)
              printf("X");
            else
              printf("_");

            if (size > 0)
              printf(" - %lld bytes", size);

            printf("\n");

            switch (type) {
              //  ================================================================
              //
              //  Symbols

              case 2: {
                //  Find symbol addresses
                //

                BX_ASSERT(entsize == 24);

                i64 prev_offset     = current_offset;
                i64 prev_byte_count = byte_count;
                io_seek(f,
                        begin_offset + offset,
                        IO_SEEK_BEGIN, io_user_data);
                current_offset = begin_offset + offset;

                printf("\n");

                for (byte_count = size; byte_count > 0;) {
                  BX_ASSERT(symbol_names_found);

                  u32 sym_name;
                  u8  sym_info;
                  u8  sym_other;
                  u16 sym_shndx;
                  u64 sym_value;
                  u64 sym_size;

                  READ(sym_name);  BX_ASSERT(n != 0);
                  READ(sym_info);  BX_ASSERT(n != 0);
                  READ(sym_other); BX_ASSERT(n != 0);
                  READ(sym_shndx); BX_ASSERT(n != 0);
                  READ(sym_value); BX_ASSERT(n != 0);
                  READ(sym_size);  BX_ASSERT(n != 0);

                  printf("    ");

                  if (sym_name != 0) {
                    if (sym_name < symbol_names_size) {
                      //  Search for the symbol name in the string table
                      //

                      i64 prev_offset = current_offset;
                      io_seek(f,
                              begin_offset + symbol_names_offset + sym_name,
                              IO_SEEK_BEGIN, io_user_data);

                      i32 padding = 48;

                      if ((sym_info & 0xf) == 1 ||
                          (sym_info & 0xf) == 2)
                        printf("%s", "\x1b[32m");

                      printf("\"");

                      for (;; --padding) {
                        c8 c;
                        n = io_read(f, 1, &c, io_user_data); if (n == 0) break;
                        if (c == '\0')
                          break;
                        printf("%c", c);
                      }

                      printf("\"");
                      if ((sym_info & 0xf) == 1 ||
                          (sym_info & 0xf) == 2)
                        printf("%s", "\x1b[37m");
                      if (padding > 0)
                        printf("%*s", padding, "");

                      io_seek(f, prev_offset, IO_SEEK_BEGIN, io_user_data);
                      current_offset = prev_offset;
                    } else
                      printf("%-50d", sym_name);
                  } else
                    printf("%*s", 50, "");

                  printf("%08llx  ", sym_value); // symbol address

                  printf("%-8s ",
                    (sym_info & 0xf) <= 4 ? (c8 const *[]) {
                                        "No type",
                                        "Data",
                                        "Func",
                                        "Section",
                                        "File",
                    }[sym_info & 0xf] : ""
                  );

                  if (sym_size != 0)
                    printf("- %lld bytes", sym_size);
                  printf("\n");
                }

                printf("\n");

                io_seek(f, prev_offset, IO_SEEK_BEGIN, io_user_data);
                current_offset = prev_offset;
                byte_count     = prev_byte_count;
              } break;

              //  ================================================================
              //
              //  Relocarions with addends

              case 4: {
              } break;

              //  ================================================================
              
              default:;
            }
          }

          printf("\n");

          io_seek(f, byte_count, IO_SEEK_CURSOR, io_user_data);
          current_offset += byte_count;

          #undef READ

          //  ================================================================
        }
      }

      for (i64 symbol_index = 0; symbol_index < num_symbols; ++symbol_index)
        if (!found[symbol_index])
          printf("      ? : %-16s - %-50s\n",
                 "<FILE NOT FOUND>",
                 symbols[symbol_index]);

      //  ================================================================
      
      io_close(f, io_user_data);
    }
  }
}

i64 io_open_read(i64 name_size, c8 *name, void *user_data) {
  i64 f;
  io_dispatch(IO_OPEN_READ, &f, &name_size, name, user_data);
  return f;
}

i64 io_open_write(i64 name_size, c8 *name, void *user_data) {
  i64 f;
  io_dispatch(IO_OPEN_WRITE, &f, &name_size, name, user_data);
  return f;
}

void io_close(i64 f, void *user_data) {
  io_dispatch(IO_CLOSE, &f, NULL, NULL, user_data);
}

b8 io_seek(i64 f, i64 offset, u16 origin, void *user_data) {
  io_dispatch(IO_SEEK, &f, &offset, &origin, user_data);
  return 1;
}

i64 io_read(i64 f, i64 size, void *data, void *user_data) {
  io_dispatch(IO_READ, &f, &size, data, user_data);
  return size;
}

i64 io_write(i64 f, i64 size, void *data, void *user_data) {
  io_dispatch(IO_WRITE, &f, &size, data, user_data);
  return size;
}

void io_chmod_exe(i64 f, void *user_data) {
  io_dispatch(IO_CHMOD_EXE, &f, NULL, NULL, user_data);
}

//  ================================================================
//
//    Helpers implementation
//
//  ================================================================

#ifndef DISABLE_HELPERS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __unix__
#include <sys/types.h>
#include <sys/stat.h>
#endif

//  Assert
//

void bx_assert(b8 condition, c8 const *message, u32 line, c8 const *file) {
  if (condition)
    return;

  fflush(stdout);
  fprintf(stderr, "\r\x1b[31mASSERTION:\x1b[37m `\x1b[33m%s\x1b[37m` is false in \x1b[36m%s:%d\x1b[37m\n", message, file, line);
  abort();
}

//  IO dispatch procedure
//

void io_dispatch(i16 op, i64 *id, i64 *size, void *data, void *user_data) {
  BX_ASSERT(id != NULL);

  (void) user_data;

  FILE **f                  = (FILE **) id;
  c8     buf[MAX_NAME_SIZE] = { 0 };

  switch (op) {
    case IO_OPEN_READ:
    case IO_OPEN_WRITE:
      BX_ASSERT(size != NULL);
      BX_ASSERT(*size > 0 && *size < MAX_NAME_SIZE);
      BX_ASSERT(data != NULL);

      bx_memcpy(buf, data, *size);
      *f = fopen(buf, op == IO_OPEN_READ ? "rb" : "wb");
      BX_ASSERT(*f != NULL);
      break;

    case IO_CLOSE:
      BX_ASSERT(*f != NULL);
      BX_ASSERT(size == NULL);
      BX_ASSERT(data == NULL);

      fclose(*f);
      break;

    case IO_SEEK: {
      BX_ASSERT(*f != NULL);
      BX_ASSERT(size != NULL);
      BX_ASSERT(data != NULL);

      u16 *origin = (u16 *) data;

      if (!(*origin == IO_SEEK_CURSOR && *size == 0)) {
        BX_ASSERT(*origin == IO_SEEK_CURSOR || *origin == IO_SEEK_BEGIN || *origin == IO_SEEK_END);
        i32 s = fseek(*f, *size, *origin == IO_SEEK_CURSOR ? SEEK_CUR :
                                 *origin == IO_SEEK_BEGIN  ? SEEK_SET :
                                                             SEEK_END);
        BX_ASSERT(s == 0);
      }
    } break;

    case IO_READ:
      BX_ASSERT(*f != NULL);
      BX_ASSERT(size != NULL);
      BX_ASSERT(data != NULL);
      BX_ASSERT(*size > 0);

      *size = fread(data, 1, *size, *f);
      break;

    case IO_WRITE:
      BX_ASSERT(*f != NULL);
      BX_ASSERT(size != NULL);
      BX_ASSERT(data != NULL);
      BX_ASSERT(*size > 0);

      *size = fwrite(data, 1, *size, *f);
      break;

    case IO_CHMOD_EXE:
      BX_ASSERT(*f != NULL);
      BX_ASSERT(size == NULL);

#ifdef __unix__
      fchmod(fileno(*f), 0775);
#endif
      break;

    default:
      BX_ASSERT(0);
  }
}

//  Global state
//

static Pool g_pool = {
  //  Statically allocate a large memory block.
  //
  //    TODO
  //    Reallocate the memory block when necessary.

  .capacity = MAX_ENTITY_COUNT,
  .entities = (Entity[MAX_ENTITY_COUNT]) { 0 },
};

//  Handy procedures
//

i64 n_i64(i64 value) {
  return node_data_i64(&g_pool, value);
}

i64 n_call(i16 convention, i64 target_proc, i64 arg_count, Var *args) {
  return node_ctrl_call(&g_pool, convention, target_proc, arg_count, args);
}

i64 n_call_by_name(i16 convention, c8 *name, i64 arg_count, Var *args) {
  return node_ctrl_call_by_name(&g_pool, convention, strlen(name), name, arg_count, args);
}

i64 n_ret(i64 val_count, Var *vals) {
  return node_ctrl_ret(&g_pool, val_count, vals);
}

i64 p_new(c8 *name) {
  i64 p = proc_init(&g_pool);
  proc_set_name(&g_pool, p, strlen(name), name);
  return p;
}

void p_add(i64 proc, i64 node) {
  proc_node_add(&g_pool, proc, node);
}

i64 u_new() {
  return unit_init(&g_pool, UNIT_CODE);
}

void u_add(i64 unit, i64 proc) {
  unit_proc_add(&g_pool, unit, proc);
}

void u_entry_point(i64 unit, i64 proc) {
  unit_set_entry_point(&g_pool, unit, proc);
}

void u_elf_x86_64(i64 unit, c8 *output_file_name) {
  i64 out = io_open_write(strlen(output_file_name), output_file_name, NULL);

  unit_write(&g_pool, unit, FORMAT_ELF | ARCH_X86_64, out, NULL);

  io_chmod_exe(out, NULL);
  io_close(out, NULL);
}

void l_code(i64 unit, i64 link_unit) {
  unit_link_add(&g_pool, unit, link_unit);
}

void l_object(i64 unit, c8 *object_library) {
  i64 l = unit_init(&g_pool, UNIT_LIBRARY_OBJECT);
  unit_set_name(&g_pool, l, strlen(object_library), object_library);
  unit_link_add(&g_pool, unit, l);
}

void l_static(i64 unit, c8 *static_library) {
  i64 l = unit_init(&g_pool, UNIT_LIBRARY_STATIC);
  unit_set_name(&g_pool, l, strlen(static_library), static_library);
  unit_link_add(&g_pool, unit, l);
}

#endif

//  ================================================================
//
//    Example
//
//  ================================================================

#if !defined(DISABLE_HELPERS) && !defined(DISABLE_TESTING)

int main(int argc, char **argv) {
  (void) argc;
  (void) argv;

  printf("node   - %d bytes\n", (i32) sizeof(Node));
  printf("proc   - %d bytes\n", (i32) sizeof(Proc));
  printf("unit   - %d bytes\n", (i32) sizeof(Unit));
  printf("entity - %d bytes\n\n", (i32) sizeof(Entity));

  i64 main = p_new("main");
  i64 n0 = n_i64(42);
  p_add(main, n0);
  p_add(main, n_ret(1, (Var[]) { {.size = 4, .type = TYPE_I32, .node = n0, } }));

  i64 u = u_new();
  u_add(u, main);
  u_entry_point(u, main);
  // l_static(u, "/lib/x86_64-linux-gnu/libc.a");
  l_static(u, "libtest.a");
  
  printf("Writing ELF x86_64 executable...\n");
  u_elf_x86_64(u, "test_foo");

  printf("\nBye!\n");
  return 0;
}

#endif

#endif