-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathbuild.c
More file actions
1930 lines (1927 loc) · 53.3 KB
/
build.c
File metadata and controls
1930 lines (1927 loc) · 53.3 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
// SPDX-License-Identifier: MIT
/*
*
* This file is part of ruri, with ABSOLUTELY NO WARRANTY.
*
* MIT License
*
* Copyright (c) 2025 Moe-hacker
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
//
// This program is a new build system for ruri
// It does not depend on any external build system.
// And it's independent of existing configure.ac and CMakeLists.txt
// I just want to show you that, we can do it, and it works fine.
//
// ANYWAY, IT IS A BIG STEP BACKWARDS THE HISTORY OF COMPUTER SCIENCE!!!
//
// This program has Super Neko Powers
//
// Damn bro, it's only for Linux
#ifndef __linux__
#error "This code is only for Linux"
#endif
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <limits.h>
#include <dirent.h>
#include <sys/time.h>
#include <float.h>
#include <linux/limits.h>
#include <sys/prctl.h>
#include <signal.h>
#include <sched.h>
#include <syscall.h>
#if __STDC_VERSION__ < 202000L
#ifndef bool
#define bool _Bool
#define true ((_Bool) + 1u)
#define false ((_Bool) + 0u)
#endif
#endif
#define ERROR_NUM 114
/////////////////////
///////catsh.h///////
/////////////////////
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <poll.h>
#include <sys/stat.h>
#include <stdint.h>
#include <fcntl.h>
#define cth_debug(x) \
do { \
x \
} while (0)
#define cth_log(format, ...) \
{ \
struct timeval tv; \
gettimeofday(&tv, NULL); \
fprintf(stderr, "[%ld.%06ld] in %s() in %s line %d:\n", tv.tv_sec, tv.tv_usec, __func__, __FILE__, __LINE__); \
fprintf(stderr, format, ##__VA_ARGS__); \
}
#define CTH_EXIT_FAILURE 114
#define CTH_EXIT_SUCCESS 0
#define CTH_VERSION_MAJOR 0
#define CTH_VERSION_MINOR 6
#define CTH_VERSION_PATCH 1
#define CTH_VERSION_STRING "0.6.1"
struct __attribute__((packed, aligned(1))) cth_result {
uint32_t cth_version;
size_t struct_size;
bool exited;
int exit_code;
char *stdout_ret;
char *stderr_ret;
pid_t pid;
pid_t ppid;
useconds_t time_used;
uint8_t reserved[256];
};
#define CTH_VERSION ((CTH_VERSION_MAJOR << 16) | (CTH_VERSION_MINOR << 8) | (CTH_VERSION_PATCH))
#define CTH_ABI_COMPATIBLE(res) ((res) != NULL && (res)->cth_version <= CTH_VERSION && (res)->struct_size == sizeof(struct cth_result))
int cth_add_arg(char ***argv, char *arg);
void cth_free_argv(char ***argv);
void cth_free_result(struct cth_result **res);
struct cth_result *cth_exec(char **argv, char *input, bool block, bool get_output);
int cth_fork_rexec_self(char *const argv[]);
int cth_exec_command(char **argv);
// TODO: non-blocking exec
int cth_wait(struct cth_result **res);
void *cth_init_argv(void);
struct cth_result *cth_exec_with_file_input(char **argv, int fd, bool block, bool get_output, void (*progress)(float, int), int progress_line_num);
void cth_show_progress(float progress, int line_num);
#define CTH_EXEC_SUCCEED(res) ((res) != NULL && (res)->exited && ((res)->exit_code == 0))
#define CTH_EXEC_FAILED(res) ((res) != NULL && (res)->exited && ((res)->exit_code != 0))
#define CTH_EXEC_RUNNING(res) ((res) != NULL && !(res)->exited)
#define CTH_EXEC_CANNOT_RUN(res) ((res) == NULL)
/////////////////////
///////catsh.h///////
/////////////////////
#define error(...) \
{ \
fprintf(stderr, "Error in %s:%s%d: ", __FILE__, __FUNCTION__, __LINE__); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
on_exit__(SIGINT); \
exit(ERROR_NUM); \
}
void remove_test_dot_c(void);
void on_exit__(int sig)
{
printf("Exiting %d......\n", getpid());
while (waitpid(-1, NULL, WNOHANG) > 0)
;
remove_test_dot_c();
exit(ERROR_NUM);
}
int fork_exec(char **argv)
{
// Return -1 if failed to exec()
// Or return same as exec()ed program.
struct cth_result *result = cth_exec(argv, NULL, true, false);
int ret = -1;
ret=result ? result->exit_code : -1;
cth_free_result(&result);
return ret;
}
char *fork_execvp_get_stdout(char **argv)
{
/*
* Warning: free() after use.
* We will fork(2) and then execvp(3).
* And then we will get the stdout of the child process.
* Return the stdout of the child process.
* If failed, return NULL.
*/
struct cth_result *result = cth_exec(argv, NULL, true, true);
char *output = result->stdout_ret ? strdup(result->stdout_ret) : NULL;
cth_free_result(&result);
return output;
}
// Never mind, this is safe broooo
char **CFLAGS = NULL;
char **LIBS = NULL;
char *CC = "cc";
char *STRIP = "strip";
char *BUILD_DIR = "out";
char *SRC_DIR = NULL;
char **OBJS = NULL;
char *OUTPUT = NULL;
char *COMMIT_ID = NULL;
int JOBS = 8;
bool FORCE = false; // Force rebuild all files
// Not only args, but (char **) in fact.
void add_args(char ***argv, const char *arg)
{
if (*argv == NULL) {
*argv = malloc(2 * sizeof(char *));
if (!*argv) {
error("Error: Failed to allocate memory for args");
}
(*argv)[0] = strdup(arg);
if (!(*argv)[0]) {
free(*argv);
*argv = NULL;
error("Error: Failed to duplicate string for args");
}
(*argv)[1] = NULL;
} else {
size_t len = 0;
while ((*argv)[len] != NULL)
len++;
char **new_argv = realloc(*argv, (len + 2) * sizeof(char *));
if (!new_argv) {
error("Error: Failed to reallocate memory for args");
}
*argv = new_argv;
(*argv)[len] = strdup(arg);
if (!(*argv)[len]) {
error("Error: Failed to duplicate string for args");
}
(*argv)[len + 1] = NULL;
}
}
// Not only args, but (char **) in fact.
void free_args(char **arg)
{
for (int i = 0; arg && arg[i] != NULL; i++) {
free(arg[i]);
}
free(arg);
}
// For testing compile environment
void remove_test_dot_c(void)
{
remove("test.c");
unlink("test.c");
rmdir("test.c");
}
void create_test_dot_c(void)
{
remove_test_dot_c();
FILE *fp = fopen("test.c", "w");
if (!fp) {
error("Failed to create test.c");
}
fprintf(fp, "#include <stdio.h>\n");
fprintf(fp, "int main(void) {\n");
fprintf(fp, " printf(\"Hello, World!\\n\");\n");
fprintf(fp, " return 0;\n");
fprintf(fp, "}\n");
fclose(fp);
}
// Check if CC supports a specific C flag
bool check_c_flag(const char *flag)
{
create_test_dot_c();
char **args = NULL;
add_args(&args, CC);
for (int i = 0; CFLAGS && CFLAGS[i] != NULL; i++) {
add_args(&args, CFLAGS[i]);
}
add_args(&args, flag);
add_args(&args, "-o");
add_args(&args, "/dev/null");
add_args(&args, "test.c");
for (int i = 0; LIBS && LIBS[i] != NULL; i++) {
add_args(&args, LIBS[i]);
}
if (fork_exec(args) != 0) {
printf("Check for flag %s :failed\n", flag);
free_args(args);
return false;
}
free_args(args);
printf("Check for flag %s :success\n", flag);
return true;
}
// Check if we can use a specific library
bool check_lib(const char *lib)
{
create_test_dot_c();
char **args = NULL;
add_args(&args, CC);
for (int i = 0; CFLAGS && CFLAGS[i] != NULL; i++) {
add_args(&args, CFLAGS[i]);
}
add_args(&args, "-o");
add_args(&args, "/dev/null");
add_args(&args, "test.c");
for (int i = 0; LIBS && LIBS[i] != NULL; i++) {
add_args(&args, LIBS[i]);
}
add_args(&args, lib);
if (fork_exec(args) != 0) {
printf("Check for lib %s :failed\n", lib);
free_args(args);
return false;
}
free_args(args);
printf("Check for lib %s :success\n", lib);
return true;
}
// init
void init_env(void)
{
create_test_dot_c();
if (getenv("CC")) {
CC = getenv("CC");
}
if (getenv("STRIP")) {
STRIP = getenv("STRIP");
}
if (getenv("CFLAGS")) {
char *flags = strdup(getenv("CFLAGS"));
if (!flags) {
error("Error: Failed to duplicate CFLAGS string");
}
char *token = strtok(flags, " ");
while (token) {
add_args(&CFLAGS, token);
token = strtok(NULL, " ");
}
free(flags);
}
char **arg = NULL;
add_args(&arg, CC);
for (int i = 0; CFLAGS && CFLAGS[i] != NULL; i++) {
add_args(&arg, CFLAGS[i]);
}
add_args(&arg, "-o");
add_args(&arg, "/dev/null");
add_args(&arg, "test.c");
if (fork_exec(arg) != 0) {
error("Error: Compiler %s failed to compile %s\n", CC, "test.c");
exit(ERROR_NUM);
}
printf("CC: %s\n", CC);
free_args(arg);
char *commit_id = fork_execvp_get_stdout((char *[]){ "git", "rev-parse", "--short", "HEAD", NULL });
if (commit_id) {
if (commit_id[strlen(commit_id) - 1] == '\n') {
commit_id[strlen(commit_id) - 1] = '\0';
}
printf("Commit ID: %s\n", commit_id);
} else {
printf("Warning: failed to get commit ID\n");
}
COMMIT_ID = commit_id;
if (fork_exec((char *[]){ STRIP, "--version", NULL }) != 0) {
STRIP = NULL;
} else {
printf("STRIP: %s\n", STRIP);
}
}
// Switch to the build directory
void switch_to_build_dir(char *dir)
{
// Check for src dir
SRC_DIR = realpath("./src", NULL);
if (!SRC_DIR) {
error("Error: failed to resolve path for ./src\n");
}
char *basedir = realpath(".", NULL);
if (!basedir) {
error("Error: failed to resolve current directory path\n");
}
static char out[PATH_MAX];
sprintf(out, "%s/%s", basedir, "ruri");
OUTPUT = out;
free(basedir);
// Change to the build directory
mkdir(dir, 0755);
if (chdir(dir) != 0) {
error("Error: failed to change directory to %s\n", dir);
}
BUILD_DIR = realpath(".", NULL);
if (!BUILD_DIR) {
error("Error: failed to resolve build directory path\n");
}
}
// Get file name without path
char *basename_of(const char *path)
{
const char *name = strrchr(path, '/');
return name ? (char *)(name + 1) : (char *)path;
}
int copy_file(const char *src, const char *dest)
{
int src_fd = open(src, O_RDONLY);
if (src_fd < 0) {
perror("Error opening source file");
return -1;
}
int dest_fd = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd < 0) {
perror("Error opening destination file");
printf("%s\n", dest);
close(src_fd);
return -1;
}
struct stat st;
if (fstat(src_fd, &st) < 0) {
perror("Error getting source file size");
close(src_fd);
close(dest_fd);
return -1;
}
ssize_t result = syscall(SYS_sendfile, dest_fd, src_fd, NULL, st.st_size);
if (result < 0) {
perror("Error copying file with sendfile");
close(src_fd);
close(dest_fd);
return -1;
}
close(src_fd);
close(dest_fd);
return 0;
}
bool file_diff(char *file1, char *file2)
{
/*
* Check if two files are different.
* Return true if they are different, false if they are the same.
*/
int fd1 = open(file1, O_RDONLY);
if (fd1 < 0) {
perror("Error opening file1");
return true;
}
int fd2 = open(file2, O_RDONLY);
if (fd2 < 0) {
perror("Error opening file2");
close(fd1);
return true;
}
// Check file size.
struct stat st1, st2;
if (fstat(fd1, &st1) < 0 || fstat(fd2, &st2) < 0) {
close(fd1);
close(fd2);
return true;
}
if (st1.st_size != st2.st_size) {
close(fd1);
close(fd2);
return true;
}
char buf1[4096], buf2[4096];
ssize_t read1, read2;
while ((read1 = read(fd1, buf1, sizeof(buf1))) > 0 && (read2 = read(fd2, buf2, sizeof(buf2))) > 0) {
if (read1 != read2 || memcmp(buf1, buf2, read1) != 0) {
close(fd1);
close(fd2);
return true; // Files are different
}
}
close(fd1);
close(fd2);
return false; // Files are the same
}
char *gen_obj_name(const char *file)
{
/*
* Generate object file name from source file name.
* For example, if file is "src/main.c", it will return "main.o".
*/
char *base = strstr(file, SRC_DIR);
if (!base) {
error("Error: Failed to find source directory in file path");
}
base += strlen(SRC_DIR) + 1;
base = strdup(base);
for (int i = 0; i < strlen(base); i++) {
if (base[i] == '/') {
base[i] = '_';
}
}
static char obj_name[PATH_MAX];
sprintf(obj_name, "%s.o", base);
free(base);
return obj_name;
}
// Compile the specified source file to file.o
void compile(char *file)
{
char **args = NULL;
add_args(&args, CC);
for (int i = 0; CFLAGS && CFLAGS[i] != NULL; i++) {
add_args(&args, CFLAGS[i]);
}
add_args(&args, "-c");
add_args(&args, "-o");
char *output_file = gen_obj_name(file);
add_args(&args, output_file);
// Check if already compiled
char saved_source_file[PATH_MAX];
sprintf(saved_source_file, ".%s.c", output_file);
if (access(saved_source_file, F_OK) == 0 && access(output_file, F_OK) == 0) {
if (!file_diff(file, saved_source_file) && !FORCE) {
printf("Compile %s :skipped\n", file);
free_args(args);
return;
}
}
copy_file(file, saved_source_file);
// Compile
remove(output_file);
unlink(output_file);
rmdir(output_file);
add_args(&args, file);
struct cth_result *exec_result = cth_exec(args, NULL, true, true);
if (!exec_result) {
error("Error: failed to execute compiler for %s\n", file);
} else if (!exec_result->exited || exec_result->exit_code != 0) {
error("Error: failed to compile %s\nCompiler output:\nstderr:\n%s\nstdout:\n%s\n", file, exec_result->stderr_ret ? exec_result->stderr_ret : "No output", exec_result->stdout_ret ? exec_result->stdout_ret : "No output");
}
free_args(args);
printf("Compile %s :success\n", file);
}
int pmcrts(const char *s1, const char *s2)
{
/*
*
* Compare two strings, but s2 is in the end of s1.
* Return the same value as strcmp() s2 and the end of s1.
* If s1 is shorter than s2, it will return -1.
*
*/
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
if (len1 < len2) {
return -1; // s1 is shorter than s2
}
return strcmp(s2, s1 + len1 - len2);
}
// Find files in a directory
char **find_file(char *dir, const char *end_match, char **blacklist)
{
DIR *d = opendir(dir);
if (!d) {
return NULL;
}
struct dirent *entry;
char **files = NULL;
while ((entry = readdir(d)) != NULL) {
if (entry->d_type == DT_REG && pmcrts(entry->d_name, end_match) == 0) {
bool skip = false;
for (int i = 0; blacklist && blacklist[i] != NULL; i++) {
if (pmcrts(entry->d_name, blacklist[i]) == 0) {
skip = true;
break;
}
}
if (!skip) {
char relative_path[PATH_MAX];
sprintf(relative_path, "%s/%s", dir, entry->d_name);
char *absolute_path = realpath(relative_path, NULL);
if (!absolute_path) {
perror("Error resolving absolute path");
continue;
}
add_args(&files, absolute_path);
free(absolute_path);
}
}
}
closedir(d);
return files;
}
// Compile source files in parallel
void compile_files_parallel(char **files, int max_processes)
{
if (!files)
return;
int file_count = 0;
while (files[file_count] != NULL)
file_count++;
if (file_count == 0)
return;
int active_processes = 0;
int completed = 0;
int current_file = 0;
while (completed < file_count) {
// Start new processes up to the limit
while (active_processes < max_processes && current_file < file_count) {
pid_t pid = fork();
if (pid == 0) {
// Child process - compile one file
compile(files[current_file]);
exit(EXIT_SUCCESS);
} else if (pid > 0) {
// Parent process
active_processes++;
current_file++;
} else {
error("Error: failed to fork process for %s\n", files[current_file]);
}
}
// Wait for at least one child to complete
if (active_processes > 0) {
int status;
pid_t finished_pid = wait(&status);
if (finished_pid > 0) {
active_processes--;
completed++;
if (WEXITSTATUS(status) != 0) {
error("Error: compilation failed in child process\n");
}
}
}
}
// Wait for any remaining processes
while (active_processes > 0) {
int status;
wait(&status);
active_processes--;
if (WEXITSTATUS(status) != 0) {
error("Error: compilation failed in child process\n");
}
}
// Add compiled object files to OBJS
for (int i = 0; i < file_count; i++) {
char *obj_file = gen_obj_name(files[i]);
add_args(&OBJS, obj_file);
}
}
// Build
void build()
{
// compile src/*.c and src/easteregg/*.c
char **files = find_file(SRC_DIR, ".c", NULL);
char easteregg_src[PATH_MAX];
sprintf(easteregg_src, "%s/easteregg", SRC_DIR);
char **easteregg_files = find_file(easteregg_src, ".c", NULL);
for (int i = 0; easteregg_files && easteregg_files[i] != NULL; i++) {
add_args(&files, easteregg_files[i]);
}
compile_files_parallel(files, JOBS);
free_args(easteregg_files);
free_args(files);
// Link
char **args = NULL;
add_args(&args, CC);
for (int i = 0; CFLAGS && CFLAGS[i] != NULL; i++) {
add_args(&args, CFLAGS[i]);
}
add_args(&args, "-o");
add_args(&args, OUTPUT);
for (int i = 0; OBJS && OBJS[i] != NULL; i++) {
add_args(&args, OBJS[i]);
}
for (int i = 0; LIBS && LIBS[i] != NULL; i++) {
add_args(&args, LIBS[i]);
}
struct cth_result *exec_result = cth_exec(args, NULL, true, true);
if (!exec_result) {
error("Error: failed to execute linker\n");
} else if (!exec_result->exited || exec_result->exit_code != 0) {
error("Error: failed to link object files\nLinker output:\nstderr:\n%s\nstdout:\n%s\n", exec_result->stderr_ret ? exec_result->stderr_ret : "No output", exec_result->stdout_ret ? exec_result->stdout_ret : "No output");
}
printf("Link %s :success\n", OUTPUT);
free_args(args);
// Strip
if (STRIP) {
if (fork_exec((char *[]){ STRIP, OUTPUT, NULL }) != 0) {
error("Error: failed to strip object files\n");
} else {
printf("Strip %s :success\n", OUTPUT);
}
} else {
printf("Skipping strip: STRIP not set\n");
}
printf("Output: %s\n", OUTPUT);
}
// As the name said
void check_and_add_cflag(char *flag, bool panic)
{
if (check_c_flag(flag)) {
add_args(&CFLAGS, flag);
} else if (panic) {
error("Error: C flag %s is not supported\n", flag);
}
}
// As the name said
void check_and_add_lib(char *lib, bool panic)
{
if (check_lib(lib)) {
add_args(&LIBS, lib);
} else if (panic) {
error("Error: Library %s is not supported\n", lib);
}
}
// Default cflags
void default_cflags(void)
{
check_and_add_cflag("-ftrivial-auto-var-init=pattern", false);
check_and_add_cflag("-fcf-protection=full", false);
check_and_add_cflag("-flto=auto", false);
check_and_add_cflag("-fPIE", false);
check_and_add_cflag("-pie", false);
check_and_add_cflag("-Wl,-z,relro", false);
check_and_add_cflag("-Wl,-z,noexecstack", false);
check_and_add_cflag("-Wl,-z,now", false);
check_and_add_cflag("-fstack-protector-all", false);
check_and_add_cflag("-fstack-clash-protection", false);
check_and_add_cflag("-mshstk", false);
check_and_add_cflag("-Wno-unused-result", false);
check_and_add_cflag("-O2", false);
check_and_add_cflag("-Wl,--build-id=sha1", false);
check_and_add_cflag("-ffunction-sections", false);
check_and_add_cflag("-fdata-sections", false);
check_and_add_cflag("-Wl,--gc-sections", false);
check_and_add_cflag("-Wl,--strip-all", false);
check_and_add_cflag("-U_FORTIFY_SOURCE", false);
check_and_add_cflag("-D_FORTIFY_SOURCE=3", false);
}
// Dev cflags
void dev_cflags(void)
{
check_and_add_cflag("-g", true);
check_and_add_cflag("-O0", false);
check_and_add_cflag("-fno-omit-frame-pointer", false);
check_and_add_cflag("-Wl,-z,norelro", false);
check_and_add_cflag("-Wl,-z,execstack", false);
check_and_add_cflag("-fno-stack-protector", false);
check_and_add_cflag("-Wall", false);
check_and_add_cflag("-Wextra", false);
check_and_add_cflag("-pedantic", false);
check_and_add_cflag("-Wconversion", false);
check_and_add_cflag("-Wno-newline-eof", false);
check_and_add_cflag("-Wno-gnu-zero-variadic-macro-arguments", false);
check_and_add_cflag("-fsanitize=address,undefined", false);
check_and_add_cflag("-Wl,--build-id=sha1", false);
check_and_add_cflag("-ffunction-sections", false);
check_and_add_cflag("-fdata-sections", false);
check_and_add_cflag("-Wl,--gc-sections", false);
check_and_add_cflag("-DRURI_DEBUG", false);
check_and_add_cflag("-DRURI_DEV", false);
STRIP = "true";
}
void show_help(void)
{
char *self_path = realpath("/proc/self/exe", NULL);
printf("Usage: ./%s [OPTION]...\n", basename_of(self_path));
printf(" -h, --help show help\n");
printf(" -s, --static compile static binary\n");
printf(" -d, --dev compile dev version\n");
printf(" -f, --force force rebuild\n");
printf(" -j, --jobs <num> number of jobs to run simultaneously\n");
printf(" -c, --core-only build core only\n");
}
// So good brooooo, the program works with magic here.
int main(int argc, char **argv)
{
signal(SIGINT, on_exit__);
switch_to_build_dir("out");
init_env();
bool cflags_configured = false;
bool core_only = false;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--dev") == 0 || strcmp(argv[i], "-d") == 0) {
dev_cflags();
cflags_configured = true;
} else if (strcmp(argv[i], "--force") == 0 || strcmp(argv[i], "-f") == 0) {
FORCE = true;
} else if ((strcmp(argv[i], "--jobs") == 0 || strcmp(argv[i], "-j") == 0) && i + 1 < argc) {
JOBS = atoi(argv[++i]);
if (JOBS <= 0) {
error("Error: Invalid number of jobs: %s", argv[i]);
}
} else if (strcmp(argv[i], "--static") == 0 || strcmp(argv[i], "-s") == 0) {
check_and_add_cflag("-static", true);
} else if (strcmp(argv[i], "--core-only") == 0 || strcmp(argv[i], "-c") == 0) {
core_only = true;
} else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
show_help();
exit(0);
} else {
show_help();
error("Error: Unknown option: %s", argv[i]);
}
}
if (!cflags_configured) {
default_cflags();
}
check_and_add_cflag("-std=gnu11", true);
if (COMMIT_ID) {
char define_commit[PATH_MAX];
sprintf(define_commit, "-DRURI_COMMIT_ID=\"%s\"", COMMIT_ID);
check_and_add_cflag(define_commit, false);
} else {
check_and_add_cflag("-DRURI_COMMIT_ID=unknown", false);
}
if (!core_only) {
check_and_add_lib("-lcap", true);
check_and_add_lib("-lseccomp", true);
check_and_add_lib("-lpthread", false);
} else {
check_and_add_cflag("-DRURI_CORE_ONLY", true);
check_and_add_cflag("-DDISABLE_LIBCAP", true);
check_and_add_cflag("-DDISABLE_SECCOMP", true);
check_and_add_cflag("-DDISABLE_RURIENV", true);
}
build();
remove_test_dot_c();
return 0;
}
/////////////////////
///////catsh.c///////
/////////////////////
static struct cth_result *cth_new(pid_t pid, pid_t ppid)
{
/*
* Allocate and initialize a new cth_result structure.
* Returns a pointer to the new structure, or NULL on failure.
*/
struct cth_result *res = malloc(sizeof(struct cth_result));
if (res == NULL) {
return NULL;
}
res->exited = false;
res->exit_code = -1;
res->stdout_ret = NULL;
res->stderr_ret = NULL;
res->pid = pid;
res->ppid = ppid;
res->time_used = 0;
res->cth_version = CTH_VERSION;
res->struct_size = sizeof(struct cth_result);
memset(res->reserved, 0, sizeof(res->reserved));
return res;
}
int cth_add_arg(char ***argv, char *arg)
{
/*
* Add an argument to the argv array.
* *argv: Pointer to the argv array. Can be NULL initially.
* arg: The argument to add, should be a null-terminated string.
* The argv array should be NULL-terminated.
* Returns 0 on success, -1 on failure.
* Warning: This function allocates memory.
* The caller is responsible for freeing it using cth_free_argv().
*/
size_t argc = 0;
if (*argv != NULL) {
while ((*argv)[argc] != NULL) {
argc++;
}
}
char **new_argv = realloc(*argv, sizeof(char *) * (argc + 2));
if (new_argv == NULL) {
return -1;
}
new_argv[argc] = strdup(arg);
new_argv[argc + 1] = NULL;
*argv = new_argv;
return 0;
}
void cth_free_argv(char ***argv)
{
/*
* Free the argv array and its contents.
* *argv: Pointer to the argv array, can be NULL.
* After calling this function, *argv will be set to NULL.
*/
if (*argv == NULL) {
return;
}
size_t argc = 0;
while ((*argv)[argc] != NULL) {
free((*argv)[argc]);
argc++;
}
free(*argv);
*argv = NULL;
}
void cth_free_result(struct cth_result **res)
{
/*
* Free the cth_result structure and its contents.
* *res: Pointer to the cth_result structure, can be NULL.
* After calling this function, *res will be set to NULL.
*/
if (*res == NULL) {
return;
}
free((*res)->stdout_ret);
free((*res)->stderr_ret);
free(*res);
*res = NULL;
}
void *cth_init_argv(void)
{
/*
* Just a wrapper, returns NULL.
*/
return NULL;
}
static struct cth_result *cth_exec_nonblock(char **argv, char *input, bool get_output)
{
// TODO
return NULL;
}
static struct cth_result *cth_exec_block_without_stdio(char **argv)
{
/*
* Just exec the command in blocking mode, without redirecting stdin/stdout/stderr.
* This is the simplest case.
*/
pid_t pid = fork();
struct timeval start_time, end_time;
gettimeofday(&start_time, NULL);
// Just error handling.
if (pid < 0) {
return NULL;
}
// Child process, exec the command.
if (pid == 0) {
int fd = open("/dev/null", O_RDWR);
if (fd < 0) {
exit(CTH_EXIT_FAILURE);
}
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > 2) {
close(fd);
}
execvp(argv[0], argv);
exit(CTH_EXIT_FAILURE);
}
// Parent process, wait for child to exit.
struct cth_result *res = malloc(sizeof(struct cth_result));
if (res == NULL) {
return NULL;
}
res->pid = pid;
res->ppid = -1;
res->exited = false;
res->exit_code = -1;
res->stdout_ret = NULL;
res->stderr_ret = NULL;
int status = 0;
// Wait for child process, handle EINTR.
while (waitpid(pid, &status, 0) < 0) {
if (errno == EINTR) {
continue;
}
free(res);
return NULL;
}
gettimeofday(&end_time, NULL);
// Calculate time used in microseconds.
res->time_used = (end_time.tv_sec - start_time.tv_sec) * 1000000 + (end_time.tv_usec - start_time.tv_usec);
// Get exit code.
res->exited = true;
if (WIFEXITED(status)) {
res->exit_code = WEXITSTATUS(status);
} else if (WIFSIGNALED(status)) {
res->exit_code = 128 + WTERMSIG(status);
} else {
res->exit_code = -1;
}
return res;
}
static size_t pipe_buf_size(int fd)
{
/*
* Get the pipe buffer size using fcntl.
* Returns the size on success, 0 on failure.
* Note: this function will also try to set the pipe buffer size to the maximum allowed size.
* As this is a internal function, we can do this.
*/
// Try to set the pipe buffer size to a large value.
// Get max allowed size from /proc/sys/fs/pipe-max-size.
FILE *f = fopen("/proc/sys/fs/pipe-max-size", "r");
if (f) {
char line[32];
if (fgets(line, sizeof(line), f)) {
size_t max_size = strtoul(line, NULL, 10);
if (max_size > 0) {
fcntl(fd, F_SETPIPE_SZ, max_size);
}
}
fclose(f);
}
// Get the pipe buffer size using fcntl.
int size = fcntl(fd, F_GETPIPE_SZ);
if (size < 0) {
return 0;
}
return (size_t)size;
}
static struct cth_result *cth_exec_block(char **argv, char *input, bool get_output)
{
/*
* Exec the command in blocking mode, with optional stdin input and stdout/stderr capture.
* argv: The command and its arguments, NULL-terminated array of strings.
* input: The input to be passed to the command's stdin, can be NULL.
* get_output: If true, capture stdout and stderr output.