1 // Copyright 2009 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9
10 // This file implements BSD-style setproctitle() for Linux.
11 // It is written such that it can easily be compiled outside Chromium.
12 //
13 // The Linux kernel sets up two locations in memory to pass arguments and
14 // environment variables to processes. First, there are two char* arrays stored
15 // one after another: argv and environ. A pointer to argv is passed to main(),
16 // while glibc sets the global variable |environ| to point at the latter. Both
17 // of these arrays are terminated by a null pointer; the environment array is
18 // also followed by some empty space to allow additional variables to be added.
19 //
20 // These arrays contain pointers to a second location in memory, where the
21 // strings themselves are stored one after another: first all the arguments,
22 // then the environment variables.
23 //
24 // When the kernel reads the command line arguments for a process, it looks at
25 // the range of memory that it initially used for the argument list. If the
26 // terminating '\0' character is still where it expects, nothing further is
27 // done. If it has been overwritten, the kernel will scan up to the size of
28 // a page looking for another.
29 //
30 // Thus to change the process title, we must move any environment variables out
31 // of the way to make room for a potentially longer title, and then overwrite
32 // the memory pointed to by argv[0] with a single replacement string, making
33 // sure its size does not exceed the available space.
34 //
35 // See the following kernel commit for the details of the contract between
36 // kernel and setproctitle:
37 // https://github.com/torvalds/linux/commit/2954152298c37804dab49d630aa959625b50cf64
38 //
39 // It is perhaps worth noting that patches to add a system call to Linux for
40 // this, like in BSD, have never made it in: this is the "official" way to do
41 // this on Linux. Presumably it is not in glibc due to some disagreement over
42 // this position within the glibc project, leaving applications caught in the
43 // middle. (Also, only a very few applications need or want this anyway.)
44
45 #include "base/process/set_process_title_linux.h"
46
47 #include <stdarg.h>
48 #include <stddef.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <unistd.h>
53
54 #include <string>
55 #include <vector>
56
57 #include "base/files/file_util.h"
58 #include "base/no_destructor.h"
59 #include "base/numerics/safe_conversions.h"
60
61 extern char** environ;
62
63 // g_orig_argv0 is the original process name found in argv[0].
64 // It is set to a copy of argv[0] in setproctitle_init. It is nullptr if
65 // setproctitle_init was unsuccessful or not called.
66 static const char* g_orig_argv0 = nullptr;
67
68 // Following pointers hold the initial argv/envp memory range.
69 // They are initialized in setproctitle_init and are used to overwrite the
70 // argv/envp memory range with a new process title to be read by the kernel.
71 // They are nullptr if setproctitle_init was unsuccessful or not called.
72 // Note that g_envp_start is not necessary because it is the same as g_argv_end.
73 static char* g_argv_start = nullptr;
74 static char* g_argv_end = nullptr;
75 static char* g_envp_end = nullptr;
76
setproctitle(const char * fmt,...)77 void setproctitle(const char* fmt, ...) {
78 va_list ap;
79
80 // Sanity check before we try and set the process title.
81 // The BSD version allows a null fmt to restore the original title.
82 if (!g_orig_argv0 || !fmt)
83 return;
84
85 // The title can be up to the end of envp.
86 const size_t avail_size =
87 base::checked_cast<size_t>(g_envp_end - g_argv_start - 1);
88
89 // Linux 4.18--5.2 have a bug where we can never set a process title
90 // shorter than the initial argv. Check if the bug exists in the current
91 // kernel on the first call of setproctitle.
92 static const bool buggy_kernel = [avail_size] {
93 // Attempt to set an empty title. This will set cmdline to:
94 // "" (on Linux --4.17)
95 // "\0\0\0...\0\0\0.\0" (on Linux 4.18--5.2)
96 // "\0" (on Linux 5.3--)
97 memset(g_argv_start, 0, avail_size + 1);
98 g_argv_end[-1] = '.';
99
100 std::string cmdline;
101 if (!base::ReadFileToString(base::FilePath("/proc/self/cmdline"),
102 &cmdline)) {
103 return false;
104 }
105 return cmdline.size() >= 2;
106 }();
107
108 memset(g_argv_start, 0, avail_size + 1);
109
110 size_t size;
111 va_start(ap, fmt);
112 if (fmt[0] == '-') {
113 size = base::checked_cast<size_t>(
114 vsnprintf(g_argv_start, avail_size, &fmt[1], ap));
115 } else {
116 size = base::checked_cast<size_t>(
117 snprintf(g_argv_start, avail_size, "%s ", g_orig_argv0));
118 if (size < avail_size)
119 size += base::checked_cast<size_t>(
120 vsnprintf(&g_argv_start[size], avail_size - size, fmt, ap));
121 }
122 va_end(ap);
123
124 // Kernel looks for a null terminator instead of the initial argv space
125 // when the end of the space is not terminated with a null.
126 // https://github.com/torvalds/linux/commit/d26d0cd97c88eb1a5704b42e41ab443406807810
127 //
128 // If the length of the new title is shorter than the original argv space,
129 // set the last byte of the space to an arbitrary non-null character to tell
130 // the kernel that setproctitle was called.
131 //
132 // On buggy kernels we can never make the process title shorter than the
133 // initial argv. In that case, just leave the remaining bytes filled with
134 // null characters.
135 const size_t argv_size =
136 base::checked_cast<size_t>(g_argv_end - g_argv_start - 1);
137 if (!buggy_kernel && size < argv_size)
138 g_argv_end[-1] = '.';
139 }
140
141 // A version of this built into glibc would not need this function, since
142 // it could stash the argv pointer in __libc_start_main(). But we need it.
setproctitle_init(const char ** main_argv)143 void setproctitle_init(const char** main_argv) {
144 static bool init_called = false;
145 if (init_called)
146 return;
147 init_called = true;
148
149 if (!main_argv)
150 return;
151
152 // Verify that the memory layout matches expectation.
153 char** argv = const_cast<char**>(main_argv);
154 char* argv_start = argv[0];
155 char* p = argv_start;
156 for (size_t i = 0; argv[i]; ++i) {
157 if (p != argv[i])
158 return;
159 p += strlen(p) + 1;
160 }
161 char* argv_end = p;
162 size_t environ_size = 0;
163 for (size_t i = 0; environ[i]; ++i, ++environ_size) {
164 if (p != environ[i])
165 return;
166 p += strlen(p) + 1;
167 }
168 char* envp_end = p;
169
170 // Move the environment out of the way. Note that we are moving the values,
171 // not the environment array itself. Also note that we preallocate the entire
172 // vector, because a string's underlying data pointer is not stable under
173 // move operations, which could otherwise occur if building up the vector
174 // incrementally.
175 static base::NoDestructor<std::vector<std::string>> environ_copy(
176 environ_size);
177 for (size_t i = 0; environ[i]; ++i) {
178 (*environ_copy)[i] = environ[i];
179 environ[i] = &(*environ_copy)[i][0];
180 }
181
182 if (!argv[0])
183 return;
184
185 static base::NoDestructor<std::string> argv0_storage(argv[0]);
186 g_orig_argv0 = argv0_storage->data();
187 g_argv_start = argv_start;
188 g_argv_end = argv_end;
189 g_envp_end = envp_end;
190 }
191