2
3
4
5
6
7
8
9
18#include <linux/limits.h>
32#include <sys/resource.h>
34#include <sys/syscall.h>
35#include <sys/sysinfo.h>
39#include <valgrind/helgrind.h>
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.");
59static char args_doc[] =
"[DIRECTORY] [REGULAR_EXPRESSION]";
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,
""},
85 [YELLOW] =
"\033[33m",
88 [MAGENTA] =
"\033[36m",
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",
109static size_t path_data_alloc(GlobalContext *__G,
const char *path, size_t len);
111 0, 0b00000001, 0b00000010, 0, 0b00000100, 0, 0b00001000, 0,
112 0b00010000, 0, 0b00100000, 0, 0b01000000, 0, 0b10000000};
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)"),
122 {
_(
"unlink"),
'U',
_(
"bool"), 0,
_(
"unlink (delete) implies depth_first"),
124 {
_(
"xdev"),
'x',
_(
"bool"), 0,
_(
"Do not traverse mount points"),
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"),
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, "
142 {
_(
"timestamp_style"),
'y',
"CZL", 0,
143 _(
"timestamp_style for logging 1-CODER, 2-ISO8601_ZULU, 3-ISO8601_LOCAL"),
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"),
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},
159
160
161
162
163
164
165
166
167
168
169static error_t parse_opt(
int key,
char *arg,
struct argp_state *state) {
170 GlobalContext *__G = state->input;
172 bool a_toi_error =
false;
177 fprintf(stderr,
_(
"-b time must be greater than -a time.\n"));
183 if (arg && arg[0] !=
'\0') {
184 if (strcmp(arg,
"s") == 0)
189 if (arg && arg[0] !=
'\0')
193 __G
->ere = strdup(arg);
198 if (arg && arg[0] ==
'o') {
213 if (arg && arg[0] !=
'\0') {
259 if (arg && arg[0] !=
'\0') {
329 __G
->re = strdup(arg);
345 if (arg && arg[0] !=
'\0')
385 struct passwd *pwd = getpwnam(arg);
390 fprintf(stderr,
_(
"User '%s' not found.\n"), arg);
396 if (arg && arg[0] ==
'Z')
398 else if (arg && arg[0] ==
'L')
404 if (state->arg_num == 0 || state->arg_num == 1) {
405 lfargs[state->arg_num] = arg;
406 lfargc = state->arg_num + 1;
414 return ARGP_ERR_UNKNOWN;
418static struct argp argp = {options, parse_opt, args_doc,
doc,
419 nullptr,
nullptr,
nullptr};
420int main(
int argc,
char **argv) {
423 GlobalContext *__G = (GlobalContext *)calloc(1,
sizeof(GlobalContext));
447 setlocale(LC_NUMERIC,
"");
449 argp_parse(&argp, argc, argv, 0, 0, __G);
460 _(
"lf: arg1: '%s' is neither a directory nor a valid regex.\n"),
477 _(
"lf: '%s' is neither a directory nor a valid regular "
485 unsigned int nprocs = get_nprocs();
489 __G
->nthreads = (nprocs > 1) ? (nprocs - 1) : 1;
503 fprintf(stderr,
_(
"Files: %zu\n"), count);
519
520
521
522
523
524
525
526
527
528
533 eargv[eargc++] = strdup(
"sort");
539 eargv[eargc++] = strdup(
"-r");
540 eargv[eargc] =
nullptr;
541 setenv(
"LC_ALL",
"C", 1);
551 dup2(fds[0], STDIN_FILENO);
553 execvp(eargv[0], eargv);
554 fprintf(stderr,
_(
"Failed to execute sort: %s\n"), strerror(errno));
558 dup2(fds[1], STDOUT_FILENO);
559 stdout = fdopen(STDOUT_FILENO,
"w");
560 setvbuf(stdout, NULL, _IOLBF, 0);
565 for (
int i = 0; i < eargc; i++)
573
574
575
576
577
578
579
580
581
582void debug_out(GlobalContext *__G,
int argc,
char **argv) {
585 bool addspace_before =
false;
588 for (i = 0; i < argc; i++) {
589 len = len + strlen(argv[i]);
591 fprintf(stderr,
"\n");
592 len = strlen(argv[i]);
593 addspace_before =
false;
595 if (addspace_before) {
596 fprintf(stderr,
" ");
599 fprintf(stderr,
"%s", argv[i]);
600 addspace_before =
true;
605 fprintf(stderr,
"\n\n");
607 fprintf(stderr,
"%s\n",
_(
"Display Log Level"));
608 fprintf(stderr,
_(
" 1-config %s\n"),
611 fprintf(stderr,
_(
" 2-info %s\n"),
613 fprintf(stderr,
_(
" 3-errors %s\n"),
615 fprintf(stderr,
_(
" 4-debug %s\n"),
617 fprintf(stderr,
_(
" 5-cycle %s\n"),
619 fprintf(stderr,
_(
" E-enqueue %s\n"),
622 fprintf(stderr,
_(
" D-dequeue %s\n"),
625 fprintf(stderr,
_(
" A-all %s\n"),
627 fprintf(stderr,
_(
" C-count errors %s\n"),
630 fprintf(stderr,
_(
" O-only errors %s\n"),
633 fprintf(stderr,
"\n");
634 fprintf(stderr,
_(
"Search directory: %s\n\n"), __G
->base_path);
636 fprintf(stderr,
_(
"Max depth 0 (unlimited)\n\n"));
639 fprintf(stderr,
_(
"Using %d threads\n\n"), __G
->nthreads);
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"));
650 _(
"BLK b-block device"));
652 _(
"REG f-regular file"));
654 _(
"LINK l-symbolic link"));
657 _(
"UNKNOWN u-unknown"));
658 fprintf(stderr,
"\n");
661 fprintf(stderr,
"\n");
666 fprintf(stderr,
_(
" %08b Execute\n"),
LF_IXUSR);
668 fprintf(stderr,
_(
" %08b Write\n"),
LF_IWUSR);
670 fprintf(stderr,
_(
" %08b Read\n"),
LF_IRUSR);
672 fprintf(stderr,
_(
" %08b SETUID\n"),
LF_ISUID);
674 fprintf(stderr,
_(
" %08b SETGID\n"),
LF_ISGID);
676 fprintf(stderr,
"\n");
678 fprintf(stderr,
_(
"Include regex: %s\n\n"), __G
->re);
680 fprintf(stderr,
_(
"Exclude regex: %s\n\n"), __G
->ere);
684 fprintf(stderr,
_(
"Modified after: %s\n\n"), buf);
689 fprintf(stderr,
_(
"Modified before: %s\n\n"), buf);
692 const char *units[] = {
"b",
"Kb",
"Mb",
"Gb",
"Tb",
"Pb",
"Eb"};
695 while (size >= 1024 && i < 6) {
701 fprintf(stderr,
_(
"Minimum file size: %s\n\n"), buffer);
704 fprintf(stderr,
_(
"Max depth: %d\n\n"), __G
->max_depth);
706 fprintf(stderr,
_(
"Ignore case in regex matching.\n\n"));
708 fprintf(stderr,
_(
"Include hidden files.\n\n"));
710 fprintf(stderr,
_(
"Follow symbolic links.\n\n"));
712 fprintf(stderr,
_(
"Sort output in ascending order.\n\n"));
714 fprintf(stderr,
_(
"Sort output in reverse order.\n\n"));
721
722
723
724
725
726
727
728
729
730
731bool init_lf(GlobalContext *__G,
int argc,
char **argv) {
741 LogCtx *log_ctx = &x_log_ctx;
755 _(
"__G->re: '%s' Invalid pattern\n"), __G
->re);
767 _(
"__G->ere: '%s' Invalid pattern\n"), __G
->ere);
781 perror(
_(
"Mutex initialization failed"));
789 lf_log(INFO,
"Initializing lf Memory");
804 perror(
"Failed to stat base_path");
809 if (!S_ISDIR(sb.st_mode)) {
811 _(
"Warning: Base path '%s' is not a directory. No "
812 "files will be found.\n"),
828 lf_log(INFO,
_(
"Starting threads"));
832 lf_log(ERROR,
_(
"Out of memory allocating threads"));
833 fprintf(stderr,
_(
"Out of memory allocating threads\n"));
836 for (
unsigned int i = 0; i < __G
->nthreads; i++) {
840 lf_log(ERROR,
_(
"Error: Unable to create thread %d\n"), rc);
841 fprintf(stderr,
_(
"Error: Unable to create thread %d\n"), rc);
852 lf_log(INFO,
"Waiting for threads to finish...");
853 for (
unsigned int i = 0; i < __G
->nthreads; i++)
857 perror(
_(
"Mutex destroy failed"));
869
870
871
872
873
874
875
876
877
883 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
886 perror(
_(
"mmap failed to reserve queue arena memory"));
896
897
898
899
900
901
902
903
904
905
906
907
909 QueueNode root_node = {
924
925
926
927
928
938
939
940
941
942
943
944
945
946
948 if (__G ==
nullptr || output_buffer ==
nullptr, output_buffer
->len == 0)
951 fwrite_unlocked(output_buffer
->data, 1, output_buffer
->len, stdout);
953 output_buffer
->len = 0;
959
960
961
962
963
964
965
966
967
968
969
970
972 size_t path_len,
bool append_slash) {
973 if (__G ==
nullptr || output_buffer ==
nullptr || path ==
nullptr)
975 size_t line_len = path_len + (append_slash ? 1 : 0) + 1;
976 if (line_len >
sizeof(OutputBuffer)) {
978 fwrite_unlocked(path, 1, path_len, stdout);
980 fputc_unlocked(
'/', stdout);
981 fputc_unlocked(
'\n', stdout);
985 if (output_buffer
->len + line_len >
sizeof(output_buffer
->data))
987 memcpy(output_buffer
->data + output_buffer
->len, path, path_len);
988 output_buffer
->len += path_len;
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);
1000 const int SPIN_LIMIT = 8;
1003 memory_order_acquire);
1004 intptr_t diff = (intptr_t)seq - (intptr_t)pos;
1006 if (atomic_compare_exchange_weak_explicit(&__G
->enqueue_pos, &pos,
1007 pos + 1, memory_order_acquire,
1008 memory_order_relaxed))
1010 }
else if (diff < 0) {
1016 pos = atomic_load_explicit(&__G
->enqueue_pos, memory_order_relaxed);
1018 if (++spin_count > SPIN_LIMIT)
1021 if (spin_count > SPIN_LIMIT / 2)
1024#if defined(__x86_64__
)
1025 __builtin_ia32_pause();
1029 uint32_t offset = atomic_fetch_add_explicit(&__G
->path_offset, len + 1, memory_order_acquire);
1032 pos + 1, memory_order_release);
1033 atomic_thread_fence(memory_order_release);
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1051 uint_fast32_t spin_count = 0;
1052 uint_fast32_t base_idx = atomic_load_explicit(&__G
->enqueue_pos, memory_order_relaxed);
1054 bool block_available =
true;
1055 bool queue_full =
false;
1059 uint_fast32_t queue_idx;
1063 seq = atomic_load_explicit(&__G
->sequence[queue_idx], memory_order_acquire);
1064 intptr_t dif = (intptr_t)seq - (intptr_t)pos;
1067 block_available =
false;
1070 }
else if (dif > 0) {
1072 block_available =
false;
1079 if (block_available) {
1080 if (atomic_compare_exchange_weak_explicit(
1082 memory_order_relaxed, memory_order_relaxed)) {
1088 base_idx = atomic_load_explicit(&__G
->enqueue_pos, memory_order_relaxed);
1090 if (++spin_count < 64) {
1091 for (i = 0; i < spin_count; i++) {
1092#if defined(__x86_64__
)
1093 __builtin_ia32_pause();
1100 for (uint_fast32_t sidx = 0; sidx < __tl
->stage_idx; ++sidx) {
1101 uint_fast32_t enqueue_pos = (base_idx + sidx) &
QUEUE_MASK;
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);
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);
1122 uint_fast32_t target_seq = base_idx + sidx + 1;
1123 atomic_exchange_explicit(&__G
->sequence[enqueue_pos],
1124 target_seq, memory_order_release);
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1148 if (atomic_load_explicit(&__G
->shut_down, memory_order_acquire)) {
1153 intptr_t diff = (intptr_t)seq - (intptr_t)(pos + 1);
1155 if (atomic_compare_exchange_weak_explicit(&__G
->dequeue_pos, &pos,
1156 pos + 1, memory_order_acquire, memory_order_relaxed)) {
1162 }
else if (diff < 0) {
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);
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(
1171 if ((intptr_t)check_seq - (intptr_t)(check_pos + 1) < 0) {
1173 memory_order_release);
1178 if (++spin_count < 64) {
1179 for (
int i = 0; i < spin_count; i++) {
1180#if defined(__x86_64__
)
1181 __builtin_ia32_pause();
1187 pos = atomic_load_explicit(&__G
->dequeue_pos, memory_order_acquire);
1190 pos = atomic_load_explicit(&__G
->dequeue_pos, memory_order_acquire);
1195 fprintf(stderr,
"line: %d, %s, dequeued pos %lu\n", __LINE__,
__func__, *dequeue_pos);
1204
1205
1206
1207
1208
1209
1210
1211static inline void mpmc_release_slot(GlobalContext *__G, uint_fast32_t pos) {
1218
1219
1220
1221
1222
1223
1224
1225
1226
1228 GlobalContext *__G = (GlobalContext *)arg;
1234 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
1244 OutputBuffer output_buffer;
1247 uint_fast32_t q_pos = 0;
1248 LogCtx log_ctx = {};
1259 atomic_thread_fence(memory_order_acquire);
1269 uint_fast32_t cum_path_len = q_path_len;
1276 atomic_fetch_sub_explicit(&__G
->active_tasks, 1, memory_order_relaxed);
1282 uint_fast32_t write_cursor = cum_path_len;
1283 write_cursor -= q_path_len;
1284 memcpy(&__tl
.path[write_cursor],
1287 __tl
.path[cum_path_len] =
'\0';
1289 fprintf(stderr,
"line: %d, %s, T%lu, dequeued path %s\n", __LINE__,
__func__, __tl.thread_id, __tl.path);
1292 uint_fast32_t p_path_len;
1293 uint_fast32_t p_path_offset;
1296 __tl
.path[write_cursor] =
'/';
1299 write_cursor -= p_path_len;
1300 memcpy(&__tl
.path[write_cursor],
1306 fprintf(stderr,
"line: %d, %s, T%lu constructed path %s\n", __LINE__,
__func__, __tl.thread_id, __tl.path);
1315 atomic_fetch_sub_explicit(&__G
->active_tasks, 1, memory_order_relaxed);
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335void *
finder(GlobalContext *__G, ThreadLocal *__tl) {
1337 struct stat sb = {};
1339 dev_t actual_dev = 0, effective_dev = 0;
1340 ino_t actual_ino = 0, effective_ino = 0;
1341 unsigned char actual_type;
1346 struct open_how how = {
1347 .flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC,
1349 how.resolve = RESOLVE_NO_MAGICLINKS;
1351 how.resolve |= RESOLVE_NO_SYMLINKS;
1353 how.resolve |= RESOLVE_NO_XDEV;
1354 int dir_fd = openat2(AT_FDCWD, __tl
->path, &how,
sizeof(
struct open_how));
1357 lf_log(ERROR,
"OPEN_FAIL,%s,%s", __tl
->path, strerror(errno));
1359 fprintf(stderr,
"OPEN_FAIL,%s,%d:%s\n", __tl
->path, errno, strerror(errno));
1365 if (__builtin_expect(nread == -1, 0)) {
1368 lf_log(ERROR,
"READDIR_FAIL,%s,%s", __tl
->path, strerror(errno));
1373 for (uint_fast32_t bpos = 0; bpos < (size_t)nread;) {
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);
1385 if (__builtin_expect(actual_type == DT_DIR, 0)) {
1396 bool need_metadata = (__G
->follow_links && actual_type == DT_LNK);
1402 need_metadata =
true;
1405 if (__builtin_expect(need_metadata, 0)) {
1406 rc = fstatat(dir_fd, entry
->d_name, &sb, AT_SYMLINK_NOFOLLOW);
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;
1420 if (S_ISLNK(sb.st_mode)) {
1425 rc = fstatat(dir_fd, entry
->d_name, &sb, 0);
1432 effective_ino = sb.st_ino;
1433 effective_dev = sb.st_dev;
1452 bool cycle_found =
false;
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';
1463 memory_order_relaxed);
1464 lf_log(ERROR,
"READLINK_FAIL,%s/%s,%s\n",
1467 lf_log(CYCLE,
"Target item: dev: %lu, ino: %lu, Name: %s/%s\n",
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) {
1484 memory_order_relaxed);
1495 atomic_fetch_add_explicit(&__G
->active_tasks, __tl->stage_idx, memory_order_relaxed);
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);
1500 lf_log(ERROR,
"STAGE_ENQUEUE_FAIL,%s\n",
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);
1516 stage_node
->dev = effective_dev;
1517 stage_node
->ino = effective_ino;
1560 atomic_fetch_add_explicit(&__G
->active_tasks, __tl->stage_idx, memory_order_relaxed);
1562 atomic_fetch_sub_explicit(&__G
->active_tasks, __tl->stage_idx, memory_order_relaxed);
1564 memory_order_relaxed);
1566 lf_log(ERROR,
"STAGE_ENQUEUE_FAIL,%s\n",
1575
1576
1577
1578
1579
1580
1581
1582
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1609 if (reti == REG_NOMATCH)
1672 if (path_len > 2 && path[0] ==
'.' && path[1] ==
'/') {
1689
1690
1691
1692
1693
1694
1697 time_t tm = time(NULL);
1701 strftime(buf, 64,
_(
"%Y-%m-%dT%H:%M:%S%z"), tp);
1703 strftime(buf, 64,
_(
"%Y-%m-%dT%H:%M:%SZ"), tp);
1707static const char DIV100_TABLE[] =
"0001020304050607080910111213141516171819"
1708 "2021222324252627282930313233343536373839"
1709 "4041424344454647484950515253545556575859"
1710 "6061626364656667686970717273747576777879"
1711 "8081828384858687888990919293949596979899";
1712#define WRITE_STR(p, str)
1714 const char *s = (str);
1719
1720
1721
1722
1723
1724
1725
1726
1727
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];
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748static inline char *write_uint2d(
char *p,
long val) {
1749 *p++ = DIV100_TABLE[val * 2];
1750 *p++ = DIV100_TABLE[val * 2 + 1];
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767static inline char *write_interval_sec(
char *p,
long val) {
1769 return write_uint2d(p, val);
1776 temp[i++] = (
char)(
'0' + (val % 10));
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1801 clock_gettime(CLOCK_REALTIME, &tp);
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1823 clock_gettime(CLOCK_REALTIME, &tp);
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1849 clock_gettime(CLOCK_REALTIME, &tp);
1850 long cur_sec = (tp.tv_sec - log_ctx
->start_sec) % 60;
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
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);
1868 int_nsec += 1000000000L;
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
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);
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);
1890 p = write_uint2d(p, cur_sec);
1893 p = write_uint3d(p, cur_ms);
1895 p = write_uint3d(p, cur_us);
1897 p = write_uint3d(p, cur_ns);
1902 p = write_interval_sec(p, int_sec);
1905 p = write_uint3d(p, int_ms);
1907 p = write_uint3d(p, int_us);
1909 p = write_uint3d(p, int_ns);
1915
1916
1917
1918void log_open(GlobalContext *__G, LogCtx *log_ctx, size_t thread_id) {
1923 char *user = getenv(
"USER");
1927 clock_gettime(CLOCK_REALTIME, &tp);
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);
1939 strftime(tz_buf,
sizeof(tz_buf),
"%z", tm);
1954 fprintf(stderr,
"%s\n%s\n%s\n%s\n",
em0,
em1,
em2,
em3);
1960 char *p = getenv(
_(
"USER"));
1962 if (ttyname_r(STDERR_FILENO, ttyname,
sizeof(ttyname)) == 0)
1964 lf_log(ALL,
_(
"Lf_Log started by user %s, thread %lu, on terminal '%s'"),
1965 cmenu_user
, thread_id
, ttyname);
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
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, ...) {
1990 va_start(args, fmt);
2001 char old_archive[
MAXLEN];
2015 case TIMESTAMP_STYLE_COUNT:
2019 ssnprintf(log_record
, sizeof(log_record)
, "%s[%s%-8s%s]<%s:%-12s:%5d> ",
2022 size_t len = strlen(log_record);
2024 len = strlen(log_record);
2025 log_record[len++] =
'\n';
2027 if (write(__G
->log_fd, log_record, len) == -1)
2028 perror(
"Failed to write atomic log record");
2031 if (write(__G
->err_fd, log_record, len) == -1)
2032 perror(
"Failed to write atomic error record");
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2050 memset(&tmv, 0,
sizeof tmv);
2052 if (strptime(s,
"%Y-%m-%dT%H:%M:%S", &tmv) == NULL)
2054 time_t t = mktime(&tmv);
2055 if (t == (time_t)-1)
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2074 localtime_r(&t, &tmv);
2075 strftime(buf, n,
"%Y-%m-%dT%H:%M:%S", &tmv);
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2090 if (str ==
nullptr || *str ==
'\0')
2092 const char tgt[3] =
"~/";
2094 char *e = getenv(
"HOME");
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
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')
2119 if (strstr(org_s, tgt_s) ==
nullptr)
2120 return strdup(org_s);
2121 if (strstr(rep_s, tgt_s) !=
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);
2133 while ((tmp = strstr(ip, tgt_s)) !=
nullptr) {
2137 out_s = malloc(strlen(org_s) + (rep_l - tgt_l) * n + 1);
2144 char *p = strstr(ip, tgt_s);
2150 ip += head_l + tgt_l;
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2172 if (buf == NULL || buf_size == 0)
2174 int result = vsnprintf(buf, buf_size, format, args);
2179 size_t bytes_written = (size_t)result;
2181
2182 if (bytes_written >= buf_size)
2183 return buf_size - 1;
2184 return bytes_written;
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2200size_t
ssnprintf(
char *buf, size_t buf_size,
const char *format, ...) {
2201 if (buf ==
nullptr || format ==
nullptr || buf_size == 0)
2205 va_start(args, format);
2211
2212
2213
2214
2215
2216
2217
2218
2219
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))
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2243 unsigned long value = (
unsigned long)strtoull(str, &endptr, 10);
2246 switch (tolower(*endptr)) {
2248 return value * 1024ULL * 1024ULL * 1024ULL;
2250 return value * 1024ULL * 1024ULL;
2252 return value * 1024ULL;
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270int a_toi(
char *s,
bool *a_toi_error) {
2271 if (s ==
nullptr || *s ==
'\0') {
2272 *a_toi_error =
true;
2276 *a_toi_error =
false;
2279 rc = (uint)strtol(s,
nullptr, 10);
2280 if (rc < 0 || errno) {
2282 *a_toi_error =
true;
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2300 if (d ==
nullptr || s ==
nullptr)
2310 while (*s !=
'\0' && *s !=
'\n' && *s !=
'\r' && d < e) {
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2331 if (d ==
nullptr || s ==
nullptr)
2338 while (*d !=
'\0' && *d !=
'\n' && *d !=
'\r' && d < e) {
2342 while (*s !=
'\0' && *s !=
'\n' && *s !=
'\r' && d < e) {
2350
2351
2352
2353
2354
2355
2356
2357
2359 struct stat statbuf;
2360 if (stat(path, &statbuf) == 0)
2361 if (S_ISDIR(statbuf.st_mode))
2366
2367
2368
2369
2370
2371
2372
2373
2376 uint ret = regcomp(®ex, pattern, REG_EXTENDED);
char * rep_substring(const char *, const char *, const char *) __attribute__((nonnull(1
Replace all occurrences of "tgt_s" in "org_s" with "rep_s".
#define ATTR_FORMAT(archetype, fmt_idx, first_arg)
#define lf_log(level, fmt,...)
#define TIMESTAMP_STYLE(X)
#define print_file_type(mask, lf_type, dt_type, name)
#define LOG_LEVEL_LIST(X)
#define ANSI_COLOR_LIST(X)
void * worker(void *arg)
Worker thread function for processing directory nodes.
void coders_timestamp(LogCtx *log_ctx)
Generate a timestamp string for logging, including both current time and interval since last log entr...
TerminationStatus termination_status
bool global_arena_create(GlobalContext *__G)
Create a queue arena for managing directory traversal tasks.
void initialize_timer(GlobalContext *__G, LogCtx *log_ctx)
Initialize the timer for logging, capturing the start time and setting up interval tracking.
#define WRITE_STR(p, str)
unsigned char const lf_type_mask[15]
void debug_out(GlobalContext *__G, int argc, char **argv)
Display everything and the kitchen sink on stderr.
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.
void initialize_thread_timer(GlobalContext *__G, LogCtx *log_ctx)
Initialize the timer for a thread, capturing the start time and setting up interval tracking.
void * finder(GlobalContext *__G, ThreadLocal *__tl)
Traverse a directory and process its entries.
void build_path(ThreadLocal *__tl, char *file_name)
Build the full path for a file or directory entry.
void iso8601_timestamp(GlobalContext *__G, LogCtx *log_ctx)
Generate an ISO 8601 timestamp string.
bool mpmc_enqueue(GlobalContext *__G, QueueNode *node, const char *path, size_t len)
int sort_lf_output(GlobalContext *__G, int argc, char **argv)
Sort the output of the lf command using the system's sort utility.
bool mpmc_dequeue(GlobalContext *__G, uint_fast32_t *dequeue_pos)
Dequeue a node from the MPMC queue.
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.
void push_root_node(GlobalContext *__G, dev_t dev, ino_t ino)
Push the root directory node into the queue arena.
bool init_lf(GlobalContext *__G, int argc, char **argv)
Initialize the file search process.
void global_arena_destroy(GlobalContext *__G)
Destroy the queue arena and free associated resources.
bool mpmc_bulk_enqueue(GlobalContext *__G, ThreadLocal *__tl)
Bulk enqueue multiple nodes into the MPMC queue.
void flush_output_buffer(GlobalContext *__G, OutputBuffer *output_buffer)
Flush the output_buffer to stdout in a thread-safe manner.
void log_open(GlobalContext *__G, LogCtx *log_ctx, size_t thread_id)
Open the log file for writing.
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.
bool is_hidden(const char *)
const char * argp_program_version
const char * argp_program_bug_address
int main(int argc, char **argv)
Capture the current terminal settings for later restoration.
size_t strnz__cpy(char *, const char *, size_t)
safer alternative to strncpy
bool parse_local_timestamp(const char *, time_t *)
Parses an ISO 8601 timestamp string in local time and converts it to time_t.
bool is_directory(const char *)
Check if a given path is a directory.
size_t ssnprintf(char *, size_t, const char *,...)
Custom safe string formatting utility (Variadic version).
bool is_valid_regex(const char *)
Check if a given path is a regular file.
bool expand_tilde(char *, uint)
Expand a tilde (~) in a file path to the user's home directory.
size_t strnz__cat(char *, const char *, size_t)
safer alternative to strncat
bool is_symlink_to_dir(const char *)
Check if a given path is a symbolic link that points to a directory.
int a_toi(char *, bool *)
a safer alternative to atoi() for converting ASCII strings to integers.
size_t vssnprintf(char *buf, size_t buf_size, const char *format, va_list args)
Custom safe string formatting utility (va_list version).
char * format_local_timestamp(time_t, char *, size_t)
Formats a time_t as an ISO 8601 string in local time.
unsigned long a_to_ul(const char *)
Convert a string to an unsigned long with optional size suffixes.
char record[MAX_LOG_REC_LEN]
char time_buf[MAX_TIMESTAMP_LEN]
uint_fast32_t child_dirs_remaining
uint_fast32_t path_offset
char data[OUTPUT_BUFFER_BYTES]
uint_fast32_t child_dirs_remaining
OutputBuffer * output_buffer
unsigned char effective_type
uint_fast32_t parent_path_len
uint_fast32_t cum_path_offset
unsigned char include_types
atomic_size_t log_error_count
atomic_uint_fast32_t dequeue_pos
atomic_uint_fast32_t queue_idx
atomic_uint_fast32_t shut_down
atomic_uint_fast32_t active_tasks
pthread_mutex_t output_mutex
atomic_uint_fast32_t sequence[QUEUE_NODES]
atomic_uint_fast32_t thread_id
char log_record[MAX_LOG_RECORD_LEN]
unsigned char suppress_types
unsigned char include_perms
atomic_uint_fast32_t enqueue_pos
atomic_size_t error_count
char log_file_spec[MAX_PATH_LEN]
atomic_uint_fast32_t path_offset