dte test coverage


Directory: ./
File: src/main.c
Date: 2025-09-07 23:01:39
Exec Total Coverage
Lines: 186 316 58.9%
Functions: 12 15 80.0%
Branches: 85 203 41.9%

Line Branch Exec Source
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <stdbool.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/stat.h>
8 #include <sys/utsname.h>
9 #include <unistd.h>
10 #include "block.h"
11 #include "buffer.h"
12 #include "command/error.h"
13 #include "commands.h"
14 #include "compat.h"
15 #include "config.h"
16 #include "editor.h"
17 #include "encoding.h"
18 #include "exec.h"
19 #include "file-history.h"
20 #include "frame.h"
21 #include "history.h"
22 #include "load-save.h"
23 #include "move.h"
24 #include "msg.h"
25 #include "palette.h"
26 #include "search.h"
27 #include "showkey.h"
28 #include "signals.h"
29 #include "syntax/state.h"
30 #include "syntax/syntax.h"
31 #include "tag.h"
32 #include "terminal/mode.h"
33 #include "terminal/output.h"
34 #include "terminal/terminal.h"
35 #include "trace.h"
36 #include "ui.h"
37 #include "util/debug.h"
38 #include "util/exitcode.h"
39 #include "util/fd.h"
40 #include "util/log.h"
41 #include "util/macros.h"
42 #include "util/path.h"
43 #include "util/progname.h"
44 #include "util/str-util.h"
45 #include "util/string-view.h"
46 #include "util/string.h"
47 #include "util/strtonum.h"
48 #include "util/xmalloc.h"
49 #include "util/xreadwrite.h"
50 #include "version.h"
51 #include "view.h"
52 #include "window.h"
53
54 // This serves a similar purpose to ui_end(), but using only minimal program
55 // state, so as to be more suitable for use in handle_fatal_signal() and/or
56 // as a sanitizer callback
57 static void cleanup_handler(void)
58 {
59 if (child_controls_terminal) {
60 return;
61 }
62
63 static const char reset[] = "\033c"; // ECMA-48 RIS (reset to initial state)
64 (void)!xwrite_all(STDOUT_FILENO, reset, sizeof(reset) - 1);
65 term_cooked();
66 }
67
68 1 static ExitCode list_builtin_configs(void)
69 {
70 1 String str = dump_builtin_configs();
71 1 BUG_ON(!str.buffer);
72 1 ExitCode e = ec_write_stdout(str.buffer, str.len);
73 1 string_free(&str);
74 1 return e;
75 }
76
77 2 static ExitCode dump_builtin_config(const char *name)
78 {
79 2 const BuiltinConfig *cfg = get_builtin_config(name);
80
2/2
✓ Branch 0 (2→3) taken 1 times.
✓ Branch 1 (2→4) taken 1 times.
2 if (!cfg) {
81 1 return ec_usage_error("no built-in config with name '%s'", name);
82 }
83 1 return ec_write_stdout(cfg->text.data, cfg->text.length);
84 }
85
86 2 static ExitCode lint_syntax(const char *filename, SyntaxLoadFlags flags)
87 {
88 2 EditorState *e = init_editor_state(getenv("HOME"), getenv("DTE_HOME"));
89 2 e->err.print_to_stderr = true;
90 2 BUG_ON(e->status != EDITOR_INITIALIZING);
91
92 2 const Syntax *syntax = load_syntax_file(e, filename, flags | SYN_MUST_EXIST);
93
3/4
✓ Branch 0 (8→9) taken 1 times.
✓ Branch 1 (8→13) taken 1 times.
✓ Branch 2 (9→10) taken 1 times.
✗ Branch 3 (9→13) not taken.
2 bool ok = syntax && e->err.nr_errors == 0;
94
95 1 if (ok) {
96 1 const size_t n = syntax->states.count;
97
1/2
✓ Branch 0 (10→11) taken 1 times.
✗ Branch 1 (10→12) not taken.
1 const char *plural = (n == 1) ? "" : "s";
98 1 const char *name = syntax->name;
99 1 printf("OK: loaded syntax '%s' with %zu state%s\n", name, n, plural);
100 }
101
102 2 free_editor_state(e);
103
2/2
✓ Branch 0 (14→15) taken 1 times.
✓ Branch 1 (14→16) taken 1 times.
2 return ok ? EC_OK : EC_DATA_ERROR;
104 }
105
106 1 static ExitCode init_std_fds(int std_fds[2])
107 {
108 1 FILE *streams[3] = {stdin, stdout, stderr};
109
1/2
✓ Branch 0 (27→3) taken 1 times.
✗ Branch 1 (27→28) not taken.
1 for (int i = 0; i < ARRAYLEN(streams); i++) {
110
1/2
✗ Branch 0 (4→5) not taken.
✓ Branch 1 (4→6) taken 1 times.
1 if (is_controlling_tty(i)) {
111 continue;
112 }
113
114
1/2
✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→8) taken 1 times.
1 if (i < STDERR_FILENO) {
115 // Try to create a duplicate fd for redirected stdin/stdout; to
116 // allow reading/writing after freopen(3) closes the original
117 1 int fd = fcntl(i, F_DUPFD_CLOEXEC, 3);
118
1/4
✗ Branch 0 (9→10) not taken.
✓ Branch 1 (9→12) taken 1 times.
✗ Branch 2 (10→11) not taken.
✗ Branch 3 (10→12) not taken.
1 if (fd == -1 && errno != EBADF) {
119 return ec_error("fcntl", EC_OS_ERROR);
120 }
121 1 std_fds[i] = fd;
122 }
123
124 // Ensure standard streams are connected to the terminal during
125 // editor operation, regardless of how they were redirected
126
2/4
✓ Branch 0 (12→13) taken 1 times.
✗ Branch 1 (12→14) not taken.
✓ Branch 2 (15→16) taken 1 times.
✗ Branch 3 (15→19) not taken.
2 if (unlikely(!freopen("/dev/tty", i ? "w" : "r", streams[i]))) {
127 1 const char *err = strerror(errno);
128 1 fprintf(stderr, "Failed to open /dev/tty for fd %d: %s\n", i, err);
129 1 return EC_IO_ERROR;
130 }
131
132 int new_fd = fileno(streams[i]);
133 if (unlikely(new_fd != i)) {
134 // This should never happen in a single-threaded program.
135 // freopen() should call fclose() followed by open() and
136 // POSIX requires a successful call to open() to return the
137 // lowest available file descriptor.
138 fprintf(stderr, "freopen() changed fd from %d to %d\n", i, new_fd);
139 return EC_OS_ERROR;
140 }
141
142 if (unlikely(!is_controlling_tty(new_fd))) {
143 return ec_error("tcgetpgrp", EC_OS_ERROR);
144 }
145 }
146
147 return EC_OK;
148 }
149
150 8 static ExitCode init_std_fds_headless(int std_fds[2])
151 {
152 8 FILE *streams[] = {stdin, stdout};
153
2/2
✓ Branch 0 (16→3) taken 16 times.
✓ Branch 1 (16→17) taken 8 times.
24 for (int i = 0; i < ARRAYLEN(streams); i++) {
154
1/2
✓ Branch 0 (4→5) taken 16 times.
✗ Branch 1 (4→10) not taken.
16 if (!isatty(i)) {
155 // Try to duplicate redirected stdin/stdout, as described
156 // in init_std_fds()
157 16 int fd = fcntl(i, F_DUPFD_CLOEXEC, 3);
158
1/4
✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→9) taken 16 times.
✗ Branch 2 (7→8) not taken.
✗ Branch 3 (7→9) not taken.
16 if (fd == -1 && errno != EBADF) {
159 return ec_error("fcntl", EC_OS_ERROR);
160 }
161 16 std_fds[i] = fd;
162 }
163 // Always reopen stdin and stdout as /dev/null, regardless of
164 // whether they were duplicated above
165
3/4
✓ Branch 0 (10→11) taken 8 times.
✓ Branch 1 (10→12) taken 8 times.
✗ Branch 2 (13→14) not taken.
✓ Branch 3 (13→15) taken 16 times.
24 if (!freopen("/dev/null", i ? "w" : "r", streams[i])) {
166 return ec_error("freopen", EC_IO_ERROR);
167 }
168 }
169
170
1/2
✗ Branch 0 (18→19) not taken.
✓ Branch 1 (18→22) taken 8 times.
8 if (!fd_is_valid(STDERR_FILENO)) {
171 // If FD 2 isn't valid (e.g. because it was closed), point it
172 // to /dev/null to ensure open(3) doesn't allocate it to other
173 // opened files
174 if (!freopen("/dev/null", "w", stderr)) {
175 return ec_error("freopen", EC_IO_ERROR);
176 }
177 }
178
179 return EC_OK;
180 }
181
182 // Open special Buffers for duplicated stdin and/or stdout FDs, as created
183 // by init_std_fds()
184 8 static Buffer *init_std_buffer(EditorState *e, int fds[2])
185 {
186 8 const char *name = NULL;
187 8 Buffer *buffer = NULL;
188
189
1/2
✓ Branch 0 (2→3) taken 8 times.
✗ Branch 1 (2→10) not taken.
8 if (fds[STDIN_FILENO] >= 3) {
190 8 buffer = buffer_new(&e->buffers, &e->options, encoding_from_type(UTF8));
191
1/2
✓ Branch 0 (6→7) taken 8 times.
✗ Branch 1 (6→8) not taken.
8 if (read_blocks(buffer, fds[STDIN_FILENO], false)) {
192 8 name = "(stdin)";
193 8 buffer->temporary = true;
194 } else {
195 error_msg(&e->err, "Unable to read redirected stdin");
196 buffer_remove_unlock_and_free(&e->buffers, buffer, &e->err, &e->locks_ctx);
197 buffer = NULL;
198 }
199 }
200
201
1/2
✓ Branch 0 (10→11) taken 8 times.
✗ Branch 1 (10→14) not taken.
8 if (fds[STDOUT_FILENO] >= 3) {
202
1/2
✗ Branch 0 (11→12) not taken.
✓ Branch 1 (11→13) taken 8 times.
8 if (!buffer) {
203 buffer = open_empty_buffer(&e->buffers, &e->options);
204 name = "(stdout)";
205 } else {
206 name = "(stdin|stdout)";
207 }
208 8 buffer->stdout_buffer = true;
209 8 buffer->temporary = true;
210 }
211
212 8 BUG_ON(!buffer != !name);
213
1/2
✓ Branch 0 (16→17) taken 8 times.
✗ Branch 1 (16→19) not taken.
8 if (name) {
214 8 buffer_set_display_filename(buffer, xstrdup(name));
215 }
216
217 8 return buffer;
218 }
219
220 // Write the contents of the special `stdout` Buffer (as created by
221 // init_std_buffer()) to `stdout` and free its remaining allocations
222 8 static SystemErrno buffer_write_blocks_and_free(Buffer *buffer, int fd)
223 {
224 8 BUG_ON(!buffer->stdout_buffer);
225 8 const Block *blk;
226 8 SystemErrno err = 0;
227
228
2/2
✓ Branch 0 (9→5) taken 8 times.
✓ Branch 1 (9→10) taken 8 times.
16 block_for_each(blk, &buffer->blocks) {
229
1/2
✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→8) taken 8 times.
8 if (xwrite_all(fd, blk->data, blk->size) < 0) {
230 err = errno;
231 break;
232 }
233 }
234
235 // Other allocations for `buffer` should have already been freed
236 // by buffer_unlock_and_free()
237 8 free_blocks(buffer);
238 8 free(buffer);
239 8 return err;
240 }
241
242 static void init_trace_logging(LogLevel level)
243 {
244 if (!TRACE_LOGGING_ENABLED || level < LOG_LEVEL_TRACE) {
245 return;
246 }
247
248 const char *flagstr = xgetenv("DTE_LOG_TRACE");
249 if (!flagstr) {
250 LOG_NOTICE("DTE_LOG_LEVEL=trace used with no effect; DTE_LOG_TRACE also needed");
251 return;
252 }
253
254 TraceLoggingFlags flags = trace_flags_from_str(flagstr);
255 if (!flags) {
256 LOG_WARNING("no known flags in DTE_LOG_TRACE='%s'", flagstr);
257 return;
258 }
259
260 LOG_INFO("DTE_LOG_TRACE=%s", flagstr);
261 set_trace_logging_flags(flags);
262 }
263
264 8 static ExitCode init_logging(void)
265 {
266 8 const char *filename = xgetenv("DTE_LOG");
267
1/2
✗ Branch 0 (3→4) not taken.
✓ Branch 1 (3→23) taken 8 times.
8 if (!filename) {
268 return EC_OK;
269 }
270
271 const char *req_level_str = getenv("DTE_LOG_LEVEL");
272 LogLevel req_level = log_level_from_str(req_level_str);
273 if (req_level == LOG_LEVEL_NONE) {
274 return EC_OK;
275 }
276 if (req_level == LOG_LEVEL_INVALID) {
277 return ec_usage_error("invalid $DTE_LOG_LEVEL value: '%s'", req_level_str);
278 }
279
280 const char *no_color = xgetenv("NO_COLOR"); // https://no-color.org/
281 LogLevel got_level = log_open(filename, req_level, !no_color);
282 if (got_level == LOG_LEVEL_NONE) {
283 const char *err = strerror(errno);
284 fprintf(stderr, "Failed to open $DTE_LOG (%s): %s\n", filename, err);
285 return EC_IO_ERROR;
286 }
287
288 const char *got_level_str = log_level_to_str(got_level);
289 if (got_level != req_level) {
290 const char *r = req_level_str;
291 const char *g = got_level_str;
292 LOG_WARNING("log level '%s' unavailable; falling back to '%s'", r, g);
293 }
294
295 LOG_INFO("logging to '%s' (level: %s)", filename, got_level_str);
296
297 if (no_color) {
298 LOG_INFO("log colors disabled ($NO_COLOR)");
299 }
300
301 init_trace_logging(got_level);
302 return EC_OK;
303 }
304
305 8 static void read_history_files(EditorState *e, bool headless)
306 {
307 8 const size_t size_limit = 64u << 20; // 64 MiB
308 8 const char *dir = e->user_config_dir;
309 8 ErrorBuffer *ebuf = &e->err;
310
311
1/2
✗ Branch 0 (2→3) not taken.
✓ Branch 1 (2→5) taken 8 times.
8 if (e->flags & EFLAG_FILE_HIST) {
312 char *path = path_join(dir, "file-history");
313 file_history_load(&e->file_history, ebuf, path, size_limit);
314 }
315
316
1/2
✗ Branch 0 (5→6) not taken.
✓ Branch 1 (5→8) taken 8 times.
8 if (e->flags & EFLAG_CMD_HIST) {
317 char *path = path_join(dir, "command-history");
318 history_load(&e->command_history, ebuf, path, size_limit);
319 }
320
321
1/2
✗ Branch 0 (8→9) not taken.
✓ Branch 1 (8→13) taken 8 times.
8 if (e->flags & EFLAG_SEARCH_HIST) {
322 char *path = path_join(dir, "search-history");
323 history_load(&e->search_history, ebuf, path, size_limit);
324 if (e->search_history.last) {
325 search_set_regexp(&e->search, e->search_history.last->text);
326 }
327 }
328
329 // There's not much sense in saving history for headless sessions, but
330 // we do still load it (above, if applicable), to make it available to
331 // e.g. `exec -i command`
332
1/2
✓ Branch 0 (13→14) taken 8 times.
✗ Branch 1 (13→15) not taken.
8 if (headless) {
333 8 e->flags &= ~EFLAG_ALL_HIST;
334 }
335 8 }
336
337 8 static void write_history_files(EditorState *e)
338 {
339 8 EditorFlags flags = e->flags;
340
1/2
✗ Branch 0 (2→3) not taken.
✓ Branch 1 (2→4) taken 8 times.
8 if (flags & EFLAG_CMD_HIST) {
341 history_save(&e->command_history, &e->err);
342 }
343
1/2
✗ Branch 0 (4→5) not taken.
✓ Branch 1 (4→6) taken 8 times.
8 if (flags & EFLAG_SEARCH_HIST) {
344 history_save(&e->search_history, &e->err);
345 }
346
1/2
✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→8) taken 8 times.
8 if (flags & EFLAG_FILE_HIST) {
347 file_history_save(&e->file_history, &e->err);
348 }
349 8 }
350
351 static void lookup_tags (
352 EditorState *e,
353 const char *tags[],
354 size_t nr_tags,
355 View *closeable_default_view
356 ) {
357 if (nr_tags == 0 || !load_tag_file(&e->tagfile, &e->err)) {
358 return;
359 }
360
361 MessageList *msgs = &e->messages[e->options.msg_tag];
362 clear_messages(msgs);
363
364 for (size_t i = 0; i < nr_tags; i++) {
365 StringView tagname = strview(tags[i]);
366 tag_lookup(&e->tagfile, msgs, &e->err, tagname, NULL);
367 }
368
369 if (
370 activate_current_message(msgs, e->window)
371 && closeable_default_view
372 && e->window->views.count >= 2
373 ) {
374 // Close the default/empty buffer, if another buffer is opened
375 // for a tag (and no commands were executed via `-c` or `-C`)
376 view_remove(closeable_default_view);
377 }
378 }
379
380 8 static View *open_initial_buffers (
381 EditorState *e,
382 Buffer *std_buffer,
383 char *args[],
384 size_t nr_args
385 ) {
386 // Open files specified as command-line arguments
387 8 Window *window = e->window;
388
1/2
✗ Branch 0 (20→3) not taken.
✓ Branch 1 (20→21) taken 8 times.
8 for (size_t i = 0, line = 0, col = 0; i < nr_args; i++) {
389 const char *arg = args[i];
390 if (line == 0 && *arg == '+' && str_to_filepos(arg + 1, &line, &col)) {
391 // +line[:col] argument parsed (affects next argument)
392 continue;
393 }
394
395 char *alloc = NULL;
396 if (line == 0) {
397 StringView path = parse_file_line_col(arg, &line, &col);
398 if (path.length) {
399 // file:line[:col] argument parsed; extract `file` and use below
400 arg = alloc = xstrcut(path.data, path.length);
401 }
402 }
403
404 View *view = window_open_buffer(window, arg, false, NULL);
405 free(alloc);
406 if (view && line) {
407 set_view(view);
408 move_to_filepos(view, line, col);
409 }
410
411 line = 0;
412 }
413
414
1/2
✓ Branch 0 (21→22) taken 8 times.
✗ Branch 1 (21→23) not taken.
8 if (std_buffer) {
415 // Open special buffer for redirected stdin/stdout
416 8 window_add_buffer(window, std_buffer);
417 }
418
419 // Open default buffer, if none were opened above
420
1/2
✗ Branch 0 (23→24) not taken.
✓ Branch 1 (23→25) taken 8 times.
8 View *dview = window->views.count ? NULL : window_open_empty_buffer(window);
421
422 8 set_view(window_get_first_view(window));
423 8 return dview;
424 }
425
426 static const char copyright[] =
427 "dte " VERSION "\n"
428 "(C) 2013-2025 Craig Barnes\n"
429 "(C) 2010-2015 Timo Hirvonen\n"
430 "This program is free software; you can redistribute and/or modify\n"
431 "it under the terms of the GNU General Public License version 2\n"
432 "<https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.\n"
433 "There is NO WARRANTY, to the extent permitted by law.\n";
434
435 static const char usage[] =
436 "Usage: %s [OPTIONS] [[+LINE] FILE]...\n\n"
437 "Options:\n"
438 " -c COMMAND Run COMMAND after editor starts\n"
439 " -t CTAG Jump to source location of CTAG\n"
440 " -r RCFILE Read user config from RCFILE instead of ~/.dte/rc\n"
441 " -s FILE Validate dte-syntax commands in FILE and exit\n"
442 " -b NAME Print built-in config matching NAME and exit\n"
443 " -B Print list of built-in config names and exit\n"
444 " -H Don't load or save history files\n"
445 " -R Don't read user config file\n"
446 " -K Start editor in \"showkey\" mode\n"
447 " -h Display help summary and exit\n"
448 " -V Display version number and exit\n"
449 "\n";
450
451 23 int main(int argc, char *argv[])
452 {
453 23 static const char optstring[] = "hBHKPRVZC:Q:S:b:c:t:r:s:";
454 23 const char *rc = NULL;
455 23 const char *commands[8];
456 23 const char *tags[8];
457 23 size_t nr_commands = 0;
458 23 size_t nr_tags = 0;
459 23 EditorFlags histflags = EFLAG_ALL_HIST;
460 23 bool headless = false;
461 23 bool read_rc = true;
462 23 bool explicit_term_query_level = false;
463 23 unsigned int terminal_query_level = 1;
464
465
2/2
✓ Branch 0 (27→3) taken 60 times.
✓ Branch 1 (27→28) taken 9 times.
69 for (int ch; (ch = getopt(argc, argv, optstring)) != -1; ) {
466
15/17
✓ Branch 0 (3→4) taken 14 times.
✓ Branch 1 (3→5) taken 5 times.
✓ Branch 2 (3→8) taken 9 times.
✓ Branch 3 (3→11) taken 2 times.
✓ Branch 4 (3→14) taken 3 times.
✓ Branch 5 (3→15) taken 7 times.
✓ Branch 6 (3→16) taken 2 times.
✓ Branch 7 (3→17) taken 1 times.
✓ Branch 8 (3→18) taken 1 times.
✗ Branch 9 (3→19) not taken.
✓ Branch 10 (3→20) taken 1 times.
✓ Branch 11 (3→21) taken 2 times.
✗ Branch 12 (3→22) not taken.
✓ Branch 13 (3→23) taken 1 times.
✓ Branch 14 (3→24) taken 1 times.
✓ Branch 15 (3→25) taken 9 times.
✓ Branch 16 (3→121) taken 2 times.
60 switch (ch) {
467 14 case 'C':
468 14 headless = true;
469 // Fallthrough
470 19 case 'c':
471
2/2
✓ Branch 0 (5→6) taken 1 times.
✓ Branch 1 (5→7) taken 18 times.
19 if (unlikely(nr_commands >= ARRAYLEN(commands))) {
472 1 return ec_usage_error("too many -c or -C options used");
473 }
474 18 commands[nr_commands++] = optarg;
475 18 break;
476 9 case 't':
477
2/2
✓ Branch 0 (8→9) taken 1 times.
✓ Branch 1 (8→10) taken 8 times.
9 if (unlikely(nr_tags >= ARRAYLEN(tags))) {
478 1 return ec_usage_error("too many -t options used");
479 }
480 8 tags[nr_tags++] = optarg;
481 8 break;
482 2 case 'Q':
483
2/2
✓ Branch 0 (12→13) taken 1 times.
✓ Branch 1 (12→25) taken 1 times.
2 if (!str_to_uint(optarg, &terminal_query_level)) {
484 1 return ec_usage_error("invalid argument for -Q: '%s'", optarg);
485 }
486 explicit_term_query_level = true;
487 break;
488 case 'H': histflags = 0; break;
489 3 case 'r': rc = optarg; break;
490 7 case 'R': read_rc = false; break;
491 2 case 'b': return dump_builtin_config(optarg);
492 1 case 'B': return list_builtin_configs();
493 1 case 'h': return ec_printf_ok(usage, progname(argc, argv, "dte"));
494 case 'K': return showkey_loop(terminal_query_level);
495 1 case 'P': return print_256_color_palette();
496 2 case 's': return lint_syntax(optarg, 0);
497 case 'S': return lint_syntax(optarg, SYN_LINT);
498 1 case 'V': return ec_write_stdout(copyright, sizeof(copyright));
499 1 case 'Z': return ec_printf_ok("features:%s\n", buildvar_string);
500 default: return EC_USAGE_ERROR;
501 }
502 }
503
504 // stdio(3) fds must be handled before calling init_logging(), otherwise
505 // an invocation like e.g. `DTE_LOG=/dev/pts/2 dte 0<&-` could cause the
506 // logging fd to be opened as STDIN_FILENO
507 9 int std_fds[2] = {-1, -1};
508
2/2
✓ Branch 0 (28→29) taken 8 times.
✓ Branch 1 (28→30) taken 1 times.
9 ExitCode r = headless ? init_std_fds_headless(std_fds) : init_std_fds(std_fds);
509
2/2
✓ Branch 0 (31→32) taken 8 times.
✓ Branch 1 (31→34) taken 1 times.
9 r = r ? r : init_logging();
510
1/2
✗ Branch 0 (33→34) not taken.
✓ Branch 1 (33→35) taken 8 times.
8 if (unlikely(r)) {
511 1 return r;
512 }
513
514 8 struct utsname u;
515
1/2
✓ Branch 0 (36→37) taken 8 times.
✗ Branch 1 (36→42) not taken.
8 if (likely(uname(&u) >= 0)) {
516 8 LOG_INFO("system: %s/%s %s", u.sysname, u.machine, u.release);
517
1/2
✗ Branch 0 (38→39) not taken.
✓ Branch 1 (38→43) taken 8 times.
8 if (
518 !headless
519 && !explicit_term_query_level
520 && str_has_suffix(u.release, "-WSL2")
521 ) {
522 // There appears to be an issue on WSL2 where the DA1 query
523 // response is interpreted as pasted text and then inserted
524 // into the buffer at startup. For now, we simply disable
525 // querying entirely on that platform, until the problem
526 // can be investigated.
527 LOG_NOTICE("WSL2 detected; disabling all terminal queries");
528 terminal_query_level = 0;
529 }
530 } else {
531 LOG_ERRNO("uname");
532 }
533
534 8 LOG_INFO("dte version: " VERSION);
535 8 LOG_INFO("build vars:%s", buildvar_string);
536
537
1/2
✓ Branch 0 (45→46) taken 8 times.
✗ Branch 1 (45→47) not taken.
8 if (headless) {
538 8 set_signal_dispositions_headless();
539 } else {
540 set_basic_signal_dispositions();
541 }
542
543 // Note that we don't unset EFLAG_HEADLESS in e->flags until later
544 // (regardless of whether -C was used), because the terminal isn't
545 // properly initialized yet and we don't want commands running via
546 // -c or -C -interacting with it
547 8 EditorState *e = init_editor_state(getenv("HOME"), getenv("DTE_HOME"));
548
549 8 Terminal *term = &e->terminal;
550
1/2
✗ Branch 0 (51→52) not taken.
✓ Branch 1 (51→55) taken 8 times.
8 if (!headless) {
551 term_init(term, getenv("TERM"), getenv("COLORTERM"));
552 }
553
554 8 e->err.print_to_stderr = true;
555 8 Buffer *std_buffer = init_std_buffer(e, std_fds);
556
2/4
✓ Branch 0 (56→57) taken 8 times.
✗ Branch 1 (56→58) not taken.
✗ Branch 2 (57→58) not taken.
✓ Branch 3 (57→59) taken 8 times.
8 bool have_stdout_buffer = std_buffer && std_buffer->stdout_buffer;
557
558 // Create this early (needed if "lock-files" is true)
559 8 const char *cfgdir = e->user_config_dir;
560 8 BUG_ON(!cfgdir);
561
3/4
✓ Branch 0 (62→63) taken 7 times.
✓ Branch 1 (62→67) taken 1 times.
✗ Branch 2 (63→64) not taken.
✓ Branch 3 (63→67) taken 7 times.
8 if (mkdir(cfgdir, 0755) != 0 && errno != EEXIST) {
562 error_msg(&e->err, "Error creating %s: %s", cfgdir, strerror(errno));
563 histflags = 0;
564 e->options.lock_files = false;
565 }
566
567 8 e->flags |= histflags;
568 8 exec_rc_files(e, rc, read_rc);
569 8 read_history_files(e, headless);
570
571 8 e->window = new_window(e);
572 8 e->root_frame = new_root_frame(e->window);
573 8 e->status = EDITOR_RUNNING;
574 8 e->err.print_to_stderr = headless;
575 8 View *dview = open_initial_buffers(e, std_buffer, argv + optind, argc - optind);
576 8 e->err.print_to_stderr = true;
577
578
1/2
✗ Branch 0 (72→73) not taken.
✓ Branch 1 (72→76) taken 8 times.
8 if (!headless) {
579 // This is done before executing `-c` commands, so that the
580 // `exec` command can set $LINES and $COLUMNS appropriately
581 update_screen_size(term, e->root_frame);
582 }
583
584
2/2
✓ Branch 0 (77→74) taken 8 times.
✓ Branch 1 (77→78) taken 8 times.
16 for (size_t i = 0; i < nr_commands; i++) {
585 8 handle_normal_command(e, commands[i], false);
586 }
587
588 8 bool fast_exit = e->status != EDITOR_RUNNING;
589
1/2
✓ Branch 0 (78→79) taken 8 times.
✗ Branch 1 (78→80) not taken.
8 if (headless || fast_exit) {
590 // Headless mode implicitly exits after commands have finished
591 // running. We may also exit here (without drawing the UI,
592 // emitting terminal queries or entering main_loop()) if a `-c`
593 // command has already quit the editor. This prevents commands
594 // like e.g. `dte -HR -cquit` from emitting terminal queries
595 // and exiting before the responses have been read (which would
596 // typically cause the parent shell process to read them
597 // instead).
598 8 goto exit;
599 }
600
601 e->err.print_to_stderr = false;
602 lookup_tags(e, tags, nr_tags, nr_commands ? NULL : dview);
603
604 set_fatal_error_cleanup_handler(cleanup_handler);
605 set_fatal_signal_handlers();
606 set_sigwinch_handler();
607
608 bool init = term_mode_init();
609 if (unlikely(!init || !term_raw())) {
610 e->status = ec_error(init ? "tcsetattr" : "tcgetattr", EC_IO_ERROR);
611 fast_exit = true;
612 goto exit;
613 }
614
615 if (e->err.stderr_errors_printed) {
616 // Display "press any key to continue" prompt for stderr errors
617 any_key(term, e->options.esc_timeout);
618 clear_error(&e->err);
619 }
620
621 // Enable main_loop() iteration timing if $DTE_LOG_TIMING is set
622 // and logging is enabled. In theory, this could be controlled by
623 // `TraceLoggingFlags`, but trace logging is only enabled in debug
624 // builds, whereas latency timing is most useful in release builds.
625 bool timing = log_level_enabled(LOG_LEVEL_INFO) && xgetenv("DTE_LOG_TIMING");
626
627 e->flags &= ~EFLAG_HEADLESS; // See comment for init_editor_state() call above
628 ui_first_start(e, terminal_query_level);
629 main_loop(e, timing);
630 term_restore_title(term);
631
632 /*
633 * This is normally followed immediately by term_cooked() in other
634 * contexts, but in this case we want to switch back to cooked mode
635 * as late as possible. On underpowered machines, unlocking files and
636 * writing history may take some time. If cooked mode were switched
637 * to here it'd leave a window of time where we've switched back to
638 * the normal screen buffer and reset the termios ECHO flag while
639 * still being the foreground process, which would cause any input
640 * to be echoed to the terminal (before the shell takes over again
641 * and prints its prompt).
642 */
643 ui_end(&e->terminal, true);
644
645 8 exit:
646 8 e->err.print_to_stderr = true;
647 8 frame_remove(e, e->root_frame); // Unlock files and add to file history
648 8 write_history_files(e);
649 8 int exit_code = MAX(e->status, EDITOR_EXIT_OK);
650
651
1/2
✗ Branch 0 (108→109) not taken.
✓ Branch 1 (108→110) taken 8 times.
8 if (!headless && !fast_exit) {
652 // This must be done before calling buffer_write_blocks_and_free(),
653 // since output modes need to be restored to get proper line ending
654 // translation and std_fds[STDOUT_FILENO] may be a pipe to the
655 // terminal
656 term_cooked();
657 }
658
659
1/2
✓ Branch 0 (110→111) taken 8 times.
✗ Branch 1 (110→117) not taken.
8 if (have_stdout_buffer) {
660 8 SystemErrno err = buffer_write_blocks_and_free(std_buffer, std_fds[STDOUT_FILENO]);
661
1/2
✗ Branch 0 (112→113) not taken.
✓ Branch 1 (112→117) taken 8 times.
8 if (err != 0) {
662 error_msg(&e->err, "failed to write (stdout) buffer: %s", strerror(err));
663 if (exit_code == EDITOR_EXIT_OK) {
664 exit_code = EC_IO_ERROR;
665 }
666 }
667 }
668
669 8 if (DEBUG >= 1 || ASAN_ENABLED || xgetenv(ld_preload_env_var())) {
670 // Only free EditorState in debug builds or when a library/tool is
671 // checking for leaks; otherwise it's pointless to do so immediately
672 // before exiting
673 8 free_editor_state(e);
674 }
675
676 8 LOG_INFO("exiting with status %d", exit_code);
677 8 log_close();
678 8 return exit_code;
679 }
680