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