robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
10.6 KiB382 linesraw
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{
48  if (fname == NULL || fname[0] == NUL) {
49    return false;
50  }
51  FILE *log_file = fopen(fname, "a");
52  if (log_file == NULL) {
53    return false;
54  }
55  fclose(log_file);
56  return 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{
66  size_t size = sizeof(log_file_path);
67  expand_env("$" ENV_LOGFILE, log_file_path, (int)size - 1);
68  bool user_set = !strequal("$" ENV_LOGFILE, log_file_path);
69
70  if (!user_set
71      || log_file_path[0] == NUL
72      || os_isdir(log_file_path)
73      || !log_try_create(log_file_path)) {
74    if (user_set) {  // User-provided $NVIM_LOG_FILE.
75      // Used by _core/log.lua:check_log_file to validate logfile on startup.
76      os_setenv(ENV_LOGFILE_WANT, log_file_path, true);
77    }
78    // Make $XDG_STATE_HOME/logs if it does not exist.
79    char *loghome = concat_fnames_realloc(get_xdg_home(kXDGStateHome), "logs", true);
80    char *failed_dir = NULL;
81    int log_dir_failure = 0;
82    if (!os_isdir(loghome)) {
83      log_dir_failure = os_mkdir_recurse(loghome, 0700, &failed_dir, NULL);
84    }
85    XFREE_CLEAR(loghome);
86    // Invalid $NVIM_LOG_FILE or failed to expand; fall back to default.
87    char *defaultpath = stdpaths_user_state_subpath("logs/nvim.log", 0, true);
88    size_t len = xstrlcpy(log_file_path, defaultpath, size);
89    xfree(defaultpath);
90    // Fall back to $CWD/nvim.log
91    if (len >= size || !log_try_create(log_file_path)) {
92      if (!user_set) {  // Default fallback path.
93        // Used by _core/log.lua:check_log_file to validate logfile on startup.
94        os_setenv(ENV_LOGFILE_WANT, log_file_path, true);
95      }
96      len = xstrlcpy(log_file_path, "nvim.log", size);
97    }
98    // Fall back to stderr
99    if (len >= size || !log_try_create(log_file_path)) {
100      log_file_path[0] = NUL;
101      return;
102    }
103    os_setenv(ENV_LOGFILE, log_file_path, true);
104    if (log_dir_failure) {
105      WLOG("Failed to create directory %s for writing logs: %s",
106           failed_dir, os_strerror(log_dir_failure));
107    }
108    XFREE_CLEAR(failed_dir);
109  }
110}
111
112void log_init(void)
113{
114  uv_mutex_init_recursive(&mutex);
115  // AFTER init_homedir ("~", XDG) and set_init_1 (env vars). 22b52dd462e5 #11501
116  log_path_init();
117  did_log_init = true;
118}
119
120void log_lock(void)
121{
122  uv_mutex_lock(&mutex);
123}
124
125void log_unlock(void)
126{
127  uv_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,
141            const char *fmt, ...)
142  FUNC_ATTR_PRINTF(6, 7)
143{
144  static bool recursive = false;
145  static bool did_msg = false;  // Showed recursion message?
146  if (!did_log_init) {
147    g_stats.log_skip++;
148    // set_init_1 may try logging before we are ready. 6f27f5ef91b3 #10183
149    return false;
150  }
151
152  if (log_level < g_min_log_level) {
153    return 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.
159  if (entered_free_all_mem) {
160    fprintf(stderr, "FATAL: error in free_all_mem\n %s %s %d: ", context, func_name, line_num);
161    va_list args;
162    va_start(args, fmt);
163    vfprintf(stderr, fmt, args);
164    va_end(args);
165    if (eol) {
166      fprintf(stderr, "\n");
167    }
168    abort();
169  }
170#endif
171
172  log_lock();
173  if (recursive) {
174    if (!did_msg) {
175      did_msg = true;
176      msg_schedule_semsg("E5430: %s:%d: recursive log!", func_name ? func_name : context, line_num);
177    }
178    g_stats.log_skip++;
179    log_unlock();
180    return false;
181  }
182  recursive = true;
183  bool ret = false;
184  FILE *log_file = open_log_file();
185
186  va_list args;
187  va_start(args, fmt);
188  ret = v_do_log_to_file(log_file, log_level, context, func_name, line_num,
189                         eol, fmt, args);
190  va_end(args);
191
192  if (log_file != stderr && log_file != stdout) {
193    fclose(log_file);
194  }
195
196  recursive = false;
197  log_unlock();
198  return ret;
199}
200
201void log_uv_handles(void *loop)
202{
203  uv_loop_t *l = loop;
204  log_lock();
205  FILE *log_file = open_log_file();
206
207  uv_print_all_handles(l, log_file);
208
209  if (log_file != stderr && log_file != stdout) {
210    fclose(log_file);
211  }
212
213  log_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{
221  errno = 0;
222  if (log_file_path[0]) {
223    FILE *f = fopen(log_file_path, "a");
224    if (f != NULL) {
225      return 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
234  do_log_to_file(stderr, LOGLVL_ERR, NULL, __func__, __LINE__, true,
235                 "failed to open $" ENV_LOGFILE " (%s): %s",
236                 strerror(errno), log_file_path);
237  return 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{
243  void *trace[100];
244  int trace_size = backtrace(trace, ARRAY_SIZE(trace));
245
246  char exepath[MAXPATHL] = { 0 };
247  size_t exepathlen = MAXPATHL;
248  if (os_exepath(exepath, &exepathlen) != 0) {
249    abort();
250  }
251  assert(24 + exepathlen < IOSIZE);  // Must fit in `cmdbuf` below.
252
253  char cmdbuf[IOSIZE + (20 * ARRAY_SIZE(trace)) + MAXPATHL];
254  snprintf(cmdbuf, sizeof(cmdbuf), "addr2line -e %s -f -p", exepath);
255  for (int i = 1; i < trace_size; i++) {
256    char buf[20];  // 64-bit pointer 0xNNNNNNNNNNNNNNNN with leading space.
257    snprintf(buf, sizeof(buf), " %p", trace[i]);
258    xstrlcat(cmdbuf, buf, sizeof(cmdbuf));
259  }
260  // Now we have a command string like:
261  //    addr2line -e /path/to/exe -f -p 0x123 0x456 ...
262
263  do_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
265  FILE *fp = popen(cmdbuf, "r");
266  assert(fp);
267  char linebuf[IOSIZE];
268  while (fgets(linebuf, sizeof(linebuf) - 1, fp) != NULL) {
269    fprintf(log_file, "  %s", linebuf);
270  }
271  pclose(fp);
272
273  if (log_file != stderr && log_file != stdout) {
274    fclose(log_file);
275  }
276}
277
278void log_callstack(const char *const func_name, const int line_num)
279{
280  log_lock();
281  FILE *log_file = open_log_file();
282  log_callstack_to_file(log_file, func_name, line_num);
283  log_unlock();
284}
285#endif
286
287static bool do_log_to_file(FILE *log_file, int log_level, const char *context,
288                           const char *func_name, int line_num, bool eol, const char *fmt, ...)
289  FUNC_ATTR_PRINTF(7, 8)
290{
291  va_list args;
292  va_start(args, fmt);
293  bool ret = v_do_log_to_file(log_file, log_level, context, func_name,
294                              line_num, eol, fmt, args);
295  va_end(args);
296
297  return ret;
298}
299
300static bool v_do_log_to_file(FILE *log_file, int log_level, const char *context,
301                             const char *func_name, int line_num, bool eol, const char *fmt,
302                             va_list args)
303  FUNC_ATTR_PRINTF(7, 0)
304{
305  // Name of the Nvim instance that produced the log.
306  static char name[32] = { 0 };
307
308  static const char *log_levels[] = {
309    [LOGLVL_DBG] = "DBG",
310    [LOGLVL_INF] = "INF",
311    [LOGLVL_WRN] = "WRN",
312    [LOGLVL_ERR] = "ERR",
313  };
314  assert(log_level >= LOGLVL_DBG && log_level <= LOGLVL_ERR);
315
316  // Format the timestamp.
317  struct tm local_time;
318  if (os_localtime(&local_time) == NULL) {
319    return false;
320  }
321  char date_time[20];
322  if (strftime(date_time, sizeof(date_time), "%Y-%m-%dT%H:%M:%S", &local_time) == 0) {
323    return false;
324  }
325
326  int millis = 0;
327  uv_timeval64_t curtime;
328  if (uv_gettimeofday(&curtime) == 0) {
329    millis = (int)curtime.tv_usec / 1000;
330  }
331
332  bool 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
338  bool regen = ui || name[0] == NUL || name[0] == '?';
339
340  // Get a name for this Nvim instance.
341  // TODO(justinmk): expose this as v:name ?
342  if (regen) {
343    char parent_buf[MAXPATHL];
344    // Parent servername ($NVIM).
345    const char *parent = path_tail(os_getenv_buf(ENV_NVIM, parent_buf, sizeof(parent_buf)));
346    // Servername. Empty until starting=false.
347    const char *serv = path_tail(get_vim_var_str(VV_SEND_SERVER));
348    if (parent[0] != NUL) {
349      snprintf(name, sizeof(name), ui ? "ui/c/%s" : "c/%s", parent);  // "c/" = child of $NVIM.
350    } else if (serv[0] != NUL) {
351      snprintf(name, sizeof(name), ui ? "ui/%s" : "%s", serv);
352    } else {
353      int64_t pid = os_get_pid();
354      snprintf(name, sizeof(name), "%s.%-5" PRId64, ui ? "ui" : "?", pid);
355    }
356  }
357
358  // Print the log message.
359  int rv = (line_num == -1 || func_name == NULL)
360           ? fprintf(log_file, "%s %s.%03d %-10s %s",
361                     log_levels[log_level], date_time, millis, name,
362                     (context == NULL ? "?:" : context))
363           : fprintf(log_file, "%s %s.%03d %-10s %s%s:%d: ",
364                     log_levels[log_level], date_time, millis, name,
365                     (context == NULL ? "" : context),
366                     func_name, line_num);
367
368  if (rv < 0) {
369    return false;
370  }
371  if (vfprintf(log_file, fmt, args) < 0) {
372    return false;
373  }
374  if (eol) {
375    fputc('\n', log_file);
376  }
377  if (fflush(log_file) == EOF) {
378    return false;
379  }
380
381  return true;
382}