C-Menu 0.2.9
A User Interface Toolkit
Loading...
Searching...
No Matches
lf.h File Reference

Headder for lf. More...

#include <argp.h>
#include <pthread.h>
#include <regex.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <wait.h>
Include dependency graph for lf.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  GlobalContext
struct  linux_dirent64
struct  log_level
struct  LogCtx
struct  MemMetrics
struct  OutputBuffer
struct  QueueNode
struct  ThreadLocal

Macros

#define _(String)
#define __atexit
 This macro registers the end_pgm function to be called when the program exits.
#define ABS(x)
#define ANSI_COLOR_LIST(X)
#define ANSI_RESET   "\033[0m"
#define AS_ENUM(NAME)
#define AS_STRINGS(NAME)
#define ATTR_FORMAT(archetype, fmt_idx, first_arg)
#define bindtextdomain(Package, Directory)
#define CACHE_LINE_SIZE   64
#define DEFAULTSHELL   "/bin/bash"
#define DIR_BUF_SIZE   65536
#define F_NO_STDERR   1
#define lf_log(level, fmt, ...)
#define LF_VERSION   "v0.3.3"
#define LF_VERSION_MAJOR   0
#define LF_VERSION_MINOR   3
#define LF_VERSION_PATCH   3
#define LOG_LEVEL_LIST(X)
#define MAX(a, b)
#define max(a, b)
#define MAX_ARGS   64
#define MAX_DEPTH   64
#define MAX_LOG_REC_LEN   1024
#define MAX_LOG_RECORD_LEN   MAX_PATH_LEN
#define MAX_LOG_SIZE   (1024 * 1024)
#define MAX_PATH_LEN   PATH_MAX
#define MAX_THREADS   64
#define MAX_TIMESTAMP_LEN   64
#define MAXLEN   256
#define MIN(x, y)
#define min(x, y)
#define N_(String)
#define NO_PARENT   UINT32_MAX
#define nullptr   NULL
#define OUTPUT_BUFFER_BYTES   (16 * MAX_PATH_LEN)
#define PATH_BYTES   (32 * 1024 * 1024)
#define print_file_type(mask, lf_type, dt_type, name)
#define QUEUE_MASK   (QUEUE_NODES - 1)
#define QUEUE_NODES   (1024 * 1024)
#define S_QUIET   0x2000
#define S_TOLOWER(c)
#define S_TOUPPER(c)
#define S_WCOK   0x1000
#define STAGE_NODES   8
#define STAGE_PATH_BYTES   (STAGE_NODES * 1024)
#define textdomain(Domain)
#define TIMESTAMP_STYLE(X)
#define to_lowercase(c)
#define to_uppercase(c)
#define to_uppercase(c)

Typedefs

typedef uint16_t LogLevel

Enumerations

enum  __attribute { TIMESTAMP_STYLE =(AS_ENUM) TIMESTAMP_STYLE_COUNT , ANSI_COLOR_LIST =(AS_ENUM) ANSI_COLOR_COUNT }
enum  __attribute { TIMESTAMP_STYLE =(AS_ENUM) TIMESTAMP_STYLE_COUNT , ANSI_COLOR_LIST =(AS_ENUM) ANSI_COLOR_COUNT }
enum  F_Type {
  F_F0 , F_FIFO , F_CHR , F_F1 ,
  F_DIR , F_F2 , F_BLK , F_F3 ,
  F_REG , F_F4 , F_LNK , F_F5 ,
  F_SOCK , F_F6 , F_UNKNOWN
}
enum  LFFlags {
  LF_HIDE = 0b00000001 , LF_ICASE = 0b00000010 , LF_EXC_REGEX = 0b00000100 , LF_REGEX = 0b00001000 ,
  LF_EXEC = 0b00010000 , LF_USER = 0b00100000 , LF_IXUSR = 0b00000001 , LF_IWUSR = 0b00000010 ,
  LF_IRUSR = 0b00000100 , LF_ISGID = 0b00010000 , LF_ISUID = 0b00100000
}
enum  LFTypes {
  LF_FIFO = 0b00000001 , LF_CHR = 0b00000010 , LF_DIR = 0b00000100 , LF_BLK = 0b00001000 ,
  LF_REG = 0b00010000 , LF_LNK = 0b00100000 , LF_SOCK = 0b01000000 , LF_UNKNOWN = 0b10000000
}
enum  ll_e : uint16_t { LOG_LEVEL_LIST =(AS_ENUM) LOG_LEVEL_COUNT }
enum  TerminationStatus { TS_SUCCESS = 0 , TS_ERROR = 1 , TS_MATCH = 2 , TS_MATCH_PLUS_ERROR = 3 }

Functions

unsigned long a_to_ul (const char *)
 Converts a string to an unsigned long long integer, with support for suffixes K, M, and G for kilobytes, megabytes, and gigabytes respectively.
int a_toi (char *, bool *)
 a safer alternative to atoi() for converting ASCII strings to integers.
bool append_output_buffer (GlobalContext *__G, OutputBuffer *output, const char *path, size_t path_len, bool append_slash)
 Append a path to the output_buffer, flushing if necessary.
void build_path (ThreadLocal *__tl, char *file_name)
 Build the full path for a file or directory entry.
void coders_timestamp (LogCtx *log_ctx)
 Generate a timestamp string for logging, including both current time and interval since last log entry.
void debug_out (GlobalContext *__G, int, char **)
 Display everything and the kitchen sink on stderr.
bool expand_tilde (char *, uint)
 Replaces "~/" in string with the user's home directory.
void finalize_dir_node (GlobalContext *__G, size_t node_offset)
void * finder (GlobalContext *__G, ThreadLocal *tl)
 Traverse a directory and process its entries.
size_t flush_ch (GlobalContext *__G, ThreadLocal *tl)
void flush_output_buffer (GlobalContext *, OutputBuffer *)
 Flush the output_buffer to stdout in a thread-safe manner.
char * format_local_timestamp (time_t t, char *buf, size_t n)
 Formats a time_t as an ISO 8601 string in local time.
char * get_ip_addresses (char *, uint)
 Retrieves the IP addresses of the local machine and formats them into a string.
char * get_local_timestamp ()
 Returns the current local time as an ISO 8601 formatted string.
void get_proc_memory ()
char * get_user_str (char *, size_t)
 Retrieves the current user's name and UID, and formats it into a string.
bool global_arena_create (GlobalContext *__G)
 Create a queue arena for managing directory traversal tasks.
void global_arena_destroy (GlobalContext *__G)
 Destroy the queue arena and free associated resources.
bool init_lf (GlobalContext *__G, int, char **)
 Initialize the file search process.
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 initialize_timer (GlobalContext *__G, LogCtx *log_ctx)
 Initialize the timer for logging, capturing the start time and setting up interval tracking.
bool is_directory (const char *)
 Checks if the given path is a directory.
bool is_newer (char *, char *)
 Checks if the file specified by "fut" is newer than the file specified by "control".
bool is_symlink_to_dir (const char *)
 Checks if the given path is a symbolic link to a directory.
bool is_valid_regex (const char *)
 Checks if the given regular expression pattern is valid.
void iso8601_timestamp (GlobalContext *__G, LogCtx *log_ctx)
 Generate an ISO 8601 timestamp string.
void log_open (GlobalContext *__G, LogCtx *log_ctx, size_t thread_id)
 Open the log file for writing.
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.
bool mpmc_bulk_enqueue (GlobalContext *__G, ThreadLocal *__tl)
 Bulk enqueue multiple nodes into the MPMC queue.
bool mpmc_dequeue (GlobalContext *__G, uint_fast32_t *dequeue_pos)
 Dequeue a node from the MPMC queue.
bool mpmc_enqueue (GlobalContext *__G, QueueNode *node, const char *path, size_t len)
bool mpmc_enqueue_staged (GlobalContext *, ThreadLocal *__tl)
bool parse_local_timestamp (const char *s, time_t *out)
 Parses an ISO 8601 timestamp string in local time and converts it to time_t.
void path_data_destroy (GlobalContext *__G)
char * path_data_init (GlobalContext *__G, LogCtx *log_ctx)
int print_file (GlobalContext *__G, ThreadLocal *tl)
 Print the path of a file or directory entry based on filtering criteria.
void push_root_node (GlobalContext *__G, dev_t dev, ino_t ino)
 Push the root directory node into the queue arena.
char * rep_substring (const char *org_s, const char *tgt_s, const char *rep_s)
 Replace all occurrences of "tgt_s" in "org_s" with "rep_s".
int sort_lf_output (GlobalContext *__G, int, char **)
 Sort the output of the lf command using the system's sort utility.
size_t ssnprintf (char *, size_t, const char *,...)
 Custom safe string formatting utility (Variadic version).
int str_to_args (char **, char *, uint)
 Converts a string into an array of argument strings.
char * strerror__r (int errnum, char *buf, size_t buflen)
 A thread-safe alternative to strerror() that writes the error message corresponding to errnum into the provided buffer.
size_t strnz__cat (char *, const char *, size_t)
 safer alternative to strncat
size_t strnz__cpy (char *, const char *, size_t)
 safer alternative to strncpy
size_t strnz__pcat (char *d, size_t pos, const char *s, size_t max_len)
size_t vssnprintf (char *buf, size_t buf_size, const char *format, va_list args)
 Custom safe string formatting utility (va_list version).
void * worker (void *arg)
 Worker thread function for processing directory nodes.

Detailed Description

Headder for lf.

Author
Bill Waller Copyright (c) 2026 MIT License billx.nosp@m.wall.nosp@m.er@gm.nosp@m.ail..nosp@m.com
Date
2026-02-09

Definition in file lf.h.

Macro Definition Documentation

◆ _

#define _ ( String)
Value:
Definition cm.h:412

Definition at line 78 of file lf.h.

◆ __atexit

#define __atexit
Value:
{ \
int rc; \
rc = atexit(end_pgm); \
if (rc != 0) { \
fprintf(stderr, "\nCannot set exit function\n"); \
exit(EXIT_FAILURE); \
} \
}

This macro registers the end_pgm function to be called when the program exits.

It checks the return value of atexit() to ensure that the registration was successful, and if not, it prints an error message and exits with a failure status. Programs using libcm should call __atexit in their main function to ensure that the end_pgm function is registered to be called on program exit. This will help ensure that the terminal is properly restored to its original state, even if the program encounters an error or is terminated unexpectedly.

Definition at line 292 of file lf.h.

292#define __atexit \
293 { \
294 int rc; \
295 rc = atexit(end_pgm); \
296 if (rc != 0) { \
297 fprintf(stderr, "\nCannot set exit function\n"); \
298 exit(EXIT_FAILURE); \
299 } \
300 }

◆ ABS

#define ABS ( x)
Value:
({ \
__typeof__(x) _a = (x); \
_a < 0 ? -_a : _a; \
})

Definition at line 178 of file lf.h.

178#define ABS(x) \
179 ({ \
180 __typeof__(x) _a = (x); \
181 _a < 0 ? -_a : _a; \
182 })

◆ ANSI_COLOR_LIST

#define ANSI_COLOR_LIST ( X)
Value:
X(BLACK) \
X(RED) \
X(GREEN) \
X(YELLOW) \
X(BLUE) \
X(CYAN) \
X(MAGENTA) \
X(WHITE) \
X(BBLACK) \
X(BRED) \
X(BGREEN) \
X(BYELLOW) \
X(BBLUE) \
X(BCYAN) \
X(BMAGENTA) \
X(BWHITE) \
X(ORANGE) \
X(BORANGE) \
X(RESET)

Definition at line 118 of file lf.h.

118#define ANSI_COLOR_LIST(X) \
119 X(BLACK) \
120 X(RED) \
121 X(GREEN) \
122 X(YELLOW) \
123 X(BLUE) \
124 X(CYAN) \
125 X(MAGENTA) \
126 X(WHITE) \
127 X(BBLACK) \
128 X(BRED) \
129 X(BGREEN) \
130 X(BYELLOW) \
131 X(BBLUE) \
132 X(BCYAN) \
133 X(BMAGENTA) \
134 X(BWHITE) \
135 X(ORANGE) \
136 X(BORANGE) \
137 X(RESET)

◆ ANSI_RESET

#define ANSI_RESET   "\033[0m"

Definition at line 86 of file lf.h.

◆ AS_ENUM

#define AS_ENUM ( NAME)
Value:
NAME,

Definition at line 88 of file lf.h.

◆ AS_STRINGS

#define AS_STRINGS ( NAME)
Value:
#NAME,

Definition at line 87 of file lf.h.

◆ ATTR_FORMAT

#define ATTR_FORMAT ( archetype,
fmt_idx,
first_arg )
Value:
/* Unsupported compiler, strip attribute */

Definition at line 67 of file lf.h.

◆ bindtextdomain

#define bindtextdomain ( Package,
Directory )

Definition at line 81 of file lf.h.

◆ CACHE_LINE_SIZE

#define CACHE_LINE_SIZE   64

Definition at line 42 of file lf.h.

◆ DEFAULTSHELL

#define DEFAULTSHELL   "/bin/bash"

Definition at line 280 of file lf.h.

◆ DIR_BUF_SIZE

#define DIR_BUF_SIZE   65536

Definition at line 47 of file lf.h.

◆ F_NO_STDERR

#define F_NO_STDERR   1

Definition at line 267 of file lf.h.

◆ lf_log

#define lf_log ( level,
fmt,
... )
Value:
{ \
log_write(level, __G, log_ctx, __FILE__, __func__, __LINE__, \
fmt, ##__VA_ARGS__); \
}

Definition at line 519 of file lf.h.

519#define lf_log(level, fmt, ...) \
520 { \
521 log_write(level, __G, log_ctx, __FILE__, __func__, __LINE__, \
522 fmt, ##__VA_ARGS__); \
523 }

◆ LF_VERSION

#define LF_VERSION   "v0.3.3"

Definition at line 16 of file lf.h.

◆ LF_VERSION_MAJOR

#define LF_VERSION_MAJOR   0

Definition at line 13 of file lf.h.

◆ LF_VERSION_MINOR

#define LF_VERSION_MINOR   3

Definition at line 14 of file lf.h.

◆ LF_VERSION_PATCH

#define LF_VERSION_PATCH   3

Definition at line 15 of file lf.h.

◆ LOG_LEVEL_LIST

#define LOG_LEVEL_LIST ( X)
Value:
X(NONE) \
X(CONFIG) \
X(INFO) \
X(ERROR) \
X(DEBUG) \
X(CYCLE) \
X(ENQUEUE) \
X(DEQUEUE) \
X(ALL) \
X(COUNT_ERRORS) \
X(ONLY_ERRORS) \
X(SPIN_COUNT) \
X(STAGING)

Definition at line 89 of file lf.h.

89#define LOG_LEVEL_LIST(X) \
90 X(NONE) \
91 X(CONFIG) \
92 X(INFO) \
93 X(ERROR) \
94 X(DEBUG) \
95 X(CYCLE) \
96 X(ENQUEUE) \
97 X(DEQUEUE) \
98 X(ALL) \
99 X(COUNT_ERRORS) \
100 X(ONLY_ERRORS) \
101 X(SPIN_COUNT) \
102 X(STAGING)

◆ MAX

#define MAX ( a,
b )
Value:
({ \
typeof(a) _a = (a); \
typeof(y) _b = (b); \
_a > _b ? _a : _b; \
})

Definition at line 165 of file lf.h.

165#define MAX(a, b) \
166 ({ \
167 typeof(a) _a = (a); \
168 typeof(y) _b = (b); \
169 _a > _b ? _a : _b; \
170 })

◆ max

#define max ( a,
b )
Value:
({ \
__typeof__(a) _a = (a); \
__typeof__(a) _b = (b); \
_a > _b ? _a : _b; \
})

Definition at line 152 of file lf.h.

152#define max(a, b) \
153 ({ \
154 __typeof__(a) _a = (a); \
155 __typeof__(a) _b = (b); \
156 _a > _b ? _a : _b; \
157 })

◆ MAX_ARGS

#define MAX_ARGS   64

maximum number of arguments for external commands

Definition at line 37 of file lf.h.

◆ MAX_DEPTH

#define MAX_DEPTH   64

Definition at line 41 of file lf.h.

◆ MAX_LOG_REC_LEN

#define MAX_LOG_REC_LEN   1024

Definition at line 50 of file lf.h.

◆ MAX_LOG_RECORD_LEN

#define MAX_LOG_RECORD_LEN   MAX_PATH_LEN

Definition at line 46 of file lf.h.

◆ MAX_LOG_SIZE

#define MAX_LOG_SIZE   (1024 * 1024)

Definition at line 51 of file lf.h.

◆ MAX_PATH_LEN

#define MAX_PATH_LEN   PATH_MAX

Definition at line 45 of file lf.h.

◆ MAX_THREADS

#define MAX_THREADS   64

Definition at line 40 of file lf.h.

◆ MAX_TIMESTAMP_LEN

#define MAX_TIMESTAMP_LEN   64

Definition at line 141 of file lf.h.

◆ MAXLEN

#define MAXLEN   256

maximum length for various strings and buffers

Definition at line 38 of file lf.h.

◆ MIN

#define MIN ( x,
y )
Value:
({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void)(&_x == &_y); \
_x < _y ? _x : _y; \
})

Definition at line 171 of file lf.h.

171#define MIN(x, y) \
172 ({ \
173 typeof(x) _x = (x); \
174 typeof(y) _y = (y); \
175 (void)(&_x == &_y); \
176 _x < _y ? _x : _y; \
177 })

◆ min

#define min ( x,
y )
Value:
({ \
typeof(x) _x = (x); \
typeof(x) _y = (y); \
(void)(&_x == &_y); \
_x < _y ? _x : _y; \
})

Definition at line 158 of file lf.h.

158#define min(x, y) \
159 ({ \
160 typeof(x) _x = (x); \
161 typeof(x) _y = (y); \
162 (void)(&_x == &_y); \
163 _x < _y ? _x : _y; \
164 })

◆ N_

#define N_ ( String)
Value:

Definition at line 79 of file lf.h.

◆ NO_PARENT

#define NO_PARENT   UINT32_MAX

Definition at line 307 of file lf.h.

◆ nullptr

#define nullptr   NULL

Definition at line 35 of file lf.h.

◆ OUTPUT_BUFFER_BYTES

#define OUTPUT_BUFFER_BYTES   (16 * MAX_PATH_LEN)

Definition at line 52 of file lf.h.

◆ PATH_BYTES

#define PATH_BYTES   (32 * 1024 * 1024)

Definition at line 49 of file lf.h.

◆ print_file_type

#define print_file_type ( mask,
lf_type,
dt_type,
name )
Value:
{ \
fprintf(stderr, "%c %08b (%3d) %08b (%2d) %s\n", \
(mask & lf_type) ? '*' : ' ', lf_type, lf_type, dt_type, dt_type, \
name); \
}

Definition at line 447 of file lf.h.

447#define print_file_type(mask, lf_type, dt_type, name) \
448 { \
449 fprintf(stderr, "%c %08b (%3d) %08b (%2d) %s\n", \
450 (mask & lf_type) ? '*' : ' ', lf_type, lf_type, dt_type, dt_type, \
451 name); \
452 }

◆ QUEUE_MASK

#define QUEUE_MASK   (QUEUE_NODES - 1)

Definition at line 53 of file lf.h.

◆ QUEUE_NODES

#define QUEUE_NODES   (1024 * 1024)

Definition at line 48 of file lf.h.

◆ S_QUIET

#define S_QUIET   0x2000

quiet mode flag for file validation

Definition at line 282 of file lf.h.

◆ S_TOLOWER

#define S_TOLOWER ( c)
Value:
({ \
int __c = (c); \
(__c >= 'A' && __c <= 'Z') ? (__c + ('a' - 'A')) : __c; \
})

Definition at line 183 of file lf.h.

183#define S_TOLOWER(c) \
184 ({ \
185 int __c = (c); \
186 (__c >= 'A' && __c <= 'Z') ? (__c + ('a' - 'A')) : __c; \
187 })

◆ S_TOUPPER

#define S_TOUPPER ( c)
Value:
({ \
int __c = (c); \
(__c >= 'a' && __c <= 'z') ? (__c - ('a' - 'A')) : __c; \
})

Definition at line 188 of file lf.h.

188#define S_TOUPPER(c) \
189 ({ \
190 int __c = (c); \
191 (__c >= 'a' && __c <= 'z') ? (__c - ('a' - 'A')) : __c; \
192 })

◆ S_WCOK

#define S_WCOK   0x1000

write or create permitted

Definition at line 281 of file lf.h.

◆ STAGE_NODES

#define STAGE_NODES   8

Definition at line 43 of file lf.h.

◆ STAGE_PATH_BYTES

#define STAGE_PATH_BYTES   (STAGE_NODES * 1024)

Definition at line 44 of file lf.h.

◆ textdomain

#define textdomain ( Domain)

Definition at line 80 of file lf.h.

◆ TIMESTAMP_STYLE

#define TIMESTAMP_STYLE ( X)
Value:
X(ISO8601_ZULU) \
X(ISO8601_LOCAL) \
X(CODER)

Definition at line 111 of file lf.h.

111#define TIMESTAMP_STYLE(X) \
112 X(ISO8601_ZULU) \
113 X(ISO8601_LOCAL) \
114 X(CODER)

◆ to_lowercase

#define to_lowercase ( c)
Value:
if (c >= 'A' && c <= 'Z') \
c += ' '

Definition at line 196 of file lf.h.

196#define to_lowercase(c) \
197 if (c >= 'A' && c <= 'Z') \
198 c += ' '

◆ to_uppercase [1/2]

#define to_uppercase ( c)
Value:
if (c >= 'a' && c <= 'z') \
c -= ' '

Definition at line 193 of file lf.h.

193#define to_uppercase(c) \
194 if (c >= 'a' && c <= 'z') \
195 c -= ' '

◆ to_uppercase [2/2]

#define to_uppercase ( c)
Value:
if (c >= 'a' && c <= 'z') \
c -= ' '

Definition at line 193 of file lf.h.

193#define to_uppercase(c) \
194 if (c >= 'a' && c <= 'z') \
195 c -= ' '

Typedef Documentation

◆ LogLevel

typedef uint16_t LogLevel

Definition at line 110 of file lf.h.

Enumeration Type Documentation

◆ __attribute [1/2]

Enumerator
TIMESTAMP_STYLE 
ANSI_COLOR_LIST 

Definition at line 138 of file lf.h.

138 {
139 ANSI_COLOR_LIST(AS_ENUM) ANSI_COLOR_COUNT
140} __attribute((packed)) sgr_t;
__attribute
Definition lf.h:115
#define AS_ENUM(NAME)
Definition lf.h:88
#define ANSI_COLOR_LIST(X)
Definition lf.h:118

◆ __attribute [2/2]

Enumerator
TIMESTAMP_STYLE 
ANSI_COLOR_LIST 

Definition at line 115 of file lf.h.

115 {
116 TIMESTAMP_STYLE(AS_ENUM) TIMESTAMP_STYLE_COUNT
117} __attribute((packed)) tss_e;
#define TIMESTAMP_STYLE(X)
Definition lf.h:111

◆ F_Type

enum F_Type
Enumerator
F_F0 
F_FIFO 
F_CHR 
F_F1 
F_DIR 
F_F2 
F_BLK 
F_F3 
F_REG 
F_F4 
F_LNK 
F_F5 
F_SOCK 
F_F6 
F_UNKNOWN 

Definition at line 236 of file lf.h.

236 {
237 F_F0, // 0
238 F_FIFO, // 1
239 F_CHR, // 2
240 F_F1, // 3
241 F_DIR, // 4
242 F_F2, // 5
243 F_BLK, // 6
244 F_F3, // 7
245 F_REG, // 8
246 F_F4, // 9
247 F_LNK, // 10
248 F_F5, // 11
249 F_SOCK, // 12
250 F_F6, // 13
251 F_UNKNOWN, // 14
252} F_Type;
F_Type
Definition cm.h:212
@ F_REG
Definition cm.h:221
@ F_BLK
Definition cm.h:219
@ F_FIFO
Definition cm.h:214
@ F_F0
Definition cm.h:213
@ F_F3
Definition cm.h:220
@ F_SOCK
Definition cm.h:225
@ F_CHR
Definition cm.h:215
@ F_F5
Definition cm.h:224
@ F_F1
Definition cm.h:216
@ F_DIR
Definition cm.h:217
@ F_UNKNOWN
Definition cm.h:227
@ F_F2
Definition cm.h:218
@ F_F4
Definition cm.h:222
@ F_LNK
Definition cm.h:223
@ F_F6
Definition cm.h:226

◆ LFFlags

enum LFFlags
Enumerator
LF_HIDE 

byte 0 - bits 0-7 Selection Flags 1 Don't list hidden files

LF_ICASE 

2 Ignore case in search

LF_EXC_REGEX 

4 Exclude files matching regex

LF_REGEX 

8 Include files matching regex

LF_EXEC 

16 Execute command each file

LF_USER 

32 Select User Name

LF_IXUSR 

<< 16 byte 1 - bits 8-15 1 Select Files with Execute Permission

LF_IWUSR 

2 Select Files with Write Permission

LF_IRUSR 

4 Select Files with Read Permission

LF_ISGID 

16 Select Setgid Files

LF_ISUID 

32 Select Setuid Files

Definition at line 209 of file lf.h.

209 {
211 LF_HIDE = 0b00000001,
212 LF_ICASE = 0b00000010,
213 LF_EXC_REGEX = 0b00000100,
214 LF_REGEX = 0b00001000,
215 LF_EXEC = 0b00010000,
216 LF_USER = 0b00100000,
219 LF_IXUSR = 0b00000001,
220 LF_IWUSR = 0b00000010,
221 LF_IRUSR = 0b00000100,
222 LF_ISGID = 0b00010000,
223 LF_ISUID = 0b00100000,
224} LFFlags;
LFFlags
Used for xterm256 color conversions.
Definition cm.h:183
@ 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_ICASE
Definition cm.h:186
@ LF_ISGID
Definition cm.h:196
@ LF_EXEC
Definition cm.h:189
@ LF_REGEX
Definition cm.h:188
@ LF_USER
Definition cm.h:190
@ LF_IXUSR
Definition cm.h:193
@ LF_IWUSR
Definition cm.h:194

◆ LFTypes

enum LFTypes

byte 2 - bits 16-23 File types

Enumerator
LF_FIFO 

1 named pipe

LF_CHR 

2 character device

LF_DIR 

4 directory

LF_BLK 

8 block

LF_REG 

16 regular file

LF_LNK 

32 link

LF_SOCK 

64 socket

LF_UNKNOWN 

128 unknown

Definition at line 226 of file lf.h.

226 {
227 LF_FIFO = 0b00000001,
228 LF_CHR = 0b00000010,
229 LF_DIR = 0b00000100,
230 LF_BLK = 0b00001000,
231 LF_REG = 0b00010000,
232 LF_LNK = 0b00100000,
233 LF_SOCK = 0b01000000,
234 LF_UNKNOWN = 0b10000000
235} LFTypes;
LFTypes
Definition cm.h:201
@ LF_FIFO
Definition cm.h:202
@ LF_UNKNOWN
Definition cm.h:209
@ LF_SOCK
Definition cm.h:208
@ LF_BLK
Definition cm.h:205
@ LF_CHR
Definition cm.h:203
#define LF_DIR
Definition futil.c:44
#define LF_REG
Definition futil.c:45
#define LF_LNK
Definition futil.c:43

◆ ll_e

enum ll_e : uint16_t
Enumerator
LOG_LEVEL_LIST 

Definition at line 103 of file lf.h.

@ LOG_LEVEL_COUNT
Definition ui_backend.h:232
#define LOG_LEVEL_LIST(X)
Definition lf.h:89
ll_e
Definition lf.h:103

◆ TerminationStatus

Enumerator
TS_SUCCESS 
TS_ERROR 
TS_MATCH 
TS_MATCH_PLUS_ERROR 

Definition at line 370 of file lf.h.

370 {
371 TS_SUCCESS = 0,
372 TS_ERROR = 1,
373 TS_MATCH = 2,
TerminationStatus
Definition lf.h:370
@ TS_SUCCESS
Definition lf.h:371
@ TS_MATCH_PLUS_ERROR
Definition lf.h:374
@ TS_MATCH
Definition lf.h:373
@ TS_ERROR
Definition lf.h:372

Function Documentation

◆ append_output_buffer()

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.

Parameters
lfA pointer to the GlobalContext struct containing the output mutex.
output_bufferA pointer to the OutputBuffer struct where the path will be appended.
pathThe path string to append to the output_buffer.
path_lenThe length of the path string.
append_slashA boolean indicating whether to append a slash after the path.
Returns
true if the path was successfully appended or flushed, false otherwise.

This function appends a given path to the output_buffer. If the combined length of the current buffer and the new path exceeds the buffer's capacity, it flushes the buffer to stdout before appending. It also handles appending a slash if specified. The function ensures thread-safe access to stdout using a mutex during flushing.

Definition at line 971 of file lf.c.

972 {
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}
void flush_output_buffer(GlobalContext *__G, OutputBuffer *output_buffer)
Flush the output_buffer to stdout in a thread-safe manner.
Definition lf.c:947
size_t len
Definition lf.h:322
char data[OUTPUT_BUFFER_BYTES]
Definition lf.h:321
pthread_mutex_t output_mutex
Definition lf.h:394

References OutputBuffer::data, flush_output_buffer(), OutputBuffer::len, and GlobalContext::output_mutex.

Referenced by print_file().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ build_path()

void build_path ( ThreadLocal * __tl,
char * file_name )

Build the full path for a file or directory entry.

Parameters
tlA pointer to the ThreadLocal struct containing the current directory context.
file_nameThe name of the file or directory entry to append to the path.

This function constructs the full path for a given file or directory entry by appending its name to the parent path stored in the ThreadLocal context. It updates the path length and ensures that the resulting path is null-terminated. This function is used during directory traversal to prepare paths for processing and output.

Definition at line 1583 of file lf.c.

1583 {
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}
char * d_name
Definition lf.h:348
uint_fast32_t d_name_len
Definition lf.h:347
uint_fast32_t path_len
Definition lf.h:337
uint_fast32_t parent_path_len
Definition lf.h:346
char path[MAX_PATH_LEN]
Definition lf.h:349

References ThreadLocal::d_name, ThreadLocal::d_name_len, ThreadLocal::parent_path_len, ThreadLocal::path, and ThreadLocal::path_len.

Referenced by finder().

Here is the caller graph for this function:

◆ coders_timestamp()

void coders_timestamp ( LogCtx * log_ctx)

Generate a timestamp string for logging, including both current time and interval since last log entry.

coders_timestamp

Parameters
log_ctxA pointer to the LogCtx struct containing timing information.
Returns
void

This function calculates the current time since the start of the program and the interval since the last log entry. It formats these values into a timestamp string stored in log_ctx->time_buf. The timestamp includes seconds, milliseconds, microseconds, and nanoseconds, with color-coded formatting for better visibility in logs. If you are wondering about the seemingly complex output section, it is designed to mitigate the classical and unavoidable observation error.

Definition at line 1847 of file lf.c.

1847 {
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}
const char * sgr_c[]
Definition lf.c:81
#define WRITE_STR(p, str)
Definition lf.c:1712
long p_int_sec
Definition lf.h:146
long p_int_nsec
Definition lf.h:145
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

References LogCtx::p_int_nsec, LogCtx::p_int_sec, sgr_c, LogCtx::start_nsec, LogCtx::start_sec, and LogCtx::time_buf.

Referenced by log_write().

Here is the caller graph for this function:

◆ debug_out()

void debug_out ( GlobalContext * __G,
int argc,
char ** argv )

Display everything and the kitchen sink on stderr.

Parameters
lfA pointer to the GlobalContext struct containing the debug settings.
argcThe number of command-line arguments.
argvAn array of command-line argument strings.

This function outputs debug information to stderr if debugging is enabled in the GlobalContext. It includes a timestamp, user information, IP addresses, command-line arguments, and various configuration settings. The output is formatted for readability and includes details about file types, permissions, regex patterns, and other relevant settings.

Definition at line 582 of file lf.c.

582 {
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"));
656 print_file_type(__G->include_types, LF_UNKNOWN, DT_UNKNOWN,
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}
#define print_file_type(mask, lf_type, dt_type, name)
Definition lf.h:447
#define LF_VERSION
Definition lf.h:16
log_level ll_t[]
Definition lf.c:63
#define _(String)
Definition amort.c:23
size_t ssnprintf(char *buf, size_t buf_size, const char *format,...)
A safer snprintf that ensures null-termination and handles edge cases.
Definition lf.c:2200
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 char include_types
Definition lf.h:423
time_t after
Definition lf.h:411
unsigned int nthreads
Definition lf.h:399
char * base_path
Definition lf.h:415
time_t before
Definition lf.h:412
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
unsigned char include_perms
Definition lf.h:422
ll_e disp_level_mask
Definition lf.h:437
char * user_name
Definition lf.h:418
bool sort_reverse
Definition lf.h:431
off_t file_size_min
Definition lf.h:402
uint32_t max_depth
Definition lf.h:413
bool ignore_case
Definition lf.h:429
uintmax_t user_id
Definition lf.h:401
long flags
Definition lf.h:406
bool sort
Definition lf.h:430

References GlobalContext::after, GlobalContext::base_path, GlobalContext::before, log_level::bits, GlobalContext::disp_level_mask, GlobalContext::ere, GlobalContext::file_size_min, GlobalContext::flags, GlobalContext::follow_links, format_local_timestamp(), GlobalContext::ignore_case, GlobalContext::include_hidden, GlobalContext::include_perms, GlobalContext::include_types, LF_BLK, LF_CHR, LF_DIR, LF_EXC_REGEX, LF_FIFO, LF_IRUSR, LF_ISGID, LF_ISUID, LF_IWUSR, LF_IXUSR, LF_LNK, LF_REG, LF_REGEX, LF_SOCK, LF_UNKNOWN, LF_USER, ll_t, GlobalContext::max_depth, GlobalContext::nthreads, GlobalContext::re, GlobalContext::sort, GlobalContext::sort_reverse, ssnprintf(), GlobalContext::suppress_types, GlobalContext::user_id, and GlobalContext::user_name.

Referenced by init_lf().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ finalize_dir_node()

void finalize_dir_node ( GlobalContext * __G,
size_t node_offset )

◆ finder()

void * finder ( GlobalContext * __G,
ThreadLocal * __tl )

Traverse a directory and process its entries.

Parameters
lfA pointer to the GlobalContext struct containing the search settings.
tlA pointer to the ThreadLocal struct containing the current directory context.
Returns
NULL upon completion.

This function opens a directory specified in the ThreadLocal context, reads its entries, and processes each entry based on the provided settings in the GlobalContext. It handles filtering of directory entries, retrieves advanced metadata if necessary, and manages the traversal of subdirectories. The function also logs errors and flushes output buffers as needed. It is designed to be called by worker threads for concurrent processing of directories.

Definition at line 1335 of file lf.c.

1335 {
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;
1345 __tl->stage_node->path_offset = 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);
1521 __tl->cum_path_offset += __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 }
1534 __tl->child_dirs_remaining++;
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}
#define DIR_BUF_SIZE
Definition lf.h:47
#define STAGE_PATH_BYTES
Definition lf.h:44
#define lf_log(level, fmt,...)
Definition lf.h:519
#define NO_PARENT
Definition lf.h:307
#define STAGE_NODES
Definition lf.h:43
#define MAX_PATH_LEN
Definition lf.h:45
void build_path(ThreadLocal *__tl, char *file_name)
Build the full path for a file or directory entry.
Definition lf.c:1583
bool mpmc_bulk_enqueue(GlobalContext *__G, ThreadLocal *__tl)
Bulk enqueue multiple nodes into the MPMC queue.
Definition lf.c:1048
int print_file(GlobalContext *__G, ThreadLocal *__tl)
Print the path of a file or directory entry based on filtering criteria.
Definition lf.c:1602
Definition lf.h:142
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
char * dir_buf
Definition lf.h:353
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
char * path_data
Definition lf.h:330
uint_fast32_t stage_idx
Definition lf.h:344
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
uint_fast32_t cum_path_offset
Definition lf.h:342
atomic_uint_fast32_t active_tasks
Definition lf.h:387
bool f_logging
Definition lf.h:436
bool only_errors
Definition lf.h:439
bool hidden_only
Definition lf.h:433
atomic_size_t error_count
Definition lf.h:395
QueueNode * queue
Definition lf.h:381
ll_e file_level_mask
Definition lf.h:438
bool xdev
Definition lf.h:427

References GlobalContext::active_tasks, log_level::bits, build_path(), QueueNode::child_dirs_remaining, ThreadLocal::child_dirs_remaining, ThreadLocal::cum_path_offset, linux_dirent64::d_name, ThreadLocal::d_name, ThreadLocal::d_name_len, linux_dirent64::d_reclen, linux_dirent64::d_type, QueueNode::depth, ThreadLocal::depth, QueueNode::dev, ThreadLocal::dir_buf, GlobalContext::disp_level_mask, ThreadLocal::effective_type, GlobalContext::error_count, GlobalContext::f_logging, GlobalContext::file_level_mask, flush_output_buffer(), GlobalContext::follow_links, GlobalContext::hidden_only, GlobalContext::include_hidden, QueueNode::ino, ll_t, ThreadLocal::log_ctx, log_write(), GlobalContext::max_depth, mpmc_bulk_enqueue(), GlobalContext::only_errors, ThreadLocal::output_buffer, QueueNode::parent_idx, ThreadLocal::path, ThreadLocal::path_data, QueueNode::path_len, QueueNode::path_offset, print_file(), GlobalContext::queue, ThreadLocal::queue_idx, ThreadLocal::stage_idx, ThreadLocal::stage_node, and GlobalContext::xdev.

Referenced by worker().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ flush_ch()

size_t flush_ch ( GlobalContext * __G,
ThreadLocal * tl )

◆ flush_output_buffer()

void flush_output_buffer ( GlobalContext * __G,
OutputBuffer * output_buffer )

Flush the output_buffer to stdout in a thread-safe manner.

Parameters
lfA pointer to the GlobalContext struct containing the output mutex.
output_bufferA pointer to the OutputBuffer struct containing the data to be flushed.

This function writes the contents of the output_buffer to stdout using fwrite_unlocked for efficiency. It uses a mutex to ensure that only one thread can write to stdout at a time, preventing interleaved output from multiple threads. After flushing, it resets the length of the output_buffer to zero.

Definition at line 947 of file lf.c.

947 {
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}

References OutputBuffer::data, OutputBuffer::len, and GlobalContext::output_mutex.

Referenced by append_output_buffer(), and finder().

Here is the caller graph for this function:

◆ get_proc_memory()

void get_proc_memory ( )

◆ global_arena_create()

bool global_arena_create ( GlobalContext * __G)

Create a queue arena for managing directory traversal tasks.

Parameters
lfA pointer to the GlobalContext struct where the queue arena will be created.
max_nodesThe maximum number of nodes that the queue arena can hold.

This function allocates memory for a QueueArena structure and initializes its properties. It uses mmap to allocate a contiguous block of memory for the queue nodes, allowing for efficient management of directory traversal tasks in a multi-threaded environment. The cursor is initialized to zero, indicating that no nodes have been added yet.

Definition at line 878 of file lf.c.

878 {
879 __G->queue_bytes = sizeof(QueueNode) * QUEUE_NODES;
880 __G->path_bytes = 32 * QUEUE_NODES;
881 __G->arena_bytes = (__G->queue_bytes + __G->path_bytes);
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}
#define QUEUE_NODES
Definition lf.h:48
size_t arena_bytes
Definition lf.h:391
size_t path_bytes
Definition lf.h:393
atomic_uint_fast32_t sequence[QUEUE_NODES]
Definition lf.h:390
size_t queue_bytes
Definition lf.h:392
char * path_data
Definition lf.h:382
void * arena
Definition lf.h:380

References GlobalContext::arena, GlobalContext::arena_bytes, GlobalContext::path_bytes, GlobalContext::path_data, GlobalContext::queue, GlobalContext::queue_bytes, and GlobalContext::sequence.

Referenced by init_lf().

Here is the caller graph for this function:

◆ global_arena_destroy()

void global_arena_destroy ( GlobalContext * __G)

Destroy the queue arena and free associated resources.

Parameters
lfA pointer to the GlobalContext struct containing the queue arena.

This function unmaps the memory allocated for the queue arena using munmap. It checks if the arena pointer is valid before attempting to unmap it, ensuring that resources are properly released when they are no longer needed.

Definition at line 929 of file lf.c.

929 {
930 if (!__G->arena)
931 return;
932 munmap(__G->arena, __G->arena_bytes);
933}

References GlobalContext::arena, and GlobalContext::arena_bytes.

Referenced by init_lf().

Here is the caller graph for this function:

◆ init_lf()

bool init_lf ( GlobalContext * __G,
int argc,
char ** argv )

Initialize the file search process.

Parameters
lfA pointer to the GlobalContext struct containing the search settings.
argcThe number of command-line arguments.
argvAn array of command-line argument strings.
Returns
true if initialization is successful, false otherwise.

This function initializes the file search process based on the provided settings in the GlobalContext struct. It sets up file type inclusion and suppression, compiles regular expressions if specified, and creates a multi-producer, multi-consumer queue for managing directory traversal tasks. It also initializes threads for concurrent processing of directory entries.

Definition at line 731 of file lf.c.

731 {
732 if (__G->disp_level_mask || __G->file_level_mask)
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}
#define MAX_LOG_REC_LEN
Definition lf.h:50
void * worker(void *arg)
Worker thread function for processing directory nodes.
Definition lf.c:1227
TerminationStatus termination_status
Definition lf.c:60
bool global_arena_create(GlobalContext *__G)
Create a queue arena for managing directory traversal tasks.
Definition lf.c:878
void debug_out(GlobalContext *__G, int argc, char **argv)
Display everything and the kitchen sink on stderr.
Definition lf.c:582
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
void global_arena_destroy(GlobalContext *__G)
Destroy the queue arena and free associated resources.
Definition lf.c:929
atomic_uint_fast32_t dequeue_pos
Definition lf.h:386
atomic_uint_fast32_t shut_down
Definition lf.h:384
atomic_uint_fast32_t thread_id
Definition lf.h:389
char log_record[MAX_LOG_RECORD_LEN]
Definition lf.h:425
atomic_uint_fast32_t enqueue_pos
Definition lf.h:385
regex_t compiled_ere
Definition lf.h:421
int reg_flags
Definition lf.h:414
pthread_t * threads
Definition lf.h:397
regex_t compiled_re
Definition lf.h:420

References GlobalContext::base_path, GlobalContext::compiled_ere, GlobalContext::compiled_re, debug_out(), GlobalContext::dequeue_pos, GlobalContext::disp_level_mask, GlobalContext::enqueue_pos, GlobalContext::ere, GlobalContext::f_logging, GlobalContext::file_level_mask, GlobalContext::flags, global_arena_create(), global_arena_destroy(), GlobalContext::ignore_case, GlobalContext::include_hidden, GlobalContext::include_types, LF_EXC_REGEX, LF_HIDE, LF_REGEX, GlobalContext::log_record, GlobalContext::nthreads, GlobalContext::output_mutex, LogCtx::p_int_nsec, LogCtx::p_int_sec, push_root_node(), GlobalContext::re, LogCtx::record, GlobalContext::reg_flags, GlobalContext::shut_down, ssnprintf(), LogCtx::start_nsec, LogCtx::start_sec, GlobalContext::suppress_types, termination_status, GlobalContext::thread_id, GlobalContext::threads, TS_ERROR, TS_SUCCESS, and worker().

Referenced by main(), and sort_lf_output().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ initialize_thread_timer()

void initialize_thread_timer ( GlobalContext * __G,
LogCtx * log_ctx )

Initialize the timer for a thread, capturing the start time and setting up interval tracking.

Parameters
lfA pointer to the GlobalContext struct containing the search settings.
log_ctxA pointer to the LogCtx struct where timing information will be stored.
Returns
void

This function retrieves the current time using clock_gettime and initializes both the start time and the previous interval time in the provided LogCtx structure. It also sets the corresponding values in the GlobalContext structure for global timing reference. This setup is essential for accurate timestamping of log entries and interval calculations during program execution.

Definition at line 1799 of file lf.c.

1799 {
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}
long start_nsec
Definition lf.h:407
long start_sec
Definition lf.h:408

References LogCtx::p_int_nsec, LogCtx::p_int_sec, GlobalContext::start_nsec, LogCtx::start_nsec, GlobalContext::start_sec, and LogCtx::start_sec.

Referenced by worker().

Here is the caller graph for this function:

◆ initialize_timer()

void initialize_timer ( GlobalContext * __G,
LogCtx * log_ctx )

Initialize the timer for logging, capturing the start time and setting up interval tracking.

Parameters
lfA pointer to the GlobalContext struct containing the search settings.
log_ctxA pointer to the LogCtx struct where timing information will be stored.
Returns
void

This function retrieves the current time using clock_gettime and initializes both the start time and the previous interval time in the provided LogCtx structure. It also sets the corresponding values in the GlobalContext structure for global timing reference. This setup is essential for accurate timestamping of log entries and interval calculations during program execution.

Definition at line 1821 of file lf.c.

1821 {
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}
long p_int_sec
Definition lf.h:410
long p_int_nsec
Definition lf.h:409

References GlobalContext::p_int_nsec, LogCtx::p_int_nsec, GlobalContext::p_int_sec, LogCtx::p_int_sec, GlobalContext::start_nsec, LogCtx::start_nsec, GlobalContext::start_sec, and LogCtx::start_sec.

Referenced by worker().

Here is the caller graph for this function:

◆ iso8601_timestamp()

void iso8601_timestamp ( GlobalContext * __G,
LogCtx * log_ctx )

Generate an ISO 8601 timestamp string.

iso8601_timestamp

Parameters
bufBuffer to store the timestamp string
nSize of the buffer
localIf true, use local time; if false, use UTC
Returns
Pointer to the buffer containing the timestamp string

Definition at line 1695 of file lf.c.

1695 {
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}
tss_e timestamp_style
Definition lf.h:435

References ssnprintf(), LogCtx::time_buf, and GlobalContext::timestamp_style.

Referenced by log_write().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ log_open()

void log_open ( GlobalContext * __G,
LogCtx * log_ctx,
size_t thread_id )

Open the log file for writing.

log_open

Returns
FILE pointer to the opened log file

Definition at line 1918 of file lf.c.

1918 {
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"),
1949 __G->log_file_spec);
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"),
1953 __G->log_file_spec);
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}
#define MAXLEN
Definition lf.h:38
char em1[MAXLEN]
Definition lf.c:43
char em2[MAXLEN]
Definition lf.c:44
char em3[MAXLEN]
Definition lf.c:45
char em0[MAXLEN]
Definition lf.c:42
size_t strnz__cpy(char *, const char *, size_t)
safer alternative to strncpy
Definition lf.c:2299
int log_fd
Definition lf.h:404
char log_file_spec[MAX_PATH_LEN]
Definition lf.h:405

References GlobalContext::disp_level_mask, em0, em1, em2, em3, GlobalContext::f_logging, GlobalContext::file_level_mask, GlobalContext::log_fd, GlobalContext::log_file_spec, log_write(), GlobalContext::p_int_nsec, LogCtx::p_int_nsec, GlobalContext::p_int_sec, LogCtx::p_int_sec, ssnprintf(), GlobalContext::start_nsec, LogCtx::start_nsec, GlobalContext::start_sec, LogCtx::start_sec, and strnz__cpy().

Referenced by log_write().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ log_write()

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.

Parameters
levelThe log level (e.g., INFO, ERROR)
lfPointer to the GlobalContext struct containing logging settings
log_ctxPointer to the LogCtx struct for the current thread
fileThe source file name where the log is generated
funcThe function name where the log is generated
lineThe line number in the source file where the log is generated
fmtThe format string for the log message
...Additional arguments for the format string

This function checks if the specified log level is enabled for file or display output. If enabled, it formats the log message with a timestamp, source information, and user-provided message. It handles opening the log file if necessary and manages log rotation based on size limits. The formatted message is written to the appropriate output destinations.

Definition at line 1984 of file lf.c.

1985 {
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}
#define MAX_LOG_SIZE
Definition lf.h:51
#define ANSI_RESET
Definition lf.h:86
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
void iso8601_timestamp(GlobalContext *__G, LogCtx *log_ctx)
Generate an ISO 8601 timestamp string.
Definition lf.c:1695
void log_open(GlobalContext *__G, LogCtx *log_ctx, size_t thread_id)
Open the log file for writing.
Definition lf.c:1918
size_t strnz__cat(char *, const char *, size_t)
safer alternative to strncat
Definition lf.c:2330
size_t vssnprintf(char *buf, size_t buf_size, const char *format, va_list args)
A safer vsnprintf that ensures null-termination and handles edge cases.
Definition lf.c:2169
int err_fd
Definition lf.h:403

References log_level::bits, coders_timestamp(), GlobalContext::disp_level_mask, GlobalContext::err_fd, GlobalContext::file_level_mask, iso8601_timestamp(), ll_t, GlobalContext::log_fd, GlobalContext::log_file_spec, log_open(), log_level::name, log_level::SGR, ssnprintf(), strnz__cat(), strnz__cpy(), LogCtx::thread_id, LogCtx::time_buf, GlobalContext::timestamp_style, and vssnprintf().

Referenced by finder(), and log_open().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ mpmc_bulk_enqueue()

bool mpmc_bulk_enqueue ( GlobalContext * __G,
ThreadLocal * __tl )

Bulk enqueue multiple nodes into the MPMC queue.

Parameters
lfA pointer to the GlobalContext struct containing the queue.
tlA pointer to the ThreadLocal struct containing the nodes to enqueue.
Returns
true if the bulk enqueue was successful, false if the queue is full.

This function attempts to enqueue multiple nodes from a thread-local buffer into a multi-producer, multi-consumer (MPMC) queue. It checks for available slots in the queue and uses atomic operations to reserve space for the nodes. If successful, it copies the nodes and their associated path data into the global queue and updates the sequence numbers accordingly. If the queue is full, it returns false, indicating that the caller should fall back to local stack or single enqueue.

Definition at line 1048 of file lf.c.

1048 {
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}
#define QUEUE_MASK
Definition lf.h:53
#define PATH_BYTES
Definition lf.h:49
atomic_uint_fast32_t path_offset
Definition lf.h:383

References ThreadLocal::cum_path_offset, GlobalContext::enqueue_pos, GlobalContext::path_data, ThreadLocal::path_data, QueueNode::path_len, GlobalContext::path_offset, QueueNode::path_offset, GlobalContext::queue, GlobalContext::sequence, ThreadLocal::stage_idx, and ThreadLocal::stage_node.

Referenced by finder().

Here is the caller graph for this function:

◆ mpmc_dequeue()

bool mpmc_dequeue ( GlobalContext * __G,
uint_fast32_t * dequeue_pos )

Dequeue a node from the MPMC queue.

Parameters
lfA pointer to the GlobalContext struct containing the queue.
dequeue_posA pointer to a uint_fast32_t variable where the dequeued position will be stored.
Returns
true if a node was successfully dequeued, false if the queue is empty or shut down.

This function attempts to dequeue a node from a multi-producer, multi-consumer (MPMC) queue. It checks for available nodes in the queue and uses atomic operations to claim a node for processing. If successful, it updates the sequence number for the dequeued position and returns true. If the queue is empty or has been shut down, it returns false, indicating that there are no more nodes to process.

Definition at line 1144 of file lf.c.

1144 {
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}
#define CACHE_LINE_SIZE
Definition lf.h:42

References GlobalContext::active_tasks, GlobalContext::dequeue_pos, GlobalContext::enqueue_pos, GlobalContext::sequence, and GlobalContext::shut_down.

Referenced by worker().

Here is the caller graph for this function:

◆ mpmc_enqueue()

bool mpmc_enqueue ( GlobalContext * __G,
QueueNode * node,
const char * path,
size_t len )

Definition at line 997 of file lf.c.

997 {
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}

References GlobalContext::enqueue_pos, GlobalContext::path_data, GlobalContext::path_offset, GlobalContext::queue, and GlobalContext::sequence.

Referenced by push_root_node().

Here is the caller graph for this function:

◆ mpmc_enqueue_staged()

bool mpmc_enqueue_staged ( GlobalContext * ,
ThreadLocal * __tl )

◆ path_data_destroy()

void path_data_destroy ( GlobalContext * __G)

◆ path_data_init()

char * path_data_init ( GlobalContext * __G,
LogCtx * log_ctx )

◆ print_file()

int print_file ( GlobalContext * __G,
ThreadLocal * __tl )

Print the path of a file or directory entry based on filtering criteria.

Parameters
lfA pointer to the GlobalContext struct containing the search settings.
tlA pointer to the ThreadLocal struct containing the current directory context.
Returns
true if the file or directory entry was printed, false otherwise.

This function checks various filtering criteria specified in the GlobalContext, such as type suppression, regex matching, user ownership, permissions, modification time, and file size. If the entry passes all filters, it increments the file count and appends the path to the output buffer for printing. The function returns true if the entry was printed and false if it was excluded based on any of the filtering criteria.

Definition at line 1602 of file lf.c.

1602 {
1603 while (1) {
1604 if (__G->suppress_types & lf_type_mask[__tl->effective_type])
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}
unsigned char const lf_type_mask[15]
Definition lf.c:110
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
bool stat_cached
Definition lf.h:351
struct stat * cached_sb
Definition lf.h:350
atomic_size_t file_count
Definition lf.h:400
bool count_silently
Definition lf.h:442

References GlobalContext::after, append_output_buffer(), GlobalContext::before, ThreadLocal::cached_sb, GlobalContext::compiled_ere, GlobalContext::compiled_re, GlobalContext::count_silently, ThreadLocal::effective_type, GlobalContext::file_count, GlobalContext::file_size_min, GlobalContext::flags, GlobalContext::include_perms, LF_EXC_REGEX, LF_IRUSR, LF_ISGID, LF_ISUID, LF_IWUSR, LF_IXUSR, LF_REGEX, lf_type_mask, LF_USER, GlobalContext::only_errors, ThreadLocal::output_buffer, ThreadLocal::path, ThreadLocal::path_len, ThreadLocal::stat_cached, GlobalContext::suppress_types, termination_status, TS_MATCH, and GlobalContext::user_id.

Referenced by finder().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ push_root_node()

void push_root_node ( GlobalContext * __G,
dev_t dev,
ino_t ino )

Push the root directory node into the queue arena.

Parameters
lfA pointer to the GlobalContext struct containing the queue arena.
path_offsetThe offset of the root path in the path arena.
path_lenThe length of the root path string.
devThe device ID of the root directory.
inoThe inode number of the root directory.
Returns
The index of the newly created root node in the queue arena.

This function initializes and pushes the root directory node into the queue arena. It allocates a new directory context and cycle context for the root node, sets up its properties, and returns its index in the queue arena. This is typically called at the start of a file search operation to establish the starting point for traversal.

Definition at line 908 of file lf.c.

908 {
909 QueueNode root_node = {
910 .parent_idx = NO_PARENT,
911 .path_offset = 0,
912 .path_len = strlen(__G->base_path),
913 .child_dirs_remaining = 0,
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}
bool mpmc_enqueue(GlobalContext *__G, QueueNode *node, const char *path, size_t len)
Definition lf.c:997
atomic_uint_fast32_t queue_idx
Definition lf.h:388

References GlobalContext::active_tasks, GlobalContext::base_path, QueueNode::child_dirs_remaining, QueueNode::depth, QueueNode::dev, QueueNode::ino, mpmc_enqueue(), QueueNode::parent_idx, QueueNode::path_len, QueueNode::path_offset, and GlobalContext::queue_idx.

Referenced by init_lf().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ sort_lf_output()

int sort_lf_output ( GlobalContext * __G,
int argc,
char ** argv )

Sort the output of the lf command using the system's sort utility.

Parameters
lfA pointer to the GlobalContext struct containing the search settings.
argcThe number of command-line arguments.
argvAn array of command-line argument strings.

This function sets up a pipeline to sort the output of the lf command. It creates a pipe, forks a child process to execute the sort command, and redirects the standard input and output streams accordingly. The sort command is executed with optional flags for parallel processing and buffer size, as well as a reverse sort option if specified in the GlobalContext. The function waits for the child process to complete before returning.

Definition at line 529 of file lf.c.

529 {
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}
#define MAX_ARGS
Definition lf.h:37
bool init_lf(GlobalContext *__G, int argc, char **argv)
Initialize the file search process.
Definition lf.c:731
char * eargv[MAXARGS]
Definition futil.c:51
int eargc
Definition futil.c:50

References init_lf(), GlobalContext::sort_reverse, and TS_ERROR.

Referenced by main().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ strnz__pcat()

size_t strnz__pcat ( char * d,
size_t pos,
const char * s,
size_t max_len )

Definition at line 577 of file futil.c.

577 {
578 if (d == nullptr || s == nullptr)
579 return 0;
580 if (max_len == 0)
581 return 0;
582 char *e;
583 size_t len = pos;
584 d += pos;
585 e = d + max_len;
586 while (*s != '\0' && *s != '\n' && *s != '\r' && d < e) {
587 *d++ = *s++;
588 len++;
589 }
590 *d = '\0';
591 return len;
592}

◆ worker()

void * worker ( void * arg)

Worker thread function for processing directory nodes.

Parameters
argA pointer to the GlobalContext struct containing the search settings.
Returns
NULL upon completion.

This function is executed by each worker thread. It dequeues directory nodes from the global queue, reconstructs their paths, and invokes the finder function to process them. Each thread maintains its own local context, including a stage arena for temporary storage of nodes and path data. The function continues processing until there are no more nodes to dequeue or the search is shut down.

Definition at line 1227 of file lf.c.

1227 {
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);
1314 __G->queue[q_pos].child_dirs_remaining = __tl.child_dirs_remaining;
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}
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
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
bool mpmc_dequeue(GlobalContext *__G, uint_fast32_t *dequeue_pos)
Dequeue a node from the MPMC queue.
Definition lf.c:1144
size_t stage_queue_size
Definition lf.h:332
size_t stage_arena_size
Definition lf.h:331
size_t stage_path_size
Definition lf.h:333
void * stage_arena
Definition lf.h:328

References GlobalContext::active_tasks, QueueNode::child_dirs_remaining, ThreadLocal::child_dirs_remaining, ThreadLocal::cum_path_offset, ThreadLocal::dir_buf, GlobalContext::f_logging, finder(), initialize_thread_timer(), initialize_timer(), OutputBuffer::len, ThreadLocal::log_ctx, GlobalContext::log_fd, mpmc_dequeue(), ThreadLocal::output_buffer, QueueNode::parent_idx, ThreadLocal::parent_path_len, ThreadLocal::path, GlobalContext::path_data, ThreadLocal::path_data, QueueNode::path_len, QueueNode::path_offset, GlobalContext::queue, ThreadLocal::queue_idx, ThreadLocal::stage_arena, ThreadLocal::stage_arena_size, ThreadLocal::stage_idx, ThreadLocal::stage_node, ThreadLocal::stage_path_size, ThreadLocal::stage_queue_size, GlobalContext::thread_id, LogCtx::thread_id, and ThreadLocal::thread_id.

Referenced by init_lf().

Here is the call graph for this function:
Here is the caller graph for this function: