1 // Copyright (c) 2011 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.
5 #include "content/common/set_process_title.h"
7 #include "build/build_config.h"
9 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
16 #include "base/command_line.h"
17 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
20 #include <sys/prctl.h>
22 #include "base/file_path.h"
23 #include "base/file_util.h"
24 #include "base/string_util.h"
25 // Linux/glibc doesn't natively have setproctitle().
26 #include "content/common/set_process_title_linux.h"
27 #endif // defined(OS_LINUX)
29 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_SOLARIS)
31 void SetProcessTitleFromCommandLine(const char** main_argv
) {
32 // Build a single string which consists of all the arguments separated
33 // by spaces. We can't actually keep them separate due to the way the
34 // setproctitle() function works.
36 bool have_argv0
= false;
40 setproctitle_init(main_argv
);
42 // In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us
43 // show up as "exe" in process listings. Read the symlink /proc/self/exe and
44 // use the path it points at for our process title. Note that this is only for
45 // display purposes and has no TOCTTOU security implications.
47 FilePath
self_exe("/proc/self/exe");
48 if (file_util::ReadSymbolicLink(self_exe
, &target
)) {
50 title
= target
.value();
51 // If the binary has since been deleted, Linux appends " (deleted)" to the
52 // symlink target. Remove it, since this is not really part of our name.
53 const std::string kDeletedSuffix
= " (deleted)";
54 if (EndsWith(title
, kDeletedSuffix
, true))
55 title
.resize(title
.size() - kDeletedSuffix
.size());
56 #if defined(PR_SET_NAME)
57 // If PR_SET_NAME is available at compile time, we try using it. We ignore
58 // any errors if the kernel does not support it at runtime though. When
59 // available, this lets us set the short process name that shows when the
60 // full command line is not being displayed in most process listings.
61 prctl(PR_SET_NAME
, FilePath(title
).BaseName().value().c_str());
62 #endif // defined(PR_SET_NAME)
64 #endif // defined(OS_LINUX)
66 const CommandLine
* command_line
= CommandLine::ForCurrentProcess();
67 for (size_t i
= 1; i
< command_line
->argv().size(); ++i
) {
70 title
+= command_line
->argv()[i
];
72 // Disable prepending argv[0] with '-' if we prepended it ourselves above.
73 setproctitle(have_argv0
? "-%s" : "%s", title
.c_str());
78 // All other systems (basically Windows & Mac) have no need or way to implement
80 void SetProcessTitleFromCommandLine(const char** /* main_argv */) {