_build.inc.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. // gcc -lutil build.c -o hacer && ./hacer
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6. #include <errno.h>
  7. #include <stdarg.h>
  8. #include <signal.h>
  9. #include <unistd.h>
  10. #include <sys/prctl.h>
  11. #include <pty.h>
  12. #include <fcntl.h>
  13. #include <fnmatch.h>
  14. #include <dirent.h>
  15. #include <libgen.h>
  16. #include <sys/stat.h>
  17. #include <sys/types.h>
  18. #include <sys/wait.h>
  19. #include <sys/sysinfo.h>
  20. // link with -lutil
  21. // list all <header> files in use
  22. //egrep -ro '^\s*#\s*include\s+<(.*)>' src/ | sed -e 's/^.*<\(.*\)>.*$/\1/'
  23. char** g_gcc_opts_list;
  24. char* g_gcc_opts_flat;
  25. char* g_gcc_include;
  26. char* g_gcc_libs;
  27. int g_nprocs;
  28. struct child_process_info {
  29. int pid;
  30. char state; // 'q'ueued, 'r'unning, 'd'ead
  31. int exit_status;
  32. int pty;
  33. int child_stdin;
  34. int child_stdout;
  35. int child_stderr;
  36. FILE* f_stdin;
  37. FILE* f_stdout;
  38. FILE* f_stderr;
  39. char* output_buffer;
  40. size_t buf_alloc;
  41. size_t buf_len;
  42. };
  43. typedef struct rglob_entry {
  44. char type;
  45. char* full_path;
  46. char* file_name;
  47. // char* dir_name;
  48. } rglob_entry;
  49. typedef struct rglob {
  50. char* pattern;
  51. int len;
  52. int alloc;
  53. rglob_entry* entries;
  54. } rglob;
  55. typedef struct strlist {
  56. int len;
  57. int alloc;
  58. char** entries;
  59. } strlist;
  60. void free_strpp(char** l) {
  61. for(char** s = l; *s; s++) free(*s);
  62. free(l);
  63. }
  64. #define PP_ARG_N(_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, N, ...) N
  65. #define PP_RSEQ_N() 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
  66. #define PP_NARG_(...) PP_ARG_N(__VA_ARGS__)
  67. #define PP_NARG(...) PP_NARG_(__VA_ARGS__, PP_RSEQ_N())
  68. #define check_alloc(x) \
  69. if((x)->len + 1 >= (x)->alloc) { \
  70. (x)->alloc *= 2; \
  71. (x)->entries = realloc((x)->entries, (x)->alloc * sizeof(*(x)->entries)); \
  72. }
  73. void strlist_init(strlist* sl) {
  74. sl->len = 0;
  75. sl->alloc = 32;
  76. sl->entries = malloc(sl->alloc * sizeof(*sl->entries));
  77. }
  78. strlist* strlist_new() {
  79. strlist* sl = malloc(sizeof(*sl));
  80. strlist_init(sl);
  81. return sl;
  82. }
  83. void strlist_push(strlist* sl, char* e) {
  84. check_alloc(sl);
  85. sl->entries[sl->len++] = e;
  86. sl->entries[sl->len] = 0;
  87. }
  88. typedef unsigned long hash_t;
  89. hash_t strhash(char* str) {
  90. unsigned long h = 0;
  91. int c;
  92. while(c = *str++) {
  93. h = c + (h << 6) + (h << 16) - h;
  94. }
  95. return h;
  96. }
  97. hash_t strnhash(char* str, size_t n) {
  98. unsigned long h = 0;
  99. int c;
  100. while((c = *str++) && n--) {
  101. h = c + (h << 6) + (h << 16) - h;
  102. }
  103. return h;
  104. }
  105. typedef struct {
  106. hash_t hash;
  107. char* str;
  108. unsigned int len;
  109. int refs;
  110. } string_cache_bucket;
  111. typedef struct {
  112. int fill;
  113. int alloc;
  114. string_cache_bucket* buckets;
  115. } string_cache_t;
  116. string_cache_t string_cache;
  117. void string_cache_init(int alloc) {
  118. string_cache.fill = 0;
  119. string_cache.alloc = alloc ? alloc : 1024;
  120. string_cache.buckets = calloc(1, string_cache.alloc * sizeof(*string_cache.buckets));
  121. }
  122. int string_cache_find_bucket(string_cache_t* ht, hash_t hash, char* key) {
  123. int b = hash % ht->alloc;
  124. for(int i = 0; i < ht->alloc; i++) {
  125. // empty bucket
  126. if(ht->buckets[b].str == NULL) return b;
  127. // full bucket
  128. if(ht->buckets[b].hash == hash) {
  129. if(0 == strcmp(key, ht->buckets[b].str)) {
  130. return b;
  131. }
  132. }
  133. // probe forward on collisions
  134. b = (b + 1) % ht->alloc;
  135. }
  136. // should never reach here
  137. printf("oops. -1 bucket \n");
  138. return -1;
  139. }
  140. void string_cache_expand(string_cache_t* ht) {
  141. int old_alloc = ht->alloc;
  142. ht->alloc *= 2;
  143. string_cache_bucket* old = ht->buckets;
  144. ht->buckets = calloc(1, ht->alloc * sizeof(*ht->buckets));
  145. for(int i = 0, f = 0; i < old_alloc && f < ht->fill; i++) {
  146. if(!old[i].str) continue;
  147. int b = string_cache_find_bucket(ht, old[i].hash, old[i].str);
  148. ht->buckets[b] = old[i];
  149. f++;
  150. }
  151. free(old);
  152. }
  153. char* strcache(char* in) {
  154. hash_t hash = strhash(in);
  155. int b = string_cache_find_bucket(&string_cache, hash, in);
  156. if(!string_cache.buckets[b].str) {
  157. if(string_cache.fill > string_cache.alloc * .80) {
  158. string_cache_expand(&string_cache);
  159. // the bucket location has changed
  160. b = string_cache_find_bucket(&string_cache, hash, in);
  161. }
  162. string_cache.fill++;
  163. string_cache.buckets[b].str = strdup(in);
  164. string_cache.buckets[b].hash = hash;
  165. string_cache.buckets[b].refs = 1;
  166. string_cache.buckets[b].len = strlen(in);
  167. }
  168. else {
  169. string_cache.buckets[b].refs++;
  170. }
  171. return string_cache.buckets[b].str;
  172. }
  173. char* strncache(char* in, size_t n) {
  174. hash_t hash = strnhash(in, n);
  175. int b = string_cache_find_bucket(&string_cache, hash, in);
  176. if(!string_cache.buckets[b].str) {
  177. if(string_cache.fill > string_cache.alloc * .80) {
  178. string_cache_expand(&string_cache);
  179. // the bucket location has changed
  180. b = string_cache_find_bucket(&string_cache, hash, in);
  181. }
  182. string_cache.fill++;
  183. string_cache.buckets[b].str = strndup(in, n);
  184. string_cache.buckets[b].hash = hash;
  185. string_cache.buckets[b].refs = 1;
  186. string_cache.buckets[b].len = n;
  187. }
  188. else {
  189. string_cache.buckets[b].refs++;
  190. }
  191. return string_cache.buckets[b].str;
  192. }
  193. void struncache(char* in) {
  194. hash_t hash = strhash(in);
  195. int b = string_cache_find_bucket(&string_cache, hash, in);
  196. if(!string_cache.buckets[b].str) {
  197. // normal string, free it
  198. free(in);
  199. return;
  200. }
  201. string_cache.buckets[b].refs--;
  202. if(string_cache.buckets[b].refs == 0) {
  203. // just do nothing for now. deletion is a pain.
  204. }
  205. }
  206. typedef struct {
  207. hash_t hash;
  208. char* key;
  209. void* value;
  210. } hashbucket;
  211. typedef struct hashtable {
  212. int fill;
  213. int alloc;
  214. hashbucket* buckets;
  215. } hashtable;
  216. void hash_init(hashtable* ht, int alloc) {
  217. ht->fill = 0;
  218. ht->alloc = alloc ? alloc : 128;
  219. ht->buckets = calloc(1, ht->alloc * sizeof(*ht->buckets));
  220. }
  221. hashtable* hash_new(int alloc) {
  222. hashtable* ht = malloc(sizeof(*ht));
  223. hash_init(ht, alloc);
  224. return ht;
  225. }
  226. int hash_find_bucket(hashtable* ht, hash_t hash, char* key) {
  227. int b = hash % ht->alloc;
  228. for(int i = 0; i < ht->alloc; i++) {
  229. // empty bucket
  230. if(ht->buckets[b].key == NULL) return b;
  231. // full bucket
  232. if(ht->buckets[b].hash == hash) {
  233. if(0 == strcmp(key, ht->buckets[b].key)) {
  234. return b;
  235. }
  236. }
  237. // probe forward on collisions
  238. b = (b + 1) % ht->alloc;
  239. }
  240. // should never reach here
  241. printf("oops. -1 bucket \n");
  242. return -1;
  243. }
  244. void hash_expand(hashtable* ht) {
  245. int old_alloc = ht->alloc;
  246. ht->alloc *= 2;
  247. hashbucket* old = ht->buckets;
  248. ht->buckets = calloc(1, ht->alloc * sizeof(*ht->buckets));
  249. for(int i = 0, f = 0; i < old_alloc && f < ht->fill; i++) {
  250. if(!old[i].key) continue;
  251. int b = hash_find_bucket(ht, old[i].hash, old[i].key);
  252. ht->buckets[b] = old[i];
  253. f++;
  254. }
  255. free(old);
  256. }
  257. void hash_insert(hashtable* ht, char* key, void* value) {
  258. hash_t hash = strhash(key);
  259. int b = hash_find_bucket(ht, hash, key);
  260. if(!ht->buckets[b].key) {
  261. if(ht->fill > ht->alloc * .80) {
  262. hash_expand(ht);
  263. // the bucket location has changed
  264. b = hash_find_bucket(ht, hash, key);
  265. }
  266. ht->fill++;
  267. }
  268. ht->buckets[b].key = strcache(key);
  269. ht->buckets[b].hash = hash;
  270. ht->buckets[b].value = value;
  271. }
  272. void* hash_find(hashtable* ht, char* key) {
  273. hash_t hash = strhash(key);
  274. int b = hash_find_bucket(ht, hash, key);
  275. return ht->buckets[b].value;
  276. }
  277. // splits on whitespace
  278. char** strsplit(char* splitters, char* in) {
  279. char* e;
  280. int alloc = 32;
  281. int len = 0;
  282. char** list = malloc(alloc * sizeof(*list));
  283. for(char* s = in; *s;) {
  284. e = strpbrk(s, splitters);
  285. if(!e) e = s + strlen(s);
  286. if(len >= alloc - 1) {
  287. alloc *= 2;
  288. list = realloc(list, alloc* sizeof(*list));
  289. }
  290. list[len++] = strndup(s, e - s);
  291. e += strspn(e, splitters);
  292. s = e;
  293. }
  294. list[len] = NULL;
  295. return list;
  296. }
  297. struct child_process_info* exec_cmdline_pipe(char* cmdline);
  298. struct child_process_info* exec_process_pipe(char* exec_path, char* args[]);
  299. int mkdirp(char* path, mode_t mode);
  300. char* resolve_path(char* in, time_t* mtime_out);
  301. #define path_join(...) path_join_(PP_NARG(__VA_ARGS__), __VA_ARGS__)
  302. char* path_join_(size_t nargs, ...);
  303. #define concat_lists(...) concat_lists_(PP_NARG(__VA_ARGS__), __VA_ARGS__)
  304. char** concat_lists_(int nargs, ...);
  305. #define strjoin(j, ...) strjoin_(j, PP_NARG(__VA_ARGS__), __VA_ARGS__)
  306. char* strjoin_(char* joiner, size_t nargs, ...);
  307. #define strcatdup(...) strcatdup_(PP_NARG(__VA_ARGS__), __VA_ARGS__)
  308. char* strcatdup_(size_t nargs, ...);
  309. void recursive_glob(char* base_path, char* pattern, int flags, rglob* results);
  310. char* dir_name(char* path);
  311. char* base_name(char* path);
  312. size_t list_len(char** list);
  313. char* join_str_list(char* list[], char* joiner);
  314. char* sprintfdup(char* fmt, ...);
  315. char* read_whole_file(char* path, size_t* srcLen);
  316. static inline char* strskip(char* s, char* skip) {
  317. return s + strspn(s, skip);
  318. }
  319. #define FSU_EXCLUDE_HIDDEN (1<<0)
  320. #define FSU_NO_FOLLOW_SYMLINKS (1<<1)
  321. #define FSU_INCLUDE_DIRS (1<<2)
  322. #define FSU_EXCLUDE_FILES (1<<3)
  323. char* pkg_config(char** packages, char* opts) {
  324. char* tmp;
  325. char* pkgs = join_str_list(packages, " ");
  326. for(char* c = opts; *c; c++) {
  327. switch(*c) {
  328. case 'c':
  329. case 'C':
  330. case 'i':
  331. case 'I':
  332. tmp = strjoin(" ", "--cflags", pkgs);
  333. free(pkgs);
  334. pkgs = tmp;
  335. break;
  336. case 'l':
  337. case 'L':
  338. tmp = strjoin(" ", "--libs", pkgs);
  339. free(pkgs);
  340. pkgs = tmp;
  341. break;
  342. }
  343. }
  344. tmp = strjoin(" ", "pkg-config", pkgs);
  345. free(pkgs);
  346. FILE* f = popen(tmp, "r");
  347. free(tmp);
  348. if(!f) {
  349. fprintf(stderr, "Could not run command '%s'\n", tmp);
  350. exit(1);
  351. return NULL;
  352. }
  353. int len = 2048;
  354. int fill = 0;
  355. char* buffer = malloc(len * sizeof(*buffer));
  356. while(!feof(f)) {
  357. if(fill + 1 >= len) {
  358. len *= 2;
  359. buffer = realloc(buffer, len * sizeof(*buffer));
  360. }
  361. fill += fread(buffer + fill, 1, len - fill - 1, f);
  362. }
  363. buffer[fill] = 0;
  364. pclose(f);
  365. // strip out newlines and other garbage
  366. for(char* c = buffer; *c; c++) if(isspace(*c)) *c = ' ';
  367. return buffer;
  368. }
  369. // return 0 to continue, nonzero to stop all directory scanning
  370. typedef int (*readDirCallbackFn)(char* /*fullPath*/, char* /*fileName*/, unsigned char /*type*/, void* /*data*/);
  371. // returns negative on error, nonzero if scanning was halted by the callback
  372. int recurse_dirs(
  373. char* path,
  374. readDirCallbackFn fn,
  375. void* data,
  376. int depth,
  377. unsigned int flags
  378. );
  379. typedef struct realname_entry {
  380. char* realname;
  381. time_t mtime;
  382. } realname_entry;
  383. struct {
  384. /*
  385. struct {
  386. int len;
  387. int alloc;
  388. struct {
  389. char* fake_name;
  390. realname_entry* entry;
  391. }* entries;
  392. } lookup; */
  393. hashtable names;
  394. int len;
  395. int alloc;
  396. struct realname_entry* entries;
  397. } realname_cache;
  398. void realname_cache_init();
  399. time_t realname_cache_add(char* fake_name, char* real_name);
  400. realname_entry* realname_cache_search_real(char* real_name);
  401. realname_entry* realname_cache_search(char* fake_name);
  402. char* realname_cache_find(char* fake_name);
  403. hashtable mkdir_cache;
  404. strlist compile_cache;
  405. void mkdirp_cached(char* path, mode_t mode) {
  406. void* there = hash_find(&mkdir_cache, path);
  407. if(!there) {
  408. hash_insert(&mkdir_cache, path, NULL);
  409. mkdirp(path, mode);
  410. }
  411. }
  412. void read_cpi(struct child_process_info* cpi) {
  413. while(1) {
  414. if(cpi->buf_len > cpi->buf_alloc - 128) {
  415. cpi->buf_alloc *= 2;
  416. cpi->output_buffer = realloc(cpi->output_buffer, cpi->buf_alloc * sizeof(*cpi->output_buffer));
  417. }
  418. int ret = read(cpi->pty, cpi->output_buffer + cpi->buf_len, cpi->buf_alloc - cpi->buf_len - 1);
  419. if(ret > 0) cpi->buf_len += ret;
  420. else return;
  421. }
  422. return ;
  423. }
  424. char* printpct(float f) {
  425. static char buf[32];
  426. if(f != 100) sprintf(buf, "\e[1;33m %2.0f%%\e[0m", f);
  427. else sprintf(buf, "\e[1;32m100%%\e[0m", f);
  428. return buf;
  429. }
  430. int execute_mt(strlist* cmds, int threads, char* fmt, struct child_process_info*** cpis) {
  431. int ret = 0;
  432. int running = 0;
  433. struct child_process_info** procs = calloc(1, cmds->len * sizeof(*procs));
  434. if(cpis) *cpis = procs;
  435. if(fmt) printf(fmt, printpct(0)), fflush(stdout);
  436. int waiting = cmds->len;
  437. while(waiting > 0) {
  438. for(int i = 0; i < cmds->len; i++) {
  439. // keep the cores full
  440. if(!procs[i] && running < threads) {
  441. procs[i] = exec_cmdline_pipe(cmds->entries[i]);
  442. procs[i]->state = 'r';
  443. running++;
  444. }
  445. if(!procs[i] || procs[i]->state == 'd') continue;
  446. read_cpi(procs[i]);
  447. int status;
  448. // returns 0 if nothing happened, -1 on error, childpid if it exited
  449. int pid = waitpid(procs[i]->pid, &status, WNOHANG);
  450. if(pid != 0) {
  451. procs[i]->state = 'd';
  452. waiting--;
  453. running--;
  454. if(fmt) printf("\r"), printf(fmt, printpct((cmds->len - waiting) * 100.0f / (float)cmds->len)), fflush(stdout);
  455. read_cpi(procs[i]);
  456. procs[i]->output_buffer[procs[i]->buf_len] = 0;
  457. procs[i]->exit_status = WEXITSTATUS(status);
  458. if(!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
  459. // printf("error on pid %d/%d = %d\n", pid, procs[i]->pid, WEXITSTATUS(status));
  460. // printf("%s\n", procs[i]->output_buffer);
  461. ret = 1;
  462. }
  463. }
  464. }
  465. usleep(100);
  466. }
  467. if(fmt) {
  468. printf("\r");
  469. if(ret) printf(fmt, "\e[1;31mFAIL\e[0m");
  470. else printf(fmt, "\e[32mDONE\e[0m");
  471. fflush(stdout);
  472. }
  473. printf("\n");
  474. return ret;
  475. }
  476. int compile_cache_execute() {
  477. int ret = 0;
  478. struct child_process_info** cpis;
  479. // printf("compile cache length %d", compile_cache.len);
  480. ret = execute_mt(&compile_cache, g_nprocs, "Compiling... %s", &cpis);
  481. if(ret) {
  482. for(int i = 0; i < compile_cache.len; i++ ) {
  483. if(cpis[i]->exit_status) {
  484. printf("%.*s\n", (int)cpis[i]->buf_len, cpis[i]->output_buffer);
  485. }
  486. }
  487. }
  488. // TODO free compile cache
  489. // TODO free cpis
  490. return ret;
  491. }
  492. size_t span_path(char* s) {
  493. size_t n = 0;
  494. for(; *s; s++, n++) {
  495. if(isspace(*s)) break;
  496. if(*s == '\\') {
  497. s++;
  498. n++;
  499. }
  500. }
  501. return n;
  502. }
  503. strlist* parse_gcc_dep_file(char* dep_file_path, time_t* newest_mtime) {
  504. size_t dep_src_len = 0;
  505. strlist* dep_list;
  506. time_t newest = 0;
  507. char* dep_src = read_whole_file(dep_file_path, &dep_src_len);
  508. if(!dep_src) return NULL;
  509. dep_list = strlist_new();
  510. // skip the first filename junk
  511. char* s = strchr(dep_src, ':');
  512. s++;
  513. int ret = 0;
  514. // gather dep strings, ignoring line continuations
  515. while(*s) {
  516. do {
  517. s = strskip(s, " \t\r\n");
  518. if(*s == '\\') {
  519. if(s[1] == '\r') s++;
  520. if(s[1] == '\n') s++;
  521. }
  522. } while(isspace(*s));
  523. int dlen = span_path(s);
  524. if(dlen == 0) break;
  525. time_t dep_mtime;
  526. char* dep_fake = strncache(s, dlen);
  527. char* dep_real = resolve_path(dep_fake, &dep_mtime);
  528. if(dep_mtime > newest) newest = dep_mtime;
  529. strlist_push(dep_list, dep_real);
  530. struncache(dep_fake);
  531. struncache(dep_real);
  532. s += dlen;
  533. }
  534. free(dep_src);
  535. if(newest_mtime) *newest_mtime = newest;
  536. return dep_list;
  537. }
  538. int gen_deps(char* src_path, char* dep_path, time_t src_mtime, time_t obj_mtime) {
  539. time_t dep_mtime = 0;
  540. time_t newest_mtime = 0;
  541. char* real_dep_path = resolve_path(dep_path, &dep_mtime);
  542. if(dep_mtime < src_mtime) {
  543. //gcc -MM -MG -MT $1 -MF "build/$1.d" $1 $CFLAGS $LDADD
  544. // printf(" generating deps\n");
  545. char* cmd = sprintfdup("gcc -MM -MG -MT '' -MF %s %s %s", dep_path, src_path, g_gcc_opts_flat);
  546. system(cmd);
  547. free(cmd);
  548. }
  549. strlist* deps = parse_gcc_dep_file(real_dep_path, &newest_mtime);
  550. // free or process deps
  551. return newest_mtime > obj_mtime;
  552. FAIL:
  553. return 0;
  554. }
  555. size_t list_len(char** list) {
  556. size_t total = 0;
  557. for(; *list; list++) total++;
  558. return total;
  559. }
  560. char** concat_lists_(int nargs, ...) {
  561. size_t total = 0;
  562. char** out, **end;
  563. if(nargs == 0) return NULL;
  564. // calculate total list length
  565. va_list va;
  566. va_start(va, nargs);
  567. for(size_t i = 0; i < nargs; i++) {
  568. char** s = va_arg(va, char**);
  569. if(s) total += list_len(s);
  570. }
  571. va_end(va);
  572. out = malloc((total + 1) * sizeof(char**));
  573. end = out;
  574. va_start(va, nargs);
  575. // concat lists
  576. for(size_t i = 0; i < nargs; i++) {
  577. char** s = va_arg(va, char**);
  578. size_t l = list_len(s);
  579. if(s) {
  580. memcpy(end, s, l * sizeof(*s));
  581. end += l;
  582. }
  583. }
  584. va_end(va);
  585. *end = 0;
  586. return out;
  587. }
  588. char* join_str_list(char* list[], char* joiner) {
  589. size_t list_len = 0;
  590. size_t total = 0;
  591. size_t jlen = strlen(joiner);
  592. // calculate total length
  593. for(int i = 0; list[i]; i++) {
  594. list_len++;
  595. total += strlen(list[i]);
  596. }
  597. if(total == 0) return strdup("");
  598. total += (list_len - 1) * jlen;
  599. char* out = malloc((total + 1) * sizeof(*out));
  600. char* end = out;
  601. for(int i = 0; list[i]; i++) {
  602. char* s = list[i];
  603. size_t l = strlen(s);
  604. if(i > 0) {
  605. memcpy(end, joiner, jlen);
  606. end += jlen;
  607. }
  608. if(s) {
  609. memcpy(end, s, l);
  610. end += l;
  611. }
  612. total += strlen(list[i]);
  613. }
  614. *end = 0;
  615. return out;
  616. }
  617. // concatenate all argument strings together in a new buffer
  618. char* strcatdup_(size_t nargs, ...) {
  619. size_t total = 0;
  620. char* out, *end;
  621. if(nargs == 0) return NULL;
  622. // calculate total buffer len
  623. va_list va;
  624. va_start(va, nargs);
  625. for(size_t i = 0; i < nargs; i++) {
  626. char* s = va_arg(va, char*);
  627. if(s) total += strlen(s);
  628. }
  629. va_end(va);
  630. out = malloc((total + 1) * sizeof(char*));
  631. end = out;
  632. va_start(va, nargs);
  633. for(size_t i = 0; i < nargs; i++) {
  634. char* s = va_arg(va, char*);
  635. if(s) {
  636. strcpy(end, s); // not exactly the ost efficient, but maybe faster than
  637. end += strlen(s); // a C version. TODO: test the speed
  638. };
  639. }
  640. va_end(va);
  641. *end = 0;
  642. return out;
  643. }
  644. // concatenate all argument strings together in a new buffer,
  645. // with the given joining string between them
  646. char* strjoin_(char* joiner, size_t nargs, ...) {
  647. size_t total = 0;
  648. char* out, *end;
  649. size_t j_len;
  650. if(nargs == 0) return NULL;
  651. // calculate total buffer len
  652. va_list va;
  653. va_start(va, nargs);
  654. for(size_t i = 0; i < nargs; i++) {
  655. char* s = va_arg(va, char*);
  656. if(s) total += strlen(s);
  657. }
  658. va_end(va);
  659. j_len = strlen(joiner);
  660. total += j_len * (nargs - 1);
  661. out = malloc((total + 1) * sizeof(char*));
  662. end = out;
  663. va_start(va, nargs);
  664. for(size_t i = 0; i < nargs; i++) {
  665. char* s = va_arg(va, char*);
  666. if(s) {
  667. if(i > 0) {
  668. strcpy(end, joiner);
  669. end += j_len;
  670. }
  671. strcpy(end, s); // not exactly the ost efficient, but maybe faster than
  672. end += strlen(s); // a C version. TODO: test the speed
  673. };
  674. }
  675. va_end(va);
  676. *end = 0;
  677. return out;
  678. }
  679. // allocates a new buffer and calls sprintf with it
  680. // why isn't this a standard function?
  681. char* sprintfdup(char* fmt, ...) {
  682. va_list va;
  683. va_start(va, fmt);
  684. size_t n = vsnprintf(NULL, 0, fmt, va);
  685. char* buf = malloc(n + 1);
  686. va_end(va);
  687. va_start(va, fmt);
  688. vsnprintf(buf, n + 1, fmt, va);
  689. va_end(va);
  690. return buf;
  691. }
  692. char* dir_name(char* path) {
  693. char* n = strdup(path);
  694. char* o = dirname(n);
  695. return strcache(o);
  696. }
  697. char* base_name(char* path) {
  698. char* n = strdup(path);
  699. char* o = basename(n);
  700. return strcache(o);
  701. }
  702. int rglob_fn(char* full_path, char* file_name, unsigned char type, void* _results) {
  703. rglob* res = (rglob*)_results;
  704. if(0 == fnmatch(res->pattern, file_name, 0)) {
  705. check_alloc(res);
  706. res->entries[res->len].type = type;
  707. res->entries[res->len].full_path = strcache(full_path);
  708. res->entries[res->len].file_name = strcache(file_name);
  709. res->len++;
  710. }
  711. return 0;
  712. }
  713. void recursive_glob(char* base_path, char* pattern, int flags, rglob* results) {
  714. // to pass into recurse_dirs()
  715. results->pattern = pattern;
  716. results->len = 0;
  717. results->alloc = 32;
  718. results->entries = malloc(sizeof(*results->entries) * results->alloc);
  719. recurse_dirs(base_path, rglob_fn, results, -1, flags);
  720. }
  721. // does not handle escaped slashes
  722. int mkdirp(char* path, mode_t mode) {
  723. char* clean_path = strdup(path);
  724. // inch along the path creating each directory in line
  725. for(char* p = clean_path; *p; p++) {
  726. if(*p == '/') {
  727. *p = 0;
  728. if(mkdir(clean_path, mode)) {
  729. if(errno != EEXIST) goto FAIL;
  730. }
  731. *p = '/';
  732. }
  733. }
  734. // mop up the last dir
  735. if(mkdir(clean_path, mode)) {
  736. if(errno != EEXIST) goto FAIL;
  737. }
  738. free(clean_path);
  739. return 0;
  740. FAIL:
  741. free(clean_path);
  742. return -1;
  743. }
  744. void realname_cache_init() {
  745. realname_cache.len = 0;
  746. realname_cache.alloc = 1024;
  747. realname_cache.entries = malloc(realname_cache.alloc * sizeof(*realname_cache.entries));
  748. hash_init(&realname_cache.names, 1024);
  749. }
  750. time_t realname_cache_add(char* fake_name, char* real_name) {
  751. realname_entry* e = hash_find(&realname_cache.names, fake_name);
  752. if(e) return e->mtime;
  753. e = hash_find(&realname_cache.names, real_name);
  754. if(!e) {
  755. struct stat st;
  756. lstat(real_name, &st);
  757. e = &realname_cache.entries[realname_cache.len];
  758. e->realname = strcache(real_name);
  759. e->mtime = st.st_mtim.tv_sec;
  760. realname_cache.len++;
  761. hash_insert(&realname_cache.names, real_name, e);
  762. }
  763. hash_insert(&realname_cache.names, fake_name, e);
  764. return e->mtime;
  765. }
  766. realname_entry* realname_cache_search_real(char* real_name) {
  767. for(int i = 0; i < realname_cache.len; i++) {
  768. if(0 == strcmp(real_name, realname_cache.entries[i].realname)) {
  769. return &realname_cache.entries[i];
  770. }
  771. }
  772. return NULL;
  773. }
  774. realname_entry* realname_cache_search(char* fake_name) {
  775. return hash_find(&realname_cache.names, fake_name);
  776. }
  777. char* realname_cache_find(char* fake_name) {
  778. realname_entry* r = realname_cache_search(fake_name);
  779. return r ? r->realname : NULL;
  780. }
  781. // works like realpath(), except also handles ~/
  782. char* resolve_path(char* in, time_t* mtime_out) {
  783. int tmp_was_malloced = 0;
  784. char* out, *tmp;
  785. if(!in) return NULL;
  786. realname_entry* e = realname_cache_search(in);
  787. if(e) {
  788. if(mtime_out) *mtime_out = e->mtime;
  789. return strcache(e->realname);
  790. }
  791. // skip leading whitespace
  792. while(isspace(*in)) in++;
  793. // handle home dir shorthand
  794. if(in[0] == '~') {
  795. char* home = getenv("HOME");
  796. tmp_was_malloced = 1;
  797. tmp = malloc(sizeof(*tmp) * (strlen(home) + strlen(in) + 2));
  798. strcpy(tmp, home);
  799. strcat(tmp, "/"); // just in case
  800. strcat(tmp, in + 1);
  801. }
  802. else tmp = in;
  803. out = realpath(tmp, NULL);
  804. if(tmp_was_malloced) free(tmp);
  805. time_t t = 0;
  806. if(out) {
  807. // put it in the cache
  808. t = realname_cache_add(in, out);
  809. }
  810. else {
  811. // temporary
  812. struct stat st;
  813. if(!lstat(in, &st))
  814. t = st.st_mtim.tv_sec;
  815. }
  816. if(mtime_out) *mtime_out = t;
  817. return out ? out : in;
  818. }
  819. char* path_join_(size_t nargs, ...) {
  820. size_t total = 0;
  821. char* out, *end;
  822. size_t j_len;
  823. char* joiner = "/";
  824. int escape;
  825. if(nargs == 0) return NULL;
  826. // calculate total buffer length
  827. va_list va;
  828. va_start(va, nargs);
  829. for(size_t i = 0; i < nargs; i++) {
  830. char* s = va_arg(va, char*);
  831. if(s) total += strlen(s);
  832. }
  833. va_end(va);
  834. j_len = strlen(joiner);
  835. total += j_len * (nargs - 1);
  836. out = malloc((total + 1) * sizeof(char*));
  837. end = out;
  838. va_start(va, nargs);
  839. for(size_t i = 0; i < nargs; i++) {
  840. char* s = va_arg(va, char*);
  841. size_t l = strlen(s);
  842. if(s) {
  843. if(l > 1) {
  844. escape = s[l-2] == '\\' ? 1 : 0;
  845. }
  846. if(i > 0 && (s[0] == joiner[0])) {
  847. s++;
  848. l--;
  849. }
  850. if(i > 0 && i != nargs-1 && !escape && (s[l-1] == joiner[0])) {
  851. l--;
  852. }
  853. if(i > 0) {
  854. strcpy(end, joiner);
  855. end += j_len;
  856. }
  857. // should be strncpy, but GCC is so fucking stupid that it
  858. // has a warning about using strncpy to do exactly what
  859. // strncpy does if you read the fucking man page.
  860. // fortunately, we are already terminating our strings
  861. // manually so memcpy is a drop-in replacement here.
  862. memcpy(end, s, l);
  863. end += l;
  864. }
  865. }
  866. va_end(va);
  867. *end = 0;
  868. return out;
  869. }
  870. // returns negative on error, nonzero if scanning was halted by the callback
  871. int recurse_dirs(
  872. char* path,
  873. readDirCallbackFn fn,
  874. void* data,
  875. int depth,
  876. unsigned int flags
  877. ) {
  878. DIR* derp;
  879. struct dirent* result;
  880. int stop = 0;
  881. if(fn == NULL) {
  882. fprintf(stderr, "Error: readAllDir called with null function pointer.\n");
  883. return -1;
  884. }
  885. derp = opendir(path);
  886. if(derp == NULL) {
  887. fprintf(stderr, "Error opening directory '%s': %s\n", path, strerror(errno));
  888. return -1;
  889. }
  890. while((result = readdir(derp)) && !stop) {
  891. char* n = result->d_name;
  892. unsigned char type = DT_UNKNOWN;
  893. char* fullPath;
  894. // skip self and parent dir entries
  895. if(n[0] == '.') {
  896. if(n[1] == '.' && n[2] == 0) continue;
  897. if(n[1] == 0) continue;
  898. if(flags & FSU_EXCLUDE_HIDDEN) continue;
  899. }
  900. #ifdef _DIRENT_HAVE_D_TYPE
  901. type = result->d_type; // the way life should be
  902. #else
  903. // do some slow extra bullshit to get the type
  904. fullPath = path_join(path, n);
  905. struct stat upgrade_your_fs;
  906. lstat(fullPath, &upgrade_your_fs);
  907. if(S_ISREG(upgrade_your_fs.st_mode)) type = DT_REG;
  908. else if(S_ISDIR(upgrade_your_fs.st_mode)) type = DT_DIR;
  909. else if(S_ISLNK(upgrade_your_fs.st_mode)) type = DT_LNK;
  910. #endif
  911. if(flags & FSU_NO_FOLLOW_SYMLINKS && type == DT_LNK) {
  912. continue;
  913. }
  914. #ifdef _DIRENT_HAVE_D_TYPE
  915. fullPath = path_join(path, n);
  916. #endif
  917. if(type == DT_DIR) {
  918. if(flags & FSU_INCLUDE_DIRS) {
  919. stop = fn(fullPath, n, type, data);
  920. }
  921. if(depth != 0) {
  922. stop |= recurse_dirs(fullPath, fn, data, depth - 1, flags);
  923. }
  924. }
  925. else if(type == DT_REG) {
  926. if(!(flags & FSU_EXCLUDE_FILES)) {
  927. stop = fn(fullPath, n, type, data);
  928. }
  929. }
  930. free(fullPath);
  931. }
  932. closedir(derp);
  933. return stop;
  934. }
  935. struct child_process_info* exec_cmdline_pipe(char* cmdline) {
  936. // kinda janky. it doesn't handle quotes
  937. char** args = strsplit(" ", cmdline);
  938. struct child_process_info* cpi = exec_process_pipe(args[0], args);
  939. // printf("executing '%s'\n", cmdline);
  940. // for(char** s = args; *s; s++) printf("%d - '%s'\n", (s-args), *s);
  941. free_strpp(args);
  942. return cpi;
  943. }
  944. // effectively a better, asynchronous version of system()
  945. // redirects and captures the child process i/o
  946. struct child_process_info* exec_process_pipe(char* exec_path, char* args[]) {
  947. int master, slave; // pty
  948. errno = 0;
  949. if(openpty(&master, &slave, NULL, NULL, NULL) < 0) {
  950. fprintf(stderr, "Error opening new pty for '%s' [errno=%d]\n", exec_path, errno);
  951. return NULL;
  952. }
  953. errno = 0;
  954. int childPID = fork();
  955. if(childPID == -1) {
  956. fprintf(stderr, "failed to fork trying to execute '%s'\n", exec_path);
  957. perror(strerror(errno));
  958. return NULL;
  959. }
  960. else if(childPID == 0) { // child process
  961. setsid();
  962. // redirect standard fd's to the pipe fd's
  963. if(dup2(slave, fileno(stdin)) == -1) {
  964. printf("failed 1\n");
  965. exit(errno);
  966. }
  967. if(dup2(slave, fileno(stdout)) == -1) {
  968. printf("failed 2\n");
  969. exit(errno);
  970. }
  971. if(dup2(slave, fileno(stderr)) == -1) {
  972. printf("failed 3\n");
  973. exit(errno);
  974. }
  975. if(ioctl(slave, TIOCSCTTY, NULL) < 0) {
  976. fprintf(stderr, "ioctl TIOCSCTTY failed: %s, %d\n", exec_path, errno);
  977. }
  978. // close original fd's
  979. close(master);
  980. close(slave);
  981. // die when the parent does (linux only)
  982. prctl(PR_SET_PDEATHSIG, SIGHUP);
  983. // swap for the desired program
  984. execvp(exec_path, args); // never returns if successful
  985. fprintf(stderr, "failed to execute '%s'\n", exec_path);
  986. exit(1); // kill the forked process
  987. }
  988. else { // parent process
  989. // close the child-end of the pipes
  990. struct child_process_info* cpi;
  991. cpi = calloc(1, sizeof(*cpi));
  992. cpi->pid = childPID;
  993. cpi->pty = master;
  994. cpi->state = 'q';
  995. cpi->buf_alloc = 4096;
  996. cpi->output_buffer = malloc(cpi->buf_alloc * sizeof(*cpi->output_buffer));
  997. // set to non-blocking
  998. fcntl(master, F_SETFL, fcntl(master, F_GETFL) | FNDELAY | O_NONBLOCK);
  999. close(slave);
  1000. // tcsetattr(STDIN_FILENO, TCSANOW, &master);
  1001. // fcntl(master, F_SETFL, FNDELAY);
  1002. // int status;
  1003. // returns 0 if nothing happened, -1 on error
  1004. // pid = waitpid(childPID, &status, WNOHANG);
  1005. return cpi;
  1006. }
  1007. return NULL; // shouldn't reach here
  1008. }
  1009. char* read_whole_file(char* path, size_t* srcLen) {
  1010. size_t fsize, total_read = 0, bytes_read;
  1011. char* contents;
  1012. FILE* f;
  1013. f = fopen(path, "rb");
  1014. if(!f) {
  1015. fprintf(stderr, "Could not open file \"%s\"\n", path);
  1016. return NULL;
  1017. }
  1018. fseek(f, 0, SEEK_END);
  1019. fsize = ftell(f);
  1020. rewind(f);
  1021. contents = malloc(fsize + 1);
  1022. while(total_read < fsize) {
  1023. bytes_read = fread(contents + total_read, sizeof(char), fsize - total_read, f);
  1024. total_read += bytes_read;
  1025. }
  1026. contents[fsize] = 0;
  1027. fclose(f);
  1028. if(srcLen) *srcLen = fsize;
  1029. return contents;
  1030. }