Line data Source code
1 : #ifndef FD_LOG_STYLE
2 : #if FD_HAS_HOSTED
3 : #define FD_LOG_STYLE 0
4 : #else
5 : #error "Define FD_LOG_STYLE for this platform"
6 : #endif
7 : #endif
8 :
9 : #if FD_LOG_STYLE==0 /* POSIX style */
10 :
11 : #ifndef FD_HAS_BACKTRACE
12 : #if __has_include( <execinfo.h> )
13 : #define FD_HAS_BACKTRACE 1
14 : #else
15 : #define FD_HAS_BACKTRACE 0
16 : #endif
17 : #endif
18 :
19 : /* FIXME: SANITIZE VARIOUS USER SET STRINGS */
20 :
21 : #define _GNU_SOURCE
22 :
23 : #include "fd_log.h"
24 :
25 : #include <stdio.h>
26 : #include <stdlib.h>
27 : #include <stdarg.h>
28 : #include <ctype.h>
29 : #include <errno.h>
30 : #include <fcntl.h>
31 : #include <unistd.h>
32 : #include <signal.h>
33 : #include <sched.h>
34 : #include <time.h>
35 : #if defined(__linux__)
36 : #include <syscall.h>
37 : #endif
38 : #include <sys/mman.h>
39 :
40 : #if FD_HAS_BACKTRACE
41 : #include <execinfo.h>
42 : #endif
43 :
44 : #if defined(__FreeBSD__)
45 : #include <sys/stat.h> /* S_IRUSR */
46 : #endif /* defined(__FreeBSD__) */
47 :
48 : #include "../tile/fd_tile_private.h"
49 :
50 : #ifdef __has_include
51 : #if __has_include("../../app/fdctl/version.h")
52 : #include "../../app/fdctl/version.h"
53 : #endif
54 : #endif
55 :
56 : #ifndef FDCTL_MAJOR_VERSION
57 : #define FDCTL_MAJOR_VERSION 0
58 : #endif
59 : #ifndef FDCTL_MINOR_VERSION
60 : #define FDCTL_MINOR_VERSION 0
61 : #endif
62 : #ifndef FDCTL_PATCH_VERSION
63 : #define FDCTL_PATCH_VERSION 0
64 : #endif
65 :
66 : #ifdef FD_BUILD_INFO
67 : FD_IMPORT_CSTR( fd_log_build_info, FD_BUILD_INFO );
68 : #else
69 : char const fd_log_build_info[1] __attribute__((aligned(1))) = { '\0' };
70 : ulong const fd_log_build_info_sz = 1UL;
71 : #endif
72 :
73 : /* TEXT_* are quick-and-dirty color terminal hacks. Probably should
74 : do something more robust longer term. */
75 :
76 79368 : #define TEXT_NORMAL "\033[0m"
77 : #define TEXT_BOLD "\033[1m"
78 : #define TEXT_UNDERLINE "\033[4m"
79 : #define TEXT_BLINK "\033[5m"
80 :
81 9921 : #define TEXT_BLUE "\033[34m"
82 9921 : #define TEXT_GREEN "\033[32m"
83 9921 : #define TEXT_YELLOW "\033[93m"
84 39684 : #define TEXT_RED "\033[31m"
85 :
86 : /* APPLICATION LOGICAL ID APIS ****************************************/
87 :
88 : /* App id */
89 :
90 : static ulong fd_log_private_app_id; /* 0 outside boot/halt, init on boot */
91 :
92 2409 : void fd_log_private_app_id_set( ulong app_id ) { fd_log_private_app_id = app_id; }
93 :
94 18004890 : ulong fd_log_app_id( void ) { return fd_log_private_app_id; }
95 :
96 : /* App */
97 :
98 : static char fd_log_private_app[ FD_LOG_NAME_MAX ]; /* "" outside boot/halt, init on boot */
99 :
100 : void
101 2409 : fd_log_private_app_set( char const * app ) {
102 2409 : if( FD_UNLIKELY( !app ) ) app = "[app]";
103 2409 : if( FD_LIKELY( app!=fd_log_private_app ) )
104 2409 : fd_cstr_fini( fd_cstr_append_cstr_safe( fd_cstr_init( fd_log_private_app ), app, FD_LOG_NAME_MAX-1UL ) );
105 2409 : }
106 :
107 100861 : char const * fd_log_app( void ) { return fd_log_private_app; }
108 :
109 : /* Thread ID */
110 :
111 : #if FD_HAS_THREADS
112 : static ulong fd_log_private_thread_id_ctr; /* 0 outside boot/halt, init on boot */
113 :
114 : static ulong
115 2445 : fd_log_private_thread_id_next( void ) {
116 2445 : return FD_ATOMIC_FETCH_AND_ADD( &fd_log_private_thread_id_ctr, 1UL );
117 2445 : }
118 : #endif
119 :
120 : static FD_TL ulong fd_log_private_thread_id; /* 0 at thread start */
121 : static FD_TL int fd_log_private_thread_id_init; /* 0 at thread start */
122 :
123 : void
124 2445 : fd_log_private_thread_id_set( ulong thread_id ) {
125 2445 : fd_log_private_thread_id = thread_id;
126 2445 : fd_log_private_thread_id_init = 1;
127 2445 : }
128 :
129 : ulong
130 36926253 : fd_log_thread_id( void ) {
131 36926253 : # if FD_HAS_THREADS
132 36926253 : if( FD_UNLIKELY( !fd_log_private_thread_id_init ) ) fd_log_private_thread_id_set( fd_log_private_thread_id_next() );
133 : # else
134 : FD_COMPILER_MFENCE(); /* Work around FD_FN_CONST */
135 : # endif
136 36926253 : return fd_log_private_thread_id;
137 36926253 : }
138 :
139 : /* Thread */
140 :
141 : /* Initialize name to a reasonable default thread description (FIXME:
142 : WEEN THIS OFF STDLIB) */
143 :
144 : static void
145 2454 : fd_log_private_thread_default( char * name ) { /* FD_LOG_NAME_MAX bytes */
146 2454 : sprintf( name, "%lu", fd_log_thread_id() );
147 2454 : }
148 :
149 : static FD_TL char fd_log_private_thread[ FD_LOG_NAME_MAX ]; /* "" at thread start */
150 : static FD_TL int fd_log_private_thread_init; /* 0 at thread start */
151 :
152 : void
153 2454 : fd_log_thread_set( char const * thread ) {
154 2454 : if( FD_UNLIKELY( !thread ) || FD_UNLIKELY( thread[0]=='\0') ) {
155 2454 : fd_log_private_thread_default( fd_log_private_thread );
156 2454 : fd_log_private_thread_init = 1;
157 2454 : } else if( FD_LIKELY( thread!=fd_log_private_thread ) ) {
158 0 : fd_cstr_fini( fd_cstr_append_cstr_safe( fd_cstr_init( fd_log_private_thread ), thread, FD_LOG_NAME_MAX-1UL ) );
159 0 : fd_log_private_thread_init = 1;
160 0 : }
161 2454 : }
162 :
163 : char const *
164 1261949 : fd_log_thread( void ) {
165 1261949 : if( FD_UNLIKELY( !fd_log_private_thread_init ) ) fd_log_thread_set( NULL );
166 1261949 : return fd_log_private_thread;
167 1261949 : }
168 :
169 : /* APPLICATION PHYSICAL ID APIS ***************************************/
170 :
171 : /* Host ID */
172 :
173 : static ulong fd_log_private_host_id; /* 0 outside boot/halt, initialized on boot */
174 :
175 2409 : void fd_log_private_host_id_set( ulong host_id ) { fd_log_private_host_id = host_id; }
176 :
177 4854 : ulong fd_log_host_id( void ) { return fd_log_private_host_id; }
178 :
179 : /* Host */
180 :
181 : static char fd_log_private_host[ FD_LOG_NAME_MAX ]; /* "" outside boot/halt, initialized on boot */
182 :
183 100861 : char const * fd_log_host( void ) { return fd_log_private_host; }
184 :
185 : void
186 2409 : fd_log_private_host_set( char const * host ) {
187 2409 : if( FD_UNLIKELY( !host ) || FD_UNLIKELY( host[0]=='\0') ) host = "[host]";
188 2409 : if( FD_LIKELY( host!=fd_log_private_host ) )
189 2409 : fd_cstr_fini( fd_cstr_append_cstr_safe( fd_cstr_init( fd_log_private_host ), host, FD_LOG_NAME_MAX-1UL ) );
190 2409 : }
191 :
192 : /* CPU ID */
193 :
194 : /* First CPU scheduled to run on or ULONG_MAX on failure */
195 :
196 : ulong
197 2409 : fd_log_private_cpu_id_default( void ) {
198 2409 : FD_CPUSET_DECL( cpu_set );
199 2409 : if( FD_UNLIKELY( fd_cpuset_getaffinity( (pid_t)0, cpu_set ) ) ) return ULONG_MAX;
200 2409 : ulong idx = fd_cpuset_first( cpu_set );
201 2409 : idx = fd_ulong_if( idx<FD_TILE_MAX, idx, ULONG_MAX );
202 2409 : return idx;
203 2409 : }
204 :
205 : static FD_TL ulong fd_log_private_cpu_id; /* 0 at thread start */
206 : static FD_TL int fd_log_private_cpu_id_init; /* 0 at thread start */
207 :
208 : void
209 2418 : fd_log_private_cpu_id_set( ulong cpu_id ) {
210 2418 : fd_log_private_cpu_id = cpu_id;
211 2418 : fd_log_private_cpu_id_init = 1;
212 2418 : }
213 :
214 : ulong
215 18921363 : fd_log_cpu_id( void ) {
216 18921363 : if( FD_UNLIKELY( !fd_log_private_cpu_id_init ) ) fd_log_private_cpu_id_set( fd_log_private_cpu_id_default() );
217 18921363 : return fd_log_private_cpu_id;
218 18921363 : }
219 :
220 : /* CPU */
221 :
222 : /* Initialize name to a reasonable default CPU description (FIXME: WEEN
223 : THIS OFF STDLIB) */
224 :
225 : static void
226 2454 : fd_log_private_cpu_default( char * name ) { /* FD_LOG_NAME_MAX bytes */
227 2454 : FD_CPUSET_DECL( set );
228 :
229 2454 : int err = fd_cpuset_getaffinity( (pid_t)0, set );
230 2454 : if( FD_UNLIKELY( err ) ) { sprintf( name, "e%i", err ); return; }
231 :
232 2454 : ulong cnt = fd_cpuset_cnt( set );
233 2454 : if( FD_UNLIKELY( !((0UL<cnt) & (cnt<=FD_TILE_MAX)) ) ) { sprintf( name, "ec" ); return; }
234 :
235 2454 : ulong idx = fd_cpuset_first( set );
236 2454 : sprintf( name, (cnt>1) ? "f%lu" : "%lu", idx );
237 2454 : }
238 :
239 : static FD_TL char fd_log_private_cpu[ FD_LOG_NAME_MAX ]; /* "" at thread start */
240 : static FD_TL int fd_log_private_cpu_init; /* 0 at thread start */
241 :
242 : void
243 2454 : fd_log_cpu_set( char const * cpu ) {
244 2454 : if( FD_UNLIKELY( !cpu ) || FD_UNLIKELY( cpu[0]=='\0') ) {
245 2454 : fd_log_private_cpu_default( fd_log_private_cpu );
246 2454 : fd_log_private_cpu_init = 1;
247 2454 : } else if( FD_LIKELY( cpu!=fd_log_private_cpu ) ) {
248 0 : fd_cstr_fini( fd_cstr_append_cstr_safe( fd_cstr_init( fd_log_private_cpu ), cpu, FD_LOG_NAME_MAX-1UL ) );
249 0 : fd_log_private_cpu_init = 1;
250 0 : }
251 2454 : }
252 :
253 : char const *
254 1261949 : fd_log_cpu( void ) {
255 1261949 : if( FD_UNLIKELY( !fd_log_private_cpu_init ) ) fd_log_cpu_set( NULL );
256 1261949 : return fd_log_private_cpu;
257 1261949 : }
258 :
259 : /* THREAD GROUP ID APIS ***********************************************/
260 :
261 : /* Group id */
262 :
263 : static ulong fd_log_private_group_id; /* 0 outside boot/halt, init on boot */
264 :
265 2409 : void fd_log_private_group_id_set( ulong group_id ) { fd_log_private_group_id = group_id; }
266 :
267 311398705 : ulong fd_log_group_id( void ) { return fd_log_private_group_id; }
268 :
269 : /* Group */
270 :
271 : static char fd_log_private_group[ FD_LOG_NAME_MAX ]; /* "" outside boot/halt, init on boot */
272 :
273 100860 : char const * fd_log_group( void ) { return fd_log_private_group; }
274 :
275 : void
276 2409 : fd_log_private_group_set( char const * group ) {
277 2409 : if( FD_UNLIKELY( !group ) || FD_UNLIKELY( group[0]=='\0') ) group = "[group]";
278 2409 : if( FD_LIKELY( group!=fd_log_private_group ) )
279 2409 : fd_cstr_fini( fd_cstr_append_cstr_safe( fd_cstr_init( fd_log_private_group ), group, FD_LOG_NAME_MAX-1UL ) );
280 2409 : }
281 :
282 : /* System TID or ULONG_MAX on failure */
283 :
284 : ulong
285 2445 : fd_log_private_tid_default( void ) {
286 2445 : # if defined(__linux__)
287 2445 : long tid = syscall( SYS_gettid );
288 : # else
289 : long tid = getpid();
290 : # endif
291 2445 : return fd_ulong_if( tid>0L, (ulong)tid, ULONG_MAX );
292 2445 : }
293 :
294 : static FD_TL ulong fd_log_private_tid; /* 0 at thread start */
295 : static FD_TL int fd_log_private_tid_init; /* 0 at thread start */
296 :
297 : void
298 2445 : fd_log_private_tid_set( ulong tid ) {
299 2445 : fd_log_private_tid = tid;
300 2445 : fd_log_private_tid_init = 1;
301 2445 : }
302 :
303 : ulong
304 1264321 : fd_log_tid( void ) {
305 1264321 : if( FD_UNLIKELY( !fd_log_private_tid_init ) ) fd_log_private_tid_set( fd_log_private_tid_default() );
306 1264321 : return fd_log_private_tid;
307 1264321 : }
308 :
309 : /* User id */
310 :
311 : static ulong
312 2409 : fd_log_private_user_id_default( void ) {
313 2409 : return (ulong)getuid(); /* POSIX spec seems ambiguous as to whether or not this is a signed type */
314 2409 : }
315 :
316 : static ulong fd_log_private_user_id; /* 0 outside boot/halt, init on boot */
317 : static int fd_log_private_user_id_init;
318 :
319 : void
320 2409 : fd_log_private_user_id_set( ulong user_id ) {
321 2409 : fd_log_private_user_id = user_id;
322 2409 : fd_log_private_user_id_init = 1;
323 2409 : }
324 :
325 : ulong
326 2445 : fd_log_user_id( void ) {
327 2445 : if( FD_UNLIKELY( !fd_log_private_user_id_init ) ) {
328 0 : fd_log_private_user_id = fd_log_private_user_id_default();
329 0 : fd_log_private_user_id_init = 1;
330 0 : }
331 2445 : return fd_log_private_user_id;
332 2445 : }
333 :
334 : /* User */
335 :
336 : static char fd_log_private_user[ FD_LOG_NAME_MAX ]; /* "" outside boot/halt, init on boot */
337 :
338 100861 : char const * fd_log_user( void ) { return fd_log_private_user; }
339 :
340 : void
341 2409 : fd_log_private_user_set( char const * user ) {
342 2409 : if( FD_UNLIKELY( !user ) || FD_UNLIKELY( user[0]=='\0') ) user = "[user]";
343 2409 : if( FD_LIKELY( user!=fd_log_private_user ) )
344 2409 : fd_cstr_fini( fd_cstr_append_cstr_safe( fd_cstr_init( fd_log_private_user ), user, FD_LOG_NAME_MAX-1UL ) );
345 2409 : }
346 :
347 : int
348 0 : fd_log_group_id_query( ulong group_id ) {
349 0 : if( group_id==fd_log_group_id() ) return FD_LOG_GROUP_ID_QUERY_LIVE; /* Avoid O/S call for self queries */
350 0 : pid_t pid = (pid_t)group_id;
351 0 : if( FD_UNLIKELY( ((group_id!=(ulong)pid) | (pid<=(pid_t)0)) ) ) return FD_LOG_GROUP_ID_QUERY_INVAL;
352 0 : if( !kill( (pid_t)group_id, 0 ) ) return FD_LOG_GROUP_ID_QUERY_LIVE;
353 0 : if( FD_LIKELY( errno==ESRCH ) ) return FD_LOG_GROUP_ID_QUERY_DEAD;
354 0 : if( FD_LIKELY( errno==EPERM ) ) return FD_LOG_GROUP_ID_QUERY_PERM;
355 0 : return FD_LOG_GROUP_ID_QUERY_FAIL;
356 0 : }
357 :
358 : /* WALLCLOCK APIS *****************************************************/
359 :
360 : long
361 129860108 : fd_log_wallclock_host( void const * _ ) {
362 129860108 : (void)_;
363 129860108 : struct timespec ts[1];
364 129860108 : clock_gettime( CLOCK_REALTIME, ts );
365 129860108 : return ((long)1e9)*((long)ts->tv_sec) + (long)ts->tv_nsec;
366 129860108 : }
367 :
368 : static fd_clock_func_t fd_log_private_clock_func = fd_log_wallclock_host;
369 : static void const * fd_log_private_clock_args = NULL;
370 :
371 : long
372 128639572 : fd_log_wallclock( void ) {
373 128639572 : return fd_log_private_clock_func( fd_log_private_clock_args );
374 128639572 : }
375 :
376 : void
377 : fd_log_wallclock_set( fd_clock_func_t clock,
378 0 : void const * args ) {
379 0 : fd_log_private_clock_func = clock;
380 0 : fd_log_private_clock_args = args;
381 0 : }
382 :
383 : char *
384 : fd_log_wallclock_cstr( long now,
385 105411 : char * buf ) {
386 105411 : uint YYYY;
387 105411 : uint MM;
388 105411 : uint DD;
389 105411 : uint hh;
390 105411 : uint mm;
391 105411 : ulong ns;
392 105411 : int tz;
393 :
394 105411 : static long const ns_per_m = 60000000000L;
395 105411 : static long const ns_per_s = 1000000000L;
396 :
397 105411 : static FD_TL long now_ref = 1262325600000000000L; /* 2010-01-01 00:00:00.000000000 GMT-06 */
398 105411 : static FD_TL uint YYYY_ref = 2010U; /* Initialized to what now0 corresponds to */
399 105411 : static FD_TL uint MM_ref = 1U; /* " */
400 105411 : static FD_TL uint DD_ref = 1U; /* " */
401 105411 : static FD_TL uint hh_ref = 0U; /* " */
402 105411 : static FD_TL uint mm_ref = 0U; /* " */
403 105411 : static FD_TL int tz_ref = -6; /* " */
404 :
405 105411 : if( FD_LIKELY( (now_ref<=now) & (now<(now_ref+ns_per_m)) ) ) {
406 :
407 : /* now is near the reference timestamp so we reuse the reference
408 : calculation timestamp. */
409 :
410 102946 : YYYY = YYYY_ref;
411 102946 : MM = MM_ref;
412 102946 : DD = DD_ref;
413 102946 : hh = hh_ref;
414 102946 : mm = mm_ref;
415 102946 : ns = (ulong)(now - now_ref);
416 102946 : tz = tz_ref;
417 :
418 102946 : } else {
419 :
420 2465 : long _t = now / ns_per_s;
421 2465 : long _ns = now - ns_per_s*_t;
422 2465 : if( _ns<0L ) _ns += ns_per_s, _t--;
423 2465 : time_t t = (time_t)_t;
424 :
425 2465 : struct tm tm[1];
426 2465 : static FD_TL int localtime_broken = 0;
427 2465 : if( FD_UNLIKELY( !localtime_broken && !localtime_r( &t, tm ) ) ) localtime_broken = 1;
428 2465 : if( FD_UNLIKELY( localtime_broken ) ) { /* If localtime_r doesn't work, pretty print as a raw UNIX time */
429 : /* Note: These can all run in parallel */
430 0 : fd_cstr_append_fxp10_as_text( buf, ' ', fd_char_if( now<0L, '-', '\0' ), 9UL, fd_long_abs( now ), 29UL );
431 0 : fd_cstr_append_text ( buf+29, " s UNIX", 7UL );
432 0 : fd_cstr_append_char ( buf+36, '\0' );
433 0 : return buf;
434 0 : }
435 :
436 2465 : YYYY = (uint)(1900+tm->tm_year);
437 2465 : MM = (uint)( 1+tm->tm_mon );
438 2465 : DD = (uint)tm->tm_mday;
439 2465 : hh = (uint)tm->tm_hour;
440 2465 : mm = (uint)tm->tm_min;
441 2465 : ns = ((ulong)((uint)tm->tm_sec))*((ulong)ns_per_s) + ((ulong)_ns);
442 2465 : # if defined(__linux__)
443 2465 : tz = (int)(-timezone/3600L+(long)tm->tm_isdst);
444 : # else
445 : tz = 0;
446 : # endif
447 :
448 2465 : now_ref = now - (long)ns;
449 2465 : YYYY_ref = YYYY;
450 2465 : MM_ref = MM;
451 2465 : DD_ref = DD;
452 2465 : hh_ref = hh;
453 2465 : mm_ref = mm;
454 2465 : tz_ref = tz;
455 :
456 2465 : }
457 :
458 : /* Note: These can all run in parallel! */
459 105411 : fd_cstr_append_uint_as_text ( buf, '0', '\0', YYYY, 4UL );
460 105411 : fd_cstr_append_char ( buf+ 4, '-' );
461 105411 : fd_cstr_append_uint_as_text ( buf+ 5, '0', '\0', MM, 2UL );
462 105411 : fd_cstr_append_char ( buf+ 7, '-' );
463 105411 : fd_cstr_append_uint_as_text ( buf+ 8, '0', '\0', DD, 2UL );
464 105411 : fd_cstr_append_char ( buf+10, ' ' );
465 105411 : fd_cstr_append_uint_as_text ( buf+11, '0', '\0', hh, 2UL );
466 105411 : fd_cstr_append_char ( buf+13, ':' );
467 105411 : fd_cstr_append_uint_as_text ( buf+14, '0', '\0', mm, 2UL );
468 105411 : fd_cstr_append_char ( buf+16, ':' );
469 105411 : fd_cstr_append_fxp10_as_text( buf+17, '0', '\0', 9UL, ns, 12UL );
470 105411 : fd_cstr_append_text ( buf+29, " GMT", 4UL );
471 105411 : fd_cstr_append_char ( buf+33, fd_char_if( tz<0, '-', '+' ) );
472 105411 : fd_cstr_append_uint_as_text ( buf+34, '0', '\0', fd_int_abs( tz ), 2UL );
473 105411 : fd_cstr_append_char ( buf+36, '\0' );
474 105411 : return buf;
475 105411 : }
476 :
477 : long
478 504 : fd_log_sleep( long dt ) {
479 504 : if( FD_UNLIKELY( dt < 1L ) ) {
480 0 : sched_yield();
481 0 : return 0L;
482 0 : }
483 :
484 : /* dt is in [1,LONG_MAX] at this point */
485 504 : long ns_dt = fd_long_min( dt, (((long)1e9)<<31)-1L ); /* in [1,2^31*1e9) and <= dt at this point */
486 504 : dt -= ns_dt;
487 :
488 504 : struct timespec req[1];
489 504 : struct timespec rem[1];
490 504 : req->tv_sec = (time_t)( ((ulong)ns_dt) / ((ulong)1e9) ); /* in [0,2^31-1] */
491 504 : req->tv_nsec = (long) ( ((ulong)ns_dt) % ((ulong)1e9) ); /* in [0,1e9) */
492 504 : if( FD_UNLIKELY( nanosleep( req, rem ) ) && FD_LIKELY( errno==EINTR ) ) dt += ((long)1e9)*((long)rem->tv_sec) + rem->tv_nsec;
493 504 : return dt;
494 504 : }
495 :
496 : long
497 3 : fd_log_wait_until( long then ) {
498 3 : long now;
499 258737 : for(;;) {
500 258737 : now = fd_log_wallclock();
501 258737 : long rem = then - now;
502 258737 : if( FD_LIKELY( rem<=0L ) ) break; /* we've waited long enough */
503 258734 : if( FD_UNLIKELY( rem>(long)1e9 ) ) { /* long wait (over ~1 s) ... sleep until medium long */
504 0 : fd_log_sleep( rem-(long)0.1e9 );
505 0 : continue;
506 0 : }
507 258734 : if( FD_UNLIKELY( rem>(long)0.1e9 ) ) { /* medium long wait (over ~0.1 s) ... yield */
508 0 : FD_YIELD();
509 0 : continue;
510 0 : }
511 258734 : if( FD_UNLIKELY( rem>(long)1e3 ) ) { /* medium short wait (over ~1 us) ... hyperthreading friendly spin */
512 258648 : FD_SPIN_PAUSE();
513 258648 : continue;
514 258648 : }
515 : /* short wait ... spin on fd_log_wallclock */
516 258734 : }
517 3 : return now;
518 3 : }
519 :
520 : /* LOG APIS ***********************************************************/
521 :
522 : char fd_log_private_path[ 1024 ]; /* "" outside boot/halt, init at boot */
523 : static int fd_log_private_fileno = -1; /* -1 outside boot/halt, init at boot */
524 : static int fd_log_private_dedup; /* 0 outside boot/halt, init at boot */
525 :
526 : void
527 4290 : fd_log_flush( void ) {
528 4290 : int log_fileno = FD_VOLATILE_CONST( fd_log_private_fileno );
529 4290 : if( FD_LIKELY( log_fileno!=-1 ) ) fsync( log_fileno );
530 4290 : }
531 :
532 : static int fd_log_private_colorize; /* 0 outside boot/halt, init at boot */
533 : static int fd_log_private_level_logfile; /* 0 outside boot/halt, init at boot */
534 : static int fd_log_private_level_stderr; /* 0 outside boot/halt, init at boot */
535 : static int fd_log_private_level_flush; /* 0 outside boot/halt, init at boot */
536 : static int fd_log_private_level_core; /* 0 outside boot/halt, init at boot */
537 : static int fd_log_private_unclean_exit;
538 :
539 2409 : int fd_log_colorize ( void ) { return FD_VOLATILE_CONST( fd_log_private_colorize ); }
540 1395926 : int fd_log_level_logfile( void ) { return FD_VOLATILE_CONST( fd_log_private_level_logfile ); }
541 1261878 : int fd_log_level_stderr ( void ) { return FD_VOLATILE_CONST( fd_log_private_level_stderr ); }
542 107307 : int fd_log_level_flush ( void ) { return FD_VOLATILE_CONST( fd_log_private_level_flush ); }
543 3534 : int fd_log_level_core ( void ) { return FD_VOLATILE_CONST( fd_log_private_level_core ); }
544 :
545 2409 : void fd_log_colorize_set ( int mode ) { FD_VOLATILE( fd_log_private_colorize ) = mode; }
546 2418 : void fd_log_level_logfile_set( int level ) { FD_VOLATILE( fd_log_private_level_logfile ) = level; }
547 2421 : void fd_log_level_stderr_set ( int level ) { FD_VOLATILE( fd_log_private_level_stderr ) = level; }
548 2409 : void fd_log_level_flush_set ( int level ) { FD_VOLATILE( fd_log_private_level_flush ) = level; }
549 2421 : void fd_log_level_core_set ( int level ) { FD_VOLATILE( fd_log_private_level_core ) = level; }
550 :
551 0 : int fd_log_private_logfile_fd( void ) { return FD_VOLATILE_CONST( fd_log_private_fileno ); }
552 :
553 0 : void fd_log_enable_unclean_exit( void ) { fd_log_private_unclean_exit = 1; }
554 :
555 : /* Buffer size used for vsnprintf calls (this is also one more than the
556 : maximum size that this can passed to fd_io_write) */
557 :
558 3001450 : #define FD_LOG_BUF_SZ (32UL*4096UL)
559 :
560 : /* Lock to used by fd_log_private_fprintf_0 to sequence calls writes
561 : between different _processes_ that share the same fd. */
562 :
563 : static int fd_log_private_shared_lock_local[1] __attribute__((aligned(128))); /* location of lock if boot mmap fails */
564 : int * fd_log_private_shared_lock = fd_log_private_shared_lock_local; /* Local lock outside boot/halt, init at boot */
565 :
566 : void
567 : fd_log_private_fprintf_0( int fd,
568 113404 : char const * fmt, ... ) {
569 :
570 : /* Note: while this function superficially looks vdprintf-ish, we don't
571 : use that as it can do all sorts of unpleasantness under the hood
572 : (fflush, mutex / futex on fd, non-AS-safe buffering, ...) that this
573 : function deliberately avoids. Also, the function uses the shared
574 : lock to help keep messages generated from processes that share the
575 : same log fd sane. */
576 :
577 : /* TODO:
578 : - Consider moving to util/io as fd_io_printf or renaming to
579 : fd_log_printf?
580 : - Is msg better to have on stack or in thread local storage?
581 : - Is msg even necessary given shared lock? (probably still useful to
582 : keep the message write to be a single-system-call best effort)
583 : - Allow partial write to fd_io_write? (e.g. src_min=0 such that
584 : the fd_io_write below is guaranteed to be a single system call) */
585 :
586 113404 : char msg[ FD_LOG_BUF_SZ ];
587 :
588 113404 : va_list ap;
589 113404 : va_start( ap, fmt );
590 113404 : int len = vsnprintf( msg, FD_LOG_BUF_SZ, fmt, ap );
591 113404 : if( len<0 ) len = 0; /* cmov */
592 113404 : if( len>(int)(FD_LOG_BUF_SZ-1UL) ) len = (int)(FD_LOG_BUF_SZ-1UL); /* cmov */
593 113404 : msg[ len ] = '\0';
594 113404 : va_end( ap );
595 :
596 113404 : # if FD_HAS_ATOMIC
597 113404 : FD_COMPILER_MFENCE();
598 117636 : while(( FD_LIKELY( FD_ATOMIC_CAS( fd_log_private_shared_lock, 0, 1 ) ) )) ;
599 113404 : FD_COMPILER_MFENCE();
600 113404 : # endif
601 :
602 113404 : ulong wsz;
603 113404 : fd_io_write( fd, msg, (ulong)len, (ulong)len, &wsz ); /* Note: we ignore errors because what are we doing to do? log them? */
604 :
605 113404 : # if FD_HAS_ATOMIC
606 113404 : FD_COMPILER_MFENCE();
607 113404 : FD_VOLATILE( *fd_log_private_shared_lock ) = 0;
608 113404 : FD_COMPILER_MFENCE();
609 113404 : # endif
610 :
611 113404 : }
612 :
613 : /* This is the same as fd_log_private_fprintf_0 except that it does not try to
614 : take a lock when writing to the log file. This should almost never be used
615 : except in exceptional cases when logging while the process is shutting down.
616 :
617 : It exists because if a child process dies while holding the lock, we may
618 : want to log some diagnostic messages when tearing down the process tree. */
619 : void
620 : fd_log_private_fprintf_nolock_0( int fd,
621 0 : char const * fmt, ... ) {
622 :
623 : /* Note: while this function superficially looks vdprintf-ish, we don't
624 : use that as it can do all sorts of unpleasantness under the hood
625 : (fflush, mutex / futex on fd, non-AS-safe buffering, ...) that this
626 : function deliberately avoids. Also, the function uses the shared
627 : lock to help keep messages generated from processes that share the
628 : same log fd sane. */
629 :
630 : /* TODO:
631 : - Consider moving to util/io as fd_io_printf or renaming to
632 : fd_log_printf?
633 : - Is msg better to have on stack or in thread local storage?
634 : - Is msg even necessary given shared lock? (probably still useful to
635 : keep the message write to be a single-system-call best effort)
636 : - Allow partial write to fd_io_write? (e.g. src_min=0 such that
637 : the fd_io_write below is guaranteed to be a single system call) */
638 :
639 0 : char msg[ FD_LOG_BUF_SZ ];
640 :
641 0 : va_list ap;
642 0 : va_start( ap, fmt );
643 0 : int len = vsnprintf( msg, FD_LOG_BUF_SZ, fmt, ap );
644 0 : if( len<0 ) len = 0; /* cmov */
645 0 : if( len>(int)(FD_LOG_BUF_SZ-1UL) ) len = (int)(FD_LOG_BUF_SZ-1UL); /* cmov */
646 0 : msg[ len ] = '\0';
647 0 : va_end( ap );
648 :
649 0 : ulong wsz;
650 0 : fd_io_write( fd, msg, (ulong)len, (ulong)len, &wsz ); /* Note: we ignore errors because what are we doing to do? log them? */
651 0 : }
652 :
653 : /* Log buffer used by fd_log_private_0 and fd_log_private_hexdump_msg */
654 :
655 : static FD_TL char fd_log_private_log_msg[ FD_LOG_BUF_SZ ];
656 :
657 : char const *
658 1387321 : fd_log_private_0( char const * fmt, ... ) {
659 1387321 : va_list ap;
660 1387321 : va_start( ap, fmt );
661 1387321 : int len = vsnprintf( fd_log_private_log_msg, FD_LOG_BUF_SZ, fmt, ap );
662 1387321 : if( len<0 ) len = 0; /* cmov */
663 1387321 : if( len>(int)(FD_LOG_BUF_SZ-1UL) ) len = (int)(FD_LOG_BUF_SZ-1UL); /* cmov */
664 1387321 : fd_log_private_log_msg[ len ] = '\0';
665 1387321 : va_end( ap );
666 1387321 : return fd_log_private_log_msg;
667 1387321 : }
668 :
669 : char const *
670 : fd_log_private_hexdump_msg( char const * descr,
671 : void const * mem,
672 6186 : ulong sz ) {
673 :
674 3139722 : # define FD_LOG_HEXDUMP_BYTES_PER_LINE (16UL)
675 6186 : # define FD_LOG_HEXDUMP_BLOB_DESCRIPTION_MAX_LEN (32UL)
676 6186 : # define FD_LOG_HEXDUMP_MAX_INPUT_BLOB_SZ (1664UL) /* multiple of 128 >= 1542 */
677 :
678 3537600 : # define FD_LOG_HEXDUMP_ADD_TO_LOG_BUF(...) do { log_buf_ptr += fd_int_max( sprintf( log_buf_ptr, __VA_ARGS__ ), 0 ); } while(0)
679 6186 : char * log_buf_ptr = fd_log_private_log_msg; /* used by FD_LOG_HEXDUMP_ADD_TO_LOG_BUF macro */
680 :
681 : /* Print the hexdump header */
682 : /* FIXME: consider additional sanitization of descr or using compiler
683 : tricks to prevent user from passing a non-const-char string (i.e.
684 : data they got from somewhere else that might not be sanitized). */
685 :
686 6186 : if( FD_UNLIKELY( !descr ) ) {
687 :
688 0 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( "HEXDUMP - (%lu bytes at 0x%lx)", sz, (ulong)mem );
689 :
690 6186 : } else if( FD_UNLIKELY( strlen( descr )>FD_LOG_HEXDUMP_BLOB_DESCRIPTION_MAX_LEN ) ) {
691 :
692 3 : char tmp[ FD_LOG_HEXDUMP_BLOB_DESCRIPTION_MAX_LEN + 1UL ];
693 3 : fd_cstr_fini( fd_cstr_append_text( fd_cstr_init( tmp ), descr, FD_LOG_HEXDUMP_BLOB_DESCRIPTION_MAX_LEN ) );
694 3 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( "HEXDUMP \"%s\"... (%lu bytes at 0x%lx)", tmp, sz, (ulong)mem );
695 :
696 6183 : } else {
697 :
698 6183 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( "HEXDUMP \"%s\" (%lu bytes at 0x%lx)", descr, sz, (ulong)mem );
699 :
700 6183 : }
701 :
702 6186 : if( FD_UNLIKELY( !sz ) ) return fd_log_private_log_msg;
703 :
704 6186 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( "\n" );
705 :
706 6186 : if( FD_UNLIKELY( !mem ) ) {
707 0 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( "\t... snip (unreadable memory) ..." );
708 0 : return fd_log_private_log_msg;
709 0 : }
710 :
711 6186 : char line_buf[ FD_LOG_HEXDUMP_BYTES_PER_LINE+1 ];
712 6186 : char const * blob = (char const *)mem;
713 6186 : ulong blob_off = 0UL;
714 6186 : ulong blob_sz = fd_ulong_min( sz, FD_LOG_HEXDUMP_MAX_INPUT_BLOB_SZ );
715 :
716 3139230 : for( ; blob_off<blob_sz; blob_off++ ) {
717 3133044 : ulong col_idx = blob_off % FD_LOG_HEXDUMP_BYTES_PER_LINE;
718 :
719 : /* New line. Print previous line's ASCII representation and then print the offset. */
720 3133044 : if( FD_UNLIKELY( !col_idx ) ) {
721 195846 : if( FD_LIKELY( blob_off ) ) FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( " %s\n", line_buf );
722 195846 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( "\t%04lx: ", blob_off );
723 195846 : }
724 : /* FIXME: consider extra space between col 7 and 8 to make easier
725 : for visual inspection */
726 :
727 3133044 : char c = blob[blob_off];
728 3133044 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( " %02x", (uint)(uchar)c );
729 :
730 : /* If not a printable ASCII character, output a dot. */
731 3133044 : line_buf[ col_idx ] = fd_char_if( fd_isalnum( (int)c ) | fd_ispunct( (int)c ) | (c==' '), c, '.' );
732 3133044 : line_buf[ col_idx+1UL ] = '\0';
733 3133044 : }
734 :
735 : /* Print the 2nd column of last blob line */
736 6678 : while( blob_off % FD_LOG_HEXDUMP_BYTES_PER_LINE ) {
737 492 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( " " );
738 492 : blob_off++;
739 492 : }
740 6186 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( " %s", line_buf );
741 :
742 6186 : if( FD_UNLIKELY( blob_sz < sz ) )
743 0 : FD_LOG_HEXDUMP_ADD_TO_LOG_BUF( "\n\t... snip (printed %lu bytes, omitted %lu bytes) ...", blob_sz, sz-blob_sz );
744 :
745 6186 : return fd_log_private_log_msg;
746 :
747 6186 : # undef FD_LOG_HEXDUMP_BYTES_PER_LINE
748 6186 : # undef FD_LOG_HEXDUMP_BLOB_DESCRIPTION_MAX_LEN
749 6186 : # undef FD_LOG_HEXDUMP_MAX_INPUT_BLOB_SZ
750 6186 : # undef FD_LOG_HEXDUMP_ADD_TO_LOG_BUF
751 6186 : }
752 :
753 : void
754 : fd_log_private_1( int level,
755 : long now,
756 : char const * file,
757 : int line,
758 : char const * func,
759 1393515 : char const * msg ) {
760 :
761 1393515 : if( level<fd_log_level_logfile() ) return;
762 :
763 : /* These are thread init so we call them regardless of permanent log
764 : enabled to their initialization time is guaranteed independent of
765 : whether the permanent log is enabled. */
766 :
767 1259472 : char const * thread = fd_log_thread();
768 1259472 : char const * cpu = fd_log_cpu();
769 1259472 : ulong tid = fd_log_tid();
770 :
771 1259472 : int log_fileno = FD_VOLATILE_CONST( fd_log_private_fileno );
772 1259472 : int to_logfile = (log_fileno!=-1);
773 1259472 : int to_stderr = (level>=fd_log_level_stderr());
774 1259472 : if( !(to_logfile | to_stderr) ) return;
775 :
776 : /* Deduplicate the log if requested */
777 :
778 1194219 : if( fd_log_private_dedup ) {
779 :
780 : /* Compute if this message appears to be a recent duplicate of
781 : a previous log message */
782 :
783 1194211 : ulong hash = fd_cstr_hash_append( fd_cstr_hash_append( fd_cstr_hash_append( fd_ulong_hash(
784 1194211 : (ulong)(8L*(long)line+(long)level) ), file ), func ), msg );
785 :
786 1194211 : static long const dedup_interval = 20000000L; /* 1/50 s */
787 :
788 1194211 : static FD_TL int init; /* 0 on thread start */
789 1194211 : static FD_TL ulong last_hash; /* 0UL on thread start */
790 1194211 : static FD_TL long then; /* 0L on thread start */
791 :
792 1194211 : int is_dup = init & (hash==last_hash) & ((now-then)<dedup_interval);
793 1194211 : init = 1;
794 :
795 : /* Update how many messages from this thread in row have been
796 : duplicates */
797 :
798 1194211 : static FD_TL ulong dedup_cnt; /* 0UL on thread start */
799 1194211 : static FD_TL int in_dedup; /* 0 on thread start */
800 :
801 1194211 : if( is_dup ) dedup_cnt++;
802 104182 : else {
803 104182 : if( in_dedup ) {
804 :
805 : /* This message appears to end a long string of duplicates.
806 : Log the end of the deduplication. */
807 :
808 285 : char then_cstr[ FD_LOG_WALLCLOCK_CSTR_BUF_SZ ];
809 285 : fd_log_wallclock_cstr( then, then_cstr );
810 :
811 285 : if( to_logfile )
812 285 : fd_log_private_fprintf_0( log_fileno, "SNIP %s %6lu:%-6lu %s:%s:%-4s %s:%s:%-4s "
813 285 : "stopped repeating (%lu identical messages)\n",
814 285 : then_cstr, fd_log_group_id(),tid, fd_log_user(),fd_log_host(),cpu,
815 285 : fd_log_app(),fd_log_group(),thread, dedup_cnt+1UL );
816 :
817 285 : if( to_stderr ) {
818 219 : char * then_short_cstr = then_cstr+5; then_short_cstr[21] = '\0'; /* Lop off the year, ns resolution and timezone */
819 219 : fd_log_private_fprintf_0( STDERR_FILENO, "SNIP %s %-6lu %-4s %-4s stopped repeating (%lu identical messages)\n",
820 219 : then_short_cstr, tid,cpu,thread, dedup_cnt+1UL );
821 219 : }
822 :
823 285 : in_dedup = 0;
824 285 : }
825 :
826 104182 : dedup_cnt = 0UL;
827 104182 : }
828 :
829 : /* dedup_cnt previous messages from this thread appear to be
830 : duplicates. Decide whether to let the raw message print or
831 : deduplicate to the log. FIXME: CONSIDER RANDOMIZING THE
832 : THROTTLE. */
833 :
834 1194211 : static ulong const dedup_thresh = 3UL; /* let initial dedup_thresh duplicates go out the door */
835 1194211 : static long const dedup_throttle = 1000000000L; /* ~1s, how often to update status on current duplication */
836 :
837 1194211 : static FD_TL long dedup_last; /* 0L on thread start */
838 :
839 1194211 : if( dedup_cnt < dedup_thresh ) dedup_last = now;
840 1089319 : else {
841 1089319 : if( (now-dedup_last) >= dedup_throttle ) {
842 66 : char now_cstr[ FD_LOG_WALLCLOCK_CSTR_BUF_SZ ];
843 66 : fd_log_wallclock_cstr( now, now_cstr );
844 66 : if( to_logfile )
845 66 : fd_log_private_fprintf_0( log_fileno, "SNIP %s %6lu:%-6lu %s:%s:%-4s %s:%s:%-4s repeating (%lu identical messages)\n",
846 66 : now_cstr, fd_log_group_id(),tid, fd_log_user(),fd_log_host(),cpu,
847 66 : fd_log_app(),fd_log_group(),thread, dedup_cnt+1UL );
848 66 : if( to_stderr ) {
849 66 : char * now_short_cstr = now_cstr+5; now_short_cstr[21] = '\0'; /* Lop off the year, ns resolution and timezone */
850 66 : fd_log_private_fprintf_0( STDERR_FILENO, "SNIP %s %-6lu %-4s %-4s repeating (%lu identical messages)\n",
851 66 : now_short_cstr, tid,cpu,thread, dedup_cnt+1UL );
852 66 : }
853 66 : dedup_last = now;
854 66 : }
855 1089319 : in_dedup = 1;
856 1089319 : }
857 :
858 1194211 : last_hash = hash;
859 1194211 : then = now;
860 :
861 1194211 : if( in_dedup ) return;
862 1194211 : }
863 :
864 104898 : char now_cstr[ FD_LOG_WALLCLOCK_CSTR_BUF_SZ ];
865 104898 : fd_log_wallclock_cstr( now, now_cstr );
866 :
867 104898 : static char const * level_cstr[] = {
868 104898 : /* 0 */ "DEBUG ",
869 104898 : /* 1 */ "INFO ",
870 104898 : /* 2 */ "NOTICE ",
871 104898 : /* 3 */ "WARNING",
872 104898 : /* 4 */ "ERR ",
873 104898 : /* 5 */ "CRIT ",
874 104898 : /* 6 */ "ALERT ",
875 104898 : /* 7 */ "EMERG "
876 104898 : };
877 :
878 104898 : if( to_logfile )
879 98029 : fd_log_private_fprintf_0( log_fileno, "%s %s %6lu:%-6lu %s:%s:%-4s %s:%s:%-4s %s(%i)[%s]: %s\n",
880 98029 : level_cstr[level], now_cstr, fd_log_group_id(),tid, fd_log_user(),fd_log_host(),cpu,
881 98029 : fd_log_app(),fd_log_group(),thread, file,line,func, msg );
882 :
883 104898 : if( to_stderr ) {
884 9921 : static char const * color_level_cstr[] = {
885 9921 : /* 0 */ TEXT_NORMAL "DEBUG ",
886 9921 : /* 1 */ TEXT_BLUE "INFO " TEXT_NORMAL,
887 9921 : /* 2 */ TEXT_GREEN "NOTICE " TEXT_NORMAL,
888 9921 : /* 3 */ TEXT_YELLOW "WARNING" TEXT_NORMAL,
889 9921 : /* 4 */ TEXT_RED "ERR " TEXT_NORMAL,
890 9921 : /* 5 */ TEXT_RED TEXT_BOLD "CRIT " TEXT_NORMAL,
891 9921 : /* 6 */ TEXT_RED TEXT_BOLD TEXT_UNDERLINE "ALERT " TEXT_NORMAL,
892 9921 : /* 7 */ TEXT_RED TEXT_BOLD TEXT_UNDERLINE TEXT_BLINK "EMERG " TEXT_NORMAL
893 9921 : };
894 9921 : char * now_short_cstr = now_cstr+5; now_short_cstr[21] = '\0'; /* Lop off the year, ns resolution and timezone */
895 9921 : fd_log_private_fprintf_0( STDERR_FILENO, "%s %s %-6lu %-4s %-4s %s(%i): %s\n",
896 9921 : fd_log_private_colorize ? color_level_cstr[level] : level_cstr[level],
897 9921 : now_short_cstr, tid,cpu,thread, file, line, msg );
898 9921 : }
899 :
900 104898 : if( level<fd_log_level_flush() ) return;
901 :
902 4257 : fd_log_flush();
903 4257 : }
904 :
905 : void
906 : fd_log_private_2( int level,
907 : long now,
908 : char const * file,
909 : int line,
910 : char const * func,
911 1125 : char const * msg ) {
912 1125 : fd_log_private_1( level, now, file, line, func, msg );
913 :
914 1125 : if( level<fd_log_level_core() ) {
915 1125 : # if defined(__linux__)
916 1125 : if( fd_log_private_unclean_exit ) {
917 0 : syscall( SYS_exit_group, 1 );
918 0 : }
919 1125 : # endif /* defined(__linux__) */
920 1125 : exit(1); /* atexit will call fd_log_private_cleanup implicitly */
921 1125 : }
922 :
923 0 : abort();
924 1125 : }
925 :
926 : void
927 : fd_log_private_raw_2( char const * file,
928 : int line,
929 : char const * func,
930 0 : char const * msg ) {
931 0 : fd_log_private_fprintf_nolock_0( STDERR_FILENO, "%s(%i)[%s]: %s\n", file, line, func, msg );
932 0 : # if defined(__linux__)
933 0 : syscall( SYS_exit_group, 1 );
934 : # else
935 : exit(1);
936 : # endif
937 0 : abort();
938 0 : }
939 :
940 : /* BOOT/HALT APIS *****************************************************/
941 :
942 : static void
943 3684 : fd_log_private_cleanup( void ) {
944 :
945 : /* The atexit below means that all calls to "exit();" implicitly
946 : become "fd_log_private_cleanup(); exit();". It also implies that
947 : programs that terminate via a top level return from main implicitly
948 : call fd_log_private_cleanup().
949 :
950 : As such it is possible that a thread other than the booter will
951 : trigger cleanup either by triggering this directly (e.g. calling
952 : exit) or indirectly (e.g. by logging a message with an exit
953 : triggering priority) and that the booter itself might call this
954 : more than once sequentially (e.g. fd_halt() calling cleanup
955 : explicitly followed by return from main triggering it again.
956 :
957 : Accordingly we protect this with a ONCE block so it only will
958 : execute once per program. Further, if cleanup gets triggered by
959 : multiple threads concurrently, the ONCE block will prevent them
960 : from progressing until the first thread that hits the once block
961 : has completed cleanup. */
962 :
963 12186 : FD_ONCE_BEGIN {
964 2409 : int log_fileno = FD_VOLATILE_CONST( fd_log_private_fileno );
965 2409 : if( log_fileno==-1 ) fd_log_private_fprintf_0( STDERR_FILENO, "No log\n" );
966 585 : else if( !strcmp( fd_log_private_path, "-" ) ) fd_log_private_fprintf_0( STDERR_FILENO, "Log to stdout\n" );
967 573 : else {
968 573 : # if FD_HAS_THREADS
969 573 : if( fd_log_private_thread_id_ctr>1UL ) { /* There are potentially other log users running */
970 : /* Just closing the permanent log file is not multithreading
971 : safe in the case where other threads are still running
972 : normally and thus potentially logging to the permanent log.
973 : Such should not happen in a correctly written and functioning
974 : application but logging exists in large part to help
975 : understand when applications misbehave. So we try to be as
976 : robust and informative as we can here. FIXME: THE SECOND
977 : USLEEP IS AN UGLY HACK TO REDUCE (BUT NOT FULLY ELIMINATE)
978 : THE RISK OF USE AFTER CLOSE BY THOSE OTHER THREADS. IT IS
979 : POSSIBLE WITH A MORE INVASIVE CHANGES TO FULLY ELIMINATE THIS
980 : RISK. */
981 0 : usleep( (useconds_t)40000 ); /* Give potentially concurrent users a chance to get their dying messages out */
982 0 : FD_COMPILER_MFENCE();
983 0 : FD_VOLATILE( fd_log_private_fileno ) = -1; /* Turn off the permanent log for concurrent users */
984 0 : FD_COMPILER_MFENCE();
985 0 : usleep( (useconds_t)40000 ); /* Give any concurrent log operations progress at turn off a chance to wrap */
986 0 : }
987 : # else
988 : FD_VOLATILE( fd_log_private_fileno ) = -1;
989 : # endif
990 :
991 573 : fsync( log_fileno );
992 573 : sync();
993 573 : fd_log_private_fprintf_0( STDERR_FILENO, "Log at \"%s\"\n", fd_log_private_path );
994 573 : }
995 2409 : } FD_ONCE_END;
996 3684 : }
997 :
998 : static void
999 : fd_log_private_sig_abort( int sig,
1000 : siginfo_t * info,
1001 0 : void * context ) {
1002 0 : (void)info; (void)context;
1003 :
1004 : /* Hopefully all out streams are idle now and we have flushed out
1005 : all non-logging activity ... log a backtrace */
1006 :
1007 : # if FD_HAS_BACKTRACE
1008 :
1009 : void * btrace[128];
1010 : int btrace_cnt = backtrace( btrace, 128 );
1011 :
1012 : int log_fileno = FD_VOLATILE_CONST( fd_log_private_fileno );
1013 : if( log_fileno!=-1 ) {
1014 : fd_log_private_fprintf_0( log_fileno, "Caught signal %i, backtrace:\n", sig );
1015 : backtrace_symbols_fd( btrace, btrace_cnt, log_fileno );
1016 : fsync( log_fileno );
1017 : }
1018 :
1019 : fd_log_private_fprintf_0( STDERR_FILENO, "\nCaught signal %i, backtrace:\n", sig );
1020 : backtrace_symbols_fd( btrace, btrace_cnt, STDERR_FILENO );
1021 : fsync( STDERR_FILENO );
1022 :
1023 : # else /* !FD_HAS_BACKTRACE */
1024 :
1025 0 : int log_fileno = FD_VOLATILE_CONST( fd_log_private_fileno );
1026 0 : if( log_fileno!=-1 ) fd_log_private_fprintf_0( log_fileno, "Caught signal %i.\n", sig );
1027 :
1028 0 : fd_log_private_fprintf_0( STDERR_FILENO, "\nCaught signal %i.\n", sig );
1029 :
1030 0 : # endif /* FD_HAS_BACKTRACE */
1031 :
1032 : /* Do final log cleanup */
1033 :
1034 0 : fd_log_private_cleanup();
1035 :
1036 0 : usleep( (useconds_t)1000000 ); /* Give some time to let streams drain */
1037 :
1038 0 : raise( sig ); /* Continue with the original handler (probably the default and that will produce the core) */
1039 0 : }
1040 :
1041 : static void
1042 47880 : fd_log_private_sig_trap( int sig ) {
1043 47880 : struct sigaction act[1];
1044 : /* FIXME: CONSIDER NOT OVERRIDING IF THE SIGNAL HANDLER HAS ALREADY
1045 : BEEN SET BY THE USER. */
1046 47880 : act->sa_sigaction = fd_log_private_sig_abort;
1047 47880 : if( sigemptyset( &act->sa_mask ) ) FD_LOG_ERR(( "sigempty set failed" ));
1048 47880 : act->sa_flags = (int)(SA_SIGINFO | SA_RESETHAND);
1049 47880 : if( sigaction( sig, act, NULL ) ) FD_LOG_ERR(( "unable to override signal %i", sig ));
1050 47880 : }
1051 :
1052 : static int
1053 : fd_log_private_open_path( int cmdline,
1054 2409 : char const * log_path ) {
1055 2409 : ulong log_path_sz = log_path ? (strlen( log_path )+1UL) : 0UL;
1056 :
1057 2409 : if( !log_path_sz ) { /* Use default log path */
1058 0 : char tag[ FD_LOG_WALLCLOCK_CSTR_BUF_SZ ];
1059 0 : fd_log_wallclock_cstr( fd_log_wallclock(), tag );
1060 0 : for( ulong b=0UL; tag[b]; b++ ) if( tag[b]==' ' || tag[b]=='-' || tag[b]=='.' || tag[b]==':' ) tag[b] = '_';
1061 0 : ulong len; fd_cstr_printf( fd_log_private_path, 1024UL, &len, "/tmp/fd-%i.%i.%i_%lu_%s_%s_%s",
1062 0 : FDCTL_MAJOR_VERSION, FDCTL_MINOR_VERSION, FDCTL_PATCH_VERSION,
1063 0 : fd_log_group_id(), fd_log_user(), fd_log_host(), tag );
1064 0 : if( len==1023UL ) { fd_log_private_fprintf_0( STDERR_FILENO, "default log path too long; unable to boot\n" ); exit(1); }
1065 0 : }
1066 2409 : else if( log_path_sz==1UL ) fd_log_private_path[0] = '\0'; /* User disabled */
1067 585 : else if( log_path_sz<=1024UL ) fd_memcpy( fd_log_private_path, log_path, log_path_sz ); /* User specified */
1068 0 : else { fd_log_private_fprintf_0( STDERR_FILENO, "log path too long; unable to boot\n" ); exit(1); } /* Invalid */
1069 :
1070 2409 : int log_fileno;
1071 2409 : if( fd_log_private_path[0]=='\0' ) {
1072 1824 : if( cmdline ) fd_log_private_fprintf_0( STDERR_FILENO, "--log-path \"\"\nNo log\n" );
1073 0 : else fd_log_private_fprintf_0( STDERR_FILENO, "No log\n" );
1074 1824 : log_fileno = -1;
1075 1824 : } else if( !strcmp( fd_log_private_path, "-" ) ) {
1076 12 : if( cmdline ) fd_log_private_fprintf_0( STDERR_FILENO, "--log-path \"-\"\nLog to stdout\n" );
1077 0 : else fd_log_private_fprintf_0( STDERR_FILENO, "Log to stdout\n" );
1078 12 : log_fileno = STDOUT_FILENO;
1079 573 : } else {
1080 573 : if( cmdline && !log_path_sz ) fd_log_private_fprintf_0( STDERR_FILENO, "--log-path not specified; using autogenerated path\n" );
1081 573 : log_fileno = open( fd_log_private_path, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH );
1082 573 : if( log_fileno==-1 ) {
1083 0 : fd_log_private_fprintf_0( STDERR_FILENO, "open failed (--log-path \"%s\"); unable to boot (%d-%s)\n", fd_log_private_path, errno, fd_io_strerror( errno ) );
1084 0 : exit(1);
1085 0 : }
1086 573 : fd_log_private_fprintf_0( STDERR_FILENO, "Log at \"%s\"\n", fd_log_private_path );
1087 573 : }
1088 2409 : return log_fileno;
1089 2409 : }
1090 :
1091 : void
1092 : fd_log_private_boot( int * pargc,
1093 2409 : char *** pargv ) {
1094 : //FD_LOG_INFO(( "fd_log: booting" )); /* Log not online yet */
1095 :
1096 2409 : char buf[ FD_LOG_NAME_MAX ];
1097 :
1098 2409 : fd_log_private_shared_lock = fd_log_private_shared_lock_local;
1099 :
1100 : /* Init our our application logical ids */
1101 : /* FIXME: CONSIDER EXPLICIT SPECIFICATION OF RANGE OF THREADS
1102 : INSTEAD OF ATOMIC COUNTER FROM BASE */
1103 :
1104 2409 : fd_log_private_app_id_set( fd_env_strip_cmdline_ulong( pargc, pargv, "--log-app-id", "FD_LOG_APP_ID", 0UL ) );
1105 :
1106 2409 : fd_log_private_app_set( fd_env_strip_cmdline_cstr( pargc, pargv, "--log-app", "FD_LOG_APP", NULL ) );
1107 :
1108 2409 : # if FD_HAS_THREADS
1109 2409 : fd_log_private_thread_id_ctr = fd_env_strip_cmdline_ulong( pargc, pargv, "--log-thread-id", "FD_LOG_THREAD_ID", 0UL );
1110 2409 : ulong thread_id = fd_log_private_thread_id_next();
1111 : # else
1112 : ulong thread_id = fd_env_strip_cmdline_ulong( pargc, pargv, "--log-thread-id", "FD_LOG_THREAD_ID", 0UL );
1113 : # endif
1114 2409 : fd_log_private_thread_id_set( thread_id );
1115 :
1116 2409 : fd_log_thread_set( fd_env_strip_cmdline_cstr( pargc, pargv, "--log-thread", "FD_LOG_THREAD", NULL ) );
1117 :
1118 : /* Init our application physical ids */
1119 : /* We ignore any user specified cpu-id in favor of the actual core
1120 : assigned by the host OS. We strip it from the command line so
1121 : downstream command line handling is identical from user's point of
1122 : view. */
1123 :
1124 2409 : fd_log_private_host_id_set( fd_env_strip_cmdline_ulong( pargc, pargv, "--log-host-id", "FD_LOG_HOST_ID", 0UL ) );
1125 :
1126 2409 : char const * host = fd_env_strip_cmdline_cstr( pargc, pargv, "--log-host", "FD_LOG_HOST", NULL );
1127 2409 : if( !host ) { if( !gethostname( buf, FD_LOG_NAME_MAX ) ) buf[ FD_LOG_NAME_MAX-1UL ] = '\0', host = buf; }
1128 2409 : fd_msan_unpoison( (void *)host, FD_LOG_NAME_MAX );
1129 2409 : fd_log_private_host_set( host );
1130 :
1131 2409 : fd_env_strip_cmdline_ulong( pargc, pargv, "--log-cpu-id", "FD_LOG_CPU_ID", 0UL ); /* FIXME: LOG IGNORING? */
1132 2409 : fd_log_private_cpu_id_set( fd_log_private_cpu_id_default() );
1133 :
1134 2409 : fd_log_cpu_set( fd_env_strip_cmdline_cstr( pargc, pargv, "--log-cpu", "FD_LOG_CPU", NULL ) );
1135 :
1136 : /* Init our thread group ids */
1137 : /* We ignore any user specified group id and tid in favor of the actual
1138 : group id and tid assigned by the host OS. We strip it from the
1139 : command line so downstream command line handling is identical from
1140 : user's point of view. */
1141 :
1142 2409 : fd_env_strip_cmdline_ulong( pargc, pargv, "--log-group-id", "FD_LOG_GROUP_ID", 0UL ); /* FIXME: LOG IGNORING? */
1143 2409 : pid_t pid = getpid();
1144 2409 : fd_log_private_group_id_set( fd_ulong_if( pid>(pid_t)0, (ulong)pid, ULONG_MAX ) );
1145 :
1146 2409 : char const * group = fd_env_strip_cmdline_cstr( pargc, pargv, "--log-group", "FD_LOG_GROUP", NULL );
1147 2409 : # if defined(__linux__)
1148 2409 : if( !group ) group = program_invocation_short_name;
1149 : # elif defined(__FreeBSD__)
1150 : if( !group ) group = getprogname();
1151 : # endif
1152 2409 : if( !group ) group = (pargc && pargv && (*pargc)>0) ? (*pargv)[0] : NULL;
1153 2409 : fd_log_private_group_set( group );
1154 :
1155 2409 : fd_env_strip_cmdline_ulong( pargc, pargv, "--log-tid", "FD_LOG_TID", 0UL ); /* FIXME: LOG IGNORING? */
1156 2409 : fd_log_private_tid_set( fd_log_private_tid_default() );
1157 :
1158 2409 : fd_env_strip_cmdline_ulong( pargc, pargv, "--log-user-id", "FD_LOG_USER_ID", 0UL ); /* FIXME: LOG IGNORING? */
1159 2409 : fd_log_private_user_id_set( fd_log_private_user_id_default() );
1160 :
1161 2409 : char const * user = fd_env_strip_cmdline_cstr( pargc, pargv, "--log-user", "FD_LOG_USER", NULL );
1162 2409 : if( !user ) user = getenv( "LOGNAME" );
1163 2409 : if( !user ) user = getlogin();
1164 2409 : fd_log_private_user_set( user );
1165 :
1166 : /* Configure the log */
1167 :
1168 2409 : fd_log_private_dedup = fd_env_strip_cmdline_int( pargc, pargv, "--log-dedup", "FD_LOG_DEDUP", 1 );
1169 :
1170 2409 : int colorize = 0;
1171 2409 : do {
1172 2409 : char const * cstr = fd_env_strip_cmdline_cstr( pargc, pargv, "--log-colorize", "FD_LOG_COLORIZE", NULL );
1173 2409 : if( cstr ) { colorize = fd_cstr_to_int( cstr ); break; }
1174 :
1175 2409 : cstr = fd_env_strip_cmdline_cstr( NULL, NULL, NULL, "COLORTERM", NULL );
1176 2409 : if( cstr && !strcmp( cstr, "truecolor" ) ) { colorize = 1; break; }
1177 :
1178 2409 : cstr = fd_env_strip_cmdline_cstr( NULL, NULL, NULL, "TERM", NULL );
1179 2409 : if( cstr && !strcmp( cstr, "xterm-256color" ) ) { colorize = 1; break; }
1180 :
1181 2409 : } while(0);
1182 0 : fd_log_colorize_set( colorize );
1183 :
1184 2409 : fd_log_level_logfile_set( fd_env_strip_cmdline_int( pargc, pargv, "--log-level-logfile", "FD_LOG_LEVEL_LOGFILE", 1 ) );
1185 2409 : fd_log_level_stderr_set ( fd_env_strip_cmdline_int( pargc, pargv, "--log-level-stderr", "FD_LOG_LEVEL_STDERR", 2 ) );
1186 2409 : fd_log_level_flush_set ( fd_env_strip_cmdline_int( pargc, pargv, "--log-level-flush", "FD_LOG_LEVEL_FLUSH", 3 ) );
1187 2409 : fd_log_level_core_set ( fd_env_strip_cmdline_int( pargc, pargv, "--log-level-core", "FD_LOG_LEVEL_CORE", 5 ) );
1188 :
1189 : /* Hook up signal handlers */
1190 :
1191 2409 : int log_backtrace = fd_env_strip_cmdline_int( pargc, pargv, "--log-backtrace", "FD_LOG_BACKTRACE", 1 );
1192 2409 : if( log_backtrace ) {
1193 :
1194 : # if FD_HAS_BACKTRACE
1195 : /* If libgcc isn't already linked into the program when a trapped
1196 : signal is received by an application, calls to backtrace and
1197 : backtrace_symbols_fd within the signal handler can silently
1198 : invoke the dynamic linker, which in turn can do silent async
1199 : signal unsafe behavior behind our back. We do dummy calls to
1200 : backtrace and backtrace_symbols_fd here to avoid dynamic linking
1201 : surprises in the signal handler. (Hat tip to runtimeverification
1202 : for finding this.) */
1203 :
1204 : void * btrace[128];
1205 : int btrace_cnt = backtrace( btrace, 128 );
1206 : int fd = open( "/dev/null", O_WRONLY | O_APPEND );
1207 : if( FD_UNLIKELY( fd==-1 ) )
1208 : fd_log_private_fprintf_0( STDERR_FILENO,
1209 : "open( \"/dev/null\", O_WRONLY | O_APPEND ) failed (%i-%s); attempting to continue\n",
1210 : errno, fd_io_strerror( errno ) );
1211 : else {
1212 : backtrace_symbols_fd( btrace, btrace_cnt, fd );
1213 : if( FD_UNLIKELY( close( fd ) ) )
1214 : fd_log_private_fprintf_0( STDERR_FILENO,
1215 : "close( \"/dev/null\" ) failed (%i-%s); attempting to continue\n",
1216 : errno, fd_io_strerror( errno ) );
1217 : }
1218 : # endif /* FD_HAS_BACKTRACE */
1219 :
1220 : /* This is all overridable POSIX sigs whose default behavior is to
1221 : abort the program. It will backtrace and then fallback to the
1222 : default behavior. */
1223 2394 : if( !fd_log_private_unclean_exit ) {
1224 2394 : fd_log_private_sig_trap( SIGABRT );
1225 2394 : fd_log_private_sig_trap( SIGALRM );
1226 2394 : fd_log_private_sig_trap( SIGFPE );
1227 2394 : fd_log_private_sig_trap( SIGHUP );
1228 2394 : fd_log_private_sig_trap( SIGILL );
1229 2394 : fd_log_private_sig_trap( SIGINT );
1230 2394 : fd_log_private_sig_trap( SIGQUIT );
1231 2394 : fd_log_private_sig_trap( SIGPIPE );
1232 2394 : fd_log_private_sig_trap( SIGSEGV );
1233 2394 : fd_log_private_sig_trap( SIGTERM );
1234 2394 : fd_log_private_sig_trap( SIGUSR1 );
1235 2394 : fd_log_private_sig_trap( SIGUSR2 );
1236 2394 : fd_log_private_sig_trap( SIGBUS );
1237 2394 : fd_log_private_sig_trap( SIGPOLL );
1238 2394 : fd_log_private_sig_trap( SIGPROF );
1239 2394 : fd_log_private_sig_trap( SIGSYS );
1240 2394 : fd_log_private_sig_trap( SIGTRAP );
1241 2394 : fd_log_private_sig_trap( SIGVTALRM );
1242 2394 : fd_log_private_sig_trap( SIGXCPU );
1243 2394 : fd_log_private_sig_trap( SIGXFSZ );
1244 2394 : }
1245 2394 : }
1246 :
1247 : /* Hook up the permanent log */
1248 2409 : char const * log_path = fd_env_strip_cmdline_cstr( pargc, pargv, "--log-path", "FD_LOG_PATH", NULL );
1249 2409 : FD_VOLATILE( fd_log_private_fileno ) = fd_log_private_open_path( 1, log_path );
1250 :
1251 2409 : if( !fd_log_private_unclean_exit ) {
1252 2409 : if( atexit( fd_log_private_cleanup ) ) { fd_log_private_fprintf_0( STDERR_FILENO, "atexit failed; unable to boot\n" ); exit(1); }
1253 2409 : }
1254 :
1255 : /* At this point, logging online */
1256 2409 : if( fd_log_build_info_sz>1UL ) FD_LOG_INFO(( "fd_log: build info:\n%s", fd_log_build_info ));
1257 0 : else FD_LOG_INFO(( "fd_log: build info not available" ));
1258 2409 : FD_LOG_INFO(( "fd_log: --log-path %s", fd_log_private_path ));
1259 2409 : FD_LOG_INFO(( "fd_log: --log-dedup %i", fd_log_private_dedup ));
1260 2409 : FD_LOG_INFO(( "fd_log: --log-colorize %i", fd_log_colorize() ));
1261 2409 : FD_LOG_INFO(( "fd_log: --log-level-logfile %i", fd_log_level_logfile() ));
1262 2409 : FD_LOG_INFO(( "fd_log: --log-level-stderr %i", fd_log_level_stderr() ));
1263 2409 : FD_LOG_INFO(( "fd_log: --log-level-flush %i", fd_log_level_flush() ));
1264 2409 : FD_LOG_INFO(( "fd_log: --log-level-core %i", fd_log_level_core() ));
1265 2409 : FD_LOG_INFO(( "fd_log: --log-app-id %lu", fd_log_app_id() ));
1266 2409 : FD_LOG_INFO(( "fd_log: --log-app %s", fd_log_app() ));
1267 2409 : FD_LOG_INFO(( "fd_log: --log-thread-id %lu", fd_log_thread_id() ));
1268 2409 : FD_LOG_INFO(( "fd_log: --log-thread %s", fd_log_thread() ));
1269 2409 : FD_LOG_INFO(( "fd_log: --log-host-id %lu", fd_log_host_id() ));
1270 2409 : FD_LOG_INFO(( "fd_log: --log-host %s", fd_log_host() ));
1271 2409 : FD_LOG_INFO(( "fd_log: --log-cpu-id %lu", fd_log_cpu_id() ));
1272 2409 : FD_LOG_INFO(( "fd_log: --log-cpu %s", fd_log_cpu() ));
1273 2409 : FD_LOG_INFO(( "fd_log: --log-group-id %lu", fd_log_group_id() ));
1274 2409 : FD_LOG_INFO(( "fd_log: --log-group %s", fd_log_group() ));
1275 2409 : FD_LOG_INFO(( "fd_log: --log-tid %lu", fd_log_tid() ));
1276 2409 : FD_LOG_INFO(( "fd_log: --log-user-id %lu", fd_log_user_id() ));
1277 2409 : FD_LOG_INFO(( "fd_log: --log-user %s", fd_log_user() ));
1278 :
1279 2409 : FD_LOG_INFO(( "fd_log: boot success" ));
1280 2409 : }
1281 :
1282 : void
1283 : fd_log_private_boot_custom( int * lock,
1284 : ulong app_id,
1285 : char const * app,
1286 : ulong thread_id,
1287 : char const * thread,
1288 : ulong host_id,
1289 : char const * host,
1290 : ulong cpu_id,
1291 : char const * cpu,
1292 : ulong group_id,
1293 : char const * group,
1294 : ulong tid,
1295 : ulong user_id,
1296 : char const * user,
1297 : int dedup,
1298 : int colorize,
1299 : int level_logfile,
1300 : int level_stderr,
1301 : int level_flush,
1302 : int level_core,
1303 : int log_fd,
1304 0 : char const * log_path ) {
1305 0 : fd_log_private_shared_lock = lock;
1306 :
1307 0 : fd_log_private_app_id_set( app_id );
1308 0 : fd_log_private_app_set( app );
1309 0 : fd_log_private_thread_id_set( thread_id );
1310 0 : fd_log_thread_set( thread );
1311 0 : fd_log_private_host_id_set( host_id );
1312 0 : fd_log_private_host_set( host );
1313 0 : fd_log_private_cpu_id_set( cpu_id );
1314 0 : fd_log_cpu_set( cpu );
1315 0 : fd_log_private_group_id_set( group_id );
1316 0 : fd_log_private_group_set( group );
1317 0 : fd_log_private_tid_set( tid );
1318 0 : fd_log_private_user_id_set( user_id );
1319 0 : fd_log_private_user_set( user );
1320 :
1321 0 : fd_log_private_dedup = dedup;
1322 0 : fd_log_colorize_set( colorize );
1323 :
1324 0 : fd_log_level_logfile_set( level_logfile );
1325 0 : fd_log_level_stderr_set ( level_stderr );
1326 0 : fd_log_level_flush_set ( level_flush );
1327 0 : fd_log_level_core_set ( level_core );
1328 :
1329 : /* Hook up the permanent log */
1330 0 : if( -1!=log_fd ) {
1331 : /* Log file descriptor was set up before boot, user wishes to log there directly. */
1332 0 : fd_log_private_path[0] = '\0';
1333 0 : FD_VOLATILE( fd_log_private_fileno ) = log_fd;
1334 0 : } else {
1335 0 : FD_VOLATILE( fd_log_private_fileno ) = fd_log_private_open_path( 0, log_path );
1336 0 : }
1337 :
1338 : /* At this point, logging online */
1339 0 : if( fd_log_build_info_sz>1UL ) FD_LOG_INFO(( "fd_log: build info:\n%s", fd_log_build_info ));
1340 0 : else FD_LOG_INFO(( "fd_log: build info not available" ));
1341 0 : FD_LOG_INFO(( "fd_log: --log-path %s", fd_log_private_path ));
1342 0 : FD_LOG_INFO(( "fd_log: --log-dedup %i", fd_log_private_dedup ));
1343 0 : FD_LOG_INFO(( "fd_log: --log-colorize %i", fd_log_colorize() ));
1344 0 : FD_LOG_INFO(( "fd_log: --log-level-logfile %i", fd_log_level_logfile() ));
1345 0 : FD_LOG_INFO(( "fd_log: --log-level-logfile %i", fd_log_level_logfile() ));
1346 0 : FD_LOG_INFO(( "fd_log: --log-level-stderr %i", fd_log_level_stderr() ));
1347 0 : FD_LOG_INFO(( "fd_log: --log-level-flush %i", fd_log_level_flush() ));
1348 0 : FD_LOG_INFO(( "fd_log: --log-level-core %i", fd_log_level_core() ));
1349 0 : FD_LOG_INFO(( "fd_log: --log-app-id %lu", fd_log_app_id() ));
1350 0 : FD_LOG_INFO(( "fd_log: --log-app %s", fd_log_app() ));
1351 0 : FD_LOG_INFO(( "fd_log: --log-thread-id %lu", fd_log_thread_id() ));
1352 0 : FD_LOG_INFO(( "fd_log: --log-thread %s", fd_log_thread() ));
1353 0 : FD_LOG_INFO(( "fd_log: --log-host-id %lu", fd_log_host_id() ));
1354 0 : FD_LOG_INFO(( "fd_log: --log-host %s", fd_log_host() ));
1355 0 : FD_LOG_INFO(( "fd_log: --log-cpu-id %lu", fd_log_cpu_id() ));
1356 0 : FD_LOG_INFO(( "fd_log: --log-cpu %s", fd_log_cpu() ));
1357 0 : FD_LOG_INFO(( "fd_log: --log-group-id %lu", fd_log_group_id() ));
1358 0 : FD_LOG_INFO(( "fd_log: --log-group %s", fd_log_group() ));
1359 0 : FD_LOG_INFO(( "fd_log: --log-tid %lu", fd_log_tid() ));
1360 0 : FD_LOG_INFO(( "fd_log: --log-user-id %lu", fd_log_user_id() ));
1361 0 : FD_LOG_INFO(( "fd_log: --log-user %s", fd_log_user() ));
1362 :
1363 0 : FD_LOG_INFO(( "fd_log: boot success" ));
1364 0 : }
1365 :
1366 : void
1367 1275 : fd_log_private_halt( void ) {
1368 1275 : FD_LOG_INFO(( "fd_log: halting" ));
1369 :
1370 1275 : fd_log_private_cleanup();
1371 :
1372 : /* At this point, log is offline */
1373 :
1374 1275 : fd_log_private_path[0] = '\0';
1375 : //fd_log_private_fileno = -1; /* Already handled by cleanup */
1376 1275 : fd_log_private_dedup = 0;
1377 :
1378 1275 : fd_log_private_level_core = 0;
1379 1275 : fd_log_private_level_flush = 0;
1380 1275 : fd_log_private_level_stderr = 0;
1381 1275 : fd_log_private_level_logfile = 0;
1382 1275 : fd_log_private_colorize = 0;
1383 :
1384 1275 : fd_log_private_clock_func = fd_log_wallclock_host;
1385 1275 : fd_log_private_clock_args = NULL;
1386 :
1387 1275 : fd_log_private_user[0] = '\0';
1388 1275 : fd_log_private_user_id_init = 0;
1389 1275 : fd_log_private_user_id = 0UL;
1390 1275 : fd_log_private_tid_init = 0;
1391 1275 : fd_log_private_tid = 0UL;
1392 1275 : fd_log_private_group[0] = '\0';
1393 1275 : fd_log_private_group_id = 0UL;
1394 :
1395 1275 : fd_log_private_cpu_init = 0;
1396 1275 : fd_log_private_cpu[0] = '\0';
1397 1275 : fd_log_private_cpu_id_init = 0;
1398 1275 : fd_log_private_cpu_id = 0UL;
1399 1275 : fd_log_private_host[0] = '\0';
1400 1275 : fd_log_private_host_id = 0UL;
1401 :
1402 1275 : fd_log_private_thread_init = 0;
1403 1275 : fd_log_private_thread[0] = '\0';
1404 1275 : fd_log_private_thread_id_init = 0;
1405 1275 : fd_log_private_thread_id = 0UL;
1406 1275 : # if FD_HAS_THREADS
1407 1275 : fd_log_private_thread_id_ctr = 0UL;
1408 1275 : # endif
1409 1275 : fd_log_private_app[0] = '\0';
1410 1275 : fd_log_private_app_id = 0UL;
1411 :
1412 1275 : if( FD_LIKELY( fd_log_private_shared_lock!=fd_log_private_shared_lock_local ) ) {
1413 : /* Note: the below will not unmap this in any clones that also
1414 : inherited this mapping unless they were cloned with CLONE_VM. In
1415 : cases like this, the caller is expected to handle the cleanup
1416 : semantics sanely (e.g. only have the parent do boot/halt and then
1417 : children only use log while parent has log booted). */
1418 0 : if( FD_UNLIKELY( munmap( fd_log_private_shared_lock, sizeof(int) ) ) )
1419 0 : fd_log_private_fprintf_0( STDERR_FILENO,
1420 0 : "munmap( fd_log_private_shared_lock, sizeof(int) ) failed (%i-%s); attempting to continue",
1421 0 : errno, fd_io_strerror( errno ) );
1422 0 : }
1423 1275 : fd_log_private_shared_lock = NULL;
1424 :
1425 : //FD_LOG_INFO(( "fd_log: halt success" )); /* Log not online anymore */
1426 1275 : }
1427 :
1428 : #include <sys/resource.h>
1429 :
1430 : ulong
1431 2409 : fd_log_private_main_stack_sz( void ) {
1432 :
1433 : /* We are extra paranoid about what rlimit returns and we don't trust
1434 : environments that claim an unlimited stack size (because it just
1435 : isn't unlimited ... even if rlimit says otherwise ... which it will
1436 : if a user tries to be clever with a "ulimit -s unlimited" ... e.g.
1437 : tile0's stack highest address is at 128 TiB-4KiB typically on
1438 : modern Linux and grows down while the text / data / heap grow up
1439 : from 0B ... so stack size is practically always going to be << 128
1440 : TiB irrespective of any getrlimit claim). TODO: It looks like
1441 : pthead_attr_getstack might be getrlimit based under the hood, so
1442 : maybe just use pthread_attr_getstack here too? */
1443 :
1444 2409 : struct rlimit rlim[1];
1445 2409 : int err = getrlimit( RLIMIT_STACK, rlim );
1446 2409 : if( FD_UNLIKELY( err ) ) {
1447 0 : FD_LOG_WARNING(( "fd_log: getrlimit failed (%i-%s)", errno, fd_io_strerror( errno ) ));
1448 0 : return 0UL;
1449 0 : }
1450 :
1451 2409 : ulong stack_sz = (ulong)rlim->rlim_cur;
1452 2409 : if( FD_UNLIKELY( (rlim->rlim_cur>rlim->rlim_max) | (rlim->rlim_max>RLIM_INFINITY ) |
1453 2409 : (rlim->rlim_cur==RLIM_INFINITY) | (rlim->rlim_cur!=(rlim_t)stack_sz) ) ) {
1454 0 : FD_LOG_WARNING(( "fd_log: unexpected stack limits (rlim_cur %lu, rlim_max %lu)",
1455 0 : (ulong)rlim->rlim_cur, (ulong)rlim->rlim_max ));
1456 0 : return 0UL;
1457 0 : }
1458 :
1459 2409 : return stack_sz;
1460 2409 : }
1461 :
1462 : /* When pthread_setstack is not used to explicitly set the memory region
1463 : for a new thread's stack, pthread_create will create a memory region
1464 : (using either the requested size or a default size). And, while
1465 : pthread allows us to set and get the size of the stack region it
1466 : creates and we can get a pointer into a thread's stack by just
1467 : declaring a stack variable in that thread and we obviously know where
1468 : a thread's stack is when we explicitly specify it to pthread create,
1469 : pthreads does not seem to provide a simple way to get the extents of
1470 : the stacks it creates.
1471 :
1472 : But the relationship between a pointer in the stack and the stack
1473 : extents is non-trival because pthreads will use some of the stack for
1474 : things like thread local storage (and it will not tell us how much
1475 : stack was used by that and this is practically only known after
1476 : linking is complete and then it is not simply exposed to the
1477 : application).
1478 :
1479 : Similar uncertainty applies to the first thread's stack. We can
1480 : learn how large the stack is and get a pointer into the stack via a
1481 : stack variable but we have no simple way to get the extents. And, in
1482 : this case on recent Linux, things like command line strings and
1483 : environment strings are typically allowed to consume up to 1/4 of
1484 : main's thread stack ... these are only known at application load
1485 : time. (There is the additional caveat that the main stack might be
1486 : dynamically allocated such that the address space reserved for it
1487 : might not be backed by memory yet.)
1488 :
1489 : But, if we want to do useful run-time stack diagnostics (e.g. alloca
1490 : bounds checking / stack overflow prevention / etc), having explicit
1491 : knowledge of a thread's stack extents is very useful. Hence the
1492 : below. It would be nice if there was portable and non-horrific way
1493 : to do this (an even more horrific way is trigger seg faults by
1494 : scanning for the guard pages and then recover from the seg fault via
1495 : a longjmp ... shivers). */
1496 :
1497 : void
1498 : fd_log_private_stack_discover( ulong stack_sz,
1499 : ulong * _stack0,
1500 2409 : ulong * _stack1 ) {
1501 :
1502 2409 : if( FD_UNLIKELY( !stack_sz ) ) {
1503 0 : *_stack0 = 0UL;
1504 0 : *_stack1 = 0UL;
1505 0 : return;
1506 0 : }
1507 :
1508 2409 : ulong stack0 = 0UL;
1509 2409 : ulong stack1 = 0UL;
1510 :
1511 : /* Create a variable on the caller's stack and scan the thread group's
1512 : memory map for the memory region holding the variable. That should
1513 : be the caller's stack. */
1514 :
1515 2409 : uchar stack_mem[1];
1516 2409 : FD_VOLATILE( stack_mem[0] ) = (uchar)1; /* Paranoia to make sure compiler puts this in stack */
1517 2409 : ulong stack_addr = (ulong)stack_mem;
1518 :
1519 2409 : int filefd;
1520 2409 : if( FD_UNLIKELY( ( filefd = open( "/proc/self/maps", O_RDONLY ) ) < 0 ) ) {
1521 0 : FD_LOG_WARNING(( "open( \"/proc/self/maps\" ) failed (%i-%s)", errno, fd_io_strerror( errno ) ));
1522 0 : *_stack0 = 0UL;
1523 0 : *_stack1 = 0UL;
1524 0 : return;
1525 0 : }
1526 :
1527 2409 : char filebuf[1<<12];
1528 2409 : ulong filelen = 0;
1529 2409 : char * p = filebuf;
1530 2409 : int found = 0;
1531 110922 : while( !found ) {
1532 :
1533 : /* Scan a line */
1534 :
1535 110922 : int full_line = 0;
1536 110922 : char * nextp;
1537 10780140 : for( nextp = p; nextp < filebuf + filelen; ) {
1538 10775322 : if( *(nextp++) == '\n' ) {
1539 106104 : full_line = 1;
1540 106104 : break;
1541 106104 : }
1542 10775322 : }
1543 110922 : if( !full_line ) {
1544 : /* We need to read more data. First shift the old data down. */
1545 4818 : filelen = (ulong)((filebuf + filelen) - p);
1546 4818 : if( filelen )
1547 0 : memmove( filebuf, p, filelen );
1548 4818 : p = filebuf;
1549 : /* Now read data */
1550 4818 : ssize_t tlen;
1551 4818 : if( FD_UNLIKELY( ( tlen = read( filefd, filebuf + filelen, sizeof(filebuf)-1U-filelen ) ) < 0 ) ) {
1552 0 : FD_LOG_WARNING(( "read( \"/proc/self/maps\" ) failed (%i-%s)", errno, fd_io_strerror( errno ) ));
1553 0 : break;
1554 0 : }
1555 4818 : if( tlen == 0 ) break; /* End of file */
1556 4818 : filelen += (ulong)tlen;
1557 4818 : filebuf[filelen] = '\0'; /* For sscanf */
1558 4818 : continue;
1559 4818 : }
1560 :
1561 106104 : ulong m0;
1562 106104 : ulong m1;
1563 106104 : int r = sscanf( p, "%lx-%lx", &m0, &m1 );
1564 106104 : p = nextp;
1565 106104 : if( FD_UNLIKELY( r !=2 ) ) continue;
1566 :
1567 : /* Test if the stack allocation is in the discovered region */
1568 :
1569 106104 : if( FD_UNLIKELY( (m0<=stack_addr) & (stack_addr<m1) ) ) {
1570 2409 : found = 1;
1571 2409 : ulong msz = m1 - m0;
1572 2409 : if( msz==stack_sz ) { /* Memory region matches expectations */
1573 0 : stack0 = m0;
1574 0 : stack1 = m1;
1575 2409 : } else if( ((fd_log_group_id()==fd_log_tid()) & (msz<stack_sz)) ) {
1576 : /* This is the main thread, which, on recent Linux, seems to
1577 : just reserve address space for main's stack at program
1578 : start up to the application stack size limits then uses
1579 : page faults to dynamically back the stack with DRAM as the
1580 : stack grows (which is awful for performance, jitter and
1581 : reliability ... sigh). This assumes stack grows down such
1582 : that m1 is the fixed value in this process. */
1583 2409 : stack0 = m1 - stack_sz;
1584 2409 : stack1 = m1;
1585 2409 : } else {
1586 0 : FD_LOG_WARNING(( "unexpected caller stack memory region size (got %lu bytes, expected %lu bytes)", msz, stack_sz ));
1587 : /* don't trust the discovered region */
1588 0 : }
1589 2409 : break;
1590 2409 : }
1591 :
1592 106104 : }
1593 2409 : if( !found )
1594 0 : FD_LOG_WARNING(( "unable to find stack size around address 0x%lx", stack_addr ));
1595 :
1596 2409 : close(filefd);
1597 :
1598 2409 : *_stack0 = stack0;
1599 2409 : *_stack1 = stack1;
1600 2409 : }
1601 :
1602 : #else
1603 : #error "Unknown FD_LOG_STYLE"
1604 : #endif
|