-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathLinker.cpp
More file actions
1992 lines (1760 loc) · 57.6 KB
/
Linker.cpp
File metadata and controls
1992 lines (1760 loc) · 57.6 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
#ifdef WIN32
#define YY_NO_UNISTD_H
#endif
#include <stdio.h>
#include <string.h>
#include "asmx86.h"
#include "Linker.h"
#include "CodeParser.h"
#include "CodeLexer.h"
#include "Optimize.h"
#include "OutputX86.h"
#include "OutputX64.h"
#include "ElfOutput.h"
#include "MachOOutput.h"
#include "PeOutput.h"
using namespace std;
using namespace asmx86;
// Internal libraries
extern unsigned char Obj_x86_lib[];
extern unsigned int Obj_x86_lib_len;
extern unsigned char Obj_x64_lib[];
extern unsigned int Obj_x64_lib_len;
extern unsigned char Obj_quark_lib[];
extern unsigned int Obj_quark_lib_len;
extern unsigned char Obj_mips_lib[];
extern unsigned int Obj_mips_lib_len;
extern unsigned char Obj_mipsel_lib[];
extern unsigned int Obj_mipsel_lib_len;
extern unsigned char Obj_arm_lib[];
extern unsigned int Obj_arm_lib_len;
extern unsigned char Obj_armeb_lib[];
extern unsigned int Obj_armeb_lib_len;
extern unsigned char Obj_aarch64_lib[];
extern unsigned int Obj_aarch64_lib_len;
extern unsigned char Obj_ppc_lib[];
extern unsigned int Obj_ppc_lib_len;
extern unsigned char Obj_ppcel_lib[];
extern unsigned int Obj_ppcel_lib_len;
extern unsigned char Obj_linux_x86_lib[];
extern unsigned int Obj_linux_x86_lib_len;
extern unsigned char Obj_linux_x64_lib[];
extern unsigned int Obj_linux_x64_lib_len;
extern unsigned char Obj_linux_quark_lib[];
extern unsigned int Obj_linux_quark_lib_len;
extern unsigned char Obj_linux_mips_lib[];
extern unsigned int Obj_linux_mips_lib_len;
extern unsigned char Obj_linux_mipsel_lib[];
extern unsigned int Obj_linux_mipsel_lib_len;
extern unsigned char Obj_linux_arm_lib[];
extern unsigned int Obj_linux_arm_lib_len;
extern unsigned char Obj_linux_armeb_lib[];
extern unsigned int Obj_linux_armeb_lib_len;
extern unsigned char Obj_linux_aarch64_lib[];
extern unsigned int Obj_linux_aarch64_lib_len;
extern unsigned char Obj_linux_ppc_lib[];
extern unsigned int Obj_linux_ppc_lib_len;
extern unsigned char Obj_linux_ppcel_lib[];
extern unsigned int Obj_linux_ppcel_lib_len;
extern unsigned char Obj_freebsd_x86_lib[];
extern unsigned int Obj_freebsd_x86_lib_len;
extern unsigned char Obj_freebsd_x64_lib[];
extern unsigned int Obj_freebsd_x64_lib_len;
extern unsigned char Obj_freebsd_quark_lib[];
extern unsigned int Obj_freebsd_quark_lib_len;
extern unsigned char Obj_mac_x86_lib[];
extern unsigned int Obj_mac_x86_lib_len;
extern unsigned char Obj_mac_x64_lib[];
extern unsigned int Obj_mac_x64_lib_len;
extern unsigned char Obj_mac_quark_lib[];
extern unsigned int Obj_mac_quark_lib_len;
extern unsigned char Obj_windows_x86_lib[];
extern unsigned int Obj_windows_x86_lib_len;
extern unsigned char Obj_windows_x64_lib[];
extern unsigned int Obj_windows_x64_lib_len;
extern unsigned char Obj_windows_quark_lib[];
extern unsigned int Obj_windows_quark_lib_len;
extern unsigned char Obj_windows_arm_lib[];
extern unsigned int Obj_windows_arm_lib_len;
extern int Code_parse(ParserState* state);
extern void Code_set_lineno(int line, void* yyscanner);
extern Output* CreateQuarkCodeGen(const Settings& settings, Function* startFunc);
extern Output* CreateMipsCodeGen(const Settings& settings, Function* startFunc);
extern Output* CreateArmCodeGen(const Settings& settings, Function* startFunc);
extern Output* CreateAArch64CodeGen(const Settings& settings, Function* startFunc);
extern Output* CreatePpcCodeGen(const Settings& settings, Function* startFunc);
Linker::Linker(const Settings& settings): m_settings(settings), m_precompiledPreprocess("precompiled headers", NULL, settings),
m_precompileState(settings, "precompiled headers", NULL), m_initExpression(new Expr(EXPR_SEQUENCE))
{
m_markovReady = false;
}
Linker::~Linker()
{
}
size_t Linker::AddInstructionToMarkovChain(uint16_t& prev, uint8_t* data, size_t len)
{
Instruction instr;
if (m_settings.preferredBits == 32)
{
if (!Disassemble32(data, 0, len, &instr))
return 1;
}
else
{
if (!Disassemble64(data, 0, len, &instr))
return 1;
}
if (instr.length == 0)
return 1;
// Skip instructions that don't satisfy the blacklist
bool ok = true;
for (size_t j = 0; j < instr.length; j++)
{
for (vector<uint8_t>::iterator k = m_settings.blacklist.begin(); k != m_settings.blacklist.end(); k++)
{
if (data[j] == *k)
{
ok = false;
break;
}
}
if (!ok)
break;
}
if (ok)
{
m_markovChain[prev][string((char*)data, instr.length)]++;
// Insert all instructions into slot 0xffff (invalid for X86), this will be what is used when inserting
// an instruction from a fresh state (or one which has no valid transitions)
m_markovChain[0xffff][string((char*)data, instr.length)]++;
if (instr.length == 1)
prev = data[0];
else
prev = ((uint16_t)data[0]) | ((uint16_t)data[1] << 8);
}
return instr.length;
}
void Linker::PrepareMarkovInstructionsFromFile(const string& filename)
{
// Markov chain generation only supported on x86 for now
if (m_settings.architecture != ARCH_X86)
return;
FILE* fp = fopen(filename.c_str(), "rb");
if (!fp)
return;
fseek(fp, 0, SEEK_END);
size_t len = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* data = new uint8_t[len];
if (fread(data, len, 1, fp) <= 0)
{
fclose(fp);
return;
}
fclose(fp);
uint16_t prev = 0x90;
for (size_t i = 0; i < len; )
{
size_t maxLen = len - i;
if (maxLen > 15)
maxLen = 15;
i += AddInstructionToMarkovChain(prev, &data[i], maxLen);
}
m_markovReady = true;
}
void Linker::PrepareMarkovInstructionsFromBlocks(const vector<ILBlock*>& codeBlocks)
{
// Markov chain generation only supported on x86 for now
if (m_settings.architecture != ARCH_X86)
return;
uint16_t prev = 0x90;
for (vector<ILBlock*>::const_iterator i = codeBlocks.begin(); i != codeBlocks.end(); i++)
{
for (size_t j = 0; j < (*i)->GetOutputBlock()->len; j++)
{
size_t maxLen = (*i)->GetOutputBlock()->len - j;
if (maxLen > 15)
maxLen = 15;
j += AddInstructionToMarkovChain(prev, &((uint8_t*)(*i)->GetOutputBlock()->code)[j], maxLen);
}
}
m_markovReady = true;
}
void Linker::InsertMarkovInstructions(OutputBlock* block, size_t len)
{
uint16_t prev = 0xffff;
while (len > 0)
{
size_t total = 0;
for (map<string, size_t>::iterator i = m_markovChain[prev].begin(); i != m_markovChain[prev].end(); i++)
total += i->second;
if (total == 0)
{
if (prev == 0xffff)
{
// No valid starting instructions, just generate random data
vector<uint8_t> available;
for (size_t i = 0; i < 256; i++)
{
bool ok = true;
for (vector<uint8_t>::iterator j = m_settings.blacklist.begin(); j != m_settings.blacklist.end(); j++)
{
if (i == *j)
{
ok = false;
break;
}
}
if (ok)
available.push_back((uint8_t)i);
}
for (size_t i = 0; i < len; i++)
{
uint8_t choice = available[rand() % available.size()];
*(uint8_t*)block->PrepareWrite(1) = choice;
block->FinishWrite(1);
}
return;
}
// No valid transition states, start from the top
prev = 0xffff;
continue;
}
// Pick a random instruction, ensuring that the weighting is correct
size_t cur = 0;
size_t pick = rand() % total;
string instruction;
for (map<string, size_t>::iterator i = m_markovChain[prev].begin(); i != m_markovChain[prev].end(); i++)
{
cur += i->second;
if (cur > pick)
{
instruction = i->first;
break;
}
}
if (instruction.size() == 1)
prev = instruction[0];
else
prev = ((uint16_t)instruction[0]) | ((uint16_t)instruction[1] << 8);
memcpy(block->PrepareWrite(instruction.size()), instruction.c_str(), instruction.size());
block->FinishWrite(instruction.size());
if (instruction.size() > len)
break;
len -= instruction.size();
}
}
bool Linker::ImportLibrary(InputBlock* input)
{
// Deserialize precompiled header state
if (!m_precompiledPreprocess.Deserialize(input))
return false;
if (!m_precompileState.Deserialize(input))
return false;
// Deserialize functions
size_t functionCount;
if (!input->ReadNativeInteger(functionCount))
return false;
for (size_t i = 0; i < functionCount; i++)
{
Function* func = Function::Deserialize(input);
if (!func)
return false;
m_functions.push_back(func);
}
// Deserialize variables
size_t variableCount;
if (!input->ReadNativeInteger(variableCount))
return false;
for (size_t i = 0; i < variableCount; i++)
{
Variable* var = Variable::Deserialize(input);
if (!var)
return false;
m_variables.push_back(var);
}
// Deserialize function name map
size_t functionMapCount;
if (!input->ReadNativeInteger(functionMapCount))
return false;
for (size_t i = 0; i < functionMapCount; i++)
{
string name;
if (!input->ReadString(name))
return false;
Function* func = Function::Deserialize(input);
if (!func)
return false;
m_functionsByName[name] = func;
}
// Deserialize variable name map
size_t variableMapCount;
if (!input->ReadNativeInteger(variableMapCount))
return false;
for (size_t i = 0; i < variableMapCount; i++)
{
string name;
if (!input->ReadString(name))
return false;
Variable* var = Variable::Deserialize(input);
if (!var)
return false;
m_variablesByName[name] = var;
}
// Deserialize initialization expression
m_initExpression = Expr::Deserialize(input);
if (!m_initExpression)
return false;
return true;
}
bool Linker::ImportStandardLibrary()
{
unsigned char* lib = NULL;
unsigned int len = 0;
if (m_settings.architecture == ARCH_X86)
{
switch (m_settings.os)
{
case OS_LINUX:
if (m_settings.preferredBits == 32)
{
lib = Obj_linux_x86_lib;
len = Obj_linux_x86_lib_len;
}
else
{
lib = Obj_linux_x64_lib;
len = Obj_linux_x64_lib_len;
}
break;
case OS_FREEBSD:
if (m_settings.preferredBits == 32)
{
lib = Obj_freebsd_x86_lib;
len = Obj_freebsd_x86_lib_len;
}
else
{
lib = Obj_freebsd_x64_lib;
len = Obj_freebsd_x64_lib_len;
}
break;
case OS_MAC:
if (m_settings.preferredBits == 32)
{
lib = Obj_mac_x86_lib;
len = Obj_mac_x86_lib_len;
}
else
{
lib = Obj_mac_x64_lib;
len = Obj_mac_x64_lib_len;
}
break;
case OS_WINDOWS:
if (m_settings.preferredBits == 32)
{
lib = Obj_windows_x86_lib;
len = Obj_windows_x86_lib_len;
}
else
{
lib = Obj_windows_x64_lib;
len = Obj_windows_x64_lib_len;
}
break;
default:
if (m_settings.preferredBits == 32)
{
lib = Obj_x86_lib;
len = Obj_x86_lib_len;
}
else
{
lib = Obj_x64_lib;
len = Obj_x64_lib_len;
}
break;
}
}
else if (m_settings.architecture == ARCH_QUARK)
{
switch (m_settings.os)
{
case OS_LINUX:
lib = Obj_linux_quark_lib;
len = Obj_linux_quark_lib_len;
break;
case OS_FREEBSD:
lib = Obj_freebsd_quark_lib;
len = Obj_freebsd_quark_lib_len;
break;
case OS_MAC:
lib = Obj_mac_quark_lib;
len = Obj_mac_quark_lib_len;
break;
case OS_WINDOWS:
lib = Obj_windows_quark_lib;
len = Obj_windows_quark_lib_len;
break;
default:
lib = Obj_quark_lib;
len = Obj_quark_lib_len;
break;
}
}
else if (m_settings.architecture == ARCH_MIPS)
{
if (m_settings.bigEndian)
{
switch (m_settings.os)
{
case OS_LINUX:
lib = Obj_linux_mips_lib;
len = Obj_linux_mips_lib_len;
break;
default:
lib = Obj_mips_lib;
len = Obj_mips_lib_len;
break;
}
}
else
{
switch (m_settings.os)
{
case OS_LINUX:
lib = Obj_linux_mipsel_lib;
len = Obj_linux_mipsel_lib_len;
break;
default:
lib = Obj_mipsel_lib;
len = Obj_mipsel_lib_len;
break;
}
}
}
else if (m_settings.architecture == ARCH_ARM)
{
if (m_settings.bigEndian)
{
switch (m_settings.os)
{
case OS_LINUX:
lib = Obj_linux_armeb_lib;
len = Obj_linux_armeb_lib_len;
break;
default:
lib = Obj_armeb_lib;
len = Obj_armeb_lib_len;
break;
}
}
else
{
switch (m_settings.os)
{
case OS_LINUX:
lib = Obj_linux_arm_lib;
len = Obj_linux_arm_lib_len;
break;
case OS_WINDOWS:
lib = Obj_windows_arm_lib;
len = Obj_windows_arm_lib_len;
break;
default:
lib = Obj_arm_lib;
len = Obj_arm_lib_len;
break;
}
}
}
else if (m_settings.architecture == ARCH_AARCH64)
{
if (!m_settings.bigEndian)
{
switch (m_settings.os)
{
case OS_LINUX:
lib = Obj_linux_aarch64_lib;
len = Obj_linux_aarch64_lib_len;
break;
default:
lib = Obj_aarch64_lib;
len = Obj_aarch64_lib_len;
break;
}
}
}
else if (m_settings.architecture == ARCH_PPC)
{
if (m_settings.bigEndian)
{
switch (m_settings.os)
{
case OS_LINUX:
lib = Obj_linux_ppc_lib;
len = Obj_linux_ppc_lib_len;
break;
default:
lib = Obj_ppc_lib;
len = Obj_ppc_lib_len;
break;
}
}
else
{
switch (m_settings.os)
{
case OS_LINUX:
lib = Obj_linux_ppcel_lib;
len = Obj_linux_ppcel_lib_len;
break;
default:
lib = Obj_ppcel_lib;
len = Obj_ppcel_lib_len;
break;
}
}
}
if (len != 0)
{
InputBlock input;
input.code = lib;
input.len = len;
input.offset = 0;
if (!ImportLibrary(&input))
return false;
}
return true;
}
bool Linker::PrecompileHeader(const string& path)
{
m_precompiledPreprocess.IncludeFile(path);
if (m_precompiledPreprocess.HasErrors())
return false;
return true;
}
bool Linker::PrecompileSource(const string& source)
{
m_precompiledPreprocess.IncludeSource(source);
if (m_precompiledPreprocess.HasErrors())
return false;
return true;
}
bool Linker::FinalizePrecompiledHeaders()
{
yyscan_t scanner;
Code_lex_init(&scanner);
m_precompileState.SetScanner(scanner);
YY_BUFFER_STATE buf = Code__scan_string(m_precompiledPreprocess.GetOutput().c_str(), scanner);
Code__switch_to_buffer(buf, scanner);
Code_set_lineno(1, scanner);
bool ok = true;
if (Code_parse(&m_precompileState) != 0)
ok = false;
if (m_precompileState.HasErrors())
ok = false;
Code_lex_destroy(scanner);
return ok;
}
bool Linker::CompileSource(const std::string& source, const std::string& filename)
{
string preprocessed;
if (!PreprocessState::PreprocessSource(m_settings, source, filename, preprocessed, &m_precompiledPreprocess))
return false;
yyscan_t scanner;
Code_lex_init(&scanner);
ParserState parser(&m_precompileState, filename.c_str(), scanner);
YY_BUFFER_STATE buf = Code__scan_string(preprocessed.c_str(), scanner);
Code__switch_to_buffer(buf, scanner);
Code_set_lineno(1, scanner);
bool ok = true;
if (Code_parse(&parser) != 0)
ok = false;
if (parser.HasErrors())
ok = false;
Code_lex_destroy(scanner);
if (!ok)
return false;
// Apply fixed function addresses, but ensure that user specified address takes priority
for (map<string, uint64_t>::const_iterator i = parser.GetFixedFunctionAddresses().begin();
i != parser.GetFixedFunctionAddresses().end(); ++i)
{
if ((m_settings.funcAddrs.find(i->first) == m_settings.funcAddrs.end()) &&
(m_settings.funcPtrAddrs.find(i->first) == m_settings.funcPtrAddrs.end()))
m_settings.funcAddrs[i->first] = i->second;
}
for (map<string, uint64_t>::const_iterator i = parser.GetFixedFunctionPointers().begin();
i != parser.GetFixedFunctionPointers().end(); ++i)
{
if ((m_settings.funcAddrs.find(i->first) == m_settings.funcAddrs.end()) &&
(m_settings.funcPtrAddrs.find(i->first) == m_settings.funcPtrAddrs.end()))
m_settings.funcPtrAddrs[i->first] = i->second;
}
// First, propogate type information
parser.SetInitExpression(parser.GetInitExpression()->Simplify(&parser));
parser.GetInitExpression()->ComputeType(&parser, NULL);
for (map< string, Ref<Function> >::const_iterator i = parser.GetFunctions().begin();
i != parser.GetFunctions().end(); i++)
{
if (!i->second->IsFullyDefined())
continue;
i->second->SetBody(i->second->GetBody()->Simplify(&parser));
i->second->GetBody()->ComputeType(&parser, i->second);
i->second->SetBody(i->second->GetBody()->Simplify(&parser));
i->second->GetBody()->ComputeType(&parser, i->second);
}
if (parser.HasErrors())
return false;
// Generate IL
for (map< string, Ref<Function> >::const_iterator i = parser.GetFunctions().begin();
i != parser.GetFunctions().end(); i++)
{
if (!i->second->IsFullyDefined())
continue;
i->second->GenerateIL(&parser);
i->second->ReportUndefinedLabels(&parser);
}
if (parser.HasErrors())
return false;
// Link functions to other files
for (map< string, Ref<Function> >::const_iterator i = parser.GetFunctions().begin();
i != parser.GetFunctions().end(); i++)
{
if (i->second->IsFullyDefined())
{
// Function is defined in this file
if (i->second->IsLocalScope())
{
// Function is in local scope, add it to list but not to name table
m_functions.push_back(i->second);
}
else
{
// Funciton is in global scope
if (m_functionsByName.find(i->second->GetName()) != m_functionsByName.end())
{
// Function by this name already defined in another file
Function* prev = m_functionsByName[i->second->GetName()];
if (prev->IsFullyDefined())
{
// Both functions have a body, this is an error
parser.Error();
fprintf(stderr, "%s:%d: error: duplicate function '%s' during link\n",
i->second->GetLocation().fileName.c_str(),
i->second->GetLocation().lineNumber, i->second->GetName().c_str());
fprintf(stderr, "%s:%d: previous definition of '%s'\n",
prev->GetLocation().fileName.c_str(), prev->GetLocation().lineNumber,
prev->GetName().c_str());
}
else
{
// Other function was a prototype, check for compatibility
vector< pair< Ref<Type>, string> > params;
for (vector<FunctionParameter>::const_iterator j =
prev->GetParameters().begin(); j != prev->GetParameters().end(); j++)
params.push_back(pair< Ref<Type>, string>(j->type, j->name));
if (!i->second->IsCompatible(prev->GetReturnValue(),
prev->GetCallingConvention(), params, prev->HasVariableArguments()))
{
parser.Error();
fprintf(stderr, "%s:%d: error: function '%s' incompatible with prototype\n",
i->second->GetLocation().fileName.c_str(),
i->second->GetLocation().lineNumber,
i->second->GetName().c_str());
fprintf(stderr, "%s:%d: prototype definition of '%s'\n",
prev->GetLocation().fileName.c_str(),
prev->GetLocation().lineNumber,
prev->GetName().c_str());
}
if (prev->IsImportedFunction())
{
parser.Error();
fprintf(stderr, "%s:%d: error: imported function '%s' cannot have implementation\n",
i->second->GetLocation().fileName.c_str(),
i->second->GetLocation().lineNumber,
i->second->GetName().c_str());
fprintf(stderr, "%s:%d: prototype definition of '%s'\n",
prev->GetLocation().fileName.c_str(),
prev->GetLocation().lineNumber,
prev->GetName().c_str());
}
// Replace old references with the fully defined one
for (vector< Ref<Function> >::iterator j = m_functions.begin();
j != m_functions.end(); j++)
(*j)->ReplaceFunction(prev, i->second);
m_initExpression->ReplaceFunction(prev, i->second);
}
}
m_functions.push_back(i->second);
m_functionsByName[i->second->GetName()] = i->second;
}
}
else
{
// Function is a prototype only, ignore local scope
if (!i->second->IsLocalScope())
{
if (m_functionsByName.find(i->second->GetName()) != m_functionsByName.end())
{
// Function by this name already defined in another file
Function* prev = m_functionsByName[i->second->GetName()];
// Check for compatibility
vector< pair< Ref<Type>, string> > params;
for (vector<FunctionParameter>::const_iterator j =
prev->GetParameters().begin(); j != prev->GetParameters().end(); j++)
params.push_back(pair< Ref<Type>, string>(j->type, j->name));
if (!i->second->IsCompatible(prev->GetReturnValue(),
prev->GetCallingConvention(), params, prev->HasVariableArguments()))
{
parser.Error();
fprintf(stderr, "%s:%d: error: function '%s' incompatible with prototype\n",
prev->GetLocation().fileName.c_str(),
prev->GetLocation().lineNumber,
prev->GetName().c_str());
fprintf(stderr, "%s:%d: prototype definition of '%s'\n",
i->second->GetLocation().fileName.c_str(),
i->second->GetLocation().lineNumber,
i->second->GetName().c_str());
}
if (i->second->IsImportedFunction() != prev->IsImportedFunction())
{
parser.Error();
fprintf(stderr, "%s:%d: error: function '%s' incompatible with prototype\n",
prev->GetLocation().fileName.c_str(),
prev->GetLocation().lineNumber,
prev->GetName().c_str());
fprintf(stderr, "%s:%d: prototype definition of '%s'\n",
i->second->GetLocation().fileName.c_str(),
i->second->GetLocation().lineNumber,
i->second->GetName().c_str());
}
// Replace references with existing definition
for (map< string, Ref<Function> >::const_iterator j =
parser.GetFunctions().begin(); j != parser.GetFunctions().end(); j++)
j->second->ReplaceFunction(i->second, prev);
parser.GetInitExpression()->ReplaceFunction(i->second, prev);
}
else
{
// New prototype, add to list of functions
m_functions.push_back(i->second);
m_functionsByName[i->second->GetName()] = i->second;
}
}
}
}
if (parser.HasErrors())
return false;
// Add initialization expression to global expression
m_initExpression->AddChild(parser.GetInitExpression());
// Link variables to other files
for (vector< Ref<Variable> >::const_iterator i = parser.GetGlobalScope()->GetVariables().begin();
i != parser.GetGlobalScope()->GetVariables().end(); i++)
{
if ((*i)->IsExternal())
{
// Variable is external
if (m_variablesByName.find((*i)->GetName()) != m_variablesByName.end())
{
// Variable is defined in another file
Variable* prev = m_variablesByName[(*i)->GetName()];
// Check for compatibility
if ((*prev->GetType()) != (*(*i)->GetType()))
{
parser.Error();
fprintf(stderr, "%s:%d: error: variable '%s' incompatible with previous definition\n",
(*i)->GetLocation().fileName.c_str(),
(*i)->GetLocation().lineNumber,
(*i)->GetName().c_str());
fprintf(stderr, "%s:%d: previous definition of '%s'\n",
prev->GetLocation().fileName.c_str(),
prev->GetLocation().lineNumber,
prev->GetName().c_str());
}
if (!prev->IsExternal())
{
// Previous definition is complete, replace references with the correct definition
for (vector< Ref<Function> >::iterator j = m_functions.begin(); j != m_functions.end(); j++)
(*j)->ReplaceVariable(*i, prev);
m_initExpression->ReplaceVariable(*i, prev);
}
}
else
{
// New definition
m_variables.push_back(*i);
m_variablesByName[(*i)->GetName()] = *i;
}
}
else if ((*i)->IsLocalScope())
{
// Variable is local to the file, add to list but do not bind in name table
m_variables.push_back(*i);
}
else
{
// Variable is global
if (m_variablesByName.find((*i)->GetName()) != m_variablesByName.end())
{
// Variable is defined in another file
Variable* prev = m_variablesByName[(*i)->GetName()];
// Check for compatibility and duplicates
if (!prev->IsExternal())
{
parser.Error();
fprintf(stderr, "%s:%d: error: duplicate variable '%s' during link\n",
(*i)->GetLocation().fileName.c_str(),
(*i)->GetLocation().lineNumber,
(*i)->GetName().c_str());
fprintf(stderr, "%s:%d: previous definition of '%s'\n",
prev->GetLocation().fileName.c_str(),
prev->GetLocation().lineNumber,
prev->GetName().c_str());
}
else if ((*prev->GetType()) != (*(*i)->GetType()))
{
parser.Error();
fprintf(stderr, "%s:%d: error: variable '%s' incompatible with previous definition\n",
(*i)->GetLocation().fileName.c_str(),
(*i)->GetLocation().lineNumber,
(*i)->GetName().c_str());
fprintf(stderr, "%s:%d: previous definition of '%s'\n",
prev->GetLocation().fileName.c_str(),
prev->GetLocation().lineNumber,
prev->GetName().c_str());
}
// Replace old external references with this definition
for (vector< Ref<Function> >::iterator j = m_functions.begin();
j != m_functions.end(); j++)
(*j)->ReplaceVariable(prev, *i);
m_initExpression->ReplaceVariable(prev, *i);
}
// Add definition to variable list
m_variables.push_back(*i);
m_variablesByName[(*i)->GetName()] = *i;
}
}
if (parser.HasErrors())
return false;
return true;
}
bool Linker::OutputLibrary(OutputBlock* output)
{
// Serialize precompiled header state
m_precompiledPreprocess.Serialize(output);
m_precompileState.Serialize(output);
// Serialize function objects
output->WriteInteger(m_functions.size());
for (vector< Ref<Function> >::iterator i = m_functions.begin(); i != m_functions.end(); i++)
(*i)->Serialize(output);
// Serialize variable objects
output->WriteInteger(m_variables.size());
for (vector< Ref<Variable> >::iterator i = m_variables.begin(); i != m_variables.end(); i++)
(*i)->Serialize(output);
// Serialize function name map
output->WriteInteger(m_functionsByName.size());
for (map< string, Ref<Function> >::iterator i = m_functionsByName.begin(); i != m_functionsByName.end(); i++)
{
output->WriteString(i->first);
i->second->Serialize(output);
}
// Serialize variable name map
output->WriteInteger(m_variablesByName.size());
for (map< string, Ref<Variable> >::iterator i = m_variablesByName.begin(); i != m_variablesByName.end(); i++)
{
output->WriteString(i->first);
i->second->Serialize(output);
}
// Serialize initialization expression
m_initExpression->Serialize(output);
return true;
}
uint32_t Linker::GetCaseInsensitiveNameHash(const std::string& name)
{
uint32_t hash = 0;
for (size_t i = 0; i < name.size(); i++)
{
hash = (hash >> 13) | (hash << 19);
if (name[i] >= 'a')
hash += name[i] - 0x20;
else
hash += name[i];
}
return hash;
}
uint32_t Linker::GetNameHash(const std::string& name)
{
uint32_t hash = 0;
for (size_t i = 0; i < name.size(); i++)
{
hash = (hash >> 13) | (hash << 19);