robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// 2// Log module 3// 4// How Linux printk() handles recursion, buffering, etc: 5// https://lwn.net/Articles/780556/ 6// 7 8#include <assert.h> 9#include <errno.h> 10#include <inttypes.h> 11#include <stdarg.h> 12#include <stdbool.h> 13#include <stdio.h> 14#include <stdlib.h> 15#include <string.h> 16#include <time.h> 17#include <uv.h> 18 19#include "auto/config.h" 20#include "nvim/ascii_defs.h" 21#include "nvim/eval/vars.h" 22#include "nvim/globals.h" 23#include "nvim/log.h" 24#include "nvim/memory.h" 25#include "nvim/message.h" 26#include "nvim/os/fs.h" 27#include "nvim/os/os.h" 28#include "nvim/os/os_defs.h" 29#include "nvim/os/stdpaths_defs.h" 30#include "nvim/os/time.h" 31#include "nvim/path.h" 32#include "nvim/ui_client.h" 33 34/// Cached location of the expanded log file path decided by log_path_init(). 35static char log_file_path [MAXPATHL + 1 ]= {0 }; 36 37static bool did_log_init = false; 38static uv_mutex_t mutex ; 39 40#include "log.c.generated.h" 41 42#ifdef HAVE_EXECINFO_BACKTRACE 43# include <execinfo.h> 44#endif 45 46static bool log_try_create (char * fname ) 47{ 48if (fname == NULL || fname [0 ]== NUL ) { 49return false; 50 } 51FILE * log_file = fopen (fname ,"a" ); 52if (log_file == NULL ) { 53return false; 54 } 55fclose (log_file ); 56return true; 57} 58 59/// Initializes the log file path and sets $NVIM_LOG_FILE if empty. 60/// 61/// Tries $NVIM_LOG_FILE, or falls back to $XDG_STATE_HOME/nvim/logs/nvim.log. 62/// Failed initialization indicates either a bug in expand_env() or both 63/// $NVIM_LOG_FILE and $HOME environment variables are undefined. 64static void log_path_init (void ) 65{ 66size_t size = sizeof (log_file_path ); 67expand_env ("$" ENV_LOGFILE ,log_file_path , (int )size - 1 ); 68bool user_set = !strequal ("$" ENV_LOGFILE ,log_file_path ); 69 70if (!user_set 71|| log_file_path [0 ]== NUL 72|| os_isdir (log_file_path ) 73|| !log_try_create (log_file_path )) { 74if (user_set ) {// User-provided $NVIM_LOG_FILE. 75// Used by _core/log.lua:check_log_file to validate logfile on startup. 76os_setenv (ENV_LOGFILE_WANT ,log_file_path , true); 77 } 78// Make $XDG_STATE_HOME/logs if it does not exist. 79char * loghome = concat_fnames_realloc (get_xdg_home (kXDGStateHome ),"logs" , true); 80char * failed_dir = NULL ; 81int log_dir_failure = 0 ; 82if (!os_isdir (loghome )) { 83log_dir_failure = os_mkdir_recurse (loghome ,0700 ,& failed_dir ,NULL ); 84 } 85XFREE_CLEAR (loghome ); 86// Invalid $NVIM_LOG_FILE or failed to expand; fall back to default. 87char * defaultpath = stdpaths_user_state_subpath ("logs/nvim.log" ,0 , true); 88size_t len = xstrlcpy (log_file_path ,defaultpath ,size ); 89xfree (defaultpath ); 90// Fall back to $CWD/nvim.log 91if (len >=size || !log_try_create (log_file_path )) { 92if (!user_set ) {// Default fallback path. 93// Used by _core/log.lua:check_log_file to validate logfile on startup. 94os_setenv (ENV_LOGFILE_WANT ,log_file_path , true); 95 } 96len = xstrlcpy (log_file_path ,"nvim.log" ,size ); 97 } 98// Fall back to stderr 99if (len >=size || !log_try_create (log_file_path )) { 100log_file_path [0 ]= NUL ; 101return ; 102 } 103os_setenv (ENV_LOGFILE ,log_file_path , true); 104if (log_dir_failure ) { 105WLOG ("Failed to create directory %s for writing logs: %s" , 106failed_dir ,os_strerror (log_dir_failure )); 107 } 108XFREE_CLEAR (failed_dir ); 109 } 110} 111 112void log_init (void ) 113{ 114uv_mutex_init_recursive (& mutex ); 115// AFTER init_homedir ("~", XDG) and set_init_1 (env vars). 22b52dd462e5 #11501 116log_path_init (); 117did_log_init = true; 118} 119 120void log_lock (void ) 121{ 122uv_mutex_lock (& mutex ); 123} 124 125void log_unlock (void ) 126{ 127uv_mutex_unlock (& mutex ); 128} 129 130/// Logs a message to $NVIM_LOG_FILE. 131/// 132/// @param log_level Log level (see log.h) 133/// @param context Description of a shared context or subsystem 134/// @param func_name Function name, or NULL 135/// @param line_num Source line number, or -1 136/// @param eol Append linefeed "\n" 137/// @param fmt printf-style format string 138/// 139/// @return true if log was emitted normally, false if failed or recursive 140bool logmsg (int log_level ,const char * context ,const char * func_name ,int line_num ,bool eol , 141const char * fmt , ...) 142FUNC_ATTR_PRINTF (6 ,7 ) 143{ 144static bool recursive = false; 145static bool did_msg = false;// Showed recursion message? 146if (!did_log_init ) { 147g_stats .log_skip ++ ; 148// set_init_1 may try logging before we are ready. 6f27f5ef91b3 #10183 149return false; 150 } 151 152if (log_level < g_min_log_level ) { 153return false; 154 } 155 156#ifdef EXITFREE 157// Logging after we've already started freeing all our memory will only cause 158// pain. We need access to VV_PROGPATH, homedir, etc. 159if (entered_free_all_mem ) { 160fprintf (stderr ,"FATAL: error in free_all_mem\n %s %s %d: " ,context ,func_name ,line_num ); 161va_list args ; 162va_start (args ,fmt ); 163vfprintf (stderr ,fmt ,args ); 164va_end (args ); 165if (eol ) { 166fprintf (stderr ,"\n" ); 167 } 168abort (); 169 } 170#endif 171 172log_lock (); 173if (recursive ) { 174if (!did_msg ) { 175did_msg = true; 176msg_schedule_semsg ("E5430: %s:%d: recursive log!" ,func_name ?func_name :context ,line_num ); 177 } 178g_stats .log_skip ++ ; 179log_unlock (); 180return false; 181 } 182recursive = true; 183bool ret = false; 184FILE * log_file = open_log_file (); 185 186va_list args ; 187va_start (args ,fmt ); 188ret = v_do_log_to_file (log_file ,log_level ,context ,func_name ,line_num , 189eol ,fmt ,args ); 190va_end (args ); 191 192if (log_file != stderr && log_file != stdout ) { 193fclose (log_file ); 194 } 195 196recursive = false; 197log_unlock (); 198return ret ; 199} 200 201void log_uv_handles (void * loop ) 202{ 203uv_loop_t * l = loop ; 204log_lock (); 205FILE * log_file = open_log_file (); 206 207uv_print_all_handles (l ,log_file ); 208 209if (log_file != stderr && log_file != stdout ) { 210fclose (log_file ); 211 } 212 213log_unlock (); 214} 215 216/// Open the log file for appending. 217/// 218/// @return Log file, or stderr on failure 219FILE * open_log_file (void ) 220{ 221errno = 0 ; 222if (log_file_path [0 ]) { 223FILE * f = fopen (log_file_path ,"a" ); 224if (f != NULL ) { 225return f ; 226 } 227 } 228 229// May happen if: 230// - fopen() failed 231// - LOG() is called before log_init() 232// - Directory does not exist 233// - File is not writable 234do_log_to_file (stderr ,LOGLVL_ERR ,NULL ,__func__ ,__LINE__ , true, 235"failed to open $" ENV_LOGFILE " (%s): %s" , 236strerror (errno ),log_file_path ); 237return stderr ; 238} 239 240#ifdef HAVE_EXECINFO_BACKTRACE 241void log_callstack_to_file (FILE * log_file ,const char * const func_name ,const int line_num ) 242{ 243void * trace [100 ]; 244int trace_size = backtrace (trace ,ARRAY_SIZE (trace )); 245 246char exepath [MAXPATHL ]= {0 }; 247size_t exepathlen = MAXPATHL ; 248if (os_exepath (exepath ,& exepathlen )!= 0 ) { 249abort (); 250 } 251assert (24 + exepathlen < IOSIZE );// Must fit in `cmdbuf` below. 252 253char cmdbuf [IOSIZE + (20 * ARRAY_SIZE (trace ))+ MAXPATHL ]; 254snprintf (cmdbuf ,sizeof (cmdbuf ),"addr2line -e %s -f -p" ,exepath ); 255for (int i = 1 ;i < trace_size ;i ++ ) { 256char buf [20 ];// 64-bit pointer 0xNNNNNNNNNNNNNNNN with leading space. 257snprintf (buf ,sizeof (buf )," %p" ,trace [i ]); 258xstrlcat (cmdbuf ,buf ,sizeof (cmdbuf )); 259 } 260// Now we have a command string like: 261// addr2line -e /path/to/exe -f -p 0x123 0x456 ... 262 263do_log_to_file (log_file ,LOGLVL_DBG ,NULL ,func_name ,line_num , true,"trace:" ); 264// NOLINTNEXTLINE(bugprone-command-processor): this function is never called by default 265FILE * fp = popen (cmdbuf ,"r" ); 266assert (fp ); 267char linebuf [IOSIZE ]; 268while (fgets (linebuf ,sizeof (linebuf )- 1 ,fp )!= NULL ) { 269fprintf (log_file ," %s" ,linebuf ); 270 } 271pclose (fp ); 272 273if (log_file != stderr && log_file != stdout ) { 274fclose (log_file ); 275 } 276} 277 278void log_callstack (const char * const func_name ,const int line_num ) 279{ 280log_lock (); 281FILE * log_file = open_log_file (); 282log_callstack_to_file (log_file ,func_name ,line_num ); 283log_unlock (); 284} 285#endif 286 287static bool do_log_to_file (FILE * log_file ,int log_level ,const char * context , 288const char * func_name ,int line_num ,bool eol ,const char * fmt , ...) 289FUNC_ATTR_PRINTF (7 ,8 ) 290{ 291va_list args ; 292va_start (args ,fmt ); 293bool ret = v_do_log_to_file (log_file ,log_level ,context ,func_name , 294line_num ,eol ,fmt ,args ); 295va_end (args ); 296 297return ret ; 298} 299 300static bool v_do_log_to_file (FILE * log_file ,int log_level ,const char * context , 301const char * func_name ,int line_num ,bool eol ,const char * fmt , 302va_list args ) 303FUNC_ATTR_PRINTF (7 ,0 ) 304{ 305// Name of the Nvim instance that produced the log. 306static char name [32 ]= {0 }; 307 308static const char * log_levels []= { 309 [LOGLVL_DBG ]= "DBG" , 310 [LOGLVL_INF ]= "INF" , 311 [LOGLVL_WRN ]= "WRN" , 312 [LOGLVL_ERR ]= "ERR" , 313 }; 314assert (log_level >=LOGLVL_DBG && log_level <=LOGLVL_ERR ); 315 316// Format the timestamp. 317struct tm local_time ; 318if (os_localtime (& local_time )== NULL ) { 319return false; 320 } 321char date_time [20 ]; 322if (strftime (date_time ,sizeof (date_time ),"%Y-%m-%dT%H:%M:%S" ,& local_time )== 0 ) { 323return false; 324 } 325 326int millis = 0 ; 327uv_timeval64_t curtime ; 328if (uv_gettimeofday (& curtime )== 0 ) { 329millis = (int )curtime .tv_usec /1000 ; 330 } 331 332bool ui = !!ui_client_channel_id ;// Running as a UI client (--remote-ui). 333 334// Regenerate the name when: 335// - UI client (to ensure "ui" is in the name) 336// - not set yet 337// - no v:servername yet 338bool regen = ui || name [0 ]== NUL || name [0 ]== '?' ; 339 340// Get a name for this Nvim instance. 341// TODO(justinmk): expose this as v:name ? 342if (regen ) { 343char parent_buf [MAXPATHL ]; 344// Parent servername ($NVIM). 345const char * parent = path_tail (os_getenv_buf (ENV_NVIM ,parent_buf ,sizeof (parent_buf ))); 346// Servername. Empty until starting=false. 347const char * serv = path_tail (get_vim_var_str (VV_SEND_SERVER )); 348if (parent [0 ]!= NUL ) { 349snprintf (name ,sizeof (name ),ui ?"ui/c/%s" :"c/%s" ,parent );// "c/" = child of $NVIM. 350 }else if (serv [0 ]!= NUL ) { 351snprintf (name ,sizeof (name ),ui ?"ui/%s" :"%s" ,serv ); 352 }else { 353int64_t pid = os_get_pid (); 354snprintf (name ,sizeof (name ),"%s.%-5" PRId64 ,ui ?"ui" :"?" ,pid ); 355 } 356 } 357 358// Print the log message. 359int rv = (line_num == -1 || func_name == NULL ) 360 ?fprintf (log_file ,"%s %s.%03d %-10s %s" , 361log_levels [log_level ],date_time ,millis ,name , 362 (context == NULL ?"?:" :context )) 363 :fprintf (log_file ,"%s %s.%03d %-10s %s%s:%d: " , 364log_levels [log_level ],date_time ,millis ,name , 365 (context == NULL ?"" :context ), 366func_name ,line_num ); 367 368if (rv < 0 ) { 369return false; 370 } 371if (vfprintf (log_file ,fmt ,args )< 0 ) { 372return false; 373 } 374if (eol ) { 375fputc ('\n' ,log_file ); 376 } 377if (fflush (log_file )== EOF ) { 378return false; 379 } 380 381return true; 382}