-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknob.h
2120 lines (1870 loc) · 68.9 KB
/
knob.h
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
// Alexey Kutepov: This is a complete backward incompatible rewrite of https://github.com/tsoding/nobuild
// because I'm really unhappy with the direction it is going. It's gonna sit in this repo
// until it's matured enough and then I'll probably extract it to its own repo.
// This is a complete backward incompatible overwrite of https://github.com/tsoding/musializer/blob/master/src/nob.h
// because I intend on using it for "serious" programming projects(i.e. gamedev/edutainement)
// Copyright 2023 Alexey Kutepov <reximkut@gmail.com>
// Copyright 2023 Jean-Sébastien Nadeau <mundusnine@gmail.com>
//
// 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.
#ifndef KNOB_H_
#define KNOB_H_
#define KNOB_ASSERT assert
#define KNOB_REALLOC realloc
#define KNOB_FREE free
#ifdef _WIN32 // Look mommy, no kiddy wheels....
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#define _BSD_SOURCE
#define _XOPEN_SOURCE 700
#elif defined(__linux__)
// @TODO: The fact that we need to do this to remove warnings is just crazy, i.e. wth linux
// We need to test this with cosmocc
#ifndef __USE_XOPEN2K8
#define __USE_XOPEN2K8
#endif
#include <string.h>
#undef __USE_XOPEN2K8
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _XOPEN_SOURCE 700
#endif
#include <errno.h>
#include <ctype.h>
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <direct.h>
# include <shellapi.h>
typedef HANDLE Knob_Fd;
#if !defined(__MINGW64__) || !defined(__MINGW32__)
#define DLL_API __declspec(dllexport)
#define getcwd(buffer,size) _getcwd(buffer,size)
#define mkdir(path) _mkdir(path)
#define chdir(dirname) _chdir(dirname)
#define strdup(strSource) _strdup(strSource)
#else
#define DLL_API
#endif
#else
typedef int Knob_Fd;
# include <sys/types.h>
# include <sys/wait.h>
# include <fcntl.h>
// @TODO: The fact that we need to do this to remove warnings is just crazy, i.e. wth linux
// We need to test this with cosmocc
#define __USE_XOPEN_EXTENDED
# include <unistd.h>
#undef __USE_XOPEN_EXTENDED
#ifndef __USE_MISC
#define __USE_MISC
#endif
# include <sys/stat.h>
#endif
#ifdef _WIN32
# define KNOB_LINE_END "\r\n"
# define PATH_SEP "\\"
# define DLL_NAME ".dll"
#else
# define KNOB_LINE_END "\n"
# define PATH_SEP "/"
# define DLL_NAME ".so"
#endif
#ifdef __cplusplus
extern "C"{
#endif
typedef struct {
Knob_Fd read;
Knob_Fd write;
} Knob_Pipe;
Knob_Pipe knob_pipe_make(void);
#define KNOB_ARRAY_LEN(array) (sizeof(array)/sizeof(array[0]))
#define KNOB_ARRAY_GET(array, index) \
(KNOB_ASSERT(index >= 0), KNOB_ASSERT(index < KNOB_ARRAY_LEN(array)), array[index])
typedef enum {
KNOB_INFO,
KNOB_WARNING,
KNOB_ERROR,
} Knob_Log_Level;
void knob_log(Knob_Log_Level level, const char *fmt, ...);
// It is an equivalent of shift command from bash. It basically pops a command line
// argument from the beginning.
char *knob_shift_args(int *argc, char ***argv);
int knob_cstr_match(char* left, char* right);
int knob_cstr_ends(char* str, const char* end);
typedef struct {
const char **items;
size_t count;
size_t capacity;
} Knob_File_Paths;
typedef enum {
KNOB_FILE_REGULAR = 0,
KNOB_FILE_DIRECTORY,
KNOB_FILE_SYMLINK,
KNOB_FILE_OTHER,
} Knob_File_Type;
bool knob_mkdir_if_not_exists(const char *path);
bool knob_copy_file(const char *src_path, const char *dst_path);
bool knob_copy_directory_recursively(const char *src_path, const char *dst_path);
bool knob_read_entire_dir(const char *parent, Knob_File_Paths *children);
bool knob_write_entire_file(const char *path, void *data, size_t size);
Knob_File_Type knob_get_file_type(const char *path);
#define knob_return_defer(value) do { result = (value); goto defer; } while(0)
// Initial capacity of a dynamic array
#define KNOB_DA_INIT_CAP 256
// Append an item to a dynamic array
#define knob_da_append(da, item) \
do { \
if ((da)->count >= (da)->capacity) { \
(da)->capacity = (da)->capacity == 0 ? KNOB_DA_INIT_CAP : (da)->capacity*2; \
(da)->items = KNOB_REALLOC((da)->items, (da)->capacity*sizeof(*(da)->items)); \
KNOB_ASSERT((da)->items != NULL && "Buy more RAM lol"); \
} \
\
(da)->items[(da)->count++] = (item); \
} while (0)
#define knob_da_free(da) KNOB_FREE((da).items)
// Append several items to a dynamic array
#define knob_da_append_many(da, new_items, new_items_count) \
do { \
if ((da)->count + new_items_count > (da)->capacity) { \
if ((da)->capacity == 0) { \
(da)->capacity = KNOB_DA_INIT_CAP; \
} \
while ((da)->count + new_items_count > (da)->capacity) { \
(da)->capacity *= 2; \
} \
(da)->items = KNOB_REALLOC((da)->items, (da)->capacity*sizeof(*(da)->items)); \
KNOB_ASSERT((da)->items != NULL && "Buy more RAM lol"); \
} \
memcpy((da)->items + (da)->count, new_items, new_items_count*sizeof(*(da)->items)); \
(da)->count += new_items_count; \
} while (0)
typedef struct {
char *items;
size_t count;
size_t capacity;
} Knob_String_Builder;
bool knob_read_entire_file(const char *path, Knob_String_Builder *sb);
// Append a sized buffer to a string builder
#define knob_sb_append_buf(sb, buf, size) knob_da_append_many(sb, buf, size)
// Append a NULL-terminated string to a string builder
#define knob_sb_append_cstr(sb, cstr) \
do { \
const char *s = (cstr); \
size_t n = strlen(s); \
knob_da_append_many(sb, s, n); \
} while (0)
// Append a single NULL character at the end of a string builder. So then you can
// use it a NULL-terminated C string
#define knob_sb_append_null(sb) knob_da_append_many(sb, "", 1)
// Free the memory allocated by a string builder
#define knob_sb_free(sb) KNOB_FREE((sb).items)
// Process handle
#ifdef _WIN32
typedef HANDLE Knob_Proc;
#define KNOB_INVALID_PROC INVALID_HANDLE_VALUE
LPSTR GetLastErrorAsString(void);
#else
typedef int Knob_Proc;
#define KNOB_INVALID_PROC (-1)
#endif // _WIN32
typedef struct {
Knob_Proc *items;
size_t count;
size_t capacity;
} Knob_Procs;
bool knob_procs_wait(Knob_Procs procs);
// Wait until the process has finished
bool knob_proc_wait(Knob_Proc proc);
// A command - the main workhorse of Knob. Knob is all about building commands an running them
typedef struct {
const char **items;
size_t count;
size_t capacity;
} Knob_Cmd;
// Render a string representation of a command into a string builder. Keep in mind the the
// string builder is not NULL-terminated by default. Use knob_sb_append_null if you plan to
// use it as a C string.
void knob_cmd_render(Knob_Cmd cmd, Knob_String_Builder *render);
#define knob_cmd_append(cmd, ...) \
knob_da_append_many(cmd, ((const char*[]){__VA_ARGS__}), (sizeof((const char*[]){__VA_ARGS__})/sizeof(const char*)))
#define knob_da_mult_append(da, ...) \
knob_da_append_many(da, ((const char*[]){__VA_ARGS__}), (sizeof((const char*[]){__VA_ARGS__})/sizeof(const char*)))
// Free all the memory allocated by command arguments
#define knob_cmd_free(cmd) KNOB_FREE(cmd.items)
// Run command asynchronously
Knob_Proc knob_cmd_run_async(Knob_Cmd cmd, Knob_Fd *fdin, Knob_Fd *fdout);
// Run command synchronously
bool knob_cmd_run_sync(Knob_Cmd cmd);
#ifndef KNOB_TEMP_CAPACITY
#define KNOB_TEMP_CAPACITY (8*1024*1024)
#endif // KNOB_TEMP_CAPACITY
char *knob_temp_strdup(const char *cstr);
void *knob_temp_alloc(size_t size);
char *knob_temp_sprintf(const char *format, ...);
void knob_temp_reset(void);
size_t knob_temp_save(void);
void knob_temp_rewind(size_t checkpoint);
int is_path1_modified_after_path2(const char *path1, const char *path2);
bool knob_rename(const char *old_path, const char *new_path);
int knob_needs_rebuild(const char *output_path, const char **input_paths, size_t input_paths_count);
int knob_needs_rebuild1(const char *output_path, const char *input_path);
int knob_file_exists(const char *file_path);
int knob_file_del(const char *file_path);
int knob_path_is_dir(const char *path);
typedef enum {
TARGET_LINUX,
TARGET_LINUX_MUSL,
TARGET_WIN64_MINGW,
TARGET_WIN64_MSVC,
TARGET_MACOS,
COUNT_TARGETS
} Knob_Target;
static_assert(5 == COUNT_TARGETS, "Amount of targets have changed");
static const char *target_names[] = {
[TARGET_LINUX] = "linux",
[TARGET_LINUX_MUSL] = "linux-musl",
[TARGET_WIN64_MINGW] = "win64-mingw",
[TARGET_WIN64_MSVC] = "win64-msvc",
[TARGET_MACOS] = "macos",
};
typedef enum {
COMPILER_COSMOCC,
COMPILER_ZIG,
COMPILER_CLANG,
COMPILER_GCC,
COMPILER_CL,
COUNT_COMPILERS
} Knob_Compiler;
static_assert(5 == COUNT_COMPILERS, "Amount of compilers have changed");
static const char *compiler_names[][2] = {
[COMPILER_COSMOCC] = {"cosmocc","-L."},
[COMPILER_ZIG] = {"zig","cc"},
[COMPILER_CLANG] = {"clang","-L/dev/null"},
[COMPILER_GCC] = {"gcc","-L/dev/null"},
[COMPILER_CL] = {"cl.exe","-L."},
};
static const char *compilerpp_names[][2] = {
[COMPILER_COSMOCC] = {"cosmoc++","-L."},
[COMPILER_ZIG] = {"zig","c++"},
[COMPILER_CLANG] = {"clang++","-L/dev/null"},
[COMPILER_GCC] = {"g++","-L/dev/null"},
[COMPILER_CL] = {"cl.exe","-L."},
};
#define GET_COMPILER_NAME(cmp) compiler_names[cmp][0] ,compiler_names[cmp][1]
#define GET_COMPILERPP_NAME(cmp) compilerpp_names[cmp][0] ,compilerpp_names[cmp][1]
#define CONFIG_PATH "./build/config.h"
#define PLUG_PATH "./build/plug.h"
typedef enum {
BIN_O,
BIN_DLL,
BIN_EXE
} Knob_Binary_out;
typedef struct {
Knob_Target target;
Knob_Compiler compiler;
int debug_mode;
const char* build_to;
Knob_Binary_out output_type;
Knob_File_Paths c_files;
Knob_File_Paths cpp_files;
Knob_File_Paths includes;
Knob_File_Paths defines;
Knob_File_Paths c_flags;
Knob_File_Paths cpp_flags;
} Knob_Config;
void knob_create_default_config(const char* project_name,Knob_String_Builder *content,Knob_Cmd* user_conf);
/*
* Initialize build config
*/
void knob_config_init(Knob_Config *config);
/*
* Add a define to the config. It's the users responsibility to add `-D` to the define string
*/
void knob_config_add_define(Knob_Config* config,const char* define);
void knob_config_add_c_flag(Knob_Config* config,const char* flag);
void knob_config_add_cpp_flag(Knob_Config* config,const char* flag);
/*
* Add a define to the config. The implementation adds `-I`.
*/
void knob_config_add_includes(Knob_Config* config,const char* filepaths[],size_t len);
/*
* Add files with the extensions `*.c` and `*.cpp` to the build config.
*/
void knob_config_add_files(Knob_Config* config,const char* filepaths[],size_t len);
int knob_config_build(Knob_Config* config,Knob_File_Paths* outs);
void knob_create_plug(void);
//@TODO: Add reload_plug_here
void knob_cmd_add_compiler(Knob_Cmd* cmd,Knob_Config* config);
void knob_cmd_add_includes(Knob_Cmd* cmd,Knob_Config* config);
int knob_compile_run_submodule(const char* path,Knob_Config* config,Knob_File_Paths* files_to_link,Knob_Cmd* cmd_to_pass,const char* path_to_knobh);
// int knob_get_submodule()
#ifndef CC
# define CC_PATH ""
# if _WIN32
# if defined(__GNUC__)
# define CC "gcc"
# elif defined(__clang__)
# define CC "clang"
# elif defined(_MSC_VER)
# define CC "cl.exe"
# endif
# else
# define CC "cc"
# endif
#endif
// TODO: add MinGW support for Go Rebuild Urself™ Technology
#ifndef KNOB_REBUILD_URSELF
#define KNOB_REBUILD_URSELF(binary_path, source_path) CC_PATH CC, "-o", binary_path, source_path
#endif
typedef int (*submodule_entrypoint)(Knob_Config* /*parent_config*/, Knob_File_Paths* /*project_name##_link_files*/, int /*argc*/,char** /*argv*/);
#ifdef KNOB_SUBMODULE
#define MAIN(project_name) \
static char* proj_name = #project_name; \
DLL_API int project_name##_entrypoint(Knob_Config* parent_config, Knob_File_Paths* project_name##_link_files, int argc,char** argv)
#else
#define MAIN(project_name) int main(int argc,char** argv)
#endif
// Go Rebuild Urself™ Technology
//
// How to use it:
// int main(int argc, char** argv) {
// GO_REBUILD_URSELF(argc, argv);
// // actual work
// return 0;
// }
//
// After your added this macro every time you run ./nobuild it will detect
// that you modified its original source code and will try to rebuild itself
// before doing any actual work. So you only need to bootstrap your build system
// once.
//
// The modification is detected by comparing the last modified times of the executable
// and its source code. The same way the make utility usually does it.
//
// The rebuilding is done by using the REBUILD_URSELF macro which you can redefine
// if you need a special way of bootstraping your build system. (which I personally
// do not recommend since the whole idea of nobuild is to keep the process of bootstrapping
// as simple as possible and doing all of the actual work inside of the nobuild)
//
#define KNOB_GO_REBUILD_URSELF(argc, argv) \
do { \
const char *source_path = __FILE__; \
assert(argc >= 1); \
const char *binary_path = argv[0]; \
\
int rebuild_is_needed = knob_needs_rebuild(binary_path, &source_path, 1); \
if (rebuild_is_needed < 0) exit(1); \
if (rebuild_is_needed) { \
Knob_String_Builder sb = {0}; \
knob_sb_append_cstr(&sb, binary_path); \
knob_sb_append_cstr(&sb, ".old"); \
knob_sb_append_null(&sb); \
\
if (!knob_rename(binary_path, sb.items)) exit(1); \
Knob_Cmd rebuild = {0}; \
knob_cmd_append(&rebuild, KNOB_REBUILD_URSELF(binary_path, source_path)); \
bool rebuild_succeeded = knob_cmd_run_sync(rebuild); \
knob_cmd_free(rebuild); \
if (!rebuild_succeeded) { \
knob_rename(sb.items, binary_path); \
exit(1); \
} \
\
Knob_Cmd cmd = {0}; \
knob_da_append_many(&cmd, argv, argc); \
if (!knob_cmd_run_sync(cmd)) exit(1); \
exit(0); \
} \
} while(0)
// The implementation idea is stolen from https://github.com/zhiayang/nabs
typedef struct {
size_t count;
const char *data;
} Knob_String_View;
const char *knob_temp_sv_to_cstr(Knob_String_View sv);
Knob_String_View knob_sv_chop_by_delim(Knob_String_View *sv, char delim);
Knob_String_View knob_sv_trim(Knob_String_View sv);
bool knob_sv_eq(Knob_String_View a, Knob_String_View b);
Knob_String_View knob_sv_from_cstr(const char *cstr);
Knob_String_View knob_sv_from_parts(const char *data, size_t count);
// printf macros for String_View
#ifndef SV_Fmt
#define SV_Fmt "%.*s"
#endif // SV_Fmt
#ifndef SV_Arg
#define SV_Arg(sv) (int) (sv).count, (sv).data
#endif // SV_Arg
// USAGE:
// String_View name = ...;
// printf("Name: "SV_Fmt"\n", SV_Arg(name));
// minirent.h HEADER BEGIN ////////////////////////////////////////
// Copyright 2021 Alexey Kutepov <reximkut@gmail.com>
//
// 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.
//
// ============================================================
//
// minirent — 0.0.1 — A subset of dirent interface for Windows.
//
// https://github.com/tsoding/minirent
//
// ============================================================
//
// ChangeLog (https://semver.org/ is implied)
//
// 0.0.2 Automatically include dirent.h on non-Windows
// platforms
// 0.0.1 First Official Release
#ifndef _WIN32
#include <dirent.h>
#else // _WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
struct dirent
{
char d_name[MAX_PATH+1];
};
typedef struct DIR DIR;
DIR *opendir(const char *dirpath);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
#endif // _WIN32
// minirent.h HEADER END ////////////////////////////////////////
#endif // KNOB_H_
// dynlib.h HEADER BEGIN ////////////////////////////////////////
// Copyright 2023 Jean-Sébastien Nadeau <mundusnine@gmail.com>
//
// 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.
//
// ============================================================
/*
* Single-header library for dynamic library loading
* Define in only one .c or .cpp file DYNLIB_IMPL
*/
static char dynlib_last_err[256] = {0};
typedef void (*func_ptr)(void);
void* dynlib_load(const char *dllfile);
int dynlib_unload(void *handle);
void* dynlib_loadfunc(void *handle, const char *name);
// dynlib.h HEADER END ////////////////////////////////////////
int knob_sleep_ms(int milliseconds);
#ifdef __cplusplus
}
#endif
#if defined(KNOB_IMPLEMENTATION)
#ifdef _WIN32
LPSTR GetLastErrorAsString(void)
{
// https://stackoverflow.com/questions/1387064/how-to-get-the-error-message-from-the-error-code-returned-by-getlasterror
DWORD errorMessageId = GetLastError();
assert(errorMessageId != 0);
LPSTR messageBuffer = NULL;
DWORD size =
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, // DWORD dwFlags,
NULL, // LPCVOID lpSource,
errorMessageId, // DWORD dwMessageId,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // DWORD dwLanguageId,
(LPSTR) &messageBuffer, // LPTSTR lpBuffer,
0, // DWORD nSize,
NULL // va_list *Arguments
);
return messageBuffer;
}
#endif
static size_t knob_temp_size = 0;
static char knob_temp[KNOB_TEMP_CAPACITY] = {0};
bool knob_mkdir_if_not_exists(const char *path)
{
#ifdef _WIN32
int result = mkdir(path);
#else
int result = mkdir(path, 0755);
#endif
if (result < 0) {
if (errno == EEXIST) {
knob_log(KNOB_INFO, "directory `%s` already exists", path);
return true;
}
knob_log(KNOB_ERROR, "could not create directory `%s`: %s", path, strerror(errno));
return false;
}
knob_log(KNOB_INFO, "created directory `%s`", path);
return true;
}
bool knob_copy_file(const char *src_path, const char *dst_path)
{
knob_log(KNOB_INFO, "copying %s -> %s", src_path, dst_path);
#ifdef _WIN32
if (!CopyFile(src_path, dst_path, FALSE)) {
knob_log(KNOB_ERROR, "Could not copy file: %lu", GetLastError());
return false;
}
return true;
#else
int src_fd = -1;
int dst_fd = -1;
size_t buf_size = 32*1024;
char *buf = KNOB_REALLOC(NULL, buf_size);
KNOB_ASSERT(buf != NULL && "Buy more RAM lol!!");
bool result = true;
src_fd = open(src_path, O_RDONLY);
if (src_fd < 0) {
knob_log(KNOB_ERROR, "Could not open file %s: %s", src_path, strerror(errno));
knob_return_defer(false);
}
struct stat src_stat;
if (fstat(src_fd, &src_stat) < 0) {
knob_log(KNOB_ERROR, "Could not get mode of file %s: %s", src_path, strerror(errno));
knob_return_defer(false);
}
dst_fd = open(dst_path, O_CREAT | O_TRUNC | O_WRONLY, src_stat.st_mode);
if (dst_fd < 0) {
knob_log(KNOB_ERROR, "Could not create file %s: %s", dst_path, strerror(errno));
knob_return_defer(false);
}
for (;;) {
ssize_t n = read(src_fd, buf, buf_size);
if (n == 0) break;
if (n < 0) {
knob_log(KNOB_ERROR, "Could not read from file %s: %s", src_path, strerror(errno));
knob_return_defer(false);
}
char *buf2 = buf;
while (n > 0) {
ssize_t m = write(dst_fd, buf2, n);
if (m < 0) {
knob_log(KNOB_ERROR, "Could not write to file %s: %s", dst_path, strerror(errno));
knob_return_defer(false);
}
n -= m;
buf2 += m;
}
}
defer:
free(buf);
close(src_fd);
close(dst_fd);
return result;
#endif
}
void knob_cmd_render(Knob_Cmd cmd, Knob_String_Builder *render)
{
memset(render->items,0,render->capacity);
size_t i = 0;
for (; i < cmd.count; ++i) {
const char *arg = cmd.items[i];
if (arg == NULL) break;
if (i > 0) knob_sb_append_cstr(render, " ");
if (!strchr(arg, ' ')) {
knob_sb_append_cstr(render, arg);
} else {
knob_da_append(render, '\'');
knob_sb_append_cstr(render, arg);
knob_da_append(render, '\'');
}
}
knob_sb_append_null(render);
return;
}
Knob_Proc knob_cmd_run_async(Knob_Cmd cmd, Knob_Fd *fdin, Knob_Fd *fdout)
{
#ifdef _WIN32
// https://docs.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output
STARTUPINFO siStartInfo;
ZeroMemory(&siStartInfo, sizeof(siStartInfo));
siStartInfo.cb = sizeof(STARTUPINFO);
// NOTE: theoretically setting NULL to std handles should not be a problem
// https://docs.microsoft.com/en-us/windows/console/getstdhandle?redirectedfrom=MSDN#attachdetach-behavior
siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
// TODO(#32): check for errors in GetStdHandle
siStartInfo.hStdOutput = fdout ? *fdout : GetStdHandle(STD_OUTPUT_HANDLE);
siStartInfo.hStdInput = fdin ? *fdin : GetStdHandle(STD_INPUT_HANDLE);
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
PROCESS_INFORMATION piProcInfo;
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
Knob_String_Builder sb = {0};
knob_cmd_render(cmd,&sb);
BOOL bSuccess =
CreateProcess(
NULL,
// TODO(#33): cmd_run_async on Windows does not render command line properly
// It may require wrapping some arguments with double-quotes if they contains spaces, etc.
sb.items,
NULL,
NULL,
TRUE,
0,
NULL,
NULL,
&siStartInfo,
&piProcInfo
);
if (!bSuccess) {
knob_log(KNOB_ERROR,"Could not create child process %s: %s\n",
sb.items, GetLastErrorAsString());
}
CloseHandle(piProcInfo.hThread);
return piProcInfo.hProcess;
#else
pid_t cpid = fork();
if (cpid < 0) {
knob_log(KNOB_ERROR,"Could not fork child process: %s",strerror(errno));
}
if (cpid == 0) {
// NOTE: This leaks a bit of memory in the child process.
// But do we actually care? It's a one off leak anyway...
Knob_Cmd cmd_null = {0};
knob_da_append_many(&cmd_null, cmd.items, cmd.count);
knob_cmd_append(&cmd_null, NULL);
if (fdin) {
if (dup2(*fdin, STDIN_FILENO) < 0) {
knob_log(KNOB_ERROR,"Could not setup stdin for child process: %s", strerror(errno));
}
close(*fdin);
}
if (fdout) {
if (dup2(*fdout, STDOUT_FILENO) < 0) {
knob_log(KNOB_ERROR,"Could not setup stdout for child process: %s", strerror(errno));
}
close(*fdout);
}
if (execvp(cmd.items[0], (char * const*) cmd_null.items) < 0) {
knob_log(KNOB_ERROR, "Could not exec child process: %s", strerror(errno));
exit(1);
}
}
return cpid;
#endif // _WIN32
}
bool knob_procs_wait(Knob_Procs procs)
{
bool success = true;
for (size_t i = 0; i < procs.count; ++i) {
success = knob_proc_wait(procs.items[i]) && success;
}
return success;
}
bool knob_proc_wait(Knob_Proc proc)
{
if (proc == KNOB_INVALID_PROC) return false;
#ifdef _WIN32
DWORD result = WaitForSingleObject(
proc, // HANDLE hHandle,
INFINITE // DWORD dwMilliseconds
);
if (result == WAIT_FAILED) {
knob_log(KNOB_ERROR, "could not wait on child process: %lu", GetLastError());
return false;
}
DWORD exit_status;
if (!GetExitCodeProcess(proc, &exit_status)) {
knob_log(KNOB_ERROR, "could not get process exit code: %lu", GetLastError());
return false;
}
if (exit_status != 0) {
knob_log(KNOB_ERROR, "command exited with exit code %lu", exit_status);
return false;
}
CloseHandle(proc);
return true;
#else
for (;;) {
int wstatus = 0;
if (waitpid(proc, &wstatus, 0) < 0) {
knob_log(KNOB_ERROR, "could not wait on command (pid %d): %s", proc, strerror(errno));
return false;
}
if (WIFEXITED(wstatus)) {
int exit_status = WEXITSTATUS(wstatus);
if (exit_status != 0) {
knob_log(KNOB_ERROR, "command exited with exit code %d", exit_status);
return false;
}
break;
}
if (WIFSIGNALED(wstatus)) {
knob_log(KNOB_ERROR, "command process was terminated by %s", strsignal(WTERMSIG(wstatus)));
return false;
}
}
return true;
#endif
}
bool knob_cmd_run_sync(Knob_Cmd cmd)
{
Knob_Proc p = knob_cmd_run_async(cmd,NULL,NULL);
if (p == KNOB_INVALID_PROC) return false;
return knob_proc_wait(p);
}
char *knob_shift_args(int *argc, char ***argv)
{
KNOB_ASSERT(*argc > 0);
char *result = **argv;
(*argv) += 1;
(*argc) -= 1;
return result;
}
int knob_cstr_match(char* left, char* right){
int i =0;
while(left[i] != '\0' && right[i] != '\0'){
if(left[i] != right[i]){
return 0;
}
++i;
}
if(left[i] != '\0' || right[i] != '\0')
return 0;
return 1;
}
int knob_cstr_ends(char* str,const char* end){
int e_len = strlen(end);
int s_len = strlen(str);
int i =1;
while(e_len-i > -1){
if(str[s_len-i] != end[e_len-i]){
return 0;
}
i++;
}
return 1;
}
Knob_Pipe knob_pipe_make(void)
{
Knob_Pipe pip = {0};
#ifdef _WIN32
// https://docs.microsoft.com/en-us/windows/win32/ProcThread/creating-a-child-process-with-redirected-input-and-output
SECURITY_ATTRIBUTES saAttr = {0};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
if (!CreatePipe(&pip.read, &pip.write, &saAttr, 0)) {
knob_log(KNOB_ERROR,"Could not create pipe: %s", GetLastErrorAsString());
}
#else
Knob_Fd pipefd[2];
if (pipe(pipefd) < 0) {
knob_log(KNOB_ERROR,"Could not create pipe: %s", strerror(errno));
}
pip.read = pipefd[0];
pip.write = pipefd[1];
#endif // _WIN32
return pip;
}
Knob_Fd knob_fd_open_for_read(const char* path)
{
#ifndef _WIN32
Knob_Fd result = open(path, O_RDONLY);
if (result < 0) {
knob_log(KNOB_ERROR,"Could not open file %s: %s", path, strerror(errno));
}
return result;
#else
// https://docs.microsoft.com/en-us/windows/win32/fileio/opening-a-file-for-reading-or-writing
SECURITY_ATTRIBUTES saAttr = {0};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
Knob_Fd result = CreateFile(
path,
GENERIC_READ,
0,
&saAttr,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if (result == INVALID_HANDLE_VALUE) {
knob_log(KNOB_ERROR,"Could not open file %s", path);
}
return result;
#endif // _WIN32
}
Knob_Fd knob_fd_open_for_write(const char* path)
{
#ifndef _WIN32
Knob_Fd result = open(path,
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (result < 0) {
knob_log(KNOB_ERROR,"could not open file %s: %s", path, strerror(errno));
}
return result;
#else
SECURITY_ATTRIBUTES saAttr = {0};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
Knob_Fd result = CreateFile(
path, // name of the write
GENERIC_WRITE, // open for writing
0, // do not share
&saAttr, // default security
CREATE_NEW, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL // no attr. template
);
if (result == INVALID_HANDLE_VALUE) {
knob_log(KNOB_ERROR,"Could not open file %s: %s", path, GetLastErrorAsString());
}
return result;
#endif // _WIN32
}
void knob_fd_close(Knob_Fd fd)
{
#ifdef _WIN32