This repository has been archived by the owner on Jun 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
magic.dee
1516 lines (1450 loc) · 45 KB
/
magic.dee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2017 Griefer@Work *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
*/
/* Target configuration */
#ifndef CONFIG_TARGET_NAME
#if defined(TARGET_ARM)
# define CONFIG_TOOLCHAIN "arm-none-eabi"
# define CONFIG_TARGET_ARCH "arm-kos"
//# define CONFIG_QEMU_FLAGS "-M","integratorcp","-cpu","cortex-a15"
//# define CONFIG_QEMU_FLAGS "-M","vexpress-a15"
# define CONFIG_QEMU_FLAGS "-M","integratorcp"
#elif defined(TARGET_X86_64)
# define CONFIG_TARGET_ARCH "x86_64-kos"
# define CONFIG_TARGET_NAME "i386-kos"
#elif defined(TARGET)
# define __TARGET_PP_STR2(x) #x
# define __TARGET_PP_STR(x) __TARGET_PP_STR2(x)
# define CONFIG_TARGET_ARCH __TARGET_PP_STR(TARGET)
#else
# define TARGET_I386 1
# define CONFIG_TARGET_ARCH "i386-kos"
# define CONFIG_TOOLCHAIN "x86_64-kos"
# define CONFIG_GCC_LIBPATH "/binutils/build-binutils-" CONFIG_TOOLCHAIN "/lib/gcc/" CONFIG_TOOLCHAIN "/6.2.0/32"
#endif
#endif /* !CONFIG_TARGET_NAME */
#ifndef CONFIG_TARGET_NAME
# define CONFIG_TARGET_NAME CONFIG_TARGET_ARCH
#endif /* !CONFIG_TARGET_NAME */
#ifndef CONFIG_TOOLCHAIN
# define CONFIG_TOOLCHAIN CONFIG_TARGET_ARCH
#endif /* !CONFIG_TOOLCHAIN */
#ifndef CONFIG_GCC_LIBPATH
# define CONFIG_GCC_LIBPATH "/binutils/build-binutils-" CONFIG_TOOLCHAIN "/lib/gcc/" CONFIG_TOOLCHAIN "/6.2.0"
#endif /* !CONFIG_GCC_LIBPATH */
#define CONFIG_APP_PATH "/bin/apps/" CONFIG_TARGET_ARCH
#define CONFIG_LIB_PATH "/bin/libs/" CONFIG_TARGET_ARCH
#define CONFIG_MOD_PATH "/bin/mods/" CONFIG_TARGET_ARCH
/* Compiler configuration */
local config_format_compiler_messages = false; /* Format GCC warning/error messages to MSVC format. */
local config_generate_preprocessor = false; /* Generate preprocessor output instead of object files. */
local config_generate_assembly = false; /* Generate assembly instead of object files. */
local config_compile_single = <false>; /* Only run one compiler at a time. */
local config_force_rebuild = <false>; /* Force a full recompilation. */
local config_force_disk = <false>; /* Force a full disk rebuild. */
local config_force_usb = false; /* Force a full USB rebuild. */
local config_build_only = false; /* Don't start emulation once compilation is done. */
local config_debug = true; /* Enable compiling with debug information. */
local config_optimize = none; /* Otherwise: A string "0", "1", etc... */
local config_max_compilers = 8; /* Max amount of compilers to run in parallel */
local config_build_path = "build/" CONFIG_TARGET_ARCH;
local config_usbdisk = <none>; /* Uncomment this if you have an H: drive, or simply don't wish to use a USB stick for testing on real hardware. */
/* Compiler script options. */
local config_verbose = false;
/* Disk configuration */
local config_disk_image = "disk/" CONFIG_TARGET_ARCH ".img"; /* Output path of the disk image. */
#ifdef TARGET_X86_64
local config_disk_size = 64*1024*1024; /* 64Mib */
#else
local config_disk_size = 32*1024*1024; /* 32Mib */
#endif
/* Runtime/Emulation configuration */
local run_mode_bochs = false; /* Use BOCHS as emulator. */
local run_mode_run_only = false; /* Skip compilation and only run the emulator. */
local run_bochs_binary = "bochs"; /* If existing & older, copy generated kernel binary here. */
local run_qemu_binary = "qemu-system-"+CONFIG_TARGET_ARCH.partition("-")[0];
local run_mode_remote = false; /* --remote */
local run_mode_usb = false; /* --usb */
local run_mode_hosted = true; /* --hosted */
local run_kernel_flat = "bin/kernel-" CONFIG_TARGET_ARCH "-flat.bin";
local run_kernel_binary = "bin/kernel-" CONFIG_TARGET_ARCH ".bin"; /* Output name of the kernel binary. */
/* Executable used for '#!$addr2line' formating of serial emulator output. */
local run_addr2line_exe = run_kernel_binary;
local run_addr2line_base = 0;
/* Default executable names. */
local const default_mtools = "mtools";
#ifdef __WINDOWS__
# define EXE(x) x ".exe"
#else
# define EXE(x) x
#endif
/* Paths to used executables */
local executables = dict {
"mtools" : EXE("binutils/build-mtools/mtools"),
"asm" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-gcc"),
"c" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-gcc"),
"c++" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-g++"),
"cpp" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-cpp"),
"ar" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-ar"),
"ld" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-ld"),
"nm" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-nm"),
"addr2line" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-addr2line"),
"readelf" : EXE("binutils/build-binutils-" CONFIG_TOOLCHAIN "/bin/" CONFIG_TOOLCHAIN "-readelf"),
"host-asm" : EXE("gcc"),
"host-c" : EXE("gcc"),
"host-c++" : EXE("g++"),
"host-cpp" : EXE("cpp"),
"host-ar" : EXE("ar"),
"host-ld" : EXE("ld"),
"host-nm" : EXE("nm"),
"host-addr2line" : EXE("addr2line"),
"host-readelf" : EXE("readelf"),
"bochs" : EXE("bochs"),
"bochsdbg" : EXE("bochsdbg"),
"qemu-system-i386" : EXE("qemu-system-i386"),
"qemu-system-x86_64" : EXE("qemu-system-x86_64"),
"qemu-system-arm" : EXE("qemu-system-arm"),
};
#include <file>
#include <fs>
#include <util>
#include <process>
#include <thread>
#include <time>
#include <pipe>
#include <sys>
#include <error>
#include <time>
local root_folder = fs::path::head(__FILE__).replace("\\","/").rstrip("/");
if (run_qemu_binary == "qemu-system-i686")
run_qemu_binary = "qemu-system-i386";
#if __has_include("misc/paths.dee")
#include "misc/paths.dee"
#endif
#ifdef __WINDOWS__
function fix_path(rel_prefix,filename) {
if (filename.startswith("/cygdrive/")) {
filename = filename[#"/cygdrive/":];
local drive,none,path = filename.partition("/")...;
filename = drive.upper()+":/"+path;
if (filename.lower().startswith(root_folder.lower())) {
filename = rel_prefix+filename[#root_folder:].lstrip("/\\");
}
rel_prefix = "";
}
if (filename.startswith("binutils/root/")) {
local new_filename = filename[#"binutils/root/":];
if (new_filename.startswith("usr/lib/"))
filename = rel_prefix+"bin/libs/"+new_filename[#"usr/lib/":];
else if (new_filename.startswith("usr/"))
filename = rel_prefix+new_filename[#"usr/":];
else {
filename = rel_prefix+filename;
}
#ifdef CONFIG_CYGWIN_ROOT
} else if (filename.startswith("/")) {
filename = CONFIG_CYGWIN_ROOT+filename;
#endif /* CONFIG_CYGWIN_ROOT */
} else {
filename = rel_prefix+filename;
}
#ifdef __WINDOWS__
filename = filename.replace("/","\\");
#endif
return filename;
}
#endif /* __WINDOWS__ */
function fix_pathstring(path) {
local pos;
while ((pos = path.find("/..")) != -1) {
local end = path.rfind("/",0,pos);
if (end == -1) break;
path = path[:end]+path[pos+3:];
}
return path;
}
root_folder = fix_pathstring(root_folder);
fs::chdir(root_folder);
local kernel_args = sys.argv[1:];
while (kernel_args && kernel_args.front().startswith("-")) {
local arg = kernel_args.pop_front();
if (arg == "--cmd") break;
switch (arg) {
case "-f":
case "--force":
::config_force_rebuild.set(true);
break;
case "-fdisk":
case "--fdisk":
case "--force-disk":
::config_force_disk.set(true);
break;
case "-fusb":
case "--fusb":
case "--force-usb":
::config_force_usb = true;
break;
case "-b":
case "--build":
case "--build-only":
::config_build_only = true;
break;
case "-E":
case "--gen-pp":
::config_generate_preprocessor = true;
::config_build_only = true;
break;
case "-S":
case "--asm":
::config_generate_assembly = true;
::config_build_only = true;
break;
case "--format-error-messages":
::config_format_compiler_messages = true;
break;
case "--remote":
::run_mode_remote = true;
break;
case "--usb":
::run_mode_usb = true;
break;
case "-dbox":
case "--dbochs":
case "--bochs-debug":
::run_bochs_binary = "bochsdbg";
case "-box":
case "--bochs":
::run_mode_bochs = true;
break;
case "-qemu":
case "--qemu":
::run_mode_bochs = false;
break;
case "-r":
case "--run":
case "--run-only":
::run_mode_run_only = true;
break;
case "--hosted":
::run_mode_hosted = true;
break;
case "--optimize":
::config_optimize = "3";
case "--ndebug":
::config_debug = false;
break;
case "--single":
case "-1":
::config_compile_single.set(true);
break;
case "-v":
case "--verbose":
config_verbose = true;
break;
default:
if (arg.startswith("-O")) {
::config_optimize = arg[2:];
break;
}
print "Unknown argument:",repr arg;
break;
}
}
if (config_debug) {
config_build_path += "-debug";
}
#define SYNC(x) \
({ local _o = config_compile_single.get(); \
::config_compile_single.set(true); \
(x); \
::config_compile_single.set(_o); \
})
/* List of files that will/have changed since the
* last compilation, until the end of the current
* (Yes: This also contains files that will have changed later) */
local _mtime_cache = dict {};
local _mtime_change_year = 9999;
function set_file_changed(filename) {
#ifdef __WINDOWS__
filename = fs::path::abs(filename,root_folder).replace("/","\\");
#else
filename = fs::path::abs(filename,root_folder);
#endif
_mtime_cache[filename] = time.years(_mtime_change_year++);
}
function unset_file_changed(filename) {
#ifdef __WINDOWS__
filename = fs::path::abs(filename,root_folder).replace("/","\\");
#else
filename = fs::path::abs(filename,root_folder);
#endif
_mtime_cache[filename] = time(1);
}
function fast_getmtime(filename) {
local result;
#ifdef __WINDOWS__
filename = fs::path::abs(filename,root_folder).replace("/","\\");
try return _mtime_cache[filename]; catch (...);
try result = fs::getmtime(filename);
catch (...) result = fs::getmtime(filename+".exe");
#else
filename = fs::path::abs(filename,root_folder);
try return _mtime_cache[filename]; catch (...);
result = fs::getmtime(filename);
#endif
_mtime_cache[filename] = result;
return result;
}
local existing_paths = [];
function fast_mkdir(path) {
path = fs::path::abs(path,root_folder);
if (path !in existing_paths) {
existing_paths.append(path);
try fs::mkdir(path);
catch (...);
}
}
function force_mkdir(path) {
path = fs::path::exctrail(path);
local head = fs::path::head(path);
local tail = fs::path::tail(path);
if (head && !fs::exists(head)) force_mkdir(head);
try fast_mkdir(path); catch (...);
}
local print_lock = mutex();
local running_processes = [];
#define wait_all_processes() \
({ while (#running_processes) thread.sleep(1); })
#define SYNC_PRINT(...) \
({ print_lock.acquire(); \
try {\
print __VA_ARGS__; \
} finally {\
print_lock.release(); \
}\
})
function do_start_process(proc) {
if (config_verbose) {
print "PROCESS:",proc.exe," ".join(proc.argv);
}
proc.start();
}
function get_exe(name) {
if (name.startswith("/")) {
return root_folder+name;
}
if ("/" in name || "\\" in name) {
return name;
}
if (name.startswith("PATH:")) {
return name[#"PATH:":];
}
return executables[name];
}
function mtools(fun,args) {
local proc = process(executables[default_mtools],[
"-c",fun,"-i",config_disk_image,args...
]);
do_start_process(proc);
return proc.join() == 0;
}
function disk_mkdir(path) {
mtools("mmd",["-D","s","::"+path]);
}
local disk_existing_paths = [];
function disk_fast_mkdir(path) {
path = path.strip().rstrip("/");
if (path !in disk_existing_paths) {
disk_existing_paths.append(path);
try disk_mkdir(path);
catch (...);
}
}
function disk_force_mkdir(path) {
path = fs::path::exctrail(path);
local head = fs::path::head(path);
local tail = fs::path::tail(path);
if (head != "/") disk_force_mkdir(head);
try disk_fast_mkdir(path); catch (...);
}
function start_io_process(proc,process_callback) {
local process_out_read,process_out_write = pipe.new()...;
proc.stdout = process_out_write;
//proc.stderr = process_out_write;
do_start_process(proc);
process_out_write.close();
while (#running_processes > config_max_compilers) thread.sleep(1);
running_processes.append(proc);
local t = thread([]{
try {
process_callback(process_out_read);
local error = proc.join();
/* remove may fail sporadically in an SMP environment... (sorry about that) */
while (!running_processes.remove(proc));
if (error != 0) {
print "Process failed:",repr proc.cmd;
sys.exit(error);
}
} catch (e...) {
print "Process failed:",e;
print repr proc.cmd;
sys.exit(1);
}
});
t.start();
if (::config_compile_single.get()) t.join();
}
function fix_binutils(filename) {
local start = filename.rfind("/binutils/");
if (start != -1) {
filename = fix_pathstring(filename[start:]);
filename = "${ROOT}"+filename;
}
return filename;
}
function start_process(proc,proj) {
local compiler_out_read,compiler_out_write = none...;
if (config_format_compiler_messages) {
compiler_out_read,compiler_out_write = pipe.new()...;
proc.stdout = compiler_out_write;
proc.stderr = compiler_out_write;
}
do_start_process(proc);
compiler_out_write.close();
while (#running_processes > config_max_compilers) thread.sleep(1);
running_processes.append(proc);
local t = thread([]{
try {
if (config_format_compiler_messages) {
for (local line: compiler_out_read) {
local filename,lno,col,rest;
try {
filename,lno,col,rest = line.scanf("%[^:]:%[^:]:%[^:]:%[^]")...;
if (filename.endswith("/ld") || filename.endswith("-ld")) {
rest = "{} ({})".format({ rest.strip(),repr fix_binutils(filename.strip()) });
filename = lno;
lno = col;
col = none;
}
#ifdef __WINDOWS__
if (lno.startswith("/cygdrive/")) {
local a,none,b = lno[#"/cygdrive/":].partition("/")...;
SYNC_PRINT("{}:\\{}({}) : error : <{}> : {} ({})".format({
a.upper(),b.replace("/","\\"),col,proj._name,
rest,filename
}));
continue;
}
#endif
} catch (...) try {
filename,lno,rest = line.scanf("%[^:]:%[^:]:%[^]")...;
col = none;
} catch (...) try {
filename,lno,rest = line.scanf("%[^:]:%[^,]%[^]")...;
col = none;
} catch (...) {
SYNC_PRINT(line,);
continue;
}
if (!lno.isdigit()) {
if (filename.endswith("/ld") || filename.endswith("-ld")) {
rest = "{} ({})".format({ rest.strip(),repr fix_binutils(filename.strip()) });
filename = lno;
lno = "0";
if (" " in filename && "/" !in filename) {
rest = filename.strip()+": "+rest.strip();
filename = proj._outfile;
}
} else {
SYNC_PRINT(line,);
continue;
}
}
filename = filename.strip();
rest = rest.strip();
local const inc_prefix = "In file included from ";
local const frm_prefix = "from ";
if (filename.startswith(inc_prefix)) {
rest = "warning : "+inc_prefix+"here "+rest;
filename = filename[#inc_prefix:];
}
if (filename.startswith(frm_prefix)) {
rest = "warning : "+inc_prefix+"here "+rest;
filename = filename[#frm_prefix:];
}
#ifdef __WINDOWS__
filename = fix_path("../../",filename);
#endif /* __WINDOWS__ */
local msg_class = "warning";
if (col && !col.isdigit()) {
rest = col.strip()+" : "+rest.strip();
col = "";
}
if (rest.startswith("note")) {
rest = rest[#"note":];
} else if (rest.startswith("warning")) {
rest = rest[#"warning":];
} else if (rest.startswith("error")) {
rest = rest[#"error":];
msg_class = "error";
} else {
if (rest.startswith("multiple definition of"))
msg_class = "error";
}
rest = rest.strip(" :\t\r\n");
if (col) {
SYNC_PRINT("{}({},{}) : {} : <{}> : {}".format({
filename,lno,col,msg_class,proj._name,rest
}));
} else {
SYNC_PRINT("{}({}) : {} : <{}> : {}".format({
filename,lno,msg_class,proj._name,rest
}));
}
}
}
local error = proc.join();
/* remove may fail sporadically in an SMP environment... (sorry about that) */
while (!running_processes.remove(proc));
if (error != 0) {
print "Process failed:",repr proc.cmd;
sys.exit(error);
}
} catch (e...) {
print "Process failed:",e;
print repr proc.cmd;
sys.exit(1);
}
});
t.start();
if (::config_compile_single.get()) t.join();
}
class Source {
this(p_exe,p_flags,c_flags,file) {
/* NOTE: For 'justsym'-style sources, '_exe_p' is the 'nm' executable. */
this._exe_p = p_exe;
this._p_flags = copy p_flags;
this._c_flags = copy c_flags;
this._file = file;
this._changed = false;
}
get_dep_file(proj) -> config_build_path+"/"+proj._name+"/"+this._file.replace("/",".")+".mf";
get_pp_file(proj) -> config_build_path+"/"+proj._name+"/"+this._file.replace("/",".")+".E";
get_asm_file(proj) -> config_build_path+"/"+proj._name+"/"+this._file.replace("/",".")+".S";
get_sym_file(proj) -> config_build_path+"/"+proj._name+"/"+this._file.replace("/",".")+".nm";
get_o_file(proj) -> config_build_path+"/"+proj._name+"/"+this._file.replace("/",".")+".o";
get_obj_file(proj) {
if (config_generate_assembly) {
return this.get_asm_file(proj);
} else if (config_generate_preprocessor) {
return this.get_pp_file(proj);
} else {
return this.get_o_file(proj);
}
}
get_dep(proj) {
local text = file.open(this.get_dep_file(proj),"r").read();
text = text.replace("\r\n","\n").replace("\r","\n");
text = text.replace("\\\n","").replace("\n"," ");
text = text.partition(":")[2];
for (local part: text.split(" ")) {
if (part) {
#ifdef __WINDOWS__
part = fix_path("",part);
#endif /* __WINDOWS__ */
yield part;
}
}
}
must_perform_action(proj,output_file) {
if (::config_force_rebuild.get()) return true;
try {
local mtime = fast_getmtime(output_file);
for (local d: this.get_dep(proj)) {
if (fast_getmtime(d) > mtime) {
return true;
}
}
} catch (...) {
return true;
}
return false;
}
must_perform_action_nodep(proj,output_file) {
if (::config_force_rebuild.get()) return true;
try {
if (fast_getmtime(this._file) >
fast_getmtime(output_file))
return true;
} catch (...) {
return true;
}
return false;
}
must_compile(proj) -> this.must_perform_action(proj,this.get_obj_file(proj));
must_preprocess(proj) -> this.must_perform_action(proj,this.get_pp_file(proj));
must_justsym(proj) -> this.must_perform_action_nodep(proj,this.get_sym_file(proj));
unset_changes(proj) {
unset_file_changed(this._file);
try {
for (local d: this.get_dep(proj)) {
unset_file_changed(d);
}
} catch (...) {
}
}
compile(proj) {
SYNC_PRINT("["+proj.logname()+"] Compiling",repr this._file);
local objfile = this.get_obj_file(proj);
local depfile = this.get_dep_file(proj);
local compiler_args = ["-o",objfile,"-MD","-MF",depfile];
force_mkdir(fs::path::head(objfile));
if (this._exe_p !is none) {
/* TODO: Pass input through custom preprocessor. */
} else {
compiler_args.extend(this._p_flags);
}
compiler_args.extend(this._c_flags);
if (config_optimize !is none) {
compiler_args.append("-O"+config_optimize);
}
if (config_generate_assembly) {
compiler_args.append("-S");
} else if (config_generate_preprocessor) {
compiler_args.append("-E");
} else {
compiler_args.append("-c");
}
compiler_args.append(this._file);
local proc = process(get_exe(proj._exe_c),compiler_args);
start_process(proc,proj);
this.unset_changes(proj);
}
preprocess(proj) {
SYNC_PRINT("["+proj.logname()+"] Proprocessing",repr this._file);
local ppfile = this.get_pp_file(proj);
local depfile = this.get_dep_file(proj);
local pp_args = ["-E","-o",ppfile,"-MMD","-MF",depfile];
force_mkdir(fs::path::head(ppfile));
local used_pp = this._exe_p;
if (used_pp is none) used_pp = proj._exe_cpp;
pp_args.extend(this._p_flags);
pp_args.append(this._file);
local proc = process(get_exe(used_pp),pp_args);
start_process(proc,proj);
this.unset_changes(proj);
}
justsym(proj) {
SYNC_PRINT("["+proj.logname()+"] Creating symbol list for",repr this._file);
local nmfile = this.get_sym_file(proj);
local nm_args = ["-g",this._file];
force_mkdir(fs::path::head(nmfile));
nm_args.extend(this._p_flags);
local proc = process(get_exe(this._exe_p),nm_args);
start_io_process(proc,[](process_pipe){
local output = file.open(nmfile,"w");
for (local line: process_pipe) {
local addr,name;
try addr,none,name = line.scanf("%[^ ] %[^ ] %[^]")...;
catch (...) {
print "Unrecognized NM line:",repr line;
continue;
}
output.write("PROVIDE({} = 0x{});\n".format({
name.strip(),addr
}));
}
output.close();
});
}
};
local projects = [];
function files(text,def_file) {
if (text is list) {
for (local e: text)
yield files(e,def_file);
} else {
if (text && text.startswith("/")) {
text = text[1:];
} else {
text = fs::path::rel(fs::path::abs(text,
fs::path::head(def_file)),
root_folder);
}
text = text.replace("\\","/");
if ("*" in text) {
local head = fs::path::head(text);
try {
for (local q: fs::query(text)) {
yield head+q;
}
} catch (...) {
}
} else {
yield text;
}
}
}
class Project {
this(name) {
this._name = name;
this._sources = []; /* Array of 'Source' objects. */
this._l_flags = []; /* Linker flags. */
this._l_deps = []; /* Shared library dependencies. */
this._l_requires = []; /* Additional files who's absense requires a relink. */
this._l_objs = []; /* Additional object files. */
this._l_script = []; /* Linker script used ('Source' file). */
this._l_jstsym = []; /* Static link descriptors for '--just-symbols=...'. */
this._outfile = "bin/"+name; /* Binary output path. */
this._dskfile = "bin/"+name; /* Disk output path (or none if not put on disk) */
this._exe_c = "c"; /* Used compiler. */
this._exe_cpp = "cpp"; /* Used preprocessor. */
this._exe_a = none; /* Archiver executable (when 'none', do linking with '_exe_l'). */
this._exe_l = "ld"; /* Used linker. */
this._cus_link = none; /* Custom linker commandline. ("ld -o {output} {objects}") */
this._exe_nm = "nm"; /* Used linker. */
this._modes = []; /* Active user-modes. */
this._relink = false; /* Set to true if the project must be re-linked. */
this._created = false; /* Set to true when the project was been linked. */
this._deps = []; /* Dependencies on other projects */
::projects.append(this);
}
logname() {
return "{} ({})".format({ this._name, this._outfile });
}
add_source(p_exe,p_flags,c_flags,fps) {
for (local f: fps) {
this._sources.append(Source(p_exe,p_flags,c_flags,f));
}
}
add_linker_scripts(p_exe,p_flags,c_flags,filename) {
for (local f: filename) {
this._l_script.append(Source(p_exe,p_flags,c_flags,f));
}
}
add_justsyms(filename) {
for (local f: filename) {
this._l_jstsym.append(Source(this._exe_nm,[],[],f));
}
}
will_relink() {
if (!this._relink) {
set_file_changed(this._outfile);
this._relink = true;
return true;
}
return false;
}
reset_changes() {
this._relink = false;
for (local src: this._sources) src._changed = false;
for (local src: this._l_jstsym) src._changed = false;
for (local src: this._l_script) src._changed = false;
}
determine_changes() {
local result = false;
for (local src: this._sources) {
if (src.must_compile(this)) {
src._changed = true;
set_file_changed(src.get_obj_file(this));
set_file_changed(src.get_dep_file(this));
if (this.will_relink()) result = true;
}
}
for (local src: this._l_jstsym) {
if (src.must_justsym(this)) {
src._changed = true;
set_file_changed(src.get_sym_file(this));
if (this.will_relink()) result = true;
}
}
for (local script: this._l_script) {
if (script.must_preprocess(this)) {
/* Make sure not to generate line directives */
script._changed = true;
set_file_changed(script.get_pp_file(this));
set_file_changed(script.get_dep_file(this));
if (this.will_relink()) result = true;
}
}
if (result) return true;
/* Checked for changes in additional object files. */
try {
for (local s: this._l_requires) fast_getmtime(s);
local out_time = fast_getmtime(this._outfile);
for (local s: this._l_objs) {
if (out_time < fast_getmtime(s)) {
return this.will_relink();
}
}
} catch (...) {
return this.will_relink();
}
return false;
}
compile_changes() {
for (local src: this._sources) {
if (src._changed) {
src.compile(this);
}
}
for (local script: this._l_script) {
if (script._changed) {
/* Make sure not to generate line directives */
script._p_flags.remove("-P");
script._p_flags.append("-P");
script._p_flags.remove("-D__LINKER__");
script._p_flags.append("-D__LINKER__");
script.preprocess(this);
this.will_relink();
}
}
}
relink() {
if (!::config_generate_preprocessor &&
!::config_generate_assembly) {
local source_objects = [];
for (local s: this._sources) {
source_objects.append(s.get_obj_file(this));
}
source_objects.extend(this._l_objs);
force_mkdir(fs::path::head(this._outfile));
if (this._exe_a !is none) {
SYNC_PRINT("["+this.logname()+"] Archiving",repr this._outfile);
if (this._exe_a == "" && #source_objects == 1) {
try fs::unlink(this._outfile);
catch (...);
fs::copy_(fs::path::abs(source_objects[0],root_folder),
fs::path::abs(this._outfile,root_folder));
} else {
local archive_flags = [];
archive_flags.extend(this._l_flags);
archive_flags.append("rcs",this._outfile);
archive_flags.extend(source_objects);
local proc = process(get_exe(this._exe_a),archive_flags);
start_process(proc,this);
}
} else {
SYNC_PRINT("["+this.logname()+"] Linking",repr this._outfile);
local linker_flags = ["-o",this._outfile];
if (config_optimize !is none) {
linker_flags.append("-O"+config_optimize);
}
for (local src: this._l_jstsym) {
if (src._changed) {
SYNC(src.justsym(this));
}
}
for (local script: this._l_jstsym) {
linker_flags.append("--just-symbols="+script.get_sym_file(this));
}
for (local script: this._l_script) {
linker_flags.append("-T",script.get_pp_file(this));
}
linker_flags.extend(this._l_flags);
#ifdef TARGET_I386 /* TODO: Dirty hack */
if (this._exe_l.endswith("c")) {
linker_flags.append("-m32");
} else {
linker_flags.append("-m","elf_i386");
}
#endif
linker_flags.extend(source_objects);
/* Make sure that '-lgcc' goes at the end. */
if ("gcc" in this._l_deps) {
this._l_deps.remove("gcc");
this._l_deps.append("gcc");
}
for (local lib: this._l_deps)
linker_flags.append("-l"+lib);
//print repr linker_flags;
local proc = process(get_exe(this._exe_l),linker_flags);
if (this._cus_link !is none) {
SYNC(start_process(proc,this));
if (this._cus_link is string) {
local custom_proc = process(this._cus_link.format({
.input = this._outfile,
.root = root_folder,
}));
start_process(custom_proc,this);
} else {
this._cus_link(this._outfile);
}
} else {
start_process(proc,this);
}
}
}
this._created = true;
}
must_update_disk() {
if (this._dskfile is none) return false;
if (this._created || ::config_force_disk.get()) return true;
try {
if (fast_getmtime(this._outfile) > fast_getmtime(config_disk_image))
return true;
} catch (...) {
return true;
}
return false;
}
usb_outfile() {
#ifdef __WINDOWS__
return fs::path::join(config_usbdisk.get(),this._dskfile.replace("/","\\"));
#else
return fs::path::join(config_usbdisk.get(),this._dskfile);
#endif
}
must_update_usb() {
if (this._dskfile is none) return false;
if (this._created || ::config_force_usb) return true;
try {
if (fast_getmtime(this._outfile) > fast_getmtime(this.usb_outfile()))
return true;
} catch (...) {
return true;
}
return false;
}
update_disk() {
if (::config_generate_preprocessor) return;
if (::config_generate_assembly) return;
local output_file = this._dskfile;
SYNC_PRINT("["+this.logname()+"] Updating disk",repr output_file);
disk_force_mkdir(fs::path::head(output_file));
mtools("mcopy",["-D","o",this._outfile,"::"+output_file]);
}
update_usb() {
if (::config_generate_preprocessor) return;
if (::config_generate_assembly) return;
local output_file = this.usb_outfile();
SYNC_PRINT("["+this.logname()+"] Updating USB",repr output_file);
force_mkdir(fs::path::head(output_file));
try fs::unlink(output_file); catch (...);
fs::copy_(fs::path::abs(this._outfile,root_folder),output_file);
}
};
function must_update_flat_kernel() {
try {
if (fast_getmtime(run_kernel_binary) > fast_getmtime(run_kernel_flat)) {
return true;
}
} catch (...) {
return true;
}
return false;
}
//function update_flat_kernel() {
// if (::config_generate_preprocessor) return;
// if (::config_generate_assembly) return;
// if (must_update_flat_kernel()) {
// print "Updating flat kernel image";
// local update = process("bin/apps/elfimg");
// update.stdin = file.open(run_kernel_binary,"r");
// update.stdout = file.open(run_kernel_flat,"w");
// update.start();
// update.join();
// }
//}