1 // Prototypes for various functions, mostly string utilities, that are used by most parts of fish.
2 #ifndef FISH_COMMON_H
3 #define FISH_COMMON_H
4 #include "config.h"  // IWYU pragma: keep
5 
6 #include <errno.h>
7 #include <limits.h>
8 // Needed for va_list et al.
9 #include <stdarg.h>  // IWYU pragma: keep
10 #ifdef HAVE_SYS_IOCTL_H
11 #include <sys/ioctl.h>  // IWYU pragma: keep
12 #endif
13 
14 #include <algorithm>
15 #include <atomic>
16 #include <functional>
17 #include <memory>
18 #include <mutex>
19 #include <string>
20 #include <vector>
21 
22 #include "fallback.h"  // IWYU pragma: keep
23 #include "maybe.h"
24 
25 // Create a generic define for all BSD platforms
26 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
27 #define __BSD__
28 #endif
29 
30 // PATH_MAX may not exist.
31 #ifndef PATH_MAX
32 #define PATH_MAX 4096
33 #endif
34 
35 // Define a symbol we can use elsewhere in our code to determine if we're being built on MS Windows
36 // under Cygwin.
37 #if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(__CYGWIN__) || \
38     defined(__WIN32__)
39 #define OS_IS_CYGWIN
40 #endif
41 
42 // Check if Thread Sanitizer is enabled.
43 #if defined(__has_feature)
44 #if __has_feature(thread_sanitizer)
45 #define FISH_TSAN_WORKAROUNDS 1
46 #endif
47 #endif
48 #ifdef __SANITIZE_THREAD__
49 #define FISH_TSAN_WORKAROUNDS 1
50 #endif
51 
52 // Common string type.
53 typedef std::wstring wcstring;
54 typedef std::vector<wcstring> wcstring_list_t;
55 
56 struct termsize_t;
57 
58 // Maximum number of bytes used by a single utf-8 character.
59 #define MAX_UTF8_BYTES 6
60 
61 // Highest legal ASCII value.
62 #define ASCII_MAX 127u
63 
64 // Highest legal 16-bit Unicode value.
65 #define UCS2_MAX 0xFFFFu
66 
67 // Highest legal byte value.
68 #define BYTE_MAX 0xFFu
69 
70 // Unicode BOM value.
71 #define UTF8_BOM_WCHAR 0xFEFFu
72 
73 // Unicode replacement character.
74 #define REPLACEMENT_WCHAR 0xFFFDu
75 
76 // Use Unicode "noncharacters" for internal characters as much as we can. This
77 // gives us 32 "characters" for internal use that we can guarantee should not
78 // appear in our input stream. See http://www.unicode.org/faq/private_use.html.
79 #define RESERVED_CHAR_BASE static_cast<wchar_t>(0xFDD0)
80 #define RESERVED_CHAR_END static_cast<wchar_t>(0xFDF0)
81 // Split the available noncharacter values into two ranges to ensure there are
82 // no conflicts among the places we use these special characters.
83 #define EXPAND_RESERVED_BASE RESERVED_CHAR_BASE
84 #define EXPAND_RESERVED_END (EXPAND_RESERVED_BASE + 16)
85 #define WILDCARD_RESERVED_BASE EXPAND_RESERVED_END
86 #define WILDCARD_RESERVED_END (WILDCARD_RESERVED_BASE + 16)
87 // Make sure the ranges defined above don't exceed the range for noncharacters.
88 // This is to make sure we didn't do something stupid in subdividing the
89 // Unicode range for our needs.
90 //#if WILDCARD_RESERVED_END > RESERVED_CHAR_END
91 //#error
92 //#endif
93 
94 // These are in the Unicode private-use range. We really shouldn't use this
95 // range but have little choice in the matter given how our lexer/parser works.
96 // We can't use non-characters for these two ranges because there are only 66 of
97 // them and we need at least 256 + 64.
98 //
99 // If sizeof(wchar_t))==4 we could avoid using private-use chars; however, that
100 // would result in fish having different behavior on machines with 16 versus 32
101 // bit wchar_t. It's better that fish behave the same on both types of systems.
102 //
103 // Note: We don't use the highest 8 bit range (0xF800 - 0xF8FF) because we know
104 // of at least one use of a codepoint in that range: the Apple symbol (0xF8FF)
105 // on Mac OS X. See http://www.unicode.org/faq/private_use.html.
106 #define ENCODE_DIRECT_BASE static_cast<wchar_t>(0xF600)
107 #define ENCODE_DIRECT_END (ENCODE_DIRECT_BASE + 256)
108 
109 // NAME_MAX is not defined on Solaris
110 #if !defined(NAME_MAX)
111 #include <sys/param.h>
112 #if defined(MAXNAMELEN)
113 // MAXNAMELEN is defined on Linux, BSD, and Solaris among others
114 #define NAME_MAX MAXNAMELEN
115 #else
116 static_assert(false, "Neither NAME_MAX nor MAXNAMELEN is defined!");
117 #endif
118 #endif
119 
120 // PATH_MAX may not exist.
121 #ifndef PATH_MAX
122 #ifdef MAXPATHLEN
123 #define PATH_MAX MAXPATHLEN
124 #else
125 /// Fallback length of MAXPATHLEN. Hopefully a sane value.
126 #define PATH_MAX 4096
127 #endif
128 #endif
129 
130 enum escape_string_style_t {
131     STRING_STYLE_SCRIPT,
132     STRING_STYLE_URL,
133     STRING_STYLE_VAR,
134     STRING_STYLE_REGEX,
135 };
136 
137 // Flags for unescape_string functions.
138 enum {
139     UNESCAPE_DEFAULT = 0,              // default behavior
140     UNESCAPE_SPECIAL = 1 << 0,         // escape special fish syntax characters like the semicolon
141     UNESCAPE_INCOMPLETE = 1 << 1,      // allow incomplete escape sequences
142     UNESCAPE_NO_BACKSLASHES = 1 << 2,  // don't handle backslash escapes
143 };
144 typedef unsigned int unescape_flags_t;
145 
146 // Flags for the escape_string() and escape_string() functions. These are only applicable when the
147 // escape style is "script" (i.e., STRING_STYLE_SCRIPT).
148 enum {
149     /// Escape all characters, including magic characters like the semicolon.
150     ESCAPE_ALL = 1 << 0,
151     /// Do not try to use 'simplified' quoted escapes, and do not use empty quotes as the empty
152     /// string.
153     ESCAPE_NO_QUOTED = 1 << 1,
154     /// Do not escape tildes.
155     ESCAPE_NO_TILDE = 1 << 2
156 };
157 typedef unsigned int escape_flags_t;
158 
159 /// A user-visible job ID.
160 using job_id_t = int;
161 
162 /// The non user-visible, never-recycled job ID.
163 /// Every job has a unique positive value for this.
164 using internal_job_id_t = uint64_t;
165 
166 /// Issue a debug message with printf-style string formating and automatic line breaking. The string
167 /// will begin with the string \c program_name, followed by a colon and a whitespace.
168 ///
169 /// Because debug is often called to tell the user about an error, before using wperror to give a
170 /// specific error message, debug will never ever modify the value of errno.
171 ///
172 /// \param level the priority of the message. Lower number means higher priority. Messages with a
173 /// priority_number higher than \c debug_level will be ignored..
174 /// \param msg the message format string.
175 ///
176 /// Example:
177 ///
178 /// <code>debug( 1, L"Pi = %.3f", M_PI );</code>
179 ///
180 /// will print the string 'fish: Pi = 3.141', given that debug_level is 1 or higher, and that
181 /// program_name is 'fish'.
182 [[gnu::noinline, gnu::format(printf, 2, 3)]] void debug_impl(int level, const char *msg, ...);
183 [[gnu::noinline]] void debug_impl(int level, const wchar_t *msg, ...);
184 
185 /// The verbosity level of fish. If a call to debug has a severity level higher than \c debug_level,
186 /// it will not be printed.
187 extern std::atomic<int> debug_level;
188 
should_debug(int level)189 inline bool should_debug(int level) { return level <= debug_level.load(std::memory_order_relaxed); }
190 
191 /// Exits without invoking destructors (via _exit), useful for code after fork.
192 [[noreturn]] void exit_without_destructors(int code);
193 
194 /// Save the shell mode on startup so we can restore them on exit.
195 extern struct termios shell_modes;
196 
197 /// The character to use where the text has been truncated. Is an ellipsis on unicode system and a $
198 /// on other systems.
199 wchar_t get_ellipsis_char();
200 
201 /// The character or string to use where text has been truncated (ellipsis if possible, otherwise
202 /// ...)
203 const wchar_t *get_ellipsis_str();
204 
205 /// Character representing an omitted newline at the end of text.
206 const wchar_t *get_omitted_newline_str();
207 int get_omitted_newline_width();
208 
209 /// Character used for the silent mode of the read command
210 wchar_t get_obfuscation_read_char();
211 
212 /// Profiling flag. True if commands should be profiled.
213 extern bool g_profiling_active;
214 
215 /// Name of the current program. Should be set at startup. Used by the debug function.
216 extern const wchar_t *program_name;
217 
218 /// Set to false if it's been determined we can't trust the last modified timestamp on the tty.
219 extern const bool has_working_tty_timestamps;
220 
221 /// A global, empty string. This is useful for functions which wish to return a reference to an
222 /// empty string.
223 extern const wcstring g_empty_string;
224 
225 // Pause for input, then exit the program. If supported, print a backtrace first.
226 // The `return` will never be run  but silences oclint warnings. Especially when this is called
227 // from within a `switch` block. As of the time I'm writing this oclint doesn't recognize the
228 // `__attribute__((noreturn))` on the exit_without_destructors() function.
229 // TODO: we use C++11 [[noreturn]] now, does that change things?
230 #define FATAL_EXIT()                                \
231     do {                                            \
232         char exit_read_buff;                        \
233         show_stackframe(L'E');                      \
234         ignore_result(read(0, &exit_read_buff, 1)); \
235         exit_without_destructors(1);                \
236     } while (0)
237 
238 /// Exit the program at once after emitting an error message and stack trace if possible.
239 /// We use our own private implementation of `assert()` for two reasons. First, some implementations
240 /// are subtly broken. For example, using `printf()` which can cause problems when mixed with wide
241 /// stdio functions and should be writing the message to stderr rather than stdout. Second, if
242 /// possible it is useful to provide additional context such as a stack backtrace.
243 #undef assert
244 #define assert(e) (e) ? ((void)0) : __fish_assert(#e, __FILE__, __LINE__, 0)
245 #define assert_with_errno(e) (e) ? ((void)0) : __fish_assert(#e, __FILE__, __LINE__, errno)
246 #define DIE(msg) __fish_assert(msg, __FILE__, __LINE__, 0)
247 #define DIE_WITH_ERRNO(msg) __fish_assert(msg, __FILE__, __LINE__, errno)
248 /// This macro is meant to be used with functions that return zero on success otherwise return an
249 /// errno value. Most notably the pthread family of functions which we never expect to fail.
250 #define DIE_ON_FAILURE(e)                                  \
251     do {                                                   \
252         int status = e;                                    \
253         if (status != 0) {                                 \
254             __fish_assert(#e, __FILE__, __LINE__, status); \
255         }                                                  \
256     } while (0)
257 
258 [[noreturn]] void __fish_assert(const char *msg, const char *file, size_t line, int error);
259 
260 /// Shorthand for wgettext call in situations where a C-style string is needed (e.g.,
261 /// std::fwprintf()).
262 #define _(wstr) wgettext(wstr).c_str()
263 
264 /// Noop, used to tell xgettext that a string should be translated. Use this when a string cannot be
265 /// passed through wgettext() at the point where it is used. For example, when initializing a
266 /// static array or structure. You must pass the string through wgettext() when it is used.
267 /// See https://developer.gnome.org/glib/stable/glib-I18N.html#N-:CAPS
268 #define N_(wstr) wstr
269 
270 /// Test if a collection contains a value.
271 template <typename Col, typename T2>
contains(const Col & col,const T2 & val)272 bool contains(const Col &col, const T2 &val) {
273     return std::find(std::begin(col), std::end(col), val) != std::end(col);
274 }
275 
276 /// Append a vector \p donator to the vector \p receiver.
277 template <typename T>
vec_append(std::vector<T> & receiver,std::vector<T> && donator)278 void vec_append(std::vector<T> &receiver, std::vector<T> &&donator) {
279     if (receiver.empty()) {
280         receiver = std::move(donator);
281     } else {
282         receiver.insert(receiver.end(), std::make_move_iterator(donator.begin()),
283                         std::make_move_iterator(donator.end()));
284     }
285 }
286 
287 /// Move an object into a shared_ptr.
288 template <typename T>
move_to_sharedptr(T && v)289 std::shared_ptr<T> move_to_sharedptr(T &&v) {
290     return std::make_shared<T>(std::move(v));
291 }
292 
293 /// A function type to check for cancellation.
294 /// \return true if execution should cancel.
295 using cancel_checker_t = std::function<bool()>;
296 
297 /// Print a stack trace to stderr.
298 void show_stackframe(const wchar_t msg_level, int frame_count = 100, int skip_levels = 0);
299 
300 /// Returns a  wide character string equivalent of the specified multibyte character string.
301 ///
302 /// This function encodes illegal character sequences in a reversible way using the private use
303 /// area.
304 wcstring str2wcstring(const char *in);
305 wcstring str2wcstring(const char *in, size_t len);
306 wcstring str2wcstring(const std::string &in);
307 wcstring str2wcstring(const std::string &in, size_t len);
308 
309 /// Returns a newly allocated multibyte character string equivalent of the specified wide character
310 /// string.
311 ///
312 /// This function decodes illegal character sequences in a reversible way using the private use
313 /// area.
314 std::string wcs2string(const wcstring &input);
315 std::string wcs2string(const wchar_t *in, size_t len);
316 
317 /// Like wcs2string, but appends to \p receiver instead of returning a new string.
318 void wcs2string_appending(const wchar_t *in, size_t len, std::string *receiver);
319 
320 // Check if we are running in the test mode, where we should suppress error output
321 #define TESTS_PROGRAM_NAME L"(ignore)"
322 bool should_suppress_stderr_for_tests();
323 
324 void assert_is_main_thread(const char *who);
325 #define ASSERT_IS_MAIN_THREAD_TRAMPOLINE(x) assert_is_main_thread(x)
326 #define ASSERT_IS_MAIN_THREAD() ASSERT_IS_MAIN_THREAD_TRAMPOLINE(__FUNCTION__)
327 
328 void assert_is_background_thread(const char *who);
329 #define ASSERT_IS_BACKGROUND_THREAD_TRAMPOLINE(x) assert_is_background_thread(x)
330 #define ASSERT_IS_BACKGROUND_THREAD() ASSERT_IS_BACKGROUND_THREAD_TRAMPOLINE(__FUNCTION__)
331 
332 /// Useful macro for asserting that a lock is locked. This doesn't check whether this thread locked
333 /// it, which it would be nice if it did, but here it is anyways.
334 void assert_is_locked(std::mutex &mutex, const char *who, const char *caller);
335 #define ASSERT_IS_LOCKED(m) assert_is_locked(m, #m, __FUNCTION__)
336 
337 /// Format the specified size (in bytes, kilobytes, etc.) into the specified stringbuffer.
338 wcstring format_size(long long sz);
339 
340 /// Version of format_size that does not allocate memory.
341 void format_size_safe(char buff[128], unsigned long long sz);
342 
343 /// Our crappier versions of debug which is guaranteed to not allocate any memory, or do anything
344 /// other than call write(). This is useful after a call to fork() with threads.
345 void debug_safe(int level, const char *msg, const char *param1 = nullptr,
346                 const char *param2 = nullptr, const char *param3 = nullptr,
347                 const char *param4 = nullptr, const char *param5 = nullptr,
348                 const char *param6 = nullptr, const char *param7 = nullptr,
349                 const char *param8 = nullptr, const char *param9 = nullptr,
350                 const char *param10 = nullptr, const char *param11 = nullptr,
351                 const char *param12 = nullptr);
352 
353 /// Writes out a long safely.
354 void format_long_safe(char buff[64], long val);
355 void format_long_safe(wchar_t buff[64], long val);
356 void format_ullong_safe(wchar_t buff[64], unsigned long long val);
357 
358 /// "Narrows" a wide character string. This just grabs any ASCII characters and trunactes.
359 void narrow_string_safe(char buff[64], const wchar_t *s);
360 
361 using scoped_lock = std::lock_guard<std::mutex>;
362 
363 // An object wrapping a scoped lock and a value
364 // This is returned from owning_lock.acquire()
365 // Sample usage:
366 //   owning_lock<string> locked_name;
367 //   acquired_lock<string> name = name.acquire();
368 //   name.value = "derp"
369 //
370 // Or for simple cases:
371 //   name.acquire().value = "derp"
372 //
373 template <typename Data>
374 class acquired_lock {
375     template <typename T>
376     friend class owning_lock;
377 
378     template <typename T>
379     friend class acquired_lock;
380 
acquired_lock(std::mutex & lk,Data * v)381     acquired_lock(std::mutex &lk, Data *v) : lock(lk), value(v) {}
acquired_lock(std::unique_lock<std::mutex> && lk,Data * v)382     acquired_lock(std::unique_lock<std::mutex> &&lk, Data *v) : lock(std::move(lk)), value(v) {}
383 
384     std::unique_lock<std::mutex> lock;
385     Data *value;
386 
387    public:
388     // No copying, move construction only
389     acquired_lock &operator=(const acquired_lock &) = delete;
390     acquired_lock(const acquired_lock &) = delete;
391     acquired_lock(acquired_lock &&) = default;
392     acquired_lock &operator=(acquired_lock &&) = default;
393 
394     Data *operator->() { return value; }
395     const Data *operator->() const { return value; }
396     Data &operator*() { return *value; }
397     const Data &operator*() const { return *value; }
398 
399     /// Implicit conversion to const version.
400     operator acquired_lock<const Data>() {
401         // We're about to give up our lock, don't hold onto the data.
402         const Data *cvalue = value;
403         value = nullptr;
404         return acquired_lock<const Data>(std::move(lock), cvalue);
405     }
406 
407     /// Create from a global lock.
408     /// This is used in weird cases where a global lock protects more than one piece of data.
from_global(std::mutex & lk,Data * v)409     static acquired_lock from_global(std::mutex &lk, Data *v) { return acquired_lock{lk, v}; }
410 
411     /// \return a reference to the lock, for use with a condition variable.
get_lock()412     std::unique_lock<std::mutex> &get_lock() { return lock; }
413 };
414 
415 // A lock that owns a piece of data
416 // Access to the data is only provided by taking the lock
417 template <typename Data>
418 class owning_lock {
419     // No copying
420     owning_lock &operator=(const scoped_lock &) = delete;
421     owning_lock(const scoped_lock &) = delete;
422     owning_lock(owning_lock &&) = default;
423     owning_lock &operator=(owning_lock &&) = default;
424 
425     std::mutex lock;
426     Data data;
427 
428    public:
owning_lock(Data && d)429     owning_lock(Data &&d) : data(std::move(d)) {}
owning_lock(const Data & d)430     owning_lock(const Data &d) : data(d) {}
owning_lock()431     owning_lock() : data() {}
432 
acquire()433     acquired_lock<Data> acquire() { return {lock, &data}; }
434 };
435 
436 /// A scoped manager to save the current value of some variable, and optionally set it to a new
437 /// value. On destruction it restores the variable to its old value.
438 ///
439 /// This can be handy when there are multiple code paths to exit a block.
440 template <typename T>
441 class scoped_push {
442     T *const ref;
443     T saved_value;
444     bool restored;
445 
446    public:
scoped_push(T * r)447     explicit scoped_push(T *r) : ref(r), saved_value(*r), restored(false) {}
448 
scoped_push(T * r,T new_value)449     scoped_push(T *r, T new_value) : ref(r), restored(false) {
450         saved_value = std::move(*ref);
451         *ref = std::move(new_value);
452     }
453 
~scoped_push()454     ~scoped_push() { restore(); }
455 
restore()456     void restore() {
457         if (!restored) {
458             *ref = std::move(saved_value);
459             restored = true;
460         }
461     }
462 };
463 
464 wcstring format_string(const wchar_t *format, ...);
465 wcstring vformat_string(const wchar_t *format, va_list va_orig);
466 void append_format(wcstring &str, const wchar_t *format, ...);
467 void append_formatv(wcstring &target, const wchar_t *format, va_list va_orig);
468 
469 #ifdef HAVE_STD__MAKE_UNIQUE
470 using std::make_unique;
471 #else
472 /// make_unique implementation
473 template <typename T, typename... Args>
make_unique(Args &&...args)474 std::unique_ptr<T> make_unique(Args &&...args) {
475     return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
476 }
477 #endif
478 
479 /// This functions returns the end of the quoted substring beginning at \c in. The type of quoting
480 /// character is detemrined by examining \c in. Returns 0 on error.
481 ///
482 /// \param in the position of the opening quote.
483 wchar_t *quote_end(const wchar_t *pos);
484 
485 /// This function should be called after calling `setlocale()` to perform fish specific locale
486 /// initialization.
487 void fish_setlocale();
488 
489 /// Call read, blocking and repeating on EINTR. Exits on EAGAIN.
490 /// \return the number of bytes read, or 0 on EOF. On EAGAIN, returns -1 if nothing was read.
491 long read_blocked(int fd, void *buf, size_t count);
492 
493 /// Loop a write request while failure is non-critical. Return -1 and set errno in case of critical
494 /// error.
495 ssize_t write_loop(int fd, const char *buff, size_t count);
496 
497 /// Loop a read request while failure is non-critical. Return -1 and set errno in case of critical
498 /// error.
499 ssize_t read_loop(int fd, void *buff, size_t count);
500 
501 /// Replace special characters with backslash escape sequences. Newline is replaced with \n, etc.
502 ///
503 /// \param in The string to be escaped
504 /// \param flags Flags to control the escaping
505 /// \return The escaped string
506 wcstring escape_string(const wchar_t *in, escape_flags_t flags,
507                        escape_string_style_t style = STRING_STYLE_SCRIPT);
508 wcstring escape_string(const wcstring &in, escape_flags_t flags,
509                        escape_string_style_t style = STRING_STYLE_SCRIPT);
510 
511 /// \return a string representation suitable for debugging (not for presenting to the user). This
512 /// replaces non-ASCII characters with either tokens like <BRACE_SEP> or <\xfdd7>. No other escapes
513 /// are made (i.e. this is a lossy escape).
514 wcstring debug_escape(const wcstring &in);
515 
516 /// Expand backslashed escapes and substitute them with their unescaped counterparts. Also
517 /// optionally change the wildcards, the tilde character and a few more into constants which are
518 /// defined in a private use area of Unicode. This assumes wchar_t is a unicode character set.
519 
520 /// Given a null terminated string starting with a backslash, read the escape as if it is unquoted,
521 /// appending to result. Return the number of characters consumed, or none() on error.
522 maybe_t<size_t> read_unquoted_escape(const wchar_t *input, wcstring *result, bool allow_incomplete,
523                                      bool unescape_special);
524 
525 /// Unescapes a string in-place. A true result indicates the string was unescaped, a false result
526 /// indicates the string was unmodified.
527 bool unescape_string_in_place(wcstring *str, unescape_flags_t escape_special);
528 
529 /// Reverse the effects of calling `escape_string`. Returns the unescaped value by reference. On
530 /// failure, the output is set to an empty string.
531 bool unescape_string(const wchar_t *input, wcstring *output, unescape_flags_t escape_special,
532                      escape_string_style_t style = STRING_STYLE_SCRIPT);
533 
534 bool unescape_string(const wcstring &input, wcstring *output, unescape_flags_t escape_special,
535                      escape_string_style_t style = STRING_STYLE_SCRIPT);
536 
537 /// Write the given paragraph of output, redoing linebreaks to fit \p termsize.
538 wcstring reformat_for_screen(const wcstring &msg, const termsize_t &termsize);
539 
540 /// Print a short message about how to file a bug report to stderr.
541 void bugreport();
542 
543 /// Return the number of seconds from the UNIX epoch, with subsecond precision. This function uses
544 /// the gettimeofday function and will have the same precision as that function.
545 double timef();
546 
547 /// Call the following function early in main to set the main thread. This is our replacement for
548 /// pthread_main_np().
549 void set_main_thread();
550 bool is_main_thread();
551 
552 /// Configures thread assertions for testing.
553 void configure_thread_assertions_for_testing();
554 
555 /// Set up a guard to complain if we try to do certain things (like take a lock) after calling fork.
556 void setup_fork_guards(void);
557 
558 /// Save the value of tcgetpgrp so we can restore it on exit.
559 void save_term_foreground_process_group();
560 void restore_term_foreground_process_group_for_exit();
561 
562 /// Return whether we are the child of a fork.
563 bool is_forked_child(void);
564 void assert_is_not_forked_child(const char *who);
565 #define ASSERT_IS_NOT_FORKED_CHILD_TRAMPOLINE(x) assert_is_not_forked_child(x)
566 #define ASSERT_IS_NOT_FORKED_CHILD() ASSERT_IS_NOT_FORKED_CHILD_TRAMPOLINE(__FUNCTION__)
567 
568 /// Determines if we are running under Microsoft's Windows Subsystem for Linux to work around
569 /// some known limitations and/or bugs.
570 /// See https://github.com/Microsoft/WSL/issues/423 and Microsoft/WSL#2997
571 bool is_windows_subsystem_for_linux();
572 
573 /// Detect if we are running under Cygwin or Cgywin64
is_cygwin()574 constexpr bool is_cygwin() {
575 #ifdef __CYGWIN__
576     return true;
577 #else
578     return false;
579 #endif
580 }
581 
582 extern "C" {
583 [[gnu::noinline]] void debug_thread_error(void);
584 }
585 
586 /// Converts from wide char to digit in the specified base. If d is not a valid digit in the
587 /// specified base, return -1.
588 long convert_digit(wchar_t d, int base);
589 
590 /// This is a macro that can be used to silence "unused parameter" warnings from the compiler for
591 /// functions which need to accept parameters they do not use because they need to be compatible
592 /// with an interface. It's similar to the Python idiom of doing `_ = expr` at the top of a
593 /// function in the same situation.
594 #define UNUSED(expr)  \
595     do {              \
596         (void)(expr); \
597     } while (0)
598 
599 // Return true if the character is in a range reserved for fish's private use.
600 bool fish_reserved_codepoint(wchar_t c);
601 
602 /// Used for constructing mappings between enums and strings. The resulting array must be sorted
603 /// according to the `str` member since str_to_enum() does a binary search. Also the last entry must
604 /// have NULL for the `str` member and the default value for `val` to be returned if the string
605 /// isn't found.
606 template <typename T>
607 struct enum_map {
608     T val;
609     const wchar_t *const str;
610 };
611 
612 /// Given a string return the matching enum. Return the sentinel enum if no match is made. The map
613 /// must be sorted by the `str` member. A binary search is twice as fast as a linear search with 16
614 /// elements in the map.
615 template <typename T>
str_to_enum(const wchar_t * name,const enum_map<T> map[],int len)616 static T str_to_enum(const wchar_t *name, const enum_map<T> map[], int len) {
617     // Ignore the sentinel value when searching as it is the "not found" value.
618     size_t left = 0, right = len - 1;
619 
620     while (left < right) {
621         size_t mid = left + (right - left) / 2;
622         int cmp = std::wcscmp(name, map[mid].str);
623         if (cmp < 0) {
624             right = mid;  // name was smaller than mid
625         } else if (cmp > 0) {
626             left = mid + 1;  // name was larger than mid
627         } else {
628             return map[mid].val;  // found it
629         }
630     }
631     return map[len - 1].val;  // return the sentinel value
632 }
633 
634 /// Given an enum return the matching string.
635 template <typename T>
enum_to_str(T enum_val,const enum_map<T> map[])636 static const wchar_t *enum_to_str(T enum_val, const enum_map<T> map[]) {
637     for (const enum_map<T> *entry = map; entry->str; entry++) {
638         if (enum_val == entry->val) {
639             return entry->str;
640         }
641     }
642     return nullptr;
643 };
644 
645 void redirect_tty_output();
646 
647 std::string get_path_to_tmp_dir();
648 
649 bool valid_var_name_char(wchar_t chr);
650 bool valid_var_name(const wcstring &str);
651 bool valid_var_name(const wchar_t *str);
652 bool valid_func_name(const wcstring &str);
653 
654 // Return values (`$status` values for fish scripts) for various situations.
655 enum {
656     /// The status code used for normal exit in a command.
657     STATUS_CMD_OK = 0,
658     /// The status code used for failure exit in a command (but not if the args were invalid).
659     STATUS_CMD_ERROR = 1,
660     /// The status code used for invalid arguments given to a command. This is distinct from valid
661     /// arguments that might result in a command failure. An invalid args condition is something
662     /// like an unrecognized flag, missing or too many arguments, an invalid integer, etc. But
663     STATUS_INVALID_ARGS = 2,
664 
665     /// The status code used when a command was not found.
666     STATUS_CMD_UNKNOWN = 127,
667 
668     /// The status code used when an external command can not be run.
669     STATUS_NOT_EXECUTABLE = 126,
670 
671     /// The status code used when a wildcard had no matches.
672     STATUS_UNMATCHED_WILDCARD = 124,
673     /// The status code used when illegal command name is encountered.
674     STATUS_ILLEGAL_CMD = 123,
675     /// The status code used when `read` is asked to consume too much data.
676     STATUS_READ_TOO_MUCH = 122,
677     /// The status code when an expansion fails, for example, "$foo["
678     STATUS_EXPAND_ERROR = 121,
679 };
680 
681 /* Normally casting an expression to void discards its value, but GCC
682    versions 3.4 and newer have __attribute__ ((__warn_unused_result__))
683    which may cause unwanted diagnostics in that case.  Use __typeof__
684    and __extension__ to work around the problem, if the workaround is
685    known to be needed.  */
686 #if 3 < __GNUC__ + (4 <= __GNUC_MINOR__)
687 #define ignore_result(x)         \
688     (__extension__({             \
689         __typeof__(x) __x = (x); \
690         (void)__x;               \
691     }))
692 #else
693 #define ignore_result(x) ((void)(x))
694 #endif
695 
696 // Custom hash function used by unordered_map/unordered_set when key is const
697 #ifndef CONST_WCSTRING_HASH
698 #define CONST_WCSTRING_HASH 1
699 namespace std {
700 template <>
701 struct hash<const wcstring> {
702     std::size_t operator()(const wcstring &w) const {
703         std::hash<wcstring> hasher;
704         return hasher(w);
705     }
706 };
707 }  // namespace std
708 #endif
709 
710 /// Get the absolute path to the fish executable itself
711 std::string get_executable_path(const char *argv0);
712 
713 /// A RAII wrapper for resources that don't recur, so we don't have to create a separate RAII
714 /// wrapper for each function. Avoids needing to call "return cleanup()" or similar / everywhere.
715 struct cleanup_t {
716    private:
717     const std::function<void()> cleanup;
718 
719    public:
720     cleanup_t(std::function<void()> exit_actions) : cleanup{std::move(exit_actions)} {}
721     ~cleanup_t() { cleanup(); }
722 };
723 
724 bool is_console_session();
725 
726 /// Compile-time agnostic-size strcmp/wcscmp implementation. Unicode-unaware.
727 template <typename T>
728 constexpr ssize_t const_strcmp(const T *lhs, const T *rhs) {
729     return (*lhs == *rhs) ? (*lhs == 0 ? 0 : const_strcmp(lhs + 1, rhs + 1))
730                           : (*lhs > *rhs ? 1 : -1);
731 }
732 
733 /// Compile-time agnostic-size strlen/wcslen implementation. Unicode-unaware.
734 template <typename T, size_t N>
735 constexpr size_t const_strlen(const T (&val)[N], ssize_t index = -1) {
736     // N is the length of the character array, but that includes one **or more** trailing nuls.
737     static_assert(N > 0, "Invalid input to const_strlen");
738     return index == -1
739                ?
740                // Assume a minimum of one trailing nul and do a quick check for the usual case
741                // (single trailing nul) before recursing:
742                N - 1 - (N <= 2 || val[N - 2] != static_cast<T>(0) ? 0 : const_strlen(val, N - 2))
743                // Prevent an underflow in case the string is comprised of all \0 bytes
744                : index == 0
745                      ? 0
746                      // Keep back-tracking until a non-nul byte is found
747                      : (val[index] != static_cast<T>(0) ? 0 : 1 + const_strlen(val, index - 1));
748 }
749 
750 /// Compile-time assertion of alphabetical sort of array `array`, by specified
751 /// parameter `accessor`. This is only a macro because constexpr lambdas (to
752 /// specify the accessor for the sort key) are C++17 and up.
753 #define ASSERT_SORT_ORDER(array, accessor)                                                \
754     struct verify_##array##_sort_t {                                                      \
755         template <class T, size_t N>                                                      \
756         constexpr static bool validate(T (&vals)[N], size_t idx = 0) {                    \
757             return (idx == (((sizeof(array) / sizeof(vals[0]))) - 1))                     \
758                        ? true                                                             \
759                        : const_strcmp(vals[idx] accessor, vals[idx + 1] accessor) <= 0 && \
760                              verify_##array##_sort_t::validate<T, N>(vals, idx + 1);      \
761         }                                                                                 \
762     };                                                                                    \
763     static_assert(verify_##array##_sort_t::validate(array),                               \
764                   #array " members not in asciibetical order!");
765 
766 #endif  // FISH_COMMON_H
767