C-Menu 0.2.9
A User Interface Toolkit
Loading...
Searching...
No Matches
lf.c
Go to the documentation of this file.
1/** @file lf.c
2 @v0.3.3
3 @brief list files based on matching criteria
4 @author Bill Waller
5 Copyright (c) 2026
6 MIT License
7 billxwaller@gmail.com
8 @date 2026-09-22
9 */
10#define _GNU_SOURCE
11#include "lf.h"
12#include <argp.h>
13#include <dirent.h>
14#include <errno.h>
15#include <fcntl.h>
16#include <grp.h>
17#include <inttypes.h>
18#include <linux/limits.h>
19#include <locale.h>
20#include <pthread.h>
21#include <pwd.h>
22#include <regex.h>
23#include <stdarg.h>
24#include <stdatomic.h>
25#include <stdbool.h>
26#include <stddef.h>
27#include <stdint.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
31#include <sys/mman.h>
32#include <sys/resource.h>
33#include <sys/stat.h>
34#include <sys/syscall.h>
35#include <sys/sysinfo.h>
36#include <sys/types.h>
37#include <time.h>
38#include <unistd.h>
39#include <valgrind/helgrind.h>
40
41MemMetrics mm;
42char em0[MAXLEN];
43char em1[MAXLEN];
44char em2[MAXLEN];
45char em3[MAXLEN];
46char em4[MAXLEN];
47
48struct tm tm_info;
49
50// char *xpath;
52const char *argp_program_bug_address = "billxwaller@gmail.com";
53const char doc[] =
54 _("lf list files\nIf specified, DIRECTORY is the top-level\n directory to "
55 "search. REGULAR_EXPRESSION is a properly\nformatted regular expression "
56 "for which matching files\nwill be listed.");
57bool is_hidden(const char *);
58bool is_dirsys(const char *);
59static char args_doc[] = "[DIRECTORY] [REGULAR_EXPRESSION]";
60TerminationStatus termination_status;
61const char *log_s[] = {LOG_LEVEL_LIST(AS_STRINGS)};
63log_level ll_t[] = {
64 [NONE] = {'1', "NONE", 0, "\033[37m"},
65 [CONFIG] = {'1', "CONFIG", 0b1, "\033[37m"},
66 [INFO] = {'2', "INFO", 0b10, "\033[1;30;46m"},
67 [ERROR] = {'3', "ERROR", 0b100, "\033[1;38;2;255;150;0m"},
68 [DEBUG] = {'4', "DEBUG", 0b1000, "\033[31m"},
69 [CYCLE] = {'5', "CYCLE", 0b10000, "\033[33m"},
70 [ENQUEUE] = {'6', "ENQUEUE", 0b100000, "\033[35m"},
71 [DEQUEUE] = {'7', "DEQUEUE", 0b1000000, "\033[36m"},
72 [ALL] = {'A', "ALL", 0b1111111, "\033[1;47;30m"},
73 [COUNT_ERRORS] = {'C', "COUNT_ERRORS", 0b100000000, ""},
74 [ONLY_ERRORS] = {'O', "ONLY_ERRORS", 0b1000000000, ""},
75 [SPIN_COUNT] = {'S', "SPIN_COUNT", 0b10000000000, "\033[1;40;35m"},
76 [STAGING] = {'T', "STAGING", 0b100000000000, "\033[1;40;35m"},
77 [LOG_LEVEL_COUNT] = {'T', "LOG_LEVEL_COUNT", 0b1000000000000, ""},
78};
79const char *tss_s[] = {TIMESTAMP_STYLE(AS_STRINGS)};
80const char *sgr_s[] = {ANSI_COLOR_LIST(AS_STRINGS)};
81const char *sgr_c[] = {
82 [BLACK] = "\033[30m",
83 [RED] = "\033[31m",
84 [GREEN] = "\033[32m",
85 [YELLOW] = "\033[33m",
86 [BLUE] = "\033[34m",
87 [CYAN] = "\033[35m",
88 [MAGENTA] = "\033[36m",
89 [WHITE] = "\033[37m",
90 [BBLACK] = "\033[1;30m",
91 [BRED] = "\033[1;31m",
92 [BGREEN] = "\033[1;32m",
93 [BYELLOW] = "\033[1;33m",
94 [BBLUE] = "\033[1;34m",
95 [BCYAN] = "\033[1;35m",
96 [BMAGENTA] = "\033[1;36m",
97 [BWHITE] = "\033[1;37m",
98 [ORANGE] = "\033[38;5;214m",
99 [BORANGE] = "\033[1;38;2;255;150;0m",
100 [RESET] = "\033[0m",
101};
103char *lfargs[3];
104char *exec;
108char *log_p;
109static size_t path_data_alloc(GlobalContext *__G, const char *path, size_t len);
110unsigned char const lf_type_mask[15] = {
111 0, 0b00000001, 0b00000010, 0, 0b00000100, 0, 0b00001000, 0,
112 0b00010000, 0, 0b00100000, 0, 0b01000000, 0, 0b10000000};
113// ---------------------------------------------------------------
114static struct argp_option options[] = {
115 {_("after"), 'a', _("time"), 0,
116 _("Last Modified after YYYY-MM-DDTHH:MM:SS"), 0},
117 {_("before"), 'b', _("time"), 0,
118 _("Last Modified before YYYY-MM-DDTHH:MM:SS"), 0},
119 {_("max_depth"), 'd', _("number"), 0, _("Depth into directory tree"), 0},
120 {_("depth_first"), 'W', _("bool"), 0, _("Depth first order (widdershins)"),
121 0},
122 {_("unlink"), 'U', _("bool"), 0, _("unlink (delete) implies depth_first"),
123 0},
124 {_("xdev"), 'x', _("bool"), 0, _("Do not traverse mount points"),
125 0},
126 {_("ere"), 'e', _("regex"), 0, _("Exclude regular expression"), 0},
127 {_("ignore_case"), 'i', 0, 0, _("Search ignore case"), 0},
128 {_("include_perms"), 'p', _("sgrwx"), 0,
129 _("x-execute, w-write, r-read, s-setuid, g-setgid"), 0},
130 {_("re"), 'r', _("regex"), 0, _("Regular expression to search for"), 0},
131 {_("include_types"), 't', _("pcdbflsu"), 0,
132 _("p-pipe, c-character_dev, d-directory, b-block_dev, f-regular_file, "
133 "l-link, s-socket, u-unknown"),
134 0},
135 {_("file_size_min"), 's', _("size"), 0,
136 _("No Suffix-bytes, K-kilobytes, M-Megabytes, or G-Gigabytes"), 0},
137 {_("user"), 'u', _("user name"), 0, _("User Name of file owner "), 0},
138 {_("file_level_mask"), 'l', "2345EDAC", 0,
139 _("2- INFO, 3-ERROR, 4-DEBUG, 5-CYCLE, E-ENQUEUE, D-DEQUEUE, A-ALL, "
140 "C-COUNT_ERRORS"),
141 0},
142 {_("timestamp_style"), 'y', "CZL", 0,
143 _("timestamp_style for logging 1-CODER, 2-ISO8601_ZULU, 3-ISO8601_LOCAL"),
144 0},
145 {_("disp_level_mask"), 'D', "12345EDACO", 0,
146 _("1-CONFIG, 2- INFO, 3-ERROR, 4-DEBUG, 5-CYCLE, E-ENQUEUE, D-DEQUEUE, "
147 "A-ALL, C-COUNT_ERRORS, O-ONLY_ERRORS"),
148 0},
149 {_("include_hidden"), 'H', "o", OPTION_ARG_OPTIONAL,
150 _("Include hidden files (o=hidden only)"), 0},
151 {_("follow_links"), 'L', 0, 0, _("Follow symbolic links"), 0},
152 {_("sort_reverse"), 'R', 0, 0, _("Sort in Reverse order"), 0},
153 {_("sort"), 'S', 0, 0, _("Sort in Ascending order"), 0},
154 {_("nthreads"), 'T', "threads", 0, _("Number of nthreads"), 0},
155 {_("count"), 'c', "s", OPTION_ARG_OPTIONAL,
156 _("Count (s only report count)"), 0},
157 {0}};
158/** @brief Parse a single option.
159 @param key The option key.
160 @param arg The argument associated with the option.
161 @param state The current state of the argument parser.
162 @return 0 on success, ARGP_ERR_UNKNOWN for unknown options.
163 @details This function is called by the argp library to handle each
164 command-line option. It updates the GlobalContext structure based on the
165 provided options and arguments. It also performs validation and error
166 handling for specific options, such as ensuring that the before time is
167 greater than the after time.
168 */
169static error_t parse_opt(int key, char *arg, struct argp_state *state) {
170 GlobalContext *__G = state->input;
171 int i = 0;
172 bool a_toi_error = false;
173 switch (key) {
174 case 'a':
176 if (__G->after && __G->before && __G->before < __G->after) {
177 fprintf(stderr, _("-b time must be greater than -a time.\n"));
178 __G->before = 0;
179 }
180 break;
181 case 'c':
182 __G->count = true;
183 if (arg && arg[0] != '\0') {
184 if (strcmp(arg, "s") == 0)
185 __G->count_silently |= true;
186 }
187 break;
188 case 'd':
189 if (arg && arg[0] != '\0')
190 __G->max_depth = a_toi(arg, &a_toi_error);
191 break;
192 case 'e':
193 __G->ere = strdup(arg);
194 __G->flags |= LF_EXC_REGEX;
195 break;
196 case 'H':
197 __G->include_hidden = true; // Include hidden files
198 if (arg && arg[0] == 'o') {
199 __G->hidden_only = true;
200 __G->include_hidden = true;
201 }
202 __G->flags &= ~(LF_HIDE); // Turn hide flag off
203 // LF_HIDE = 0 - include hidden files,
204 // LF_HIDE = 1 - suppress hidden files
205 break;
206 case 'i':
207 __G->ignore_case = true;
208 break;
209 case 'D':
210 // "1-CONFIG, 2-INFO, 3-ERROR, 4-DEBUG, 5-CYCLE, E-ENQUEUE
211 // D-DEQUEUE, A-ALL, C-COUNT_ERRORS, O-ONLY_ERRORS"
212 // "12345EDACO"
213 if (arg && arg[0] != '\0') {
214 log_p = strdup(arg);
215 while (log_p[i]) {
216 switch (log_p[i]) {
217 case '1': // CONFIG
218 __G->disp_level_mask |= ll_t[CONFIG].bits;
219 break;
220 case '2': // INFO:
221 __G->disp_level_mask |= ll_t[INFO].bits;
222 break;
223 case '3': // ERROR
224 __G->disp_level_mask |= ll_t[ERROR].bits;
225 break;
226 case '4': // DEBUG
227 __G->disp_level_mask |= ll_t[DEBUG].bits;
228 break;
229 case '5': // CYCLE
230 __G->disp_level_mask |= ll_t[CYCLE].bits;
231 break;
232 case 'E': // ENQUEUE
233 __G->disp_level_mask |= ll_t[ENQUEUE].bits;
234 break;
235 case 'D': // DEQUEUE
236 __G->disp_level_mask |= ll_t[DEQUEUE].bits;
237 break;
238 case 'A': // ALL
239 __G->disp_level_mask |= ll_t[ALL].bits;
240 break;
241 case 'C': // COUNT_ERRORS
242 __G->disp_level_mask |= ll_t[COUNT_ERRORS].bits;
243 break;
244 case 'O': // ONLY_ERRORS
245 __G->disp_level_mask |= ll_t[ONLY_ERRORS].bits;
246 break;
247 default:
248 break;
249 }
250 i++;
251 }
252 free(log_p);
253 }
254 break;
255 case 'l':
256 // " 2-INFO, 3-ERROR, 4-DEBUG, 5-CYCLE, E-ENQUEUE
257 // D-DEQUEUE, A-ALL, C-COUNT_ERRORS, O-ONLY_ERRORS"
258 // "12345EDACO"
259 if (arg && arg[0] != '\0') {
260 log_p = strdup(arg);
261 while (log_p[i]) {
262 switch (log_p[i]) {
263 case '2': // INFO:
264 __G->file_level_mask |= ll_t[INFO].bits;
265 break;
266 case '3': // ERROR
267 __G->file_level_mask |= ll_t[ERROR].bits;
268 break;
269 case '4': // DEBUG
270 __G->file_level_mask |= ll_t[DEBUG].bits;
271 break;
272 case '5': // CYCLE
273 __G->file_level_mask |= ll_t[CYCLE].bits;
274 break;
275 case 'E': // ENQUEUE
276 __G->file_level_mask |= ll_t[ENQUEUE].bits;
277 break;
278 case 'D': // DEQUEUE
279 __G->file_level_mask |= ll_t[DEQUEUE].bits;
280 break;
281 case 'A': // ALL
282 __G->file_level_mask |= ll_t[ALL].bits;
283 break;
284 case 'C': // COUNT_ERRORS
285 __G->file_level_mask |= ll_t[COUNT_ERRORS].bits;
286 break;
287 case 'O': // ONLY_ERRORS
288 __G->file_level_mask |= ll_t[ONLY_ERRORS].bits;
289 break;
290 default:
291 break;
292 }
293 i++;
294 }
295 free(log_p);
296 }
297 break;
298 case 'L':
299 __G->follow_links = true; // follow symbolic links
300 break;
301 case 'p':
302 perms_p = arg;
303 while (perms_p[i]) {
304 switch (perms_p[i++]) {
305 case 'g':
307 break;
308 case 'r':
310 break;
311 case 's':
313 break;
314 case 'w':
316 break;
317 case 'x':
319 break;
320 default:
321 break;
322 }
323 }
324 break;
325 case 'R':
326 __G->sort_reverse = true;
327 break;
328 case 'r':
329 __G->re = strdup(arg);
330 __G->flags |= LF_REGEX;
331 break;
332 case 'S':
333 __G->sort = true;
334 break;
335 case 'W':
336 __G->depth_first = true;
337 break;
338 case 'U':
339 __G->unlink = true;
340 break;
341 case 's':
342 __G->file_size_min = (intmax_t)(a_to_ul(arg));
343 break;
344 case 'T':
345 if (arg && arg[0] != '\0')
346 __G->nthreads = a_toi(arg, &a_toi_error);
347 break;
348 case 't':
349 file_types_p = arg;
350 while (file_types_p[i]) {
351 switch (file_types_p[i++]) {
352 case 'b':
354 break;
355 case 'c':
357 break;
358 case 'd':
360 break;
361 case 'p':
363 break;
364 case 'l':
366 break;
367 case 'f': // for regular files, 'f' is more intuitive than 'r'
368 case 'r': // regular files are the most common type, so 'r' is also
369 // accepted
371 break;
372 case 's':
374 break;
375 case 'u':
377 break;
378 default:
379 break;
380 }
381 }
382 break;
383 case 'u':
384 __G->user_name = strdup(arg);
385 struct passwd *pwd = getpwnam(arg);
386 if (pwd) {
387 __G->user_id = (uintmax_t)pwd->pw_uid;
388 __G->flags |= LF_USER;
389 } else
390 fprintf(stderr, _("User '%s' not found.\n"), arg);
391 break;
392 case 'x':
393 __G->xdev = true;
394 break;
395 case 'y':
396 if (arg && arg[0] == 'Z')
397 __G->timestamp_style = ISO8601_ZULU;
398 else if (arg && arg[0] == 'L')
399 __G->timestamp_style = ISO8601_LOCAL;
400 else
401 __G->timestamp_style = CODER;
402 break;
403 case ARGP_KEY_ARG:
404 if (state->arg_num == 0 || state->arg_num == 1) {
405 lfargs[state->arg_num] = arg;
406 lfargc = state->arg_num + 1;
407 } else {
408 argp_usage(state);
409 }
410 break;
411 case ARGP_KEY_END:
412 break;
413 default:
414 return ARGP_ERR_UNKNOWN;
415 }
416 return 0;
417}
418static struct argp argp = {options, parse_opt, args_doc, doc,
419 nullptr, nullptr, nullptr};
420int main(int argc, char **argv) {
421 int stack_base;
422 mm.stack_base = (uintptr_t)&stack_base;
423 GlobalContext *__G = (GlobalContext *)calloc(1, sizeof(GlobalContext));
424 __G->count = 0;
426 __G->error_count = 0;
427 __G->disp_level_mask = 0;
428 __G->file_level_mask = 0;
429 __G->f_logging = false;
430 __G->log_fd = -1;
431 __G->log_error_count = false;
432 __G->nthreads = 0;
433 __G->ignore_case = false;
434 __G->sort = false;
435 __G->sort_reverse = false;
436 __G->timestamp_style = CODER;
437 __G->include_hidden = false; // By default, hidden files are suppressed.
438 __G->hidden_only = false;
439 __G->flags |= LF_HIDE; // Turn hide flag on
440 __G->depth_first = false;
441 __G->unlink = false;
442 __G->follow_links = false;
443 __G->count = false;
444 __G->count_silently = false;
445 __G->sbuffer = _("4G");
446 __G->xdev = false;
447 setlocale(LC_NUMERIC, "");
448 char tmp_str[MAX_PATH_LEN];
449 argp_parse(&argp, argc, argv, 0, 0, __G);
450 if (lfargc > 0) {
451 strnz__cpy(tmp_str, lfargs[0], MAXLEN - 1);
452 expand_tilde(tmp_str, MAXLEN - 1);
453 if (is_directory(tmp_str) || is_symlink_to_dir(tmp_str)) {
454 __G->base_path = strdup(tmp_str);
455 } else if (is_valid_regex(lfargs[0])) {
456 __G->re = strdup(lfargs[0]);
457 __G->flags |= LF_REGEX;
458 } else {
459 fprintf(stderr,
460 _("lf: arg1: '%s' is neither a directory nor a valid regex.\n"),
461 lfargs[0]);
462 exit(EXIT_FAILURE);
463 }
464 }
465 if (lfargc > 1) {
466 if (!__G->base_path || __G->base_path[0] == '\0') {
467 strnz__cpy(tmp_str, lfargs[1], MAXLEN - 1);
468 expand_tilde(tmp_str, MAXLEN - 1);
469 if (is_directory(tmp_str) || is_symlink_to_dir(tmp_str))
470 __G->base_path = strdup(tmp_str);
471 }
472 if ((!(__G->flags & LF_REGEX)) && is_valid_regex(lfargs[1])) {
473 __G->re = strdup(lfargs[1]);
474 __G->flags |= LF_REGEX;
475 } else {
476 fprintf(stderr,
477 _("lf: '%s' is neither a directory nor a valid regular "
478 "expression.\n"),
479 lfargs[1]);
480 exit(EXIT_FAILURE);
481 }
482 }
483 if (__G->base_path == nullptr || __G->base_path[0] == '\0')
484 __G->base_path = strdup(".");
485 unsigned int nprocs = get_nprocs();
486 if (nprocs == 0)
487 nprocs = 1;
488 if (__G->nthreads == 0)
489 __G->nthreads = (nprocs > 1) ? (nprocs - 1) : 1;
490 else {
491 if (__G->nthreads < 1)
492 __G->nthreads = 1;
493 if (__G->nthreads > nprocs)
494 __G->nthreads = nprocs;
495 }
497 if (!__G->sort) {
498 init_lf(__G, argc, argv);
499 } else
501 if (__G->count) {
502 size_t count = atomic_load(&__G->file_count);
503 fprintf(stderr, _("Files: %zu\n"), count);
504 }
505 atomic_load(&__G->error_count);
506 if (__G->log_error_count && __G->error_count > 0) {
507 fprintf(stderr, _("Errors: %zu\n"), __G->error_count);
509 }
510 free(__G->base_path);
511 free(__G->user_name);
512 free(__G->re);
513 free(__G->ere);
514 free(__G->threads);
515 free(__G);
516 exit(termination_status);
517}
518/** @brief Sort the output of the lf command using the system's sort utility.
519 @param lf A pointer to the GlobalContext struct containing the search settings.
520 @param argc The number of command-line arguments.
521 @param argv An array of command-line argument strings.
522 @details This function sets up a pipeline to sort the output of the lf
523 command. It creates a pipe, forks a child process to execute the sort
524 command, and redirects the standard input and output streams accordingly. The
525 sort command is executed with optional flags for parallel processing and
526 buffer size, as well as a reverse sort option if specified in the GlobalContext. The
527 function waits for the child process to complete before returning.
528 */
529int sort_lf_output(GlobalContext *__G, int argc, char **argv) {
530 // char tmp_str[MAXLEN];
531 char *eargv[MAX_ARGS];
532 int eargc = 0;
533 eargv[eargc++] = strdup("sort");
534 // ssnprintf(tmp_str, MAXLEN - 1, "--parallel=%d", __G->nthreads);
535 // eargv[eargc++] = strdup(tmp_str);
536 // ssnprintf(tmp_str, MAXLEN - 1, "--buffer-size=%s", __G->sbuffer);
537 // eargv[eargc++] = strdup(tmp_str);
538 if (__G->sort_reverse)
539 eargv[eargc++] = strdup("-r");
540 eargv[eargc] = nullptr;
541 setenv("LC_ALL", "C", 1); // Set locale to C for consistent sorting
542 int wstatus;
543 int fds[2];
544 pipe(fds); // Create the pipes
545 pid_t pid1 = fork();
546 if (pid1 == 0) { // Child process
547 // Child's STDIN will be redirected to the read end of the pipe, so that the
548 // sort process will read the output of the finder from the pipe. Close the
549 // write end of the pipe in the child
550 close(fds[1]);
551 dup2(fds[0], STDIN_FILENO); // Clone child's read pipe to STDIN_FILENO
552 close(fds[0]); // Close the original read end of the pipe
553 execvp(eargv[0], eargv); // Execute the sort command
554 fprintf(stderr, _("Failed to execute sort: %s\n"), strerror(errno));
555 return TS_ERROR;
556 }
557 fclose(stdout);
558 dup2(fds[1], STDOUT_FILENO); // Clone write pipe to STDOUT_FILENO
559 stdout = fdopen(STDOUT_FILENO, "w"); // Reopen STDOUT as a stream
560 setvbuf(stdout, NULL, _IOLBF, 0); // line buffering
561 init_lf(__G, argc, argv);
562 fclose(stdout);
563 close(fds[1]);
564 wait(&wstatus);
565 for (int i = 0; i < eargc; i++)
566 free(eargv[i]);
567 return 0;
568}
569// ----------------------------------------------------------------------
570// DEBUG_OUT
571// ----------------------------------------------------------------------
572/** @brief Display everything and the kitchen sink on stderr
573 @param lf A pointer to the GlobalContext struct containing the debug settings.
574 @param argc The number of command-line arguments.
575 @param argv An array of command-line argument strings.
576 @details This function outputs debug information to stderr if debugging is
577 enabled in the GlobalContext. It includes a timestamp, user information, IP
578 addresses, command-line arguments, and various configuration settings. The
579 output is formatted for readability and includes details about file types,
580 permissions, regex patterns, and other relevant settings.
581 */
582void debug_out(GlobalContext *__G, int argc, char **argv) {
583 int len = 0;
584 int i;
585 bool addspace_before = false;
586 if (!(__G->disp_level_mask & ll_t[CONFIG].bits))
587 return;
588 for (i = 0; i < argc; i++) {
589 len = len + strlen(argv[i]);
590 if (len > 72) {
591 fprintf(stderr, "\n");
592 len = strlen(argv[i]);
593 addspace_before = false;
594 }
595 if (addspace_before) {
596 fprintf(stderr, " ");
597 len++;
598 }
599 fprintf(stderr, "%s", argv[i]);
600 addspace_before = true;
601 }
602 // "1-CONFIG, 2-INFO, 3-ERROR, 4-DEBUG, 5-CYCLE, E-ENQUEUE
603 // D-DEQUEUE, C-COUNT_ERRORS, A-ALL, O-ONLY_ERRORS"
604 // "12345EDCAO"
605 fprintf(stderr, "\n\n");
606 fprintf(stderr, "%s\n\n", LF_VERSION);
607 fprintf(stderr, "%s\n", _("Display Log Level"));
608 fprintf(stderr, _(" 1-config %s\n"),
609 __G->disp_level_mask & ll_t[CONFIG].bits ? _("true")
610 : _("| false"));
611 fprintf(stderr, _(" 2-info %s\n"),
612 __G->disp_level_mask & ll_t[INFO].bits ? _("true") : _("| false"));
613 fprintf(stderr, _(" 3-errors %s\n"),
614 __G->disp_level_mask & ll_t[ERROR].bits ? _("true") : _("| false"));
615 fprintf(stderr, _(" 4-debug %s\n"),
616 __G->disp_level_mask & ll_t[DEBUG].bits ? _("true") : _("| false"));
617 fprintf(stderr, _(" 5-cycle %s\n"),
618 __G->disp_level_mask & ll_t[CYCLE].bits ? _("true") : _("| false"));
619 fprintf(stderr, _(" E-enqueue %s\n"),
620 __G->disp_level_mask & ll_t[ENQUEUE].bits ? _("true")
621 : _("| false"));
622 fprintf(stderr, _(" D-dequeue %s\n"),
623 __G->disp_level_mask & ll_t[DEQUEUE].bits ? _("true")
624 : _("| false"));
625 fprintf(stderr, _(" A-all %s\n"),
626 __G->disp_level_mask & ll_t[ALL].bits ? _("true") : _("| false"));
627 fprintf(stderr, _(" C-count errors %s\n"),
628 __G->disp_level_mask & ll_t[COUNT_ERRORS].bits ? _("true")
629 : _("| false"));
630 fprintf(stderr, _(" O-only errors %s\n"),
631 __G->disp_level_mask & ll_t[ONLY_ERRORS].bits ? _("true")
632 : _("| false"));
633 fprintf(stderr, "\n");
634 fprintf(stderr, _("Search directory: %s\n\n"), __G->base_path);
635 if (__G->max_depth == 0)
636 fprintf(stderr, _("Max depth 0 (unlimited)\n\n"));
637 else
638 fprintf(stderr, _("Max depth %d\n\n"), __G->max_depth);
639 fprintf(stderr, _("Using %d threads\n\n"), __G->nthreads);
640 fprintf(
641 stderr,
642 _("File types preceeded by an asterisk (\"*\") will be included:\n\n"));
643 fprintf(stderr, _(" LF type DT type\n"));
645 _("FIFO p-named pipe"));
647 _("CHR c-character device"));
648 print_file_type(__G->include_types, LF_DIR, DT_DIR, _("DIR d-directory"));
650 _("BLK b-block device"));
652 _("REG f-regular file"));
654 _("LINK l-symbolic link"));
655 print_file_type(__G->include_types, LF_SOCK, DT_SOCK, _("SOCK s-socket"));
657 _("UNKNOWN u-unknown"));
658 fprintf(stderr, "\n");
659 fprintf(stderr, "f->include_types = %08b\n", __G->include_types);
660 fprintf(stderr, "f->suppress_types = %08b\n", __G->suppress_types);
661 fprintf(stderr, "\n");
662 if (__G->flags & LF_USER)
663 fprintf(stderr, _("User: %s (%ju)\n"), __G->user_name, __G->user_id);
664 if (__G->include_perms) {
665 if (__G->include_perms & LF_IXUSR)
666 fprintf(stderr, _(" %08b Execute\n"), LF_IXUSR);
667 if (__G->include_perms & LF_IWUSR)
668 fprintf(stderr, _(" %08b Write\n"), LF_IWUSR);
669 if (__G->include_perms & LF_IRUSR)
670 fprintf(stderr, _(" %08b Read\n"), LF_IRUSR);
671 if (__G->include_perms & LF_ISUID)
672 fprintf(stderr, _(" %08b SETUID\n"), LF_ISUID);
673 if (__G->include_perms & LF_ISGID)
674 fprintf(stderr, _(" %08b SETGID\n"), LF_ISGID);
675 }
676 fprintf(stderr, "\n");
677 if (__G->flags & LF_REGEX)
678 fprintf(stderr, _("Include regex: %s\n\n"), __G->re);
679 if (__G->flags & LF_EXC_REGEX)
680 fprintf(stderr, _("Exclude regex: %s\n\n"), __G->ere);
681 if (__G->after) {
682 char buf[32];
683 format_local_timestamp(__G->after, buf, sizeof(buf));
684 fprintf(stderr, _("Modified after: %s\n\n"), buf);
685 }
686 if (__G->before) {
687 char buf[32];
688 format_local_timestamp(__G->before, buf, sizeof(buf));
689 fprintf(stderr, _("Modified before: %s\n\n"), buf);
690 }
691 if (__G->file_size_min) {
692 const char *units[] = {"b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb"};
693 off_t size = __G->file_size_min;
694 i = 0;
695 while (size >= 1024 && i < 6) {
696 size /= 1024;
697 i++;
698 }
699 char buffer[32];
700 ssnprintf(buffer, 32, "%ld %s", size, units[i]);
701 fprintf(stderr, _("Minimum file size: %s\n\n"), buffer);
702 }
703 if (__G->max_depth)
704 fprintf(stderr, _("Max depth: %d\n\n"), __G->max_depth);
705 if (__G->ignore_case)
706 fprintf(stderr, _("Ignore case in regex matching.\n\n"));
707 if (__G->include_hidden)
708 fprintf(stderr, _("Include hidden files.\n\n"));
709 if (__G->follow_links)
710 fprintf(stderr, _("Follow symbolic links.\n\n"));
711 if (__G->sort)
712 fprintf(stderr, _("Sort output in ascending order.\n\n"));
713 if (__G->sort_reverse)
714 fprintf(stderr, _("Sort output in reverse order.\n\n"));
715 return;
716}
717// ----------------------------------------------------------------------
718// INIT_FIND
719// ----------------------------------------------------------------------
720/** @brief Initialize the file search process.
721 @param lf A pointer to the GlobalContext struct containing the search settings.
722 @param argc The number of command-line arguments.
723 @param argv An array of command-line argument strings.
724 @return true if initialization is successful, false otherwise.
725 @details This function initializes the file search process based on the
726 provided settings in the GlobalContext struct. It sets up file type inclusion
727 and suppression, compiles regular expressions if specified, and creates a
728 multi-producer, multi-consumer queue for managing directory traversal tasks.
729 It also initializes threads for concurrent processing of directory entries.
730 */
731bool init_lf(GlobalContext *__G, int argc, char **argv) {
733 __G->f_logging = true;
734 LogCtx x_log_ctx = {
735 .start_nsec = 0,
736 .start_sec = 0,
737 .p_int_nsec = 0,
738 .p_int_sec = 0,
739 .record[0] = '\0',
740 };
741 LogCtx *log_ctx = &x_log_ctx;
742 if (!__G->include_types)
743 __G->include_types = 0xff;
744 if (__G->include_types)
745 __G->suppress_types = __G->include_types ^ 0xff;
746 __G->include_hidden = !(__G->flags & LF_HIDE);
747 int reti = 0;
748 __G->reg_flags = REG_EXTENDED;
749 if (__G->ignore_case)
750 __G->reg_flags |= REG_ICASE;
751 if (__G->flags & LF_REGEX) {
752 reti = regcomp(&__G->compiled_re, __G->re, __G->reg_flags);
753 if (reti) {
755 _("__G->re: '%s' Invalid pattern\n"), __G->re);
756 fprintf(stderr, "%s", __G->log_record);
757 if (__G->f_logging)
758 lf_log(ERROR, "%s", __G->log_record);
759 regfree(&__G->compiled_re);
760 return false;
761 }
762 }
763 if (__G->flags & LF_EXC_REGEX) {
764 reti = regcomp(&__G->compiled_ere, __G->ere, __G->reg_flags);
765 if (reti) {
767 _("__G->ere: '%s' Invalid pattern\n"), __G->ere);
768 fprintf(stderr, "%s", __G->log_record);
769 if (__G->f_logging)
770 lf_log(ERROR, "%s", __G->log_record);
771 regfree(&__G->compiled_ere);
772 return false;
773 }
774 }
775 debug_out(__G, argc, argv);
777 int rc = 0;
778 struct stat sb;
779 rc = pthread_mutex_init(&__G->output_mutex, NULL);
780 if (rc != 0)
781 perror(_("Mutex initialization failed"));
782 rc = stat(__G->base_path, &sb);
783 if (rc != 0)
784 return false;
785 // --------------------------------------------------------------------
786 // INITIALIZE ARENAS
787 // --------------------------------------------------------------------
788 if (__G->f_logging)
789 lf_log(INFO, "Initializing lf Memory");
790 atomic_init(&__G->enqueue_pos, 0);
791 atomic_init(&__G->dequeue_pos, 0);
792 atomic_init(&__G->shut_down, 0);
793 if (!global_arena_create(__G)) {
795 goto endlf;
796 }
797 atomic_init(&__G->thread_id, 0);
798 // --------------------------------------------------------------------
799 // CREATE_ROOT_NODE
800 // --------------------------------------------------------------------
801 // 4. Resolve the root path string and stat details to populate slot 0
802 size_t path_len = strlen(__G->base_path);
803 if (stat(__G->base_path, &sb) == -1) {
804 perror("Failed to stat base_path");
807 goto endlf;
808 }
809 if (!S_ISDIR(sb.st_mode)) {
811 _("Warning: Base path '%s' is not a directory. No "
812 "files will be found.\n"),
813 __G->base_path);
814 fprintf(stderr, "%s\n", __G->log_record);
815 if (__G->f_logging)
816 lf_log(ERROR, "%s", __G->log_record);
818 goto endlf;
819 }
820 if (__G->f_logging)
821 lf_log(INFO, _("Root path: %s"), __G->base_path);
822 // Push the root node into the queue arena
823 push_root_node(__G, sb.st_dev, sb.st_ino);
824 // ------------------------------------------------------------
825 // LOOSE THE THREADS
826 // ------------------------------------------------------------
827 if (__G->f_logging)
828 lf_log(INFO, _("Starting threads"));
829 __G->threads = calloc(__G->nthreads, sizeof(pthread_t));
830 if (!__G->threads) {
831 if (__G->f_logging)
832 lf_log(ERROR, _("Out of memory allocating threads"));
833 fprintf(stderr, _("Out of memory allocating threads\n"));
834 goto endlf;
835 }
836 for (unsigned int i = 0; i < __G->nthreads; i++) {
837 rc = pthread_create(&__G->threads[i], NULL, worker, __G);
838 if (rc != 0) {
839 if (__G->f_logging)
840 lf_log(ERROR, _("Error: Unable to create thread %d\n"), rc);
841 fprintf(stderr, _("Error: Unable to create thread %d\n"), rc);
842 __G->shut_down = 1;
844 goto endlf;
845 }
846 }
847// ------------------------------------------------------------
848// THREAD SHUTDOWN
849// ------------------------------------------------------------
850endlf:
851 if (__G->f_logging)
852 lf_log(INFO, "Waiting for threads to finish...");
853 for (unsigned int i = 0; i < __G->nthreads; i++)
854 pthread_join(__G->threads[i], NULL);
855 rc = pthread_mutex_destroy(&__G->output_mutex);
856 if (rc != 0)
857 perror(_("Mutex destroy failed"));
858 if (__G->flags & LF_REGEX)
859 regfree(&__G->compiled_re);
860 if (__G->flags & LF_EXC_REGEX)
861 regfree(&__G->compiled_ere);
863 return true;
864}
865// ----------------------------------------------------------------------
866// GLOBAL ARENA
867// ----------------------------------------------------------------------
868/** @brief Create a queue arena for managing directory traversal tasks.
869 @param lf A pointer to the GlobalContext struct where the queue arena will be
870 created.
871 @param max_nodes The maximum number of nodes that the queue arena can hold.
872 @details This function allocates memory for a QueueArena structure and
873 initializes its properties. It uses mmap to allocate a contiguous block of
874 memory for the queue nodes, allowing for efficient management of directory
875 traversal tasks in a multi-threaded environment. The cursor is initialized to
876 zero, indicating that no nodes have been added yet.
877 */
878bool global_arena_create(GlobalContext *__G) {
879 __G->queue_bytes = sizeof(QueueNode) * QUEUE_NODES;
880 __G->path_bytes = 32 * QUEUE_NODES;
882 __G->arena = mmap(NULL, __G->arena_bytes, PROT_NONE,
883 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
884 mprotect(__G->arena, __G->arena_bytes, PROT_READ | PROT_WRITE);
885 if (!__G->arena || __G->arena == MAP_FAILED) {
886 perror(_("mmap failed to reserve queue arena memory"));
887 return false;
888 }
889 __G->queue = (QueueNode *)__G->arena;
890 __G->path_data = (char *)__G->arena + __G->queue_bytes;
891 for (size_t i = 0; i < QUEUE_NODES; i++)
892 atomic_init(&__G->sequence[i], i);
893 return true;
894}
895/** @brief Push the root directory node into the queue arena.
896 @param lf A pointer to the GlobalContext struct containing the queue arena.
897 @param path_offset The offset of the root path in the path arena.
898 @param path_len The length of the root path string.
899 @param dev The device ID of the root directory.
900 @param ino The inode number of the root directory.
901 @return The index of the newly created root node in the queue arena.
902 @details This function initializes and pushes the root directory node into
903 the queue arena. It allocates a new directory context and cycle context for
904 the root node, sets up its properties, and returns its index in the queue
905 arena. This is typically called at the start of a file search operation to
906 establish the starting point for traversal.
907 */
908void push_root_node(GlobalContext *__G, dev_t dev, ino_t ino) {
909 QueueNode root_node = {
911 .path_offset = 0,
912 .path_len = strlen(__G->base_path),
914 .depth = 0,
915 .dev = dev,
916 .ino = ino,
917 };
918 __G->queue_idx = 0;
919 atomic_init(&__G->active_tasks, 1);
920 mpmc_enqueue(__G, &root_node, __G->base_path, strlen(__G->base_path));
921 return;
922}
923/** @brief Destroy the queue arena and free associated resources.
924 @param lf A pointer to the GlobalContext struct containing the queue arena.
925 @details This function unmaps the memory allocated for the queue arena using
926 munmap. It checks if the arena pointer is valid before attempting to unmap it,
927 ensuring that resources are properly released when they are no longer needed.
928 */
929void global_arena_destroy(GlobalContext *__G) {
930 if (!__G->arena)
931 return;
932 munmap(__G->arena, __G->arena_bytes);
933}
934// ----------------------------------------------------------------------
935// FLUSH_OUTPUT_BUFFER
936// ----------------------------------------------------------------------
937/** @brief Flush the output_buffer to stdout in a thread-safe manner.
938 @param lf A pointer to the GlobalContext struct containing the output mutex.
939 @param output_buffer A pointer to the OutputBuffer struct containing the data to be
940 flushed.
941 @details This function writes the contents of the output_buffer to stdout
942 using fwrite_unlocked for efficiency. It uses a mutex to ensure that only one
943 thread can write to stdout at a time, preventing interleaved output from
944 multiple threads. After flushing, it resets the length of the output_buffer
945 to zero.
946 */
947void flush_output_buffer(GlobalContext *__G, OutputBuffer *output_buffer) {
948 if (__G == nullptr || output_buffer == nullptr, output_buffer->len == 0)
949 return;
950 pthread_mutex_lock(&__G->output_mutex);
951 fwrite_unlocked(output_buffer->data, 1, output_buffer->len, stdout);
952 pthread_mutex_unlock(&__G->output_mutex);
953 output_buffer->len = 0;
954}
955// ----------------------------------------------------------------------
956// APPEND_OUTPUT_BUFFER
957// ----------------------------------------------------------------------
958/** @brief Append a path to the output_buffer, flushing if necessary.
959 @param lf A pointer to the GlobalContext struct containing the output mutex.
960 @param output_buffer A pointer to the OutputBuffer struct where the path will be appended.
961 @param path The path string to append to the output_buffer.
962 @param path_len The length of the path string.
963 @param append_slash A boolean indicating whether to append a slash after the path.
964 @return true if the path was successfully appended or flushed, false otherwise.
965 @details This function appends a given path to the output_buffer. If the
966 combined length of the current buffer and the new path exceeds the buffer's
967 capacity, it flushes the buffer to stdout before appending. It also handles
968 appending a slash if specified. The function ensures thread-safe access to
969 stdout using a mutex during flushing.
970*/
971bool append_output_buffer(GlobalContext *__G, OutputBuffer *output_buffer, const char *path,
972 size_t path_len, bool append_slash) {
973 if (__G == nullptr || output_buffer == nullptr || path == nullptr)
974 return false;
975 size_t line_len = path_len + (append_slash ? 1 : 0) + 1;
976 if (line_len > sizeof(OutputBuffer)) {
977 pthread_mutex_lock(&__G->output_mutex);
978 fwrite_unlocked(path, 1, path_len, stdout);
979 if (append_slash)
980 fputc_unlocked('/', stdout);
981 fputc_unlocked('\n', stdout);
982 pthread_mutex_unlock(&__G->output_mutex);
983 return true;
984 }
985 if (output_buffer->len + line_len > sizeof(output_buffer->data))
986 flush_output_buffer(__G, output_buffer);
987 memcpy(output_buffer->data + output_buffer->len, path, path_len);
988 output_buffer->len += path_len;
989 if (append_slash)
990 output_buffer->data[output_buffer->len++] = '/';
991 output_buffer->data[output_buffer->len++] = '\n';
992 return true;
993}
994// ----------------------------------------------------------------------
995// VYUKOV MPMC QUEUE
996// ----------------------------------------------------------------------
997bool mpmc_enqueue(GlobalContext *__G, QueueNode *node, const char *path, size_t len) {
998 size_t pos = atomic_load_explicit(&__G->enqueue_pos, memory_order_relaxed);
999 int spin_count = 0;
1000 const int SPIN_LIMIT = 8;
1001 while (true) {
1002 size_t seq = atomic_load_explicit(&__G->sequence[pos & QUEUE_MASK],
1003 memory_order_acquire);
1004 intptr_t diff = (intptr_t)seq - (intptr_t)pos;
1005 if (diff == 0) { // Success
1006 if (atomic_compare_exchange_weak_explicit(&__G->enqueue_pos, &pos,
1007 pos + 1, memory_order_acquire,
1008 memory_order_relaxed))
1009 break;
1010 } else if (diff < 0) { // Queue full
1011 // fprintf(stderr, "line: %d Insufficient contiguous nodes:
1012 // queue_idx %lu, seq %lu, seq - pos %lu\n", __LINE__, seq, pos, seq
1013 // - pos);
1014 return false;
1015 } else { // Contended, try again
1016 pos = atomic_load_explicit(&__G->enqueue_pos, memory_order_relaxed);
1017 }
1018 if (++spin_count > SPIN_LIMIT)
1019 return false;
1020 else {
1021 if (spin_count > SPIN_LIMIT / 2)
1022 sched_yield();
1023 }
1024#if defined(__x86_64__)
1025 __builtin_ia32_pause();
1026#endif
1027 }
1028 __G->queue[pos] = *node;
1029 uint32_t offset = atomic_fetch_add_explicit(&__G->path_offset, len + 1, memory_order_acquire);
1030 memcpy(&__G->path_data[offset], path, len);
1031 atomic_store_explicit(&__G->sequence[pos],
1032 pos + 1, memory_order_release);
1033 atomic_thread_fence(memory_order_release);
1034 return true;
1035}
1036/** @brief Bulk enqueue multiple nodes into the MPMC queue.
1037 @param lf A pointer to the GlobalContext struct containing the queue.
1038 @param tl A pointer to the ThreadLocal struct containing the nodes to enqueue.
1039 @return true if the bulk enqueue was successful, false if the queue is full.
1040 @details This function attempts to enqueue multiple nodes from a thread-local
1041 buffer into a multi-producer, multi-consumer (MPMC) queue. It checks for
1042 available slots in the queue and uses atomic operations to reserve space for
1043 the nodes. If successful, it copies the nodes and their associated path data
1044 into the global queue and updates the sequence numbers accordingly. If the
1045 queue is full, it returns false, indicating that the caller should fall back
1046 to local stack or single enqueue.
1047 */
1048bool mpmc_bulk_enqueue(GlobalContext *__G, ThreadLocal *__tl) {
1049 if (__tl->stage_idx == 0)
1050 return true;
1051 uint_fast32_t spin_count = 0;
1052 uint_fast32_t base_idx = atomic_load_explicit(&__G->enqueue_pos, memory_order_relaxed);
1053 while (true) {
1054 bool block_available = true;
1055 bool queue_full = false;
1056 uint_fast32_t i;
1057 uint_fast32_t pos;
1058 uint_fast32_t seq;
1059 uint_fast32_t queue_idx;
1060 for (i = 0; i < __tl->stage_idx; ++i) {
1061 pos = base_idx + i;
1062 queue_idx = pos & QUEUE_MASK;
1063 seq = atomic_load_explicit(&__G->sequence[queue_idx], memory_order_acquire);
1064 intptr_t dif = (intptr_t)seq - (intptr_t)pos;
1065 if (dif < 0) {
1066 // Slot is still occupied from the previous lap -> genuinely full
1067 block_available = false;
1068 queue_full = true;
1069 break;
1070 } else if (dif > 0) {
1071 // Another producer already claimed this slot -> base_idx is stale
1072 block_available = false;
1073 break;
1074 }
1075 }
1076 if (queue_full) {
1077 return false; // Caller should fall back to local stack or single enqueue
1078 }
1079 if (block_available) { // Success
1080 if (atomic_compare_exchange_weak_explicit(
1081 &__G->enqueue_pos, &base_idx, base_idx + __tl->stage_idx,
1082 memory_order_relaxed, memory_order_relaxed)) {
1083 break; // Reservation finalized; base_idx holds our starting position
1084 }
1085 // CAS failed: base_idx was automatically updated with the current enqueue_pos
1086 } else {
1087 // dif > 0: Reload fresh base_idx before backing off/retrying
1088 base_idx = atomic_load_explicit(&__G->enqueue_pos, memory_order_relaxed);
1089 }
1090 if (++spin_count < 64) {
1091 for (i = 0; i < spin_count; i++) {
1092#if defined(__x86_64__)
1093 __builtin_ia32_pause();
1094#endif
1095 }
1096 } else {
1097 sched_yield();
1098 }
1099 }
1100 for (uint_fast32_t sidx = 0; sidx < __tl->stage_idx; ++sidx) {
1101 uint_fast32_t enqueue_pos = (base_idx + sidx) & QUEUE_MASK;
1102 __G->queue[enqueue_pos] = __tl->stage_node[sidx];
1103 uint_fast32_t len_to_add = __tl->stage_node[sidx].path_len + 1;
1104 uint_fast32_t offset = atomic_fetch_add_explicit(&__G->path_offset,
1105 len_to_add, memory_order_acquire);
1106 if (__builtin_expect(offset + len_to_add >= PATH_BYTES, 0)) {
1107 fprintf(stderr, "Fatal: Path arena exhausted (%lu / %d bytes)\n", offset + len_to_add, PATH_BYTES);
1108 return false;
1109 }
1110 memcpy(&__G->path_data[offset],
1111 &__tl->path_data[__tl->stage_node[sidx].path_offset],
1112 __tl->stage_node[sidx].path_len);
1113#ifdef DEBUGZ
1114 char *path = &__tl->path_data[__tl->stage_node[sidx].path_offset];
1115 fprintf(stderr, "line: %d, %s, enqueued pos %lu, sidx %lu, path: %s\n", __LINE__, __func__, enqueue_pos, sidx, path);
1116#endif
1117 __G->queue[enqueue_pos].path_offset = offset;
1118 __G->path_data[offset + __tl->stage_node[sidx].path_len] = '\0';
1119 // ANNOTATE_HAPPENS_BEFORE(&__G->queue[enqueue_pos]);
1120 // forces unconditional atomic read-write that Helgrind can't
1121 // misinterpret
1122 uint_fast32_t target_seq = base_idx + sidx + 1;
1123 atomic_exchange_explicit(&__G->sequence[enqueue_pos],
1124 target_seq, memory_order_release);
1125 }
1126 __tl->stage_idx = 0;
1127 __tl->cum_path_offset = 0;
1128 __tl->path_data[0] = '\0';
1129 return true;
1130}
1131/** @brief Dequeue a node from the MPMC queue.
1132 @param lf A pointer to the GlobalContext struct containing the queue.
1133 @param dequeue_pos A pointer to a uint_fast32_t variable where the dequeued
1134 position will be stored.
1135 @return true if a node was successfully dequeued, false if the queue is empty or
1136 shut down.
1137 @details This function attempts to dequeue a node from a multi-producer,
1138 multi-consumer (MPMC) queue. It checks for available nodes in the queue and
1139 uses atomic operations to claim a node for processing. If successful, it
1140 updates the sequence number for the dequeued position and returns true. If the
1141 queue is empty or has been shut down, it returns false, indicating that there
1142 are no more nodes to process.
1143 */
1144bool mpmc_dequeue(GlobalContext *__G, uint_fast32_t *dequeue_pos) {
1145 alignas(CACHE_LINE_SIZE) uint_fast32_t pos = atomic_load_explicit(&__G->dequeue_pos, memory_order_relaxed);
1146 int spin_count = 0;
1147 while (true) {
1148 if (atomic_load_explicit(&__G->shut_down, memory_order_acquire)) {
1149 ANNOTATE_HAPPENS_AFTER(&__G->shut_down);
1150 return false;
1151 }
1152 alignas(CACHE_LINE_SIZE) uint_fast32_t seq = __G->sequence[pos & QUEUE_MASK];
1153 intptr_t diff = (intptr_t)seq - (intptr_t)(pos + 1);
1154 if (diff == 0) { // Catch!
1155 if (atomic_compare_exchange_weak_explicit(&__G->dequeue_pos, &pos,
1156 pos + 1, memory_order_acquire, memory_order_relaxed)) {
1157 ANNOTATE_HAPPENS_AFTER(&__G->sequence[pos & QUEUE_MASK]);
1158 *dequeue_pos = pos;
1159 break;
1160 }
1161 spin_count = 0;
1162 } else if (diff < 0) { // No Joy!
1163 if (atomic_load_explicit(&__G->active_tasks, memory_order_acquire) == 0) {
1164 uint_fast32_t check_pos =
1165 atomic_load_explicit(&__G->dequeue_pos, memory_order_acquire);
1166
1167 uint_fast32_t enq_pos = atomic_load_explicit(&__G->enqueue_pos, memory_order_acquire);
1168 if (enq_pos == check_pos) {
1169 uint_fast32_t check_seq = atomic_load_explicit(
1170 &__G->sequence[check_pos & QUEUE_MASK], memory_order_acquire);
1171 if ((intptr_t)check_seq - (intptr_t)(check_pos + 1) < 0) {
1172 atomic_exchange_explicit(&__G->shut_down, 1,
1173 memory_order_release);
1174 return false;
1175 }
1176 }
1177 }
1178 if (++spin_count < 64) {
1179 for (int i = 0; i < spin_count; i++) {
1180#if defined(__x86_64__)
1181 __builtin_ia32_pause();
1182#endif
1183 }
1184 } else {
1185 sched_yield();
1186 }
1187 pos = atomic_load_explicit(&__G->dequeue_pos, memory_order_acquire);
1188 } else {
1189 // Snatched by another thread, try again
1190 pos = atomic_load_explicit(&__G->dequeue_pos, memory_order_acquire);
1191 }
1192 *dequeue_pos = pos;
1193 }
1194#ifdef DEBUGX
1195 fprintf(stderr, "line: %d, %s, dequeued pos %lu\n", __LINE__, __func__, *dequeue_pos);
1196#endif
1197 // atomic_store_explicit(&__G->sequence[pos & QUEUE_MASK],
1198 // pos + QUEUE_NODES, memory_order_release);
1199 uint_fast32_t reset_seq = pos + QUEUE_NODES;
1200 atomic_exchange_explicit(&__G->sequence[pos & QUEUE_MASK], reset_seq, memory_order_release);
1201 return true;
1202}
1203/** @brief Release a slot in the MPMC queue after processing.
1204 @param lf A pointer to the GlobalContext struct containing the queue.
1205 @param pos The position of the slot to release.
1206 @details This function updates the sequence number for a given slot in the
1207 multi-producer, multi-consumer (MPMC) queue, indicating that the slot is now
1208 available for reuse. It uses an atomic store operation with memory_order_release
1209 to ensure proper synchronization between threads.
1210 */
1211static inline void mpmc_release_slot(GlobalContext *__G, uint_fast32_t pos) {
1212 atomic_store_explicit(&__G->sequence[pos & QUEUE_MASK],
1213 pos + QUEUE_NODES, memory_order_release);
1214 // mpmc_release_slot(__G, pos);
1215}
1216// ----------------------------------------------------------------------
1217/** @brief Worker thread function for processing directory nodes.
1218 @param arg A pointer to the GlobalContext struct containing the search settings.
1219 @return NULL upon completion.
1220 @details This function is executed by each worker thread. It dequeues
1221 directory nodes from the global queue, reconstructs their paths, and invokes
1222 the finder function to process them. Each thread maintains its own local
1223 context, including a stage arena for temporary storage of nodes and path
1224 data. The function continues processing until there are no more nodes to
1225 dequeue or the search is shut down.
1226 */
1227void *worker(void *arg) {
1228 GlobalContext *__G = (GlobalContext *)arg;
1229 ThreadLocal __tl;
1230 __tl.stage_queue_size = sizeof(QueueNode) * STAGE_NODES;
1231 __tl.stage_path_size = 32 * STAGE_NODES;
1233 void *stage_arena = mmap(NULL, __tl.stage_arena_size, PROT_NONE,
1234 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
1235 mprotect(stage_arena, __tl.stage_arena_size, PROT_READ | PROT_WRITE);
1236 __tl.stage_arena = stage_arena;
1237 __tl.stage_node = (QueueNode *)__tl.stage_arena;
1238 __tl.path_data = (char *)__tl.stage_arena + __tl.stage_queue_size;
1239 __tl.cum_path_offset = 0;
1240 __tl.stage_idx = 0;
1241 __tl.thread_id = atomic_fetch_add_explicit(&__G->thread_id, 1, memory_order_relaxed);
1242 char dir_buf[DIR_BUF_SIZE];
1243 __tl.dir_buf = dir_buf;
1244 OutputBuffer output_buffer;
1245 __tl.output_buffer = &output_buffer;
1246 __tl.output_buffer->len = 0;
1247 uint_fast32_t q_pos = 0;
1248 LogCtx log_ctx = {};
1249 __tl.log_ctx = log_ctx;
1250 log_ctx.thread_id = __tl.thread_id;
1251 if (__G->f_logging && __G->log_fd == -1)
1252 initialize_timer(__G, &log_ctx);
1253 else
1254 initialize_thread_timer(__G, &log_ctx);
1255 while (1) {
1256 if (mpmc_dequeue(__G, &q_pos) == false) {
1257 break;
1258 }
1259 atomic_thread_fence(memory_order_acquire);
1260 // ----------------------------------------------------------------
1261 // Reconstruct the relative path for the dequeued directory node
1262 // ----------------------------------------------------------------
1263 __tl.queue_idx = q_pos;
1264 uint_fast32_t q_path_len = __G->queue[q_pos].path_len;
1265 uint_fast32_t q_path_offset = __G->queue[q_pos].path_offset;
1266 // ----------------------------------------------------------------
1267 // Get the length of the parent path
1268 // ----------------------------------------------------------------
1269 uint_fast32_t cum_path_len = q_path_len; // length of dequeued dir_node path
1270 uint_fast32_t parent_idx = __G->queue[q_pos].parent_idx;
1271 while (parent_idx != NO_PARENT) {
1272 cum_path_len += __G->queue[parent_idx].path_len + 1;
1273 parent_idx = __G->queue[parent_idx].parent_idx;
1274 }
1275 if (cum_path_len >= MAX_PATH_LEN) {
1276 atomic_fetch_sub_explicit(&__G->active_tasks, 1, memory_order_relaxed);
1277 continue;
1278 }
1279 // ----------------------------------------------------------------
1280 // Reconstruct the relative path for the dequeued directory node
1281 // ----------------------------------------------------------------
1282 uint_fast32_t write_cursor = cum_path_len;
1283 write_cursor -= q_path_len;
1284 memcpy(&__tl.path[write_cursor],
1285 &__G->path_data[q_path_offset],
1286 q_path_len);
1287 __tl.path[cum_path_len] = '\0';
1288#ifdef DEBUGX
1289 fprintf(stderr, "line: %d, %s, T%lu, dequeued path %s\n", __LINE__, __func__, __tl.thread_id, __tl.path);
1290#endif
1291 parent_idx = __G->queue[q_pos].parent_idx;
1292 uint_fast32_t p_path_len;
1293 uint_fast32_t p_path_offset;
1294 while (parent_idx != NO_PARENT) {
1295 write_cursor -= 1;
1296 __tl.path[write_cursor] = '/';
1297 p_path_len = __G->queue[parent_idx].path_len;
1298 p_path_offset = __G->queue[parent_idx].path_offset;
1299 write_cursor -= p_path_len;
1300 memcpy(&__tl.path[write_cursor],
1301 &__G->path_data[p_path_offset],
1302 p_path_len);
1303 parent_idx = __G->queue[parent_idx].parent_idx;
1304 }
1305#ifdef DEBUGY
1306 fprintf(stderr, "line: %d, %s, T%lu constructed path %s\n", __LINE__, __func__, __tl.thread_id, __tl.path);
1307#endif
1308 __tl.parent_path_len = cum_path_len;
1309 // ----------------------------------------------------------------
1310 // __tl->path_data now contains a relative path to the directory to open
1311 // ----------------------------------------------------------------
1312 __tl.child_dirs_remaining = 0;
1313 finder(__G, &__tl);
1315 atomic_fetch_sub_explicit(&__G->active_tasks, 1, memory_order_relaxed);
1316 }
1317 munmap(stage_arena, __tl.stage_arena_size);
1318 return NULL;
1319}
1320// ----------------------------------------------------------------------
1321// FINDER
1322// ----------------------------------------------------------------------
1323/** @brief Traverse a directory and process its entries.
1324 @param lf A pointer to the GlobalContext struct containing the search settings.
1325 @param tl A pointer to the ThreadLocal struct containing the current directory context.
1326 @return NULL upon completion.
1327 @details This function opens a directory specified in the ThreadLocal context,
1328 reads its entries, and processes each entry based on the provided settings in
1329 the GlobalContext. It handles filtering of directory entries, retrieves
1330 advanced metadata if necessary, and manages the traversal of subdirectories.
1331 The function also logs errors and flushes output buffers as needed. It is
1332 designed to be called by worker threads for concurrent processing of
1333 directories.
1334 */
1335void *finder(GlobalContext *__G, ThreadLocal *__tl) {
1336 long nread;
1337 struct stat sb = {};
1338 struct linux_dirent64 *entry;
1339 dev_t actual_dev = 0, effective_dev = 0;
1340 ino_t actual_ino = 0, effective_ino = 0;
1341 unsigned char actual_type;
1342 int rc;
1343 LogCtx *log_ctx = &__tl->log_ctx;
1344 __tl->stage_idx = 0;
1346 struct open_how how = {
1347 .flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC,
1348 .mode = 0};
1349 how.resolve = RESOLVE_NO_MAGICLINKS;
1350 if (!__G->follow_links)
1351 how.resolve |= RESOLVE_NO_SYMLINKS;
1352 if (__G->xdev)
1353 how.resolve |= RESOLVE_NO_XDEV;
1354 int dir_fd = openat2(AT_FDCWD, __tl->path, &how, sizeof(struct open_how));
1355 if (dir_fd == -1) {
1356 if (__G->f_logging) {
1357 lf_log(ERROR, "OPEN_FAIL,%s,%s", __tl->path, strerror(errno));
1358 } else
1359 fprintf(stderr, "OPEN_FAIL,%s,%d:%s\n", __tl->path, errno, strerror(errno));
1361 return NULL;
1362 }
1363 while (1) {
1364 nread = getdents64(dir_fd, __tl->dir_buf, DIR_BUF_SIZE);
1365 if (__builtin_expect(nread == -1, 0)) {
1366 atomic_fetch_add(&__G->error_count, 1);
1367 if (__G->f_logging)
1368 lf_log(ERROR, "READDIR_FAIL,%s,%s", __tl->path, strerror(errno));
1369 break;
1370 }
1371 if (nread == 0)
1372 break;
1373 for (uint_fast32_t bpos = 0; bpos < (size_t)nread;) {
1374 entry = (struct linux_dirent64 *)(__tl->dir_buf + bpos);
1375 bpos += entry->d_reclen;
1376#ifdef DEBUGT
1377 fprintf(stderr, "line: %d, %s, T%lu entry d_name %s, d_type %d\n", __LINE__, __func__, __tl->thread_id, entry->d_name, entry->d_type);
1378#endif
1379 actual_type = entry->d_type;
1380 __tl->d_name_len = strlen(entry->d_name);
1381 __tl->effective_type = actual_type;
1382 // -------------------------------------------------------------------
1383 // FILTER DIRECTORY ENTRIES
1384 // -------------------------------------------------------------------
1385 if (__builtin_expect(actual_type == DT_DIR, 0)) {
1386 if (entry->d_name[0] == '.') {
1387 if (entry->d_name[1] == '\0')
1388 continue;
1389 if (entry->d_name[1] == '.' && entry->d_name[2] == '\0')
1390 continue;
1391 }
1392 }
1393 // -------------------------------------------------------------------
1394 // GET ADVANCED METADATA
1395 // -------------------------------------------------------------------
1396 bool need_metadata = (__G->follow_links && actual_type == DT_LNK);
1397 // Only evaluate the complex logging mask arrays if logging is
1398 // explicitly active
1399 if (__builtin_expect(__G->f_logging, 0)) {
1400 if ((__G->file_level_mask & ll_t[CYCLE].bits) ||
1401 (__G->disp_level_mask & ll_t[CYCLE].bits)) {
1402 need_metadata = true;
1403 }
1404 }
1405 if (__builtin_expect(need_metadata, 0)) {
1406 rc = fstatat(dir_fd, entry->d_name, &sb, AT_SYMLINK_NOFOLLOW);
1407 if (rc == -1) {
1408 atomic_fetch_add(&__G->error_count, 1);
1409 if (__G->f_logging)
1410 lf_log(ERROR, "LSTAT_FAIL,%s/%s,%s", __tl->path, entry->d_name,
1411 strerror(errno));
1412 } else {
1413 actual_ino = sb.st_ino;
1414 actual_dev = sb.st_dev;
1415 actual_type = (sb.st_mode & S_IFMT) >> 12;
1416 effective_dev = actual_dev;
1417 effective_ino = actual_ino;
1418 __tl->effective_type = actual_type;
1419 }
1420 if (S_ISLNK(sb.st_mode)) {
1421 if (__G->follow_links) {
1422 // -------------------------------------------------------
1423 // GET LINK METADATA
1424 // -------------------------------------------------------
1425 rc = fstatat(dir_fd, entry->d_name, &sb, 0);
1426 if (rc == -1) {
1427 atomic_fetch_add(&__G->error_count, 1);
1428 if (__G->f_logging)
1429 lf_log(ERROR, _("FSTATAT_FAIL,%s/%s,%s\n"), __tl->path, entry->d_name,
1430 strerror(errno));
1431 } else {
1432 effective_ino = sb.st_ino;
1433 effective_dev = sb.st_dev;
1434 __tl->effective_type = (sb.st_mode & S_IFMT) >> 12;
1435 }
1436 } else {
1437 __tl->effective_type = DT_REG;
1438 }
1439 }
1440 }
1441 // --------------------------------------------------------------------
1442 // DIRECTORY PROCESSING
1443 // --------------------------------------------------------------------
1444 if (__tl->effective_type == DT_DIR) {
1445 __tl->depth = __G->queue[__tl->queue_idx].depth + 1;
1446 if (__G->max_depth > 0 && __tl->depth + 1 > __G->max_depth)
1447 continue;
1448 // ----------------------------------------------------------------
1449 // HIGH-PERFORMANCE CYCLE DETECTION (Only if links followed)
1450 // ----------------------------------------------------------------
1451 if (__G->follow_links && actual_type == DT_LNK) {
1452 bool cycle_found = false;
1453 char target_path[MAX_PATH_LEN];
1454 // = {'\0'};
1455 if (__builtin_expect(__G->f_logging, 0)) {
1456 if ((__G->file_level_mask & ll_t[CYCLE].bits) ||
1457 (__G->disp_level_mask & ll_t[CYCLE].bits)) {
1458 size_t len = readlinkat(dir_fd, entry->d_name, target_path,
1459 sizeof(target_path) - 1);
1460 if (len != (size_t)-1) {
1461 target_path[len] = '\0';
1462 atomic_fetch_add_explicit(&__G->error_count, 1,
1463 memory_order_relaxed);
1464 lf_log(ERROR, "READLINK_FAIL,%s/%s,%s\n",
1465 __tl->path, entry->d_name, strerror(errno));
1466 }
1467 lf_log(CYCLE, "Target item: dev: %lu, ino: %lu, Name: %s/%s\n",
1468 effective_dev, effective_ino, __tl->path, entry->d_name);
1469 }
1470 }
1471 // CYCLE Backtrack verification
1472 uint_fast32_t current_parent_idx = __tl->queue_idx;
1473 while (current_parent_idx != NO_PARENT) {
1474 QueueNode *ancestor = &__G->queue[current_parent_idx];
1475 if (effective_dev == ancestor->dev &&
1476 effective_ino == ancestor->ino) {
1477 cycle_found = true;
1478 break;
1479 }
1480 current_parent_idx = __G->queue->parent_idx;
1481 }
1482 if (cycle_found) {
1483 atomic_fetch_add_explicit(&__G->error_count, 1,
1484 memory_order_relaxed);
1485 build_path(__tl, entry->d_name);
1486 print_file(__G, __tl);
1487 continue;
1488 }
1489 }
1490 // ----------------------------------------------------------------
1491 // STAGE BUFFERING
1492 // ----------------------------------------------------------------
1493 if ((__tl->stage_idx >= STAGE_NODES - 1) ||
1495 atomic_fetch_add_explicit(&__G->active_tasks, __tl->stage_idx, memory_order_relaxed);
1496 if (mpmc_bulk_enqueue(__G, __tl) == false) {
1497 atomic_fetch_sub_explicit(&__G->active_tasks, __tl->stage_idx, memory_order_relaxed);
1498 atomic_fetch_add_explicit(&__G->error_count, 1, memory_order_relaxed);
1499 if (__G->f_logging)
1500 lf_log(ERROR, "STAGE_ENQUEUE_FAIL,%s\n",
1501 __tl->path);
1502 return NULL;
1503 }
1504 __tl->stage_idx = 0;
1505 }
1506 __tl->d_name = entry->d_name;
1507#ifdef DEBUGT
1508 fprintf(stderr, "line: %d, %s, T%lu, path %s, d_name %s, tl->stage_idx %lu\n", __LINE__, __func__, __tl->thread_id, __tl->path, entry->d_name, __tl->stage_idx);
1509#endif
1510 QueueNode *stage_node = &__tl->stage_node[__tl->stage_idx];
1511 stage_node->parent_idx = __tl->queue_idx;
1512 stage_node->path_offset = __tl->cum_path_offset;
1513 stage_node->path_len = __tl->d_name_len;
1514 stage_node->depth = __tl->depth;
1515 stage_node->child_dirs_remaining = 0;
1516 stage_node->dev = effective_dev;
1517 stage_node->ino = effective_ino;
1518 memcpy(__tl->path_data + stage_node->path_offset,
1519 __tl->d_name,
1520 __tl->d_name_len);
1522 __tl->path_data[__tl->cum_path_offset++] = '\0';
1523 __tl->stage_idx++;
1524 // --------------------------------------------------------
1525 // CONDITIONALLY PRINT AS DIRECTORY
1526 // --------------------------------------------------------
1527 if (entry->d_name[0] == '.') {
1528 if (!__G->include_hidden && !__G->hidden_only)
1529 continue;
1530 } else {
1531 if (__G->hidden_only)
1532 continue;
1533 }
1535 if (!__G->only_errors) {
1536 build_path(__tl, entry->d_name);
1537 print_file(__G, __tl);
1538 }
1539 } else {
1540 // --------------------------------------------------------
1541 // FILE PROCESSING FAST-PATH
1542 // --------------------------------------------------------
1543 if (entry->d_name[0] == '.') {
1544 if (!__G->include_hidden && !__G->hidden_only)
1545 continue;
1546 } else {
1547 if (__G->hidden_only)
1548 continue;
1549 }
1550 if (__tl->path[0] != '\0' && !__G->only_errors) {
1551 build_path(__tl, entry->d_name);
1552 print_file(__G, __tl);
1553 }
1554 }
1555 }
1556 }
1557 close(dir_fd);
1559 if (__tl->stage_idx > 0) {
1560 atomic_fetch_add_explicit(&__G->active_tasks, __tl->stage_idx, memory_order_relaxed);
1561 if (mpmc_bulk_enqueue(__G, __tl) == false) {
1562 atomic_fetch_sub_explicit(&__G->active_tasks, __tl->stage_idx, memory_order_relaxed);
1563 atomic_fetch_add_explicit(&__G->error_count, 1,
1564 memory_order_relaxed);
1565 if (__G->f_logging)
1566 lf_log(ERROR, "STAGE_ENQUEUE_FAIL,%s\n",
1567 __tl->path);
1568 return NULL;
1569 }
1570 __tl->stage_idx = 0;
1571 }
1572 return NULL;
1573}
1574/** @brief Build the full path for a file or directory entry.
1575 @param tl A pointer to the ThreadLocal struct containing the current directory context.
1576 @param file_name The name of the file or directory entry to append to the path.
1577 @details This function constructs the full path for a given file or directory
1578 entry by appending its name to the parent path stored in the ThreadLocal
1579 context. It updates the path length and ensures that the resulting path is
1580 null-terminated. This function is used during directory traversal to prepare
1581 paths for processing and output.
1582 */
1583void build_path(ThreadLocal *__tl, char *file_name) {
1584 __tl->path_len = __tl->parent_path_len;
1585 __tl->path[__tl->path_len++] = '/';
1586 __tl->d_name = file_name;
1587 memcpy(__tl->path + __tl->path_len, file_name, __tl->d_name_len);
1588 __tl->path_len += __tl->d_name_len;
1589 __tl->path[__tl->path_len] = '\0';
1590}
1591/** @brief Print the path of a file or directory entry based on filtering criteria.
1592 @param lf A pointer to the GlobalContext struct containing the search settings.
1593 @param tl A pointer to the ThreadLocal struct containing the current directory context.
1594 @return true if the file or directory entry was printed, false otherwise.
1595 @details This function checks various filtering criteria specified in the
1596 GlobalContext, such as type suppression, regex matching, user ownership,
1597 permissions, modification time, and file size. If the entry passes all
1598 filters, it increments the file count and appends the path to the output
1599 buffer for printing. The function returns true if the entry was printed and
1600 false if it was excluded based on any of the filtering criteria.
1601 */
1602int print_file(GlobalContext *__G, ThreadLocal *__tl) {
1603 while (1) {
1605 break;
1606 // Exclude non-matching files
1607 if (__G->flags & LF_REGEX) {
1608 int reti = regexec(&__G->compiled_re, __tl->path, 0, NULL, 0);
1609 if (reti == REG_NOMATCH)
1610 break;
1612 }
1613 // Exclude matching files
1614 if (__G->flags & LF_EXC_REGEX) {
1615 int reti = regexec(&__G->compiled_ere, __tl->path, 0, NULL, 0);
1616 if (reti == 0) {
1618 break;
1619 }
1620 }
1621 // Exclude files not owned by specified user
1622 if (__G->flags & LF_USER) {
1623 if (!__tl->stat_cached && stat(__tl->path, __tl->cached_sb) == 0)
1624 __tl->stat_cached = true;
1625 if (!__tl->stat_cached || __tl->cached_sb->st_uid != __G->user_id)
1626 break;
1627 }
1628 if (__G->include_perms) {
1629 if (!__tl->stat_cached && stat(__tl->path, __tl->cached_sb) == 0)
1630 __tl->stat_cached = true;
1631 if (!__tl->stat_cached)
1632 break;
1633 if ((__G->include_perms & LF_IRUSR) && !(__tl->cached_sb->st_mode & S_IRUSR))
1634 break;
1635 else if ((__G->include_perms & LF_IWUSR) &&
1636 !(__tl->cached_sb->st_mode & S_IWUSR))
1637 break;
1638 else if ((__G->include_perms & LF_IXUSR) &&
1639 !(__tl->cached_sb->st_mode & S_IXUSR))
1640 break;
1641 else if ((__G->include_perms & LF_ISUID) &&
1642 !(__tl->cached_sb->st_mode & S_ISUID))
1643 break;
1644 else if ((__G->include_perms & LF_ISGID) &&
1645 !(__tl->cached_sb->st_mode & S_ISGID))
1646 break;
1647 }
1648 if (__G->before) { // Last file modification
1649 if (!__tl->stat_cached && stat(__tl->path, __tl->cached_sb) == 0)
1650 __tl->stat_cached = true;
1651 if (__tl->stat_cached && __tl->cached_sb->st_mtime > __G->before)
1652 break;
1653 }
1654 if (__G->after) { // Last file modification
1655 if (!__tl->stat_cached && stat(__tl->path, __tl->cached_sb) == 0)
1656 __tl->stat_cached = true;
1657 if (__tl->stat_cached && __tl->cached_sb->st_mtime < __G->after)
1658 break;
1659 }
1660 if (__G->file_size_min) {
1661 if (!__tl->stat_cached && stat(__tl->path, __tl->cached_sb) == 0)
1662 __tl->stat_cached = true;
1663 if (__tl->stat_cached && __tl->cached_sb->st_size < __G->file_size_min)
1664 break;
1665 }
1666 if (__G->only_errors)
1667 break;
1668 atomic_fetch_add(&__G->file_count, 1);
1669 char *path = __tl->path;
1670 size_t path_len = __tl->path_len;
1671 if (!__G->count_silently) {
1672 if (path_len > 2 && path[0] == '.' && path[1] == '/') {
1673 path += 2;
1674 path_len -= 2;
1675 }
1676 if (path_len > 0) {
1677 append_output_buffer(__G, __tl->output_buffer, path, path_len,
1678 __tl->effective_type == DT_DIR);
1679 }
1680 break;
1681 }
1682 }
1683 return true;
1684}
1685// -----------------------------------------------------------------------
1686// Logging
1687// -----------------------------------------------------------------------
1688/** iso8601_timestamp
1689 @brief Generate an ISO 8601 timestamp string
1690 @ingroup logging
1691 @param buf Buffer to store the timestamp string
1692 @param n Size of the buffer
1693 @param local If true, use local time; if false, use UTC
1694 @return Pointer to the buffer containing the timestamp string */
1695void iso8601_timestamp(GlobalContext *__G, LogCtx *log_ctx) {
1696 char buf[64];
1697 time_t tm = time(NULL);
1698 struct tm *tp =
1699 __G->timestamp_style == ISO8601_LOCAL ? localtime(&tm) : gmtime(&tm);
1700 if (__G->timestamp_style == ISO8601_LOCAL)
1701 strftime(buf, 64, _("%Y-%m-%dT%H:%M:%S%z"), tp);
1702 else
1703 strftime(buf, 64, _("%Y-%m-%dT%H:%M:%SZ"), tp);
1704 ssnprintf(log_ctx->time_buf, 64, "[%s]", buf);
1705 return;
1706}
1707static const char DIV100_TABLE[] = "0001020304050607080910111213141516171819"
1708 "2021222324252627282930313233343536373839"
1709 "4041424344454647484950515253545556575859"
1710 "6061626364656667686970717273747576777879"
1711 "8081828384858687888990919293949596979899";
1712#define WRITE_STR(p, str)
1713 do {
1714 const char *s = (str);
1715 while (*s)
1716 *p++ = *s++;
1717 } while (0)
1718/** @brief Write a 3-digit unsigned integer to a buffer.
1719 @ingroup logging
1720 @param p Pointer to the buffer where the integer will be written.
1721 @param val The unsigned integer value to write (0-999).
1722 @return Pointer to the next position in the buffer after writing the integer.
1723 @details This function writes a 3-digit unsigned integer to a provided
1724 buffer. It calculates the hundreds, tens, and units digits and uses a lookup
1725 table for efficient conversion of the last two digits. The function ensures
1726 that the value is correctly formatted as a 3-digit string, even if the value
1727 is less than 100, by padding with leading zeros as necessary.
1728 */
1729static inline char *write_uint3d(char *p, long val) {
1730 long hundreds = val / 100;
1731 long remainder = val % 100;
1732 *p++ = (char)('0' + hundreds);
1733 *p++ = DIV100_TABLE[remainder * 2];
1734 *p++ = DIV100_TABLE[remainder * 2 + 1];
1735 return p;
1736}
1737/** @brief Write a 2-digit unsigned integer to a buffer.
1738 @ingroup logging
1739 @param p Pointer to the buffer where the integer will be written.
1740 @param val The unsigned integer value to write (0-99).
1741 @return Pointer to the next position in the buffer after writing the integer.
1742 @details This function writes a 2-digit unsigned integer to a provided
1743 buffer. It uses a lookup table for efficient conversion of the value into its
1744 string representation. The function ensures that the value is correctly
1745 formatted as a 2-digit string, even if the value is less than 10, by padding
1746 with a leading zero as necessary.
1747 */
1748static inline char *write_uint2d(char *p, long val) {
1749 *p++ = DIV100_TABLE[val * 2];
1750 *p++ = DIV100_TABLE[val * 2 + 1];
1751 return p;
1752}
1753/** @brief Write an interval in seconds to a buffer, handling values greater
1754 than 99.
1755 @ingroup logging
1756 @param p Pointer to the buffer where the interval will be written.
1757 @param val The interval value in seconds to write.
1758 @return Pointer to the next position in the buffer after writing the
1759 interval.
1760 @details This function writes an interval value in seconds to a provided
1761 buffer. If the value is 99 or less, it uses a fast path to write two digits.
1762 For larger values, it constructs the string representation in reverse order
1763 and then copies it forward into the buffer. This approach ensures efficient
1764 handling of both small and large interval values while maintaining correct
1765 formatting.
1766 */
1767static inline char *write_interval_sec(char *p, long val) {
1768 if (val <= 99) {
1769 return write_uint2d(p, val);
1770 }
1771 // Fallback loop for large intervals: builds string backwards, then copies
1772 // forward
1773 char temp[24];
1774 int i = 0;
1775 while (val > 0) {
1776 temp[i++] = (char)('0' + (val % 10));
1777 val /= 10;
1778 }
1779 // Reverse copy into the main buffer
1780 while (i > 0) {
1781 *p++ = temp[--i];
1782 }
1783 return p;
1784}
1785/** @brief Initialize the timer for a thread, capturing the start time and
1786 setting up interval tracking.
1787 @ingroup logging
1788 @param lf A pointer to the GlobalContext struct containing the search settings.
1789 @param log_ctx A pointer to the LogCtx struct where timing information will
1790 be stored.
1791 @return void
1792 @details This function retrieves the current time using clock_gettime and
1793 initializes both the start time and the previous interval time in the
1794 provided LogCtx structure. It also sets the corresponding values in the GlobalContext
1795 structure for global timing reference. This setup is essential for accurate
1796 timestamping of log entries and interval calculations during program
1797 execution.
1798 */
1799void initialize_thread_timer(GlobalContext *__G, LogCtx *log_ctx) {
1800 struct timespec tp;
1801 clock_gettime(CLOCK_REALTIME, &tp);
1802 log_ctx->start_sec = __G->start_sec;
1803 log_ctx->start_nsec = __G->start_nsec;
1804 log_ctx->p_int_sec = tp.tv_sec;
1805 log_ctx->p_int_nsec = tp.tv_nsec;
1806}
1807/** @brief Initialize the timer for logging, capturing the start time and
1808 setting up interval tracking.
1809 @ingroup logging
1810 @param lf A pointer to the GlobalContext struct containing the search settings.
1811 @param log_ctx A pointer to the LogCtx struct where timing information will
1812 be stored.
1813 @return void
1814 @details This function retrieves the current time using clock_gettime and
1815 initializes both the start time and the previous interval time in the
1816 provided LogCtx structure. It also sets the corresponding values in the GlobalContext
1817 structure for global timing reference. This setup is essential for accurate
1818 timestamping of log entries and interval calculations during program
1819 execution.
1820 */
1821void initialize_timer(GlobalContext *__G, LogCtx *log_ctx) {
1822 struct timespec tp;
1823 clock_gettime(CLOCK_REALTIME, &tp);
1824 log_ctx->start_sec = tp.tv_sec;
1825 log_ctx->start_nsec = tp.tv_nsec;
1826 log_ctx->p_int_sec = tp.tv_sec;
1827 log_ctx->p_int_nsec = tp.tv_nsec;
1828 __G->start_sec = tp.tv_sec;
1829 __G->start_nsec = tp.tv_nsec;
1830 __G->p_int_sec = tp.tv_sec;
1831 __G->p_int_nsec = tp.tv_nsec;
1832}
1833/** coders_timestamp
1834 @brief Generate a timestamp string for logging, including both current time
1835 and interval since last log entry.
1836 @ingroup logging
1837 @param log_ctx A pointer to the LogCtx struct containing timing information.
1838 @return void
1839 @details This function calculates the current time since the start of the
1840 program and the interval since the last log entry. It formats these values
1841 into a timestamp string stored in log_ctx->time_buf. The timestamp includes
1842 seconds, milliseconds, microseconds, and nanoseconds, with color-coded
1843 formatting for better visibility in logs. If you are wondering about the
1844 seemingly complex output section, it is designed to mitigate the classical
1845 and unavoidable observation error.
1846 */
1847void coders_timestamp(LogCtx *log_ctx) {
1848 struct timespec tp;
1849 clock_gettime(CLOCK_REALTIME, &tp);
1850 long cur_sec = (tp.tv_sec - log_ctx->start_sec) % 60;
1851 long cur_nsec = (tp.tv_nsec - log_ctx->start_nsec);
1852 long cur_ms = (cur_nsec / 1000000);
1853 long cur_us = (cur_nsec / 1000) % 1000;
1854 long cur_ns = cur_nsec % 1000;
1855#ifdef DEBUG_INTERVAL_LOGGING
1856 fprintf(
1857 stderr,
1858 "DEBUG: thread: %2ld, start_sec: %010ld, start_nsec: %09ld, tp.tv_sec: "
1859 "%010ld, tp.tv_nsec: %09ld, cur: %02ld.%03ld_%03ld_%03ld\n",
1860 log_ctx->thread_id, log_ctx->start_sec, log_ctx->start_nsec, tp.tv_sec,
1861 tp.tv_nsec, cur_sec, cur_ms, cur_us, cur_ns);
1862#endif
1863 // Interval calculation: time since last log entry
1864 long int_sec = tp.tv_sec - log_ctx->p_int_sec;
1865 long int_nsec = tp.tv_nsec - log_ctx->p_int_nsec;
1866 if (int_nsec < 0) {
1867 int_sec -= 1;
1868 int_nsec += 1000000000L;
1869 }
1870 long int_ms = (int_nsec / 1000000);
1871 long int_us = (int_nsec / 1000) % 1000;
1872 long int_ns = int_nsec % 1000;
1873#ifdef DEBUG_INTERVAL_LOGGING
1874 fprintf(
1875 stderr,
1876 "DEBUG: thread: %2ld, p_int_sec: %010ld, p_int_nsec: %09ld, tp.tv_sec: "
1877 "%010ld, tp.tv_nsec: %09ld, int: %02ld.%03ld_%03ld_%03ld\n",
1878 log_ctx->thread_id, log_ctx->p_int_sec, log_ctx->p_int_nsec, tp.tv_sec,
1879 tp.tv_nsec, int_sec, int_ms, int_us, int_ns);
1880#endif
1881 log_ctx->p_int_sec = tp.tv_sec;
1882 log_ctx->p_int_nsec = tp.tv_nsec;
1883#ifdef DEBUG_INTERVAL_LOGGING
1884 fprintf(stderr, "DEBUG: thread: %2ld, p_int_sec: %010ld, p_int_nsec: %09ld\n",
1885 log_ctx->thread_id, log_ctx->p_int_sec, log_ctx->p_int_nsec);
1886#endif
1887 char *p = log_ctx->time_buf;
1888 // --- Block 1: Current Time Timestamp ---
1889 *p++ = '[';
1890 p = write_uint2d(p, cur_sec);
1891 *p++ = '.';
1892 WRITE_STR(p, sgr_c[YELLOW]);
1893 p = write_uint3d(p, cur_ms);
1894 *p++ = '_';
1895 p = write_uint3d(p, cur_us);
1896 *p++ = '_';
1897 p = write_uint3d(p, cur_ns);
1898 WRITE_STR(p, sgr_c[RESET]);
1899 *p++ = ']';
1900 // --- Block 2: Interval Time Timestamp ---
1901 *p++ = '[';
1902 p = write_interval_sec(p, int_sec); // Handles arbitrary size safely
1903 *p++ = '.';
1904 WRITE_STR(p, sgr_c[YELLOW]);
1905 p = write_uint3d(p, int_ms);
1906 *p++ = '_';
1907 p = write_uint3d(p, int_us);
1908 *p++ = '_';
1909 p = write_uint3d(p, int_ns);
1910 WRITE_STR(p, sgr_c[RESET]);
1911 *p++ = ']';
1912 *p = '\0';
1913}
1914/** log_open
1915 @brief Open the log file for writing
1916 @ingroup logging
1917 @return FILE pointer to the opened log file */
1918void log_open(GlobalContext *__G, LogCtx *log_ctx, size_t thread_id) {
1919 bool local = true;
1920 if (!__G->disp_level_mask && !__G->file_level_mask)
1921 return;
1922 if (__G->log_fd == -1) {
1923 char *user = getenv("USER");
1924 char tz_buf[16];
1925 char time_s[16];
1926 struct timespec tp;
1927 clock_gettime(CLOCK_REALTIME, &tp);
1928 log_ctx->start_sec = tp.tv_sec;
1929 log_ctx->start_nsec = tp.tv_nsec;
1930 log_ctx->p_int_sec = tp.tv_sec;
1931 log_ctx->p_int_nsec = tp.tv_nsec;
1932 __G->start_sec = tp.tv_sec;
1933 __G->start_nsec = tp.tv_nsec;
1934 __G->p_int_sec = tp.tv_sec;
1935 __G->p_int_nsec = tp.tv_nsec;
1936 struct tm *tm = local ? localtime(&tp.tv_sec) : gmtime(&tp.tv_sec);
1937 strftime(time_s, sizeof(time_s), "%Y%m%dT%H%M%S", tm);
1938 if (local) {
1939 strftime(tz_buf, sizeof(tz_buf), "%z", tm);
1940 } else {
1941 tz_buf[0] = 'Z';
1942 tz_buf[1] = '\0';
1943 }
1944 ssnprintf(__G->log_file_spec, MAXLEN - 1, "/tmp/%s_lf_%s%s.log", user,
1945 time_s, tz_buf);
1946 __G->log_fd = open(__G->log_file_spec, O_WRONLY | O_CREAT | O_APPEND, 0644);
1947 if (__G->log_fd == -1) {
1948 ssnprintf(em0, MAXLEN - 1, _("Failed to open log file: %s"),
1950 ssnprintf(em1, MAXLEN - 1, _("Error: %s"), strerror(errno));
1951 ssnprintf(em2, MAXLEN - 1, "%s: line: %d", __FILE__, __LINE__ - 4);
1952 ssnprintf(em3, MAXLEN - 1, _("remedy: delete %s and try again"),
1954 fprintf(stderr, "%s\n%s\n%s\n%s\n", em0, em1, em2, em3);
1955 exit(EXIT_FAILURE);
1956 }
1957 }
1958 char ttyname[MAXLEN];
1959 char cmenu_user[MAXLEN];
1960 char *p = getenv(_("USER"));
1961 strnz__cpy(cmenu_user, p, MAXLEN - 1);
1962 if (ttyname_r(STDERR_FILENO, ttyname, sizeof(ttyname)) == 0)
1963 if (__G->f_logging)
1964 lf_log(ALL, _("Lf_Log started by user %s, thread %lu, on terminal '%s'"),
1965 cmenu_user, thread_id, ttyname);
1966 return;
1967}
1968/** @brief Write a log message to the log file and/or display
1969 @ingroup logging
1970 @param level The log level (e.g., INFO, ERROR)
1971 @param lf Pointer to the GlobalContext struct containing logging settings
1972 @param log_ctx Pointer to the LogCtx struct for the current thread
1973 @param file The source file name where the log is generated
1974 @param func The function name where the log is generated
1975 @param line The line number in the source file where the log is generated
1976 @param fmt The format string for the log message
1977 @param ... Additional arguments for the format string
1978 @details This function checks if the specified log level is enabled for file
1979 or display output. If enabled, it formats the log message with a timestamp,
1980 source information, and user-provided message. It handles opening the log
1981 file if necessary and manages log rotation based on size limits. The
1982 formatted message is written to the appropriate output destinations.
1983 */
1984void log_write(const ll_e level, GlobalContext *__G, LogCtx *log_ctx, const char *file,
1985 const char *func, const int line, const char *fmt, ...) {
1986 if (!(__G->file_level_mask & ll_t[level].bits) &&
1987 !(__G->disp_level_mask & ll_t[level].bits))
1988 return;
1989 va_list args;
1990 va_start(args, fmt);
1991 if ((__G->file_level_mask & ll_t[level].bits) && __G->log_fd == -1)
1992 log_open(__G, log_ctx, log_ctx->thread_id);
1993 struct stat st;
1994 fstat(__G->log_fd, &st);
1995 if (__G->log_fd == -1 ||
1996 ((fstat(__G->log_fd, &st) == 0) && (st.st_size >= MAX_LOG_SIZE))) {
1997 if (__G->log_fd != -1) {
1998 close(__G->log_fd);
1999 __G->log_fd = -1;
2000 }
2001 char old_archive[MAXLEN];
2002 strnz__cpy(old_archive, __G->log_file_spec, MAXLEN - 1);
2003 strnz__cat(old_archive, ".closed", MAXLEN - 1);
2004 rename(__G->log_file_spec, old_archive);
2005 log_open(__G, log_ctx, log_ctx->thread_id);
2006 }
2007 switch (__G->timestamp_style) {
2008 case ISO8601_ZULU:
2009 case ISO8601_LOCAL:
2010 iso8601_timestamp(__G, log_ctx);
2011 break;
2012 case CODER:
2013 coders_timestamp(log_ctx);
2014 break;
2015 case TIMESTAMP_STYLE_COUNT:
2016 break;
2017 }
2018 char log_record[MAX_LOG_REC_LEN];
2019 ssnprintf(log_record, sizeof(log_record), "%s[%s%-8s%s]<%s:%-12s:%5d> ",
2020 log_ctx->time_buf, ll_t[level].SGR, ll_t[level].name, ANSI_RESET,
2021 file, func, line);
2022 size_t len = strlen(log_record);
2023 vssnprintf(log_record + len, sizeof(log_record) - len, fmt, args);
2024 len = strlen(log_record);
2025 log_record[len++] = '\n';
2026 if (__G->file_level_mask & ll_t[level].bits) {
2027 if (write(__G->log_fd, log_record, len) == -1)
2028 perror("Failed to write atomic log record");
2029 }
2030 if (__G->disp_level_mask & ll_t[level].bits) {
2031 if (write(__G->err_fd, log_record, len) == -1)
2032 perror("Failed to write atomic error record");
2033 va_end(args);
2034 return;
2035 }
2036}
2037/** @brief Parse a local timestamp string into a time_t value
2038 @ingroup utility_functions
2039 @param s - the string containing the local timestamp in the format
2040 "YYYY-MM-DDTHH:MM:SS"
2041 @param out - pointer to a time_t variable where the parsed value will be
2042 stored
2043 @returns true if parsing was successful, false otherwise
2044 @details This function uses strptime to parse a local timestamp string into
2045 a struct tm, and then converts it to a time_t value using mktime. The caller
2046 is responsible for providing a valid buffer for the output time_t value.
2047 */
2048bool parse_local_timestamp(const char *s, time_t *out) {
2049 struct tm tmv;
2050 memset(&tmv, 0, sizeof tmv);
2051 tmv.tm_isdst = -1;
2052 if (strptime(s, "%Y-%m-%dT%H:%M:%S", &tmv) == NULL)
2053 return false;
2054 time_t t = mktime(&tmv);
2055 if (t == (time_t)-1)
2056 return false;
2057 *out = t;
2058 return true;
2059}
2060/** @brief Format a time_t value into a local timestamp string
2061 @ingroup utility_functions
2062 @param t - the time_t value to format
2063 @param buf - the buffer to store the formatted timestamp
2064 @param n - the size of the buffer
2065 @returns a pointer to the buffer containing the formatted timestamp
2066 @details This function converts a time_t value into a local timestamp string
2067 in the format "YYYY-MM-DDTHH:MM:SS". It uses localtime_r to convert the
2068 time_t value into a struct tm, and then formats it using strftime. The caller
2069 is responsible for ensuring that the buffer is large enough to hold the
2070 resulting string.
2071 */
2072char *format_local_timestamp(time_t t, char *buf, size_t n) {
2073 struct tm tmv;
2074 localtime_r(&t, &tmv);
2075 strftime(buf, n, "%Y-%m-%dT%H:%M:%S", &tmv);
2076 return buf;
2077}
2078/** @brief Expand a tilde (~) in a file path to the user's home directory
2079 @ingroup utility_functions
2080 @param str - the string containing the path to expand
2081 @param path_maxlen - the maximum length of the path buffer
2082 @returns true if expansion was successful, false otherwise
2083 @details This function checks if the input string starts with a tilde (~)
2084 and replaces it with the user's home directory obtained from the HOME
2085 environment variable. It ensures that the resulting path does not exceed the
2086 specified maximum length. The caller is responsible for ensuring that the
2087 input string has enough space to accommodate the expanded path.
2088 */
2089bool expand_tilde(char *str, uint path_maxlen) {
2090 if (str == nullptr || *str == '\0')
2091 return false;
2092 const char tgt[3] = "~/";
2093 char path[MAXLEN];
2094 char *e = getenv("HOME");
2095 strnz__cpy(path, e, MAXLEN - 1);
2096 strnz__cat(path, "/", MAXLEN - 1);
2097 char *tmp;
2098 tmp = rep_substring(str, tgt, path);
2099 strnz__cpy(str, tmp, path_maxlen - 1);
2100 free(tmp);
2101 return true;
2102}
2103/** @brief Replace all occurrences of a target substring in a string with a
2104 replacement substring
2105 @ingroup utility_functions
2106 @param org_s - the original string
2107 @param tgt_s - the target substring to be replaced
2108 @param rep_s - the replacement substring
2109 @returns a newly allocated string with replacements made, or nullptr on
2110 error
2111 @details This function searches for all occurrences of the target substring
2112 in the original string and replaces them with the replacement substring. It
2113 handles edge cases such as empty strings and overlapping substrings. The
2114 caller is responsible for freeing the returned string.
2115 */
2116char *rep_substring(const char *org_s, const char *tgt_s, const char *rep_s) {
2117 if (*org_s == '\0' || *tgt_s == '\0' || *rep_s == '\0')
2118 return nullptr;
2119 if (strstr(org_s, tgt_s) == nullptr)
2120 return strdup(org_s);
2121 if (strstr(rep_s, tgt_s) != nullptr)
2122 return nullptr;
2123 if (tgt_s == rep_s || tgt_s == org_s || rep_s == org_s)
2124 return strdup(org_s);
2125 if (strcmp(org_s, tgt_s) == 0)
2126 return strdup(rep_s);
2127 char *out_s, *ip, *tmp;
2128 uint tgt_l = strlen(tgt_s);
2129 uint rep_l = strlen(rep_s);
2130 uint head_l;
2131 uint n = 0;
2132 ip = (char *)org_s;
2133 while ((tmp = strstr(ip, tgt_s)) != nullptr) {
2134 n++;
2135 ip = tmp + tgt_l;
2136 }
2137 out_s = malloc(strlen(org_s) + (rep_l - tgt_l) * n + 1);
2138 if (!out_s) {
2139 return nullptr;
2140 }
2141 tmp = out_s;
2142 ip = (char *)org_s;
2143 while (n--) {
2144 char *p = strstr(ip, tgt_s);
2145 head_l = p - ip;
2146 strnz__cpy(tmp, ip, head_l);
2147 tmp += head_l;
2148 strnz__cpy(tmp, rep_s, MAXLEN - 1);
2149 tmp += rep_l;
2150 ip += head_l + tgt_l;
2151 }
2152 strnz__cpy(tmp, ip, MAXLEN - 1);
2153 return out_s;
2154}
2155/** @brief A safer vsnprintf that ensures null-termination and handles edge
2156 cases
2157 @ingroup utility_functions
2158 @param buf - the buffer to write to
2159 @param buf_size - the size of the buffer
2160 @param format - the format string
2161 @param args - the variable argument list for formatting
2162 @returns the number of characters written, excluding the null terminator
2163 @details This function wraps vsnprintf to provide a safer interface for
2164 formatted string output. It ensures that the output is always null-terminated
2165 and handles cases where the buffer is NULL or has zero size. It also returns
2166 the number of characters that would have been written if enough space had
2167 been available, allowing for proper buffer management.
2168 */
2169size_t vssnprintf(char *buf, size_t buf_size, const char *format,
2170 va_list args) {
2171 /* Handle edge cases: an explicit NULL buffer or zero size */
2172 if (buf == NULL || buf_size == 0)
2173 return 0;
2174 int result = vsnprintf(buf, buf_size, format, args);
2175 if (result < 0) {
2176 buf[0] = '\0';
2177 return 0;
2178 }
2179 size_t bytes_written = (size_t)result;
2180 /* Check if the output was truncated due to buffer limits.
2181 * vsnprintf returns the total bytes *needed*, not bytes written. */
2182 if (bytes_written >= buf_size)
2183 return buf_size - 1; // Return the exact length of the truncated string
2184 return bytes_written;
2185}
2186/** @brief A safer snprintf that ensures null-termination and handles edge cases
2187 @ingroup utility_functions
2188 @param buf - the buffer to write to
2189 @param buf_size - the size of the buffer
2190 @param format - the format string
2191 @param ... - additional arguments for formatting
2192 @returns the number of characters written, excluding the null terminator
2193 @details This function wraps vsnprintf to provide a safer interface for
2194 formatted string output. It ensures that the output is always null-terminated
2195 and handles cases where the buffer is NULL or has zero size. It also returns
2196 the number of characters that would have been written if enough space had
2197 been available, allowing for proper buffer management.
2198 */
2199ATTR_FORMAT(printf, 3, 4)
2200size_t ssnprintf(char *buf, size_t buf_size, const char *format, ...) {
2201 if (buf == nullptr || format == nullptr || buf_size == 0)
2202 return 0;
2203 va_list args;
2204 size_t result;
2205 va_start(args, format);
2206 result = vssnprintf(buf, buf_size, format, args);
2207 va_end(args);
2208 return result;
2209}
2210/** @brief Check if a given path is a symbolic link that points to a directory
2211 @ingroup utility_functions
2212 @param path - the path to check
2213 @returns true if the path is a symbolic link to a directory, false otherwise
2214 @details This function uses lstat to determine if the specified path is a
2215 symbolic link. If it is, it then uses stat to check if the target of the
2216 symbolic link is a directory. This is useful for file system traversal and
2217 validation, especially when handling symbolic links that may point to
2218 directories.
2219 */
2220bool is_symlink_to_dir(const char *path) {
2221 struct stat link_stat;
2222 struct stat target_stat;
2223 if (lstat(path, &link_stat) == 0)
2224 if (S_ISLNK(link_stat.st_mode))
2225 if (stat(path, &target_stat) == 0)
2226 if (S_ISDIR(target_stat.st_mode))
2227 return true; // symbolic link to a directory
2228 return false;
2229}
2230/** @brief Convert a string to an unsigned long with optional size suffixes
2231 @ingroup utility_functions
2232 @param str - the string to convert
2233 @returns the converted unsigned long value, or 0 if conversion fails
2234 @details This function attempts to convert the input string str to an
2235 unsigned long integer. It supports optional size suffixes: 'k' for
2236 kilobytes, 'm' for megabytes, and 'g' for gigabytes. The conversion is done
2237 using strtoull, and if the conversion fails (e.g., due to invalid input),
2238 it returns 0. This is useful for parsing user input or configuration values
2239 that may include size specifications.
2240 */
2241unsigned long a_to_ul(const char *str) {
2242 char *endptr;
2243 unsigned long value = (unsigned long)strtoull(str, &endptr, 10);
2244 if (endptr == str)
2245 return 0;
2246 switch (tolower(*endptr)) {
2247 case 'g':
2248 return value * 1024ULL * 1024ULL * 1024ULL;
2249 case 'm':
2250 return value * 1024ULL * 1024ULL;
2251 case 'k':
2252 return value * 1024ULL;
2253 default:
2254 return value;
2255 }
2256}
2257/** @brief Convert a string to an integer with error checking
2258 @ingroup utility_functions
2259 @param s - the string to convert
2260 @param a_toi_error - pointer to a boolean that will be set to true if an
2261 error occurs
2262 @returns the converted integer, or -1 if an error occurs
2263 @details This function attempts to convert the input string s to an integer.
2264 If the conversion fails (e.g., due to invalid input or overflow), it sets
2265 the boolean pointed to by a_toi_error to true and returns -1. Otherwise, it
2266 returns the converted integer and sets a_toi_error to false. This is useful
2267 for safely parsing user input or configuration values where invalid data may
2268 be encountered.
2269 */
2270int a_toi(char *s, bool *a_toi_error) {
2271 if (s == nullptr || *s == '\0') {
2272 *a_toi_error = true;
2273 return -1;
2274 }
2275 int rc = -1;
2276 *a_toi_error = false;
2277 errno = 0;
2278 if (*s != 0)
2279 rc = (uint)strtol(s, nullptr, 10);
2280 if (rc < 0 || errno) {
2281 rc = -1;
2282 *a_toi_error = true;
2283 }
2284 return rc;
2285}
2286/** @brief safer alternative to strncpy
2287 @ingroup utility_functions
2288 @param d - destination string
2289 @param s - source string
2290 @param max_len - maximum length to copy
2291 @returns length of resulting string
2292 @details Copy string s to d, ensuring that the total length of d does not
2293 exceed max_len, and that the resulting string is null-terminated. It also
2294 treats newline and carriage return characters as string terminators,
2295 preventing them from being included in the result. This is particularly
2296 useful when copying user input or file data, where embedded newlines could
2297 cause issues.
2298 */
2299size_t strnz__cpy(char *d, const char *s, size_t max_len) {
2300 if (d == nullptr || s == nullptr)
2301 return 0;
2302 char *e;
2303 size_t len = 0;
2304 if (max_len == 0) {
2305 if (max_len > 0)
2306 *d = '\0';
2307 return 0;
2308 }
2309 e = d + max_len;
2310 while (*s != '\0' && *s != '\n' && *s != '\r' && d < e) {
2311 *d++ = *s++;
2312 len++;
2313 }
2314 *d = '\0';
2315 return len;
2316}
2317/** @brief safer alternative to strncat
2318 @ingroup utility_functions
2319 @param d - destination string
2320 @param s - source string
2321 @param max_len - maximum length to copy
2322 @returns length of resulting string
2323 @details Append string s to d, ensuring that the total length of d does not
2324 exceed max_len, and that the resulting string is null-terminated. It also
2325 treats newline and carriage return characters as string terminators,
2326 preventing them from being included in the result. This is particularly
2327 useful when concatenating user input or file data, where embedded newlines
2328 could cause issues.
2329 */
2330size_t strnz__cat(char *d, const char *s, size_t max_len) {
2331 if (d == nullptr || s == nullptr)
2332 return 0;
2333 if (max_len == 0)
2334 return 0;
2335 char *e;
2336 size_t len = 0;
2337 e = d + max_len;
2338 while (*d != '\0' && *d != '\n' && *d != '\r' && d < e) {
2339 d++;
2340 len++;
2341 }
2342 while (*s != '\0' && *s != '\n' && *s != '\r' && d < e) {
2343 *d++ = *s++;
2344 len++;
2345 }
2346 *d = '\0';
2347 return len;
2348}
2349/** @brief Check if a given path is a directory
2350 @ingroup utility_functions
2351 @param path - the file system path to check
2352 @returns true if the path is a directory, false otherwise
2353 @details This function uses the stat system call to retrieve information
2354 about the file at the specified path. It then checks the file mode to
2355 determine if it is a directory. This is useful for filtering or validating
2356 paths in file system operations.
2357 */
2358bool is_directory(const char *path) {
2359 struct stat statbuf;
2360 if (stat(path, &statbuf) == 0)
2361 if (S_ISDIR(statbuf.st_mode))
2362 return true;
2363 return false;
2364}
2365/** @brief Check if a given path is a regular file
2366 @ingroup utility_functions
2367 @param path - the file system path to check
2368 @returns true if the path is a regular file, false otherwise
2369 @details This function uses the stat system call to retrieve information
2370 about the file at the specified path. It then checks the file mode to
2371 determine if it is a regular file. This is useful for filtering or validating
2372 paths in file system operations.
2373 */
2374bool is_valid_regex(const char *pattern) {
2375 regex_t regex;
2376 uint ret = regcomp(&regex, pattern, REG_EXTENDED);
2377 regfree(&regex);
2378 if (ret == 0)
2379 return true;
2380 return false;
2381}
int stdout_fd
Definition ui_common.c:78
@ LF_EXC_REGEX
Definition cm.h:187
@ LF_HIDE
Definition cm.h:185
@ LF_ISUID
Definition cm.h:197
@ LF_IRUSR
Definition cm.h:195
@ LF_ISGID
Definition cm.h:196
@ LF_REGEX
Definition cm.h:188
@ LF_USER
Definition cm.h:190
@ LF_IXUSR
Definition cm.h:193
@ LF_IWUSR
Definition cm.h:194
@ LF_FIFO
Definition cm.h:202
@ LF_DIR
Definition cm.h:204
@ LF_UNKNOWN
Definition cm.h:209
@ LF_SOCK
Definition cm.h:208
@ LF_BLK
Definition cm.h:205
@ LF_LNK
Definition cm.h:207
@ LF_REG
Definition cm.h:206
@ LF_CHR
Definition cm.h:203
int stdin_fd
Definition ui_common.c:78
int stderr_fd
Definition lf.c:62
char * rep_substring(const char *, const char *, const char *) __attribute__((nonnull(1
Replace all occurrences of "tgt_s" in "org_s" with "rep_s".
Definition futil.c:1471
@ TS_SUCCESS
Definition lf.h:371
@ TS_MATCH
Definition lf.h:373
@ TS_ERROR
Definition lf.h:372
#define MAX_LOG_REC_LEN
Definition lf.h:50
#define DIR_BUF_SIZE
Definition lf.h:47
#define ATTR_FORMAT(archetype, fmt_idx, first_arg)
Definition lf.h:67
#define MAX_ARGS
Definition lf.h:37
#define STAGE_PATH_BYTES
Definition lf.h:44
#define QUEUE_NODES
Definition lf.h:48
#define lf_log(level, fmt,...)
Definition lf.h:519
#define QUEUE_MASK
Definition lf.h:53
#define PATH_BYTES
Definition lf.h:49
#define TIMESTAMP_STYLE(X)
Definition lf.h:111
#define NO_PARENT
Definition lf.h:307
#define print_file_type(mask, lf_type, dt_type, name)
Definition lf.h:447
#define STAGE_NODES
Definition lf.h:43
#define LOG_LEVEL_LIST(X)
Definition lf.h:89
#define MAX_LOG_SIZE
Definition lf.h:51
#define MAX_PATH_LEN
Definition lf.h:45
#define LF_VERSION
Definition lf.h:16
#define MAXLEN
Definition lf.h:38
#define ANSI_RESET
Definition lf.h:86
#define CACHE_LINE_SIZE
Definition lf.h:42
#define ANSI_COLOR_LIST(X)
Definition lf.h:118
char * exec
Definition lf.c:104
const char * sgr_c[]
Definition lf.c:81
void * worker(void *arg)
Worker thread function for processing directory nodes.
Definition lf.c:1227
void coders_timestamp(LogCtx *log_ctx)
Generate a timestamp string for logging, including both current time and interval since last log entr...
Definition lf.c:1847
char * lfargs[3]
Definition lf.c:103
int pipe_in
Definition lf.c:62
log_level ll_t[]
Definition lf.c:63
TerminationStatus termination_status
Definition lf.c:60
char em1[MAXLEN]
Definition lf.c:43
bool global_arena_create(GlobalContext *__G)
Create a queue arena for managing directory traversal tasks.
Definition lf.c:878
char * perms_p
Definition lf.c:106
void initialize_timer(GlobalContext *__G, LogCtx *log_ctx)
Initialize the timer for logging, capturing the start time and setting up interval tracking.
Definition lf.c:1821
const char * sgr_s[]
Definition lf.c:80
const char * tss_s[]
Definition lf.c:79
int tty_fd
Definition lf.c:62
char * debug_p
Definition lf.c:107
char em2[MAXLEN]
Definition lf.c:44
#define WRITE_STR(p, str)
Definition lf.c:1712
unsigned char const lf_type_mask[15]
Definition lf.c:110
void debug_out(GlobalContext *__G, int argc, char **argv)
Display everything and the kitchen sink on stderr.
Definition lf.c:582
bool append_output_buffer(GlobalContext *__G, OutputBuffer *output_buffer, const char *path, size_t path_len, bool append_slash)
Append a path to the output_buffer, flushing if necessary.
Definition lf.c:971
void initialize_thread_timer(GlobalContext *__G, LogCtx *log_ctx)
Initialize the timer for a thread, capturing the start time and setting up interval tracking.
Definition lf.c:1799
void * finder(GlobalContext *__G, ThreadLocal *__tl)
Traverse a directory and process its entries.
Definition lf.c:1335
char * file_types_p
Definition lf.c:105
void build_path(ThreadLocal *__tl, char *file_name)
Build the full path for a file or directory entry.
Definition lf.c:1583
void iso8601_timestamp(GlobalContext *__G, LogCtx *log_ctx)
Generate an ISO 8601 timestamp string.
Definition lf.c:1695
const char * log_s[]
Definition lf.c:61
bool mpmc_enqueue(GlobalContext *__G, QueueNode *node, const char *path, size_t len)
Definition lf.c:997
MemMetrics mm
Definition lf.c:41
int sort_lf_output(GlobalContext *__G, int argc, char **argv)
Sort the output of the lf command using the system's sort utility.
Definition lf.c:529
bool mpmc_dequeue(GlobalContext *__G, uint_fast32_t *dequeue_pos)
Dequeue a node from the MPMC queue.
Definition lf.c:1144
void log_write(const ll_e level, GlobalContext *__G, LogCtx *log_ctx, const char *file, const char *func, const int line, const char *fmt,...)
Write a log message to the log file and/or display.
Definition lf.c:1984
char em4[MAXLEN]
Definition lf.c:46
char em3[MAXLEN]
Definition lf.c:45
int lfargc
Definition lf.c:102
void push_root_node(GlobalContext *__G, dev_t dev, ino_t ino)
Push the root directory node into the queue arena.
Definition lf.c:908
bool init_lf(GlobalContext *__G, int argc, char **argv)
Initialize the file search process.
Definition lf.c:731
void global_arena_destroy(GlobalContext *__G)
Destroy the queue arena and free associated resources.
Definition lf.c:929
bool mpmc_bulk_enqueue(GlobalContext *__G, ThreadLocal *__tl)
Bulk enqueue multiple nodes into the MPMC queue.
Definition lf.c:1048
char em0[MAXLEN]
Definition lf.c:42
void flush_output_buffer(GlobalContext *__G, OutputBuffer *output_buffer)
Flush the output_buffer to stdout in a thread-safe manner.
Definition lf.c:947
struct tm tm_info
Definition lf.c:48
void log_open(GlobalContext *__G, LogCtx *log_ctx, size_t thread_id)
Open the log file for writing.
Definition lf.c:1918
const char doc[]
Definition lf.c:53
bool is_dirsys(const char *)
int print_file(GlobalContext *__G, ThreadLocal *__tl)
Print the path of a file or directory entry based on filtering criteria.
Definition lf.c:1602
int pipe_out
Definition lf.c:62
char * log_p
Definition lf.c:108
bool is_hidden(const char *)
const char * argp_program_version
Definition init.c:110
const char * argp_program_bug_address
Definition init.c:111
#define _(String)
Definition amort.c:23
int main(int argc, char **argv)
Capture the current terminal settings for later restoration.
Definition amort.c:41
size_t strnz__cpy(char *, const char *, size_t)
safer alternative to strncpy
Definition lf.c:2299
bool parse_local_timestamp(const char *, time_t *)
Parses an ISO 8601 timestamp string in local time and converts it to time_t.
Definition futil.c:249
bool is_directory(const char *)
Check if a given path is a directory.
Definition lf.c:2358
size_t ssnprintf(char *, size_t, const char *,...)
Custom safe string formatting utility (Variadic version).
Definition futil.c:398
bool is_valid_regex(const char *)
Check if a given path is a regular file.
Definition lf.c:2374
bool expand_tilde(char *, uint)
Expand a tilde (~) in a file path to the user's home directory.
Definition lf.c:2089
size_t strnz__cat(char *, const char *, size_t)
safer alternative to strncat
Definition lf.c:2330
bool is_symlink_to_dir(const char *)
Check if a given path is a symbolic link that points to a directory.
Definition lf.c:2220
int a_toi(char *, bool *)
a safer alternative to atoi() for converting ASCII strings to integers.
Definition futil.c:806
size_t vssnprintf(char *buf, size_t buf_size, const char *format, va_list args)
Custom safe string formatting utility (va_list version).
Definition futil.c:377
char * format_local_timestamp(time_t, char *, size_t)
Formats a time_t as an ISO 8601 string in local time.
Definition futil.c:272
unsigned long a_to_ul(const char *)
Convert a string to an unsigned long with optional size suffixes.
Definition lf.c:2241
const char * name
Definition lf.h:106
uint16_t bits
Definition lf.h:107
char SGR[64]
Definition lf.h:108
long p_int_sec
Definition lf.h:146
long p_int_nsec
Definition lf.h:145
char record[MAX_LOG_REC_LEN]
Definition lf.h:149
long start_sec
Definition lf.h:144
size_t thread_id
Definition lf.h:147
char time_buf[MAX_TIMESTAMP_LEN]
Definition lf.h:148
long start_nsec
Definition lf.h:143
unsigned short d_reclen
Definition lf.h:205
unsigned char d_type
Definition lf.h:206
char d_name[]
Definition lf.h:207
dev_t dev
Definition lf.h:314
uint_fast32_t depth
Definition lf.h:313
ino_t ino
Definition lf.h:315
uint_fast32_t parent_idx
Definition lf.h:309
uint_fast32_t path_len
Definition lf.h:311
uint_fast32_t child_dirs_remaining
Definition lf.h:312
uint_fast32_t path_offset
Definition lf.h:310
size_t len
Definition lf.h:322
char data[OUTPUT_BUFFER_BYTES]
Definition lf.h:321
char * d_name
Definition lf.h:348
size_t stage_queue_size
Definition lf.h:332
char * dir_buf
Definition lf.h:353
uint_fast32_t d_name_len
Definition lf.h:347
size_t stage_arena_size
Definition lf.h:331
uint_fast32_t depth
Definition lf.h:339
uint_fast32_t child_dirs_remaining
Definition lf.h:338
LogCtx log_ctx
Definition lf.h:354
uint_fast32_t thread_id
Definition lf.h:345
uint_fast32_t path_len
Definition lf.h:337
char * path_data
Definition lf.h:330
uint_fast32_t stage_idx
Definition lf.h:344
size_t stage_path_size
Definition lf.h:333
QueueNode * stage_node
Definition lf.h:329
OutputBuffer * output_buffer
Definition lf.h:334
uint_fast32_t queue_idx
Definition lf.h:343
unsigned char effective_type
Definition lf.h:352
void * stage_arena
Definition lf.h:328
uint_fast32_t parent_path_len
Definition lf.h:346
uint_fast32_t cum_path_offset
Definition lf.h:342
char path[MAX_PATH_LEN]
Definition lf.h:349
bool stat_cached
Definition lf.h:351
struct stat * cached_sb
Definition lf.h:350
uintptr_t stack_base
Definition lf.h:361
unsigned char include_types
Definition lf.h:423
time_t after
Definition lf.h:411
unsigned int nthreads
Definition lf.h:399
atomic_size_t log_error_count
Definition lf.h:396
size_t arena_bytes
Definition lf.h:391
bool depth_first
Definition lf.h:428
atomic_uint_fast32_t dequeue_pos
Definition lf.h:386
atomic_size_t file_count
Definition lf.h:400
long p_int_sec
Definition lf.h:410
long p_int_nsec
Definition lf.h:409
int err_fd
Definition lf.h:403
atomic_uint_fast32_t queue_idx
Definition lf.h:388
size_t path_bytes
Definition lf.h:393
char * base_path
Definition lf.h:415
time_t before
Definition lf.h:412
bool count_silently
Definition lf.h:442
atomic_uint_fast32_t shut_down
Definition lf.h:384
long start_nsec
Definition lf.h:407
bool unlink
Definition lf.h:426
atomic_uint_fast32_t active_tasks
Definition lf.h:387
char * sbuffer
Definition lf.h:419
bool count
Definition lf.h:441
pthread_mutex_t output_mutex
Definition lf.h:394
atomic_uint_fast32_t sequence[QUEUE_NODES]
Definition lf.h:390
atomic_uint_fast32_t thread_id
Definition lf.h:389
char log_record[MAX_LOG_RECORD_LEN]
Definition lf.h:425
bool f_logging
Definition lf.h:436
bool include_hidden
Definition lf.h:432
unsigned char suppress_types
Definition lf.h:424
char * ere
Definition lf.h:417
bool follow_links
Definition lf.h:434
char * re
Definition lf.h:416
size_t queue_bytes
Definition lf.h:392
unsigned char include_perms
Definition lf.h:422
ll_e disp_level_mask
Definition lf.h:437
char * path_data
Definition lf.h:382
char * user_name
Definition lf.h:418
long start_sec
Definition lf.h:408
bool sort_reverse
Definition lf.h:431
atomic_uint_fast32_t enqueue_pos
Definition lf.h:385
void * arena
Definition lf.h:380
bool only_errors
Definition lf.h:439
off_t file_size_min
Definition lf.h:402
uint32_t max_depth
Definition lf.h:413
bool ignore_case
Definition lf.h:429
bool hidden_only
Definition lf.h:433
int log_fd
Definition lf.h:404
atomic_size_t error_count
Definition lf.h:395
regex_t compiled_ere
Definition lf.h:421
int reg_flags
Definition lf.h:414
QueueNode * queue
Definition lf.h:381
char log_file_spec[MAX_PATH_LEN]
Definition lf.h:405
pthread_t * threads
Definition lf.h:397
atomic_uint_fast32_t path_offset
Definition lf.h:383
uintmax_t user_id
Definition lf.h:401
ll_e file_level_mask
Definition lf.h:438
bool xdev
Definition lf.h:427
long flags
Definition lf.h:406
bool sort
Definition lf.h:430
tss_e timestamp_style
Definition lf.h:435
regex_t compiled_re
Definition lf.h:420