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
|
/* SPDX-License-Identifier: MIT */
/*
* konbuild.h
*
* Copyright (c) 2026 KonAki
*
* 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 KONBUILD_H
#define KONBUILD_H
/*** includes ***/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <direct.h>
#else
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/wait.h>
#endif
/*** definitions ***/
#if defined(__GNUC__) || defined(__clang__)
#define KON_MAYBE_UNUSED __attribute__((unused))
#else
#define KON_MAYBE_UNUSED
#endif
#ifdef _MSC_VER
#define KON_TOOLCHAIN_MSVC 1
#else
#define KON_TOOLCHAIN_MSVC 0
#endif
static const char *kon_cc(void) KON_MAYBE_UNUSED;
static const char *kon_ar(void) KON_MAYBE_UNUSED;
typedef struct kon_cmd {
char **items;
size_t count;
size_t cap;
} KonCmd;
/* a list of paths, the strings belong to the list */
typedef struct kon_list {
char **items;
size_t count;
size_t cap;
} KonList;
void kon_pushCmd_(KonCmd *c, ...);
#define kon_pushCmd(c, ...) kon_pushCmd_((c), __VA_ARGS__, (char *)NULL)
bool kon_runCmdSync(KonCmd *c);
/* the same, with what the command prints appended to a file. NULL is the same as kon_runCmdSync */
bool kon_runCmdLog(KonCmd *c, const char *logPath);
void kon_resetCmd(KonCmd *c);
void kon_freeCmd(KonCmd *c);
/* a string that lives until the program ends (or kon_freeTemp), so a command can be filled with built up text without keeping track */
char *kon_fmt(const char *format, ...);
void kon_freeTemp(void);
/* seconds, -1 when the path is not there */
long long kon_mtime(const char *path);
bool kon_needsRebuild(const char *output, const char **sources, size_t nSources);
/* the newest file in a folder (not the folders in it) whose name ends in ext, or -1 */
long long kon_newestIn(const char *dir, const char *ext);
bool kon_exists(const char *path);
bool kon_isDir(const char *path);
bool kon_mkdir(const char *path);
/* every folder on the way, like mkdir -p */
bool kon_mkdirs(const char *path);
bool kon_remove(const char *path);
/* every file under a folder, in every folder inside it, sorted. the paths are the folder, a slash and the rest */
bool kon_listFiles(const char *dir, KonList *out);
void kon_freeList(KonList *l);
#define KON_REBUILDSELF(argc, argv) kon_rebuildSelf_(__FILE__, (argc), (argv))
void kon_rebuildSelf_(const char *src_path, int argc, char **argv);
#endif /* end of KONBUILD_H */
#ifdef KONBUILD_IMPLEMENTATION
#include <errno.h>
static const char *kon_cc(void) {
#if KON_TOOLCHAIN_MSVC
return "cl";
#else
const char *cc = getenv("CC");
return cc ? cc : "cc";
#endif
}
static const char *kon_ar(void) {
#if KON_TOOLCHAIN_MSVC
return "lib";
#else
const char *ar = getenv("AR");
return ar ? ar : "ar";
#endif
}
/*** files ***/
long long kon_mtime(const char *path) {
#ifdef _WIN32
struct _stat64 st;
if (_stat64(path, &st) != 0) return -1;
#else
struct stat st;
if (stat(path, &st) != 0) return -1;
#endif
return (long long)st.st_mtime;
}
bool kon_exists(const char *path) {
return kon_mtime(path) >= 0;
}
bool kon_isDir(const char *path) {
struct stat st;
if (stat(path, &st) != 0) return false;
return (st.st_mode & S_IFMT) == S_IFDIR;
}
bool kon_mkdir(const char *path) {
#ifdef _WIN32
if (_mkdir(path) == 0) return true;
#else
if (mkdir(path, 0755) == 0) return true;
#endif
return errno == EEXIST;
}
bool kon_mkdirs(const char *path) {
size_t n = strlen(path);
char *copy = (char *)malloc(n + 1);
size_t i;
bool ok;
if (!copy) return false;
memcpy(copy, path, n + 1);
for (i = 1; i < n; i++) {
if (copy[i] != '/' && copy[i] != '\\') continue;
copy[i] = '\0';
/* a drive like C: cannot be made, and one that is there already is fine, only the last one has to work */
kon_mkdir(copy);
copy[i] = path[i];
}
ok = kon_mkdir(copy) || kon_isDir(copy);
free(copy);
return ok;
}
bool kon_remove(const char *path) {
return remove(path) == 0;
}
bool kon_needsRebuild(const char *output, const char **sources, size_t nSources) {
long long outM = kon_mtime(output);
size_t i;
if (outM < 0) return true;
for (i = 0; i < nSources; i++)
if (kon_mtime(sources[i]) > outM) return true;
return false;
}
/*** lists ***/
static bool kon_listPush_(KonList *l, const char *s) {
size_t n = strlen(s);
char *copy;
if (l->count == l->cap) {
size_t cap = l->cap ? l->cap * 2 : 64;
char **items = (char **)realloc(l->items, cap * sizeof(char *));
if (!items) return false;
l->items = items;
l->cap = cap;
}
copy = (char *)malloc(n + 1);
if (!copy) return false;
memcpy(copy, s, n + 1);
l->items[l->count++] = copy;
return true;
}
void kon_freeList(KonList *l) {
size_t i;
for (i = 0; i < l->count; i++) free(l->items[i]);
free(l->items);
*l = (KonList){0};
}
static char *kon_join_(const char *dir, const char *name) {
size_t a = strlen(dir), b = strlen(name);
char *s = (char *)malloc(a + b + 2);
if (!s) return NULL;
memcpy(s, dir, a);
if (a > 0 && dir[a - 1] != '/' && dir[a - 1] != '\\') s[a++] = '/';
memcpy(s + a, name, b + 1);
return s;
}
/* calls back with every name in a folder, not . and .. . returns false if the folder cannot be read or the callback says stop */
static bool kon_eachName_(const char *dir, bool (*fn)(const char *name, void *user), void *user) {
#ifdef _WIN32
WIN32_FIND_DATAA fd;
HANDLE h;
char *pattern = kon_join_(dir, "*");
if (!pattern) return false;
h = FindFirstFileA(pattern, &fd);
free(pattern);
if (h == INVALID_HANDLE_VALUE) return false;
do {
if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue;
if (!fn(fd.cFileName, user)) {
FindClose(h);
return false;
}
} while (FindNextFileA(h, &fd));
FindClose(h);
return true;
#else
DIR *d = opendir(dir);
struct dirent *e;
if (!d) return false;
while ((e = readdir(d)) != NULL) {
if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue;
if (!fn(e->d_name, user)) {
closedir(d);
return false;
}
}
closedir(d);
return true;
#endif
}
typedef struct kon_newest_ {
const char *dir, *ext;
long long newest;
} kon_newest_;
static bool kon_newestName_(const char *name, void *user) {
kon_newest_ *s = (kon_newest_ *)user;
size_t n = strlen(name), e = strlen(s->ext);
if (n >= e && strcmp(name + n - e, s->ext) == 0) {
char *path = kon_join_(s->dir, name);
long long m = path ? kon_mtime(path) : -1;
free(path);
if (m > s->newest) s->newest = m;
}
return true;
}
long long kon_newestIn(const char *dir, const char *ext) {
kon_newest_ s;
s.dir = dir;
s.ext = ext;
s.newest = -1;
kon_eachName_(dir, kon_newestName_, &s);
return s.newest;
}
typedef struct kon_walk_ {
const char *dir;
KonList *out;
} kon_walk_;
static bool kon_walkInto_(const char *dir, KonList *out);
static bool kon_walkName_(const char *name, void *user) {
kon_walk_ *w = (kon_walk_ *)user;
char *path = kon_join_(w->dir, name);
bool ok;
if (!path) return false;
if (kon_isDir(path)) ok = kon_walkInto_(path, w->out);
else ok = kon_listPush_(w->out, path);
free(path);
return ok;
}
static bool kon_walkInto_(const char *dir, KonList *out) {
kon_walk_ w;
w.dir = dir;
w.out = out;
return kon_eachName_(dir, kon_walkName_, &w);
}
static int kon_compareNames_(const void *a, const void *b) {
return strcmp(*(char *const *)a, *(char *const *)b);
}
bool kon_listFiles(const char *dir, KonList *out) {
*out = (KonList){0};
if (!kon_walkInto_(dir, out)) {
kon_freeList(out);
return false;
}
if (out->count > 1) qsort(out->items, out->count, sizeof(char *), kon_compareNames_);
return true;
}
/*** commands ***/
static void kon_ensureCmd_(KonCmd *c, size_t extra) {
if (c->count + extra <= c->cap) return;
c->cap = (c->cap == 0) ? 16 : c->cap * 2;
while (c->cap < c->count + extra) c->cap *= 2;
c->items = (char **)realloc(c->items, c->cap * sizeof(char *));
if (!c->items) {
fprintf(stderr, "konbuild: out of memory\n");
exit(1);
}
}
void kon_pushCmd_(KonCmd *c, ...) {
va_list ap;
va_start(ap, c);
for (;;) {
char *a = va_arg(ap, char *);
if (!a) break;
kon_ensureCmd_(c, 1);
c->items[c->count++] = a;
}
va_end(ap);
}
void kon_resetCmd(KonCmd *c) {
c->count = 0;
}
void kon_freeCmd(KonCmd *c) {
free(c->items);
*c = (KonCmd){0};
}
static char **kon_temp_;
static size_t kon_tempCount_, kon_tempCap_;
char *kon_fmt(const char *format, ...) {
va_list ap, again;
int n;
char *s;
va_start(ap, format);
va_copy(again, ap);
n = vsnprintf(NULL, 0, format, ap);
va_end(ap);
if (n < 0) {
va_end(again);
fprintf(stderr, "konbuild: bad format\n");
exit(1);
}
s = (char *)malloc((size_t)n + 1);
if (!s) {
fprintf(stderr, "konbuild: out of memory\n");
exit(1);
}
vsnprintf(s, (size_t)n + 1, format, again);
va_end(again);
if (kon_tempCount_ == kon_tempCap_) {
kon_tempCap_ = kon_tempCap_ ? kon_tempCap_ * 2 : 64;
kon_temp_ = (char **)realloc(kon_temp_, kon_tempCap_ * sizeof(char *));
if (!kon_temp_) {
fprintf(stderr, "konbuild: out of memory\n");
exit(1);
}
}
kon_temp_[kon_tempCount_++] = s;
return s;
}
void kon_freeTemp(void) {
size_t i;
for (i = 0; i < kon_tempCount_; i++) free(kon_temp_[i]);
free(kon_temp_);
kon_temp_ = NULL;
kon_tempCount_ = kon_tempCap_ = 0;
}
static void kon_printCmd_(KonCmd *c) {
size_t i;
for (i = 0; i < c->count; i++) fprintf(stderr, "%s ", c->items[i]);
fprintf(stderr, "\n");
}
#ifdef _WIN32
/* the quoting that CommandLineToArgvW undoes: a quote is escaped with a backslash, and the backslashes right before it or before the closing quote are doubled */
static size_t kon_quoteArg_(char *out, const char *arg) {
size_t n = 0;
const char *p;
if (*arg && !strpbrk(arg, " \t\n\v\"")) {
size_t len = strlen(arg);
if (out) memcpy(out, arg, len);
return len;
}
if (out) out[n] = '"';
n++;
for (p = arg;; p++) {
size_t slashes = 0, i;
while (*p == '\\') {
p++;
slashes++;
}
if (*p == '\0') {
for (i = 0; i < slashes * 2; i++) {
if (out) out[n] = '\\';
n++;
}
break;
}
if (*p == '"') {
for (i = 0; i < slashes * 2 + 1; i++) {
if (out) out[n] = '\\';
n++;
}
} else {
for (i = 0; i < slashes; i++) {
if (out) out[n] = '\\';
n++;
}
}
if (out) out[n] = *p;
n++;
}
if (out) out[n] = '"';
n++;
return n;
}
bool kon_runCmdLog(KonCmd *c, const char *logPath) {
STARTUPINFOA si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
HANDLE log = INVALID_HANDLE_VALUE;
size_t total = 1, at = 0, i;
char *line;
bool ok;
DWORD code = 1;
kon_printCmd_(c);
if (c->count == 0) return false;
for (i = 0; i < c->count; i++) total += kon_quoteArg_(NULL, c->items[i]) + 1;
line = (char *)malloc(total);
if (!line) return false;
for (i = 0; i < c->count; i++) {
at += kon_quoteArg_(line + at, c->items[i]);
if (i + 1 < c->count) line[at++] = ' ';
}
line[at] = '\0';
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
if (logPath) {
memset(&sa, 0, sizeof(sa));
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
log = CreateFileA(logPath, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (log == INVALID_HANDLE_VALUE) {
fprintf(stderr, "konbuild: cannot open %s (%lu)\n", logPath, (unsigned long)GetLastError());
free(line);
return false;
}
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = log;
si.hStdError = log;
}
ok = CreateProcessA(NULL, line, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi) != 0;
free(line);
if (!ok) {
fprintf(stderr, "konbuild: could not start %s (%lu)\n", c->items[0], (unsigned long)GetLastError());
if (log != INVALID_HANDLE_VALUE) CloseHandle(log);
return false;
}
WaitForSingleObject(pi.hProcess, INFINITE);
GetExitCodeProcess(pi.hProcess, &code);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
if (log != INVALID_HANDLE_VALUE) CloseHandle(log);
return code == 0;
}
#else /* posix complian systems */
bool kon_runCmdLog(KonCmd *c, const char *logPath) {
pid_t pid;
int status = 0, fd = -1;
kon_printCmd_(c);
if (c->count == 0) return false;
kon_ensureCmd_(c, 1);
c->items[c->count] = NULL;
if (logPath) {
fd = open(logPath, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd < 0) {
fprintf(stderr, "konbuild: cannot open %s: %s\n", logPath, strerror(errno));
return false;
}
}
pid = fork();
if (pid < 0) {
fprintf(stderr, "konbuild: fork failed: %s\n", strerror(errno));
if (fd >= 0) close(fd);
return false;
}
if (pid == 0) {
if (fd >= 0) {
dup2(fd, 1);
dup2(fd, 2);
close(fd);
}
execvp(c->items[0], c->items);
fprintf(stderr, "konbuild: exec failed: %s: %s\n", c->items[0], strerror(errno));
_exit(127);
}
if (fd >= 0) close(fd);
while (waitpid(pid, &status, 0) < 0) {
if (errno == EINTR) continue;
fprintf(stderr, "konbuild: waitpid failed: %s\n", strerror(errno));
return false;
}
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
#endif
bool kon_runCmdSync(KonCmd *c) {
return kon_runCmdLog(c, NULL);
}
/*** rebuilding the build program ***/
void kon_rebuildSelf_(const char *src_path, int argc, char **argv) {
#ifndef _WIN32
(void)argc;
#endif
const char *self = argv[0];
const char *hdr_path = __FILE__;
long long srcM, binM, hdrM, newestM;
KonCmd cmd = {0};
#ifdef _WIN32
/* started as just "build", the file is build.exe. the old copy this leaves behind is cleared on the next start */
if (!kon_exists(self)) self = kon_fmt("%s.exe", self);
{
const char *old = kon_fmt("%s.old", self);
if (kon_exists(old)) kon_remove(old);
}
#endif
srcM = kon_mtime(src_path);
binM = kon_mtime(self);
if (srcM < 0 || binM < 0) return;
hdrM = kon_mtime(hdr_path);
newestM = (hdrM > srcM) ? hdrM : srcM;
if (newestM <= binM) return;
fprintf(stderr, "konbuild: %s or %s changed, rebuilding self...\n", src_path, hdr_path);
#ifdef _WIN32
/* a running program cannot be written over, but it can be renamed */
{
const char *old = kon_fmt("%s.old", self);
if (!MoveFileExA(self, old, MOVEFILE_REPLACE_EXISTING)) {
fprintf(stderr, "konbuild: could not move %s out of the way (%lu)\n", self, (unsigned long)GetLastError());
exit(1);
}
}
#endif
#if KON_TOOLCHAIN_MSVC
{
char *feFlag = kon_fmt("/Fe:%s", self);
kon_pushCmd(&cmd, (char *)kon_cc(), "/nologo", (char *)src_path, feFlag, NULL);
}
#else
kon_pushCmd(&cmd, (char *)kon_cc(), "-o", (char *)self, (char *)src_path, NULL);
#endif
if (!kon_runCmdSync(&cmd)) {
fprintf(stderr, "konbuild: self-rebuild failed\n");
exit(1);
}
kon_freeCmd(&cmd);
#ifdef _WIN32
{
KonCmd relaunch = {0};
bool ok;
int i;
kon_pushCmd(&relaunch, (char *)self, NULL);
for (i = 1; i < argc; i++) kon_pushCmd(&relaunch, argv[i], NULL);
ok = kon_runCmdSync(&relaunch);
kon_freeCmd(&relaunch);
exit(ok ? 0 : 1);
}
#else
execv(self, argv);
fprintf(stderr, "konbuild: exec self failed: %s\n", strerror(errno));
exit(1);
#endif
}
#endif /* end of KONBUILD_IMPLEMENTATION */
|