1 /* I/O, string, cleanup, and other random utilities for GDB.
2 Copyright (C) 1986-2024 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #ifndef UTILS_H
20 #define UTILS_H
21
22 #include "exceptions.h"
23 #include "gdbsupport/array-view.h"
24 #include "gdbsupport/function-view.h"
25 #include "gdbsupport/scoped_restore.h"
26 #include <chrono>
27
28 struct completion_match_for_lcd;
29 class compiled_regex;
30
31 /* String utilities. */
32
33 extern bool sevenbit_strings;
34
35 /* Modes of operation for strncmp_iw_with_mode. */
36
37 enum class strncmp_iw_mode
38 {
39 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
40 differences in whitespace. Returns 0 if they match, non-zero if
41 they don't (slightly different than strcmp()'s range of return
42 values). */
43 NORMAL,
44
45 /* Like NORMAL, but also apply the strcmp_iw hack. I.e.,
46 string1=="FOO(PARAMS)" matches string2=="FOO". */
47 MATCH_PARAMS,
48 };
49
50 /* Helper for strcmp_iw and strncmp_iw. Exported so that languages
51 can implement both NORMAL and MATCH_PARAMS variants in a single
52 function and defer part of the work to strncmp_iw_with_mode.
53
54 LANGUAGE is used to implement some context-sensitive
55 language-specific comparisons. For example, for C++,
56 "string1=operator()" should not match "string2=operator" even in
57 MATCH_PARAMS mode.
58
59 MATCH_FOR_LCD is passed down so that the function can mark parts of
60 the symbol name as ignored for completion matching purposes (e.g.,
61 to handle abi tags). If IGNORE_TEMPLATE_PARAMS is true, all template
62 parameter lists will be ignored when language is C++. */
63
64 extern int strncmp_iw_with_mode
65 (const char *string1, const char *string2, size_t string2_len,
66 strncmp_iw_mode mode, enum language language,
67 completion_match_for_lcd *match_for_lcd = NULL,
68 bool ignore_template_params = false);
69
70 /* Do a strncmp() type operation on STRING1 and STRING2, ignoring any
71 differences in whitespace. STRING2_LEN is STRING2's length.
72 Returns 0 if STRING1 matches STRING2_LEN characters of STRING2,
73 non-zero otherwise (slightly different than strncmp()'s range of
74 return values). Note: passes language_minimal to
75 strncmp_iw_with_mode, and should therefore be avoided if a more
76 suitable language is available. */
77 extern int strncmp_iw (const char *string1, const char *string2,
78 size_t string2_len);
79
80 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
81 differences in whitespace. Returns 0 if they match, non-zero if
82 they don't (slightly different than strcmp()'s range of return
83 values).
84
85 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
86 This "feature" is useful when searching for matching C++ function
87 names (such as if the user types 'break FOO', where FOO is a
88 mangled C++ function).
89
90 Note: passes language_minimal to strncmp_iw_with_mode, and should
91 therefore be avoided if a more suitable language is available. */
92 extern int strcmp_iw (const char *string1, const char *string2);
93
94 extern int strcmp_iw_ordered (const char *, const char *);
95
96 /* Reset the prompt_for_continue clock. */
97 void reset_prompt_for_continue_wait_time (void);
98 /* Return the time spent in prompt_for_continue. */
99 std::chrono::steady_clock::duration get_prompt_for_continue_wait_time ();
100
101 /* Parsing utilities. */
102
103 extern int parse_pid_to_attach (const char *args);
104
105 extern int parse_escape (struct gdbarch *, const char **);
106
107
108 /* Cleanup utilities. */
109
110 extern void init_page_info (void);
111
112 /* Temporarily set BATCH_FLAG and the associated unlimited terminal size.
113 Restore when destroyed. */
114
115 struct set_batch_flag_and_restore_page_info
116 {
117 public:
118
119 set_batch_flag_and_restore_page_info ();
120 ~set_batch_flag_and_restore_page_info ();
121
122 DISABLE_COPY_AND_ASSIGN (set_batch_flag_and_restore_page_info);
123
124 private:
125
126 /* Note that this doesn't use scoped_restore, because it's important
127 to control the ordering of operations in the destruction, and it
128 was simpler to avoid introducing a new ad hoc class. */
129 unsigned m_save_lines_per_page;
130 unsigned m_save_chars_per_line;
131 int m_save_batch_flag;
132 };
133
134
135 /* Path utilities. */
136
137 extern int gdb_filename_fnmatch (const char *pattern, const char *string,
138 int flags);
139
140 extern void substitute_path_component (char **stringp, const char *from,
141 const char *to);
142
143 std::string ldirname (const char *filename);
144
145 extern int count_path_elements (const char *path);
146
147 extern const char *strip_leading_path_elements (const char *path, int n);
148
149 /* GDB output, ui_file utilities. */
150
151 struct ui_file;
152
153 extern int query (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
154 extern int nquery (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
155 extern int yquery (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
156
157 extern void begin_line (void);
158
159 extern void wrap_here (int);
160
161 extern void reinitialize_more_filter (void);
162
163 /* Return the number of characters in a line. */
164
165 extern int get_chars_per_line ();
166
167 extern bool pagination_enabled;
168
169 /* A flag indicating whether to timestamp debugging messages. */
170 extern bool debug_timestamp;
171
172 extern struct ui_file **current_ui_gdb_stdout_ptr (void);
173 extern struct ui_file **current_ui_gdb_stdin_ptr (void);
174 extern struct ui_file **current_ui_gdb_stderr_ptr (void);
175 extern struct ui_file **current_ui_gdb_stdlog_ptr (void);
176
177 /* Flush STREAM. */
178 extern void gdb_flush (struct ui_file *stream);
179
180 /* The current top level's ui_file streams. */
181
182 /* Normal results */
183 #define gdb_stdout (*current_ui_gdb_stdout_ptr ())
184 /* Input stream */
185 #define gdb_stdin (*current_ui_gdb_stdin_ptr ())
186 /* Serious error notifications. This bypasses the pager, if one is in
187 use. */
188 #define gdb_stderr (*current_ui_gdb_stderr_ptr ())
189 /* Log/debug/trace messages that bypasses the pager, if one is in
190 use. */
191 #define gdb_stdlog (*current_ui_gdb_stdlog_ptr ())
192
193 /* Truly global ui_file streams. These are all defined in main.c. */
194
195 /* Target output that should bypass the pager, if one is in use. */
196 extern struct ui_file *gdb_stdtarg;
197 extern struct ui_file *gdb_stdtargin;
198
199 /* Set the screen dimensions to WIDTH and HEIGHT. */
200
201 extern void set_screen_width_and_height (int width, int height);
202
203 /* Generic stdio-like operations. */
204
205 extern void gdb_puts (const char *, struct ui_file *);
206
207 extern void gdb_puts (const std::string &s, ui_file *stream);
208
209 extern void gdb_putc (int c, struct ui_file *);
210
211 extern void gdb_putc (int c);
212
213 extern void gdb_puts (const char *);
214
215 extern void puts_tabular (char *string, int width, int right);
216
217 /* Generic printf-like operations. As an extension over plain
218 printf, these support some GDB-specific format specifiers.
219 Particularly useful here are the styling formatters: '%p[', '%p]'
220 and '%ps'. See ui_out::message for details. */
221
222 extern void gdb_vprintf (const char *, va_list) ATTRIBUTE_PRINTF (1, 0);
223
224 extern void gdb_vprintf (struct ui_file *, const char *, va_list)
225 ATTRIBUTE_PRINTF (2, 0);
226
227 extern void gdb_printf (struct ui_file *, const char *, ...)
228 ATTRIBUTE_PRINTF (2, 3);
229
230 extern void gdb_printf (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
231
232 extern void printf_unfiltered (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
233
234 extern void print_spaces (int, struct ui_file *);
235
236 extern const char *n_spaces (int);
237
238 /* Return nonzero if filtered printing is initialized. */
239 extern int filtered_printing_initialized (void);
240
241 /* Like gdb_printf, but styles the output according to STYLE,
242 when appropriate. */
243
244 extern void fprintf_styled (struct ui_file *stream,
245 const ui_file_style &style,
246 const char *fmt,
247 ...)
248 ATTRIBUTE_PRINTF (3, 4);
249
250 /* Like gdb_puts, but styles the output according to STYLE, when
251 appropriate. */
252
253 extern void fputs_styled (const char *linebuffer,
254 const ui_file_style &style,
255 struct ui_file *stream);
256
257 /* Like fputs_styled, but uses highlight_style to highlight the
258 parts of STR that match HIGHLIGHT. */
259
260 extern void fputs_highlighted (const char *str, const compiled_regex &highlight,
261 struct ui_file *stream);
262
263 /* Convert CORE_ADDR to string in platform-specific manner.
264 This is usually formatted similar to 0x%lx. */
265 extern const char *paddress (struct gdbarch *gdbarch, CORE_ADDR addr);
266
267 /* Return a string representation in hexadecimal notation of ADDRESS,
268 which is suitable for printing. */
269
270 extern const char *print_core_address (struct gdbarch *gdbarch,
271 CORE_ADDR address);
272
273 extern CORE_ADDR string_to_core_addr (const char *my_string);
274
275 extern void fprintf_symbol (struct ui_file *, const char *,
276 enum language, int);
277
278 extern void perror_warning_with_name (const char *string);
279
280 /* Issue a warning formatted as '<filename>: <explanation>', where
281 <filename> is FILENAME with filename styling applied. As such, don't
282 pass anything more than a filename in this string. The <explanation>
283 is a string returned from calling safe_strerror(SAVED_ERRNO). */
284
285 extern void warning_filename_and_errno (const char *filename,
286 int saved_errno);
287
288 /* Warnings and error messages. */
289
290 extern void (*deprecated_error_begin_hook) (void);
291
292 /* Message to be printed before the warning message, when a warning occurs. */
293
294 extern const char *warning_pre_print;
295
296 extern void demangler_vwarning (const char *file, int line,
297 const char *, va_list ap)
298 ATTRIBUTE_PRINTF (3, 0);
299
300 extern void demangler_warning (const char *file, int line,
301 const char *, ...) ATTRIBUTE_PRINTF (3, 4);
302
303
304 /* Misc. utilities. */
305
306 #ifdef HAVE_WAITPID
307 extern pid_t wait_to_die_with_timeout (pid_t pid, int *status, int timeout);
308 #endif
309
310 extern int myread (int, char *, int);
311
312 /* Resource limits used by getrlimit and setrlimit. */
313
314 enum resource_limit_kind
315 {
316 LIMIT_CUR,
317 LIMIT_MAX
318 };
319
320 /* Check whether GDB will be able to dump core using the dump_core
321 function. Returns zero if GDB cannot or should not dump core.
322 If LIMIT_KIND is LIMIT_CUR the user's soft limit will be respected.
323 If LIMIT_KIND is LIMIT_MAX only the hard limit will be respected. */
324
325 extern int can_dump_core (enum resource_limit_kind limit_kind);
326
327 /* Print a warning that we cannot dump core. */
328
329 extern void warn_cant_dump_core (const char *reason);
330
331 /* Dump core trying to increase the core soft limit to hard limit
332 first. */
333
334 extern void dump_core (void);
335
336 /* Copy NBITS bits from SOURCE to DEST starting at the given bit
337 offsets. Use the bit order as specified by BITS_BIG_ENDIAN.
338 Source and destination buffers must not overlap. */
339
340 extern void copy_bitwise (gdb_byte *dest, ULONGEST dest_offset,
341 const gdb_byte *source, ULONGEST source_offset,
342 ULONGEST nbits, int bits_big_endian);
343
344 /* When readline decides that the terminal cannot auto-wrap lines, it reduces
345 the width of the reported screen width by 1. This variable indicates
346 whether that's the case or not, allowing us to add it back where
347 necessary. See _rl_term_autowrap in readline/terminal.c. */
348
349 extern int readline_hidden_cols;
350
351 /* Assign VAL to LVAL, and set CHANGED to true if the assignment changed
352 LVAL. */
353
354 template<typename T>
355 void
assign_set_if_changed(T & lval,const T & val,bool & changed)356 assign_set_if_changed (T &lval, const T &val, bool &changed)
357 {
358 if (lval == val)
359 return;
360
361 lval = val;
362 changed = true;
363 }
364
365 /* Assign VAL to LVAL, and return true if the assignment changed LVAL. */
366
367 template<typename T>
368 bool
assign_return_if_changed(T & lval,const T & val)369 assign_return_if_changed (T &lval, const T &val)
370 {
371 if (lval == val)
372 return false;
373
374 lval = val;
375 return true;
376 }
377
378 /* A class that can be used to intercept warnings. A class is used
379 here, rather than a gdb::function_view because it proved difficult
380 to use a function view in conjunction with ATTRIBUTE_PRINTF in a
381 way that would satisfy all compilers on all systems. And, even
382 though gdb only ever uses deferred_warnings here, a virtual
383 function is used to help Insight. */
384 struct warning_hook_handler_type
385 {
386 virtual void warn (const char *format, va_list args) ATTRIBUTE_PRINTF (2, 0)
387 = 0;
388 };
389
390 typedef warning_hook_handler_type *warning_hook_handler;
391
392 /* Set the thread-local warning hook, and restore the old value when
393 finished. */
394 class scoped_restore_warning_hook
395 {
396 public:
397 explicit scoped_restore_warning_hook (warning_hook_handler new_handler);
398
399 ~scoped_restore_warning_hook ();
400
401 private:
402 scoped_restore_warning_hook (const scoped_restore_warning_hook &other)
403 = delete;
404 scoped_restore_warning_hook &operator= (const scoped_restore_warning_hook &)
405 = delete;
406
407 warning_hook_handler m_save;
408 };
409
410 /* Return the current warning handler. */
411 extern warning_hook_handler get_warning_hook_handler ();
412
413 /* In some cases GDB needs to try several different solutions to a problem,
414 if any of the solutions work then as far as the user is concerned the
415 problem is solved, and GDB should continue without warnings. However,
416 if none of the solutions work then GDB should emit any warnings that
417 occurred while trying each possible solution.
418
419 One example of this is locating separate debug info. There are several
420 different approaches for this; following the .gnu_debuglink, a build-id
421 based lookup, or using debuginfod. If any works, and debug info is
422 located, then the user doesn't want to see warnings from the earlier
423 approaches that were tried and failed.
424
425 However, GDB should emit all the warnings using separate calls to
426 warning -- this ensures that each warning is formatted on its own line,
427 and that any styling is emitted correctly.
428
429 This class helps with deferring warnings. Warnings can be added to an
430 instance of this class with the 'warn' function, and all warnings can be
431 emitted with a single call to 'emit'. */
432
433 struct deferred_warnings final : public warning_hook_handler_type
434 {
deferred_warningsfinal435 deferred_warnings ()
436 : m_can_style (gdb_stderr->can_emit_style_escape ())
437 {
438 }
439
440 /* Add a warning to the list of deferred warnings. */
warnfinal441 void warn (const char *format, ...) ATTRIBUTE_PRINTF (2, 3)
442 {
443 va_list args;
444 va_start (args, format);
445 this->warn (format, args);
446 va_end (args);
447 }
448
449 /* A variant of 'warn' so that this object can be used as a warning
450 hook; see scoped_restore_warning_hook. Note that no locking is
451 done, so users have to be careful to only install this into a
452 single thread at a time. */
warnfinal453 void warn (const char *format, va_list args) override
454 ATTRIBUTE_PRINTF (2, 0)
455 {
456 string_file msg (m_can_style);
457 msg.vprintf (format, args);
458 m_warnings.emplace_back (std::move (msg));
459 }
460
461 /* Emit all warnings. */
emitfinal462 void emit () const
463 {
464 for (const auto &w : m_warnings)
465 warning ("%s", w.c_str ());
466 }
467
468 private:
469
470 /* True if gdb_stderr supports styling at the moment this object is
471 constructed. This is done just once so that objects of this type
472 can be used off the main thread. */
473 bool m_can_style;
474
475 /* The list of all deferred warnings. */
476 std::vector<string_file> m_warnings;
477 };
478
479 #endif /* UTILS_H */
480