xref: /aosp_15_r20/external/cronet/base/process/process_util_unittest.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 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 #define _CRT_SECURE_NO_WARNINGS
6 
7 #include <stddef.h>
8 #include <stdint.h>
9 
10 #include <limits>
11 #include <string_view>
12 #include <tuple>
13 
14 #include "base/command_line.h"
15 #include "base/debug/alias.h"
16 #include "base/debug/stack_trace.h"
17 #include "base/files/file_enumerator.h"
18 #include "base/files/file_path.h"
19 #include "base/files/file_util.h"
20 #include "base/files/scoped_file.h"
21 #include "base/functional/bind.h"
22 #include "base/logging.h"
23 #include "base/path_service.h"
24 #include "base/posix/eintr_wrapper.h"
25 #include "base/process/kill.h"
26 #include "base/process/launch.h"
27 #include "base/process/memory.h"
28 #include "base/process/process.h"
29 #include "base/process/process_metrics.h"
30 #include "base/strings/string_number_conversions.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "base/synchronization/waitable_event.h"
33 #include "base/test/multiprocess_test.h"
34 #include "base/test/task_environment.h"
35 #include "base/test/test_timeouts.h"
36 #include "base/threading/platform_thread.h"
37 #include "base/threading/simple_thread.h"
38 #include "base/threading/thread.h"
39 #include "build/build_config.h"
40 #include "testing/gtest/include/gtest/gtest.h"
41 #include "testing/multiprocess_func_list.h"
42 
43 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
44 #include <malloc.h>
45 #include <sched.h>
46 #include <sys/syscall.h>
47 #endif
48 #if BUILDFLAG(IS_POSIX)
49 #include <sys/resource.h>
50 #endif
51 #if BUILDFLAG(IS_POSIX)
52 #include <dlfcn.h>
53 #include <errno.h>
54 #include <sched.h>
55 #include <signal.h>
56 #include <sys/wait.h>
57 #include <unistd.h>
58 #endif
59 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
60 #include <fcntl.h>
61 #include <sys/socket.h>
62 #include <sys/types.h>
63 #endif
64 #if BUILDFLAG(IS_WIN)
65 #include <windows.h>
66 #endif
67 #if BUILDFLAG(IS_APPLE)
68 #include <mach/vm_param.h>
69 #include <malloc/malloc.h>
70 #endif
71 #if BUILDFLAG(IS_ANDROID)
72 #include "third_party/lss/linux_syscall_support.h"
73 #endif
74 #if BUILDFLAG(IS_FUCHSIA)
75 #include <lib/fdio/fdio.h>
76 #include <lib/fdio/limits.h>
77 #include <lib/fdio/spawn.h>
78 #include <lib/sys/cpp/component_context.h>
79 #include <zircon/process.h>
80 #include <zircon/processargs.h>
81 #include <zircon/syscalls.h>
82 #include "base/files/scoped_temp_dir.h"
83 #include "base/fuchsia/file_utils.h"
84 #include "base/fuchsia/filtered_service_directory.h"
85 #include "base/fuchsia/fuchsia_logging.h"
86 #include "base/fuchsia/process_context.h"
87 #include "base/test/bind.h"
88 #endif
89 
90 namespace base {
91 
92 namespace {
93 
94 const char kSignalFileSlow[] = "SlowChildProcess.die";
95 const char kSignalFileKill[] = "KilledChildProcess.die";
96 const char kTestHelper[] = "test_child_process";
97 
98 #if BUILDFLAG(IS_POSIX)
99 const char kSignalFileTerm[] = "TerminatedChildProcess.die";
100 #endif
101 
102 #if BUILDFLAG(IS_FUCHSIA)
103 const char kSignalFileClone[] = "ClonedDir.die";
104 const char kFooDirHasStaged[] = "FooDirHasStaged.die";
105 #endif
106 
107 #if BUILDFLAG(IS_WIN)
108 const int kExpectedStillRunningExitCode = 0x102;
109 const int kExpectedKilledExitCode = 1;
110 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
111 const int kExpectedStillRunningExitCode = 0;
112 #endif
113 
114 // Sleeps until file filename is created.
WaitToDie(const char * filename)115 void WaitToDie(const char* filename) {
116   FILE* fp;
117   do {
118     PlatformThread::Sleep(Milliseconds(10));
119     fp = fopen(filename, "r");
120   } while (!fp);
121   fclose(fp);
122 }
123 
124 // Signals children they should die now.
SignalChildren(const char * filename)125 void SignalChildren(const char* filename) {
126   FILE* fp = fopen(filename, "w");
127   fclose(fp);
128 }
129 
130 // Using a pipe to the child to wait for an event was considered, but
131 // there were cases in the past where pipes caused problems (other
132 // libraries closing the fds, child deadlocking). This is a simple
133 // case, so it's not worth the risk.  Using wait loops is discouraged
134 // in most instances.
WaitForChildTermination(ProcessHandle handle,int * exit_code)135 TerminationStatus WaitForChildTermination(ProcessHandle handle,
136                                           int* exit_code) {
137   // Now we wait until the result is something other than STILL_RUNNING.
138   TerminationStatus status = TERMINATION_STATUS_STILL_RUNNING;
139   const TimeDelta kInterval = Milliseconds(20);
140   TimeDelta waited;
141   do {
142     status = GetTerminationStatus(handle, exit_code);
143     PlatformThread::Sleep(kInterval);
144     waited += kInterval;
145   } while (status == TERMINATION_STATUS_STILL_RUNNING &&
146            waited < TestTimeouts::action_max_timeout());
147 
148   return status;
149 }
150 
151 }  // namespace
152 
153 const int kSuccess = 0;
154 
155 class ProcessUtilTest : public MultiProcessTest {
156  public:
SetUp()157   void SetUp() override {
158     ASSERT_TRUE(PathService::Get(DIR_OUT_TEST_DATA_ROOT, &test_helper_path_));
159     test_helper_path_ = test_helper_path_.AppendASCII(kTestHelper);
160   }
161 
162 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
163   // Spawn a child process that counts how many file descriptors are open.
164   int CountOpenFDsInChild();
165 #endif
166   // Converts the filename to a platform specific filepath.
167   // On Android files can not be created in arbitrary directories.
168   static std::string GetSignalFilePath(const char* filename);
169 
170  protected:
171   FilePath test_helper_path_;
172 };
173 
GetSignalFilePath(const char * filename)174 std::string ProcessUtilTest::GetSignalFilePath(const char* filename) {
175 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA)
176   FilePath tmp_dir;
177   PathService::Get(DIR_TEMP, &tmp_dir);
178   // Ensure the directory exists to avoid harder to debug issues later.
179   CHECK(PathExists(tmp_dir));
180   tmp_dir = tmp_dir.Append(filename);
181   return tmp_dir.value();
182 #else
183   return filename;
184 #endif
185 }
186 
MULTIPROCESS_TEST_MAIN(SimpleChildProcess)187 MULTIPROCESS_TEST_MAIN(SimpleChildProcess) {
188   return kSuccess;
189 }
190 
191 // TODO(viettrungluu): This should be in a "MultiProcessTestTest".
TEST_F(ProcessUtilTest,SpawnChild)192 TEST_F(ProcessUtilTest, SpawnChild) {
193   Process process = SpawnChild("SimpleChildProcess");
194   ASSERT_TRUE(process.IsValid());
195   int exit_code;
196   EXPECT_TRUE(process.WaitForExitWithTimeout(TestTimeouts::action_max_timeout(),
197                                              &exit_code));
198 }
199 
MULTIPROCESS_TEST_MAIN(SlowChildProcess)200 MULTIPROCESS_TEST_MAIN(SlowChildProcess) {
201   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow).c_str());
202   return kSuccess;
203 }
204 
TEST_F(ProcessUtilTest,KillSlowChild)205 TEST_F(ProcessUtilTest, KillSlowChild) {
206   const std::string signal_file = GetSignalFilePath(kSignalFileSlow);
207   remove(signal_file.c_str());
208   Process process = SpawnChild("SlowChildProcess");
209   ASSERT_TRUE(process.IsValid());
210   SignalChildren(signal_file.c_str());
211   int exit_code;
212   EXPECT_TRUE(process.WaitForExitWithTimeout(TestTimeouts::action_max_timeout(),
213                                              &exit_code));
214   remove(signal_file.c_str());
215 }
216 
217 // Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
218 #if BUILDFLAG(IS_FUCHSIA)
219 #define MAYBE_GetTerminationStatusExit GetTerminationStatusExit
220 #else
221 #define MAYBE_GetTerminationStatusExit DISABLED_GetTerminationStatusExit
222 #endif
TEST_F(ProcessUtilTest,MAYBE_GetTerminationStatusExit)223 TEST_F(ProcessUtilTest, MAYBE_GetTerminationStatusExit) {
224   const std::string signal_file = GetSignalFilePath(kSignalFileSlow);
225   remove(signal_file.c_str());
226   Process process = SpawnChild("SlowChildProcess");
227   ASSERT_TRUE(process.IsValid());
228 
229   int exit_code = 42;
230   EXPECT_EQ(TERMINATION_STATUS_STILL_RUNNING,
231             GetTerminationStatus(process.Handle(), &exit_code));
232   EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
233 
234   SignalChildren(signal_file.c_str());
235   exit_code = 42;
236   TerminationStatus status =
237       WaitForChildTermination(process.Handle(), &exit_code);
238   EXPECT_EQ(TERMINATION_STATUS_NORMAL_TERMINATION, status);
239   EXPECT_EQ(kSuccess, exit_code);
240   remove(signal_file.c_str());
241 }
242 
243 #if BUILDFLAG(IS_FUCHSIA)
MULTIPROCESS_TEST_MAIN(ShouldNotBeLaunched)244 MULTIPROCESS_TEST_MAIN(ShouldNotBeLaunched) {
245   return 1;
246 }
247 
248 // Test that duplicate transfer & cloned paths cause the launch to fail.
249 // TODO(fxbug.dev/124840): Re-enable once the platform behaviour is fixed.
TEST_F(ProcessUtilTest,DISABLED_DuplicateTransferAndClonePaths_Fail)250 TEST_F(ProcessUtilTest, DISABLED_DuplicateTransferAndClonePaths_Fail) {
251   // Create a tempdir to transfer a duplicate "/data".
252   ScopedTempDir tmpdir;
253   ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
254 
255   LaunchOptions options;
256   options.spawn_flags = FDIO_SPAWN_CLONE_STDIO;
257 
258   // Attach the tempdir to "data", but also try to duplicate the existing "data"
259   // directory.
260   options.paths_to_clone.push_back(FilePath(kPersistedDataDirectoryPath));
261   options.paths_to_clone.push_back(FilePath("/tmp"));
262   options.paths_to_transfer.push_back(
263       {FilePath(kPersistedDataDirectoryPath),
264        OpenDirectoryHandle(tmpdir.GetPath()).TakeChannel().release()});
265 
266   // Verify that the process fails to launch.
267   Process process(SpawnChildWithOptions("ShouldNotBeLaunched", options));
268   ASSERT_FALSE(process.IsValid());
269 }
270 
271 // Test that attempting to transfer/clone to a path (e.g. "/data"), and also to
272 // a sub-path of that path (e.g. "/data/staged"), causes the process launch to
273 // fail.
274 // TODO(fxbug.dev/124840): Re-enable once the platform behaviour is fixed.
TEST_F(ProcessUtilTest,DISABLED_OverlappingPaths_Fail)275 TEST_F(ProcessUtilTest, DISABLED_OverlappingPaths_Fail) {
276   // Create a tempdir to transfer to a sub-directory path.
277   ScopedTempDir tmpdir;
278   ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
279 
280   LaunchOptions options;
281   options.spawn_flags = FDIO_SPAWN_CLONE_STDIO;
282 
283   // Attach the tempdir to "data", but also try to duplicate the existing "data"
284   // directory.
285   options.paths_to_clone.push_back(FilePath(kPersistedDataDirectoryPath));
286   options.paths_to_clone.push_back(FilePath("/tmp"));
287   options.paths_to_transfer.push_back(
288       {FilePath(kPersistedDataDirectoryPath).Append("staged"),
289        OpenDirectoryHandle(tmpdir.GetPath()).TakeChannel().release()});
290 
291   // Verify that the process fails to launch.
292   Process process(SpawnChildWithOptions("ShouldNotBeLaunched", options));
293   ASSERT_FALSE(process.IsValid());
294 }
295 
MULTIPROCESS_TEST_MAIN(CheckMountedDir)296 MULTIPROCESS_TEST_MAIN(CheckMountedDir) {
297   if (!PathExists(FilePath("/foo/staged"))) {
298     return 1;
299   }
300   WaitToDie(ProcessUtilTest::GetSignalFilePath(kFooDirHasStaged).c_str());
301   return kSuccess;
302 }
303 
304 // Test that we can install an opaque handle in the child process' namespace.
TEST_F(ProcessUtilTest,TransferHandleToPath)305 TEST_F(ProcessUtilTest, TransferHandleToPath) {
306   const std::string signal_file = GetSignalFilePath(kFooDirHasStaged);
307   remove(signal_file.c_str());
308 
309   // Create a tempdir with "staged" as its contents.
310   ScopedTempDir new_tmpdir;
311   ASSERT_TRUE(new_tmpdir.CreateUniqueTempDir());
312   FilePath staged_file_path = new_tmpdir.GetPath().Append("staged");
313   File staged_file(staged_file_path, File::FLAG_CREATE | File::FLAG_WRITE);
314   ASSERT_TRUE(staged_file.created());
315   staged_file.Close();
316 
317   // Mount the tempdir to "/foo".
318   zx::channel tmp_channel =
319       OpenDirectoryHandle(new_tmpdir.GetPath()).TakeChannel();
320 
321   ASSERT_TRUE(tmp_channel.is_valid());
322   LaunchOptions options;
323   options.paths_to_clone.push_back(FilePath("/tmp"));
324   options.paths_to_transfer.push_back(
325       {FilePath("/foo"), tmp_channel.release()});
326   options.spawn_flags = FDIO_SPAWN_CLONE_STDIO;
327 
328   // Verify from that "/foo/staged" exists from the child process' perspective.
329   Process process(SpawnChildWithOptions("CheckMountedDir", options));
330   ASSERT_TRUE(process.IsValid());
331   SignalChildren(signal_file.c_str());
332 
333   int exit_code = 42;
334   EXPECT_TRUE(process.WaitForExit(&exit_code));
335   EXPECT_EQ(kSuccess, exit_code);
336 }
337 
338 // Look through the filesystem to ensure that no other directories
339 // besides |expected_path| are in the namespace.
340 // Since GetSignalFilePath() uses "/tmp", tests for paths other than this must
341 // include two paths. "/tmp" must always be last.
CheckOnlyOnePathExists(std::string_view expected_path)342 int CheckOnlyOnePathExists(std::string_view expected_path) {
343   bool is_expected_path_tmp = expected_path == "/tmp";
344   std::vector<FilePath> paths;
345 
346   FileEnumerator enumerator(
347       FilePath("/"), false,
348       FileEnumerator::FILES | FileEnumerator::DIRECTORIES);
349   for (auto path = enumerator.Next(); !path.empty(); path = enumerator.Next()) {
350     paths.push_back(std::move(path));
351   }
352 
353   EXPECT_EQ(paths.size(), is_expected_path_tmp ? 1u : 2u);
354   EXPECT_EQ(paths[0], FilePath(expected_path))
355       << "Clone policy violation: found non-tmp directory "
356       << paths[0].MaybeAsASCII();
357 
358   if (!is_expected_path_tmp) {
359     EXPECT_EQ(paths[1], FilePath("/tmp"));
360   }
361 
362   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileClone).c_str());
363   return kSuccess;
364 }
365 
MULTIPROCESS_TEST_MAIN(CheckOnlyTmpExists)366 MULTIPROCESS_TEST_MAIN(CheckOnlyTmpExists) {
367   return CheckOnlyOnePathExists("/tmp");
368 }
369 
TEST_F(ProcessUtilTest,CloneTmp)370 TEST_F(ProcessUtilTest, CloneTmp) {
371   const std::string signal_file = GetSignalFilePath(kSignalFileClone);
372   remove(signal_file.c_str());
373 
374   LaunchOptions options;
375   options.paths_to_clone.push_back(FilePath("/tmp"));
376   options.spawn_flags = FDIO_SPAWN_CLONE_STDIO;
377 
378   Process process(SpawnChildWithOptions("CheckOnlyTmpExists", options));
379   ASSERT_TRUE(process.IsValid());
380 
381   SignalChildren(signal_file.c_str());
382 
383   int exit_code = 42;
384   EXPECT_TRUE(process.WaitForExit(&exit_code));
385   EXPECT_EQ(kSuccess, exit_code);
386 }
387 
MULTIPROCESS_TEST_MAIN(NeverCalled)388 MULTIPROCESS_TEST_MAIN(NeverCalled) {
389   CHECK(false) << "Process should not have been launched.";
390   return 99;
391 }
392 
TEST_F(ProcessUtilTest,TransferInvalidHandleFails)393 TEST_F(ProcessUtilTest, TransferInvalidHandleFails) {
394   LaunchOptions options;
395   options.paths_to_clone.push_back(FilePath("/tmp"));
396   options.paths_to_transfer.push_back({FilePath("/foo"), ZX_HANDLE_INVALID});
397   options.spawn_flags = FDIO_SPAWN_CLONE_STDIO;
398 
399   // Verify that the process is never constructed.
400   Process process(SpawnChildWithOptions("NeverCalled", options));
401   EXPECT_FALSE(process.IsValid());
402 }
403 
TEST_F(ProcessUtilTest,CloneInvalidDirFails)404 TEST_F(ProcessUtilTest, CloneInvalidDirFails) {
405   const std::string signal_file = GetSignalFilePath(kSignalFileClone);
406   remove(signal_file.c_str());
407 
408   LaunchOptions options;
409   options.paths_to_clone.push_back(FilePath("/tmp"));
410   options.paths_to_clone.push_back(FilePath("/definitely_not_a_dir"));
411   options.spawn_flags = FDIO_SPAWN_CLONE_STDIO;
412 
413   Process process(SpawnChildWithOptions("NeverCalled", options));
414   EXPECT_FALSE(process.IsValid());
415 }
416 
MULTIPROCESS_TEST_MAIN(CheckOnlyDataExists)417 MULTIPROCESS_TEST_MAIN(CheckOnlyDataExists) {
418   return CheckOnlyOnePathExists("/data");
419 }
420 
TEST_F(ProcessUtilTest,CloneAlternateDir)421 TEST_F(ProcessUtilTest, CloneAlternateDir) {
422   const std::string signal_file = GetSignalFilePath(kSignalFileClone);
423   remove(signal_file.c_str());
424 
425   LaunchOptions options;
426   options.paths_to_clone.push_back(FilePath("/data"));
427   // The DIR_TEMP path is used by GetSignalFilePath().
428   options.paths_to_clone.push_back(FilePath("/tmp"));
429   options.spawn_flags = FDIO_SPAWN_CLONE_STDIO;
430 
431   Process process(SpawnChildWithOptions("CheckOnlyDataExists", options));
432   ASSERT_TRUE(process.IsValid());
433 
434   SignalChildren(signal_file.c_str());
435 
436   int exit_code = 42;
437   EXPECT_TRUE(process.WaitForExit(&exit_code));
438   EXPECT_EQ(kSuccess, exit_code);
439 }
440 
TEST_F(ProcessUtilTest,HandlesToTransferClosedOnSpawnFailure)441 TEST_F(ProcessUtilTest, HandlesToTransferClosedOnSpawnFailure) {
442   zx::handle handles[2];
443   zx_status_t result = zx_channel_create(0, handles[0].reset_and_get_address(),
444                                          handles[1].reset_and_get_address());
445   ZX_CHECK(ZX_OK == result, result) << "zx_channel_create";
446 
447   LaunchOptions options;
448   options.handles_to_transfer.push_back({0, handles[0].get()});
449 
450   // Launch a non-existent binary, causing fdio_spawn() to fail.
451   CommandLine command_line(FilePath(
452       FILE_PATH_LITERAL("��magical_filename_that_will_never_exist_ever")));
453   Process process(LaunchProcess(command_line, options));
454   ASSERT_FALSE(process.IsValid());
455 
456   // If LaunchProcess did its job then handles[0] is no longer valid, and
457   // handles[1] should observe a channel-closed signal.
458   EXPECT_EQ(
459       zx_object_wait_one(handles[1].get(), ZX_CHANNEL_PEER_CLOSED, 0, nullptr),
460       ZX_OK);
461   EXPECT_EQ(ZX_ERR_BAD_HANDLE, zx_handle_close(handles[0].get()));
462   std::ignore = handles[0].release();
463 }
464 
TEST_F(ProcessUtilTest,HandlesToTransferClosedOnBadPathToMapFailure)465 TEST_F(ProcessUtilTest, HandlesToTransferClosedOnBadPathToMapFailure) {
466   zx::handle handles[2];
467   zx_status_t result = zx_channel_create(0, handles[0].reset_and_get_address(),
468                                          handles[1].reset_and_get_address());
469   ZX_CHECK(ZX_OK == result, result) << "zx_channel_create";
470 
471   LaunchOptions options;
472   options.handles_to_transfer.push_back({0, handles[0].get()});
473   options.spawn_flags = options.spawn_flags & ~FDIO_SPAWN_CLONE_NAMESPACE;
474   options.paths_to_clone.emplace_back(
475       "��magical_path_that_will_never_exist_ever");
476 
477   // LaunchProces should fail to open() the path_to_map, and fail before
478   // fdio_spawn().
479   Process process(LaunchProcess(CommandLine(FilePath()), options));
480   ASSERT_FALSE(process.IsValid());
481 
482   // If LaunchProcess did its job then handles[0] is no longer valid, and
483   // handles[1] should observe a channel-closed signal.
484   EXPECT_EQ(
485       zx_object_wait_one(handles[1].get(), ZX_CHANNEL_PEER_CLOSED, 0, nullptr),
486       ZX_OK);
487   EXPECT_EQ(ZX_ERR_BAD_HANDLE, zx_handle_close(handles[0].get()));
488   std::ignore = handles[0].release();
489 }
490 
TEST_F(ProcessUtilTest,FuchsiaProcessNameSuffix)491 TEST_F(ProcessUtilTest, FuchsiaProcessNameSuffix) {
492   LaunchOptions options;
493   options.process_name_suffix = "#test";
494   Process process(SpawnChildWithOptions("SimpleChildProcess", options));
495 
496   char name[256] = {};
497   size_t name_size = sizeof(name);
498   zx_status_t status =
499       zx_object_get_property(process.Handle(), ZX_PROP_NAME, name, name_size);
500   ASSERT_EQ(status, ZX_OK);
501   EXPECT_EQ(std::string(name),
502             CommandLine::ForCurrentProcess()->GetProgram().BaseName().value() +
503                 "#test");
504 }
505 
506 #endif  // BUILDFLAG(IS_FUCHSIA)
507 
508 // On Android SpawnProcess() doesn't use LaunchProcess() and doesn't support
509 // LaunchOptions::current_directory.
510 #if !BUILDFLAG(IS_ANDROID)
CheckCwdIsExpected(FilePath expected)511 static void CheckCwdIsExpected(FilePath expected) {
512   FilePath actual;
513   CHECK(GetCurrentDirectory(&actual));
514   actual = MakeAbsoluteFilePath(actual);
515   CHECK(!actual.empty());
516 
517   CHECK_EQ(expected, actual);
518 }
519 
520 // N.B. This test does extra work to check the cwd on multiple threads, because
521 // on macOS a per-thread cwd is set when using LaunchProcess().
MULTIPROCESS_TEST_MAIN(CheckCwdProcess)522 MULTIPROCESS_TEST_MAIN(CheckCwdProcess) {
523   // Get the expected cwd.
524   FilePath temp_dir;
525   CHECK(GetTempDir(&temp_dir));
526   temp_dir = MakeAbsoluteFilePath(temp_dir);
527   CHECK(!temp_dir.empty());
528 
529   // Test that the main thread has the right cwd.
530   CheckCwdIsExpected(temp_dir);
531 
532   // Create a non-main thread.
533   Thread thread("CheckCwdThread");
534   thread.Start();
535   auto task_runner = thread.task_runner();
536 
537   // A synchronization primitive used to wait for work done on the non-main
538   // thread.
539   WaitableEvent event(WaitableEvent::ResetPolicy::AUTOMATIC);
540   RepeatingClosure signal_event =
541       BindRepeating(&WaitableEvent::Signal, Unretained(&event));
542 
543   // Test that a non-main thread has the right cwd.
544   task_runner->PostTask(FROM_HERE, BindOnce(&CheckCwdIsExpected, temp_dir));
545   task_runner->PostTask(FROM_HERE, signal_event);
546 
547   event.Wait();
548 
549   // Get a new cwd for the process.
550   const FilePath home_dir = PathService::CheckedGet(DIR_HOME);
551 
552   // Change the cwd on the secondary thread. IgnoreResult is used when setting
553   // because it is checked immediately after.
554   task_runner->PostTask(FROM_HERE,
555                         BindOnce(IgnoreResult(&SetCurrentDirectory), home_dir));
556   task_runner->PostTask(FROM_HERE, BindOnce(&CheckCwdIsExpected, home_dir));
557   task_runner->PostTask(FROM_HERE, signal_event);
558 
559   event.Wait();
560 
561   // Make sure the main thread sees the cwd from the secondary thread.
562   CheckCwdIsExpected(home_dir);
563 
564   // Change the directory back on the main thread.
565   CHECK(SetCurrentDirectory(temp_dir));
566   CheckCwdIsExpected(temp_dir);
567 
568   // Ensure that the secondary thread sees the new cwd too.
569   task_runner->PostTask(FROM_HERE, BindOnce(&CheckCwdIsExpected, temp_dir));
570   task_runner->PostTask(FROM_HERE, signal_event);
571 
572   event.Wait();
573 
574   // Change the cwd on the secondary thread one more time and join the thread.
575   task_runner->PostTask(FROM_HERE,
576                         BindOnce(IgnoreResult(&SetCurrentDirectory), home_dir));
577   thread.Stop();
578 
579   // Make sure that the main thread picked up the new cwd.
580   CheckCwdIsExpected(home_dir);
581 
582   return kSuccess;
583 }
584 
TEST_F(ProcessUtilTest,CurrentDirectory)585 TEST_F(ProcessUtilTest, CurrentDirectory) {
586   // TODO(rickyz): Add support for passing arguments to multiprocess children,
587   // then create a special directory for this test.
588   FilePath tmp_dir;
589   ASSERT_TRUE(GetTempDir(&tmp_dir));
590 
591   LaunchOptions options;
592   options.current_directory = tmp_dir;
593 
594   Process process(SpawnChildWithOptions("CheckCwdProcess", options));
595   ASSERT_TRUE(process.IsValid());
596 
597   int exit_code = 42;
598   EXPECT_TRUE(process.WaitForExit(&exit_code));
599   EXPECT_EQ(kSuccess, exit_code);
600 }
601 #endif  // !BUILDFLAG(IS_ANDROID)
602 
603 #if BUILDFLAG(IS_WIN)
604 // TODO(cpu): figure out how to test this in other platforms.
TEST_F(ProcessUtilTest,GetProcId)605 TEST_F(ProcessUtilTest, GetProcId) {
606   ProcessId id1 = GetProcId(GetCurrentProcess());
607   EXPECT_NE(0ul, id1);
608   Process process = SpawnChild("SimpleChildProcess");
609   ASSERT_TRUE(process.IsValid());
610   ProcessId id2 = process.Pid();
611   EXPECT_NE(0ul, id2);
612   EXPECT_NE(id1, id2);
613 }
614 #endif  // BUILDFLAG(IS_WIN)
615 
616 #if !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_ANDROID)
617 // This test is disabled on Mac, since it's flaky due to ReportCrash
618 // taking a variable amount of time to parse and load the debug and
619 // symbol data for this unit test's executable before firing the
620 // signal handler.
621 //
622 // TODO(gspencer): turn this test process into a very small program
623 // with no symbols (instead of using the multiprocess testing
624 // framework) to reduce the ReportCrash overhead.
625 //
626 // It is disabled on Android as MultiprocessTests are started as services that
627 // the framework restarts on crashes.
628 const char kSignalFileCrash[] = "CrashingChildProcess.die";
629 
MULTIPROCESS_TEST_MAIN(CrashingChildProcess)630 MULTIPROCESS_TEST_MAIN(CrashingChildProcess) {
631   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash).c_str());
632 #if BUILDFLAG(IS_POSIX)
633   // Have to disable to signal handler for segv so we can get a crash
634   // instead of an abnormal termination through the crash dump handler.
635   ::signal(SIGSEGV, SIG_DFL);
636 #endif
637   // Make this process have a segmentation fault.
638   volatile int* oops = nullptr;
639   *oops = 0xDEAD;
640   return 1;
641 }
642 
643 // This test intentionally crashes, so we don't need to run it under
644 // AddressSanitizer.
645 #if defined(ADDRESS_SANITIZER)
646 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
647 #else
648 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
649 #endif
TEST_F(ProcessUtilTest,MAYBE_GetTerminationStatusCrash)650 TEST_F(ProcessUtilTest, MAYBE_GetTerminationStatusCrash) {
651   const std::string signal_file = GetSignalFilePath(kSignalFileCrash);
652   remove(signal_file.c_str());
653   Process process = SpawnChild("CrashingChildProcess");
654   ASSERT_TRUE(process.IsValid());
655 
656   int exit_code = 42;
657   EXPECT_EQ(TERMINATION_STATUS_STILL_RUNNING,
658             GetTerminationStatus(process.Handle(), &exit_code));
659   EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
660 
661   SignalChildren(signal_file.c_str());
662   exit_code = 42;
663   TerminationStatus status =
664       WaitForChildTermination(process.Handle(), &exit_code);
665   EXPECT_EQ(TERMINATION_STATUS_PROCESS_CRASHED, status);
666 
667 #if BUILDFLAG(IS_WIN)
668   EXPECT_EQ(static_cast<int>(0xc0000005), exit_code);
669 #elif BUILDFLAG(IS_POSIX)
670   int signaled = WIFSIGNALED(exit_code);
671   EXPECT_NE(0, signaled);
672   int signal = WTERMSIG(exit_code);
673   EXPECT_EQ(SIGSEGV, signal);
674 #endif
675 
676   // Reset signal handlers back to "normal".
677   debug::EnableInProcessStackDumping();
678   remove(signal_file.c_str());
679 }
680 #endif  // !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_ANDROID)
681 
MULTIPROCESS_TEST_MAIN(KilledChildProcess)682 MULTIPROCESS_TEST_MAIN(KilledChildProcess) {
683   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill).c_str());
684 #if BUILDFLAG(IS_WIN)
685   // Kill ourselves.
686   HANDLE handle = ::OpenProcess(PROCESS_ALL_ACCESS, 0, ::GetCurrentProcessId());
687   ::TerminateProcess(handle, kExpectedKilledExitCode);
688 #elif BUILDFLAG(IS_POSIX)
689   // Send a SIGKILL to this process, just like the OOM killer would.
690   ::kill(getpid(), SIGKILL);
691 #elif BUILDFLAG(IS_FUCHSIA)
692   zx_task_kill(zx_process_self());
693 #endif
694   return 1;
695 }
696 
697 #if BUILDFLAG(IS_POSIX)
MULTIPROCESS_TEST_MAIN(TerminatedChildProcess)698 MULTIPROCESS_TEST_MAIN(TerminatedChildProcess) {
699   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileTerm).c_str());
700   // Send a SIGTERM to this process.
701   ::kill(getpid(), SIGTERM);
702   return 1;
703 }
704 #endif  // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
705 
TEST_F(ProcessUtilTest,GetTerminationStatusSigKill)706 TEST_F(ProcessUtilTest, GetTerminationStatusSigKill) {
707   const std::string signal_file = GetSignalFilePath(kSignalFileKill);
708   remove(signal_file.c_str());
709   Process process = SpawnChild("KilledChildProcess");
710   ASSERT_TRUE(process.IsValid());
711 
712   int exit_code = 42;
713   EXPECT_EQ(TERMINATION_STATUS_STILL_RUNNING,
714             GetTerminationStatus(process.Handle(), &exit_code));
715   EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
716 
717   SignalChildren(signal_file.c_str());
718   exit_code = 42;
719   TerminationStatus status =
720       WaitForChildTermination(process.Handle(), &exit_code);
721 #if BUILDFLAG(IS_CHROMEOS)
722   EXPECT_EQ(TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM, status);
723 #else
724   EXPECT_EQ(TERMINATION_STATUS_PROCESS_WAS_KILLED, status);
725 #endif
726 
727 #if BUILDFLAG(IS_WIN)
728   EXPECT_EQ(kExpectedKilledExitCode, exit_code);
729 #elif BUILDFLAG(IS_POSIX)
730   int signaled = WIFSIGNALED(exit_code);
731   EXPECT_NE(0, signaled);
732   int signal = WTERMSIG(exit_code);
733   EXPECT_EQ(SIGKILL, signal);
734 #endif
735   remove(signal_file.c_str());
736 }
737 
738 #if BUILDFLAG(IS_POSIX)
739 // TODO(crbug.com/753490): Access to the process termination reason is not
740 // implemented in Fuchsia. Unix signals are not implemented in Fuchsia so this
741 // test might not be relevant anyway.
TEST_F(ProcessUtilTest,GetTerminationStatusSigTerm)742 TEST_F(ProcessUtilTest, GetTerminationStatusSigTerm) {
743   const std::string signal_file = GetSignalFilePath(kSignalFileTerm);
744   remove(signal_file.c_str());
745   Process process = SpawnChild("TerminatedChildProcess");
746   ASSERT_TRUE(process.IsValid());
747 
748   int exit_code = 42;
749   EXPECT_EQ(TERMINATION_STATUS_STILL_RUNNING,
750             GetTerminationStatus(process.Handle(), &exit_code));
751   EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
752 
753   SignalChildren(signal_file.c_str());
754   exit_code = 42;
755   TerminationStatus status =
756       WaitForChildTermination(process.Handle(), &exit_code);
757   EXPECT_EQ(TERMINATION_STATUS_PROCESS_WAS_KILLED, status);
758 
759   int signaled = WIFSIGNALED(exit_code);
760   EXPECT_NE(0, signaled);
761   int signal = WTERMSIG(exit_code);
762   EXPECT_EQ(SIGTERM, signal);
763   remove(signal_file.c_str());
764 }
765 #endif  // BUILDFLAG(IS_POSIX)
766 
TEST_F(ProcessUtilTest,EnsureTerminationUndying)767 TEST_F(ProcessUtilTest, EnsureTerminationUndying) {
768   test::TaskEnvironment task_environment;
769 
770   Process child_process = SpawnChild("process_util_test_never_die");
771   ASSERT_TRUE(child_process.IsValid());
772 
773   EnsureProcessTerminated(child_process.Duplicate());
774 
775 #if BUILDFLAG(IS_POSIX)
776   errno = 0;
777 #endif  // BUILDFLAG(IS_POSIX)
778 
779   // Allow a generous timeout, to cope with slow/loaded test bots.
780   bool did_exit = child_process.WaitForExitWithTimeout(
781       TestTimeouts::action_max_timeout(), nullptr);
782 
783 #if BUILDFLAG(IS_POSIX)
784   // Both EnsureProcessTerminated() and WaitForExitWithTimeout() will call
785   // waitpid(). One will succeed, and the other will fail with ECHILD. If our
786   // wait failed then check for ECHILD, and assumed |did_exit| in that case.
787   did_exit = did_exit || (errno == ECHILD);
788 #endif  // BUILDFLAG(IS_POSIX)
789 
790   EXPECT_TRUE(did_exit);
791 }
792 
MULTIPROCESS_TEST_MAIN(process_util_test_never_die)793 MULTIPROCESS_TEST_MAIN(process_util_test_never_die) {
794   while (true) {
795     PlatformThread::Sleep(Seconds(500));
796   }
797 }
798 
TEST_F(ProcessUtilTest,EnsureTerminationGracefulExit)799 TEST_F(ProcessUtilTest, EnsureTerminationGracefulExit) {
800   test::TaskEnvironment task_environment;
801 
802   Process child_process = SpawnChild("process_util_test_die_immediately");
803   ASSERT_TRUE(child_process.IsValid());
804 
805   // Wait for the child process to actually exit.
806   child_process.Duplicate().WaitForExitWithTimeout(
807       TestTimeouts::action_max_timeout(), nullptr);
808 
809   EnsureProcessTerminated(child_process.Duplicate());
810 
811   // Verify that the process is really, truly gone.
812   EXPECT_TRUE(child_process.WaitForExitWithTimeout(
813       TestTimeouts::action_max_timeout(), nullptr));
814 }
815 
MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately)816 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately) {
817   return kSuccess;
818 }
819 
820 #if BUILDFLAG(IS_WIN)
821 // TODO(estade): if possible, port this test.
TEST_F(ProcessUtilTest,LaunchAsUser)822 TEST_F(ProcessUtilTest, LaunchAsUser) {
823   UserTokenHandle token;
824   ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token));
825   LaunchOptions options;
826   options.as_user = token;
827   EXPECT_TRUE(
828       LaunchProcess(MakeCmdLine("SimpleChildProcess"), options).IsValid());
829 }
830 
MULTIPROCESS_TEST_MAIN(ChildVerifiesCetDisabled)831 MULTIPROCESS_TEST_MAIN(ChildVerifiesCetDisabled) {
832   // Policy not defined for Win < Win10 20H1 but that's ok.
833   PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY policy = {};
834   if (GetProcessMitigationPolicy(GetCurrentProcess(),
835                                  ProcessUserShadowStackPolicy, &policy,
836                                  sizeof(policy))) {
837     if (policy.EnableUserShadowStack)
838       return 1;
839   }
840   return kSuccess;
841 }
842 
TEST_F(ProcessUtilTest,LaunchDisablingCetCompat)843 TEST_F(ProcessUtilTest, LaunchDisablingCetCompat) {
844   LaunchOptions options;
845   // This only has an effect on Windows > 20H2 with CET hardware but
846   // is safe on every platform.
847   options.disable_cetcompat = true;
848   EXPECT_TRUE(LaunchProcess(MakeCmdLine("ChildVerifiesCetDisabled"), options)
849                   .IsValid());
850 }
851 
852 static const char kEventToTriggerHandleSwitch[] = "event-to-trigger-handle";
853 
MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess)854 MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess) {
855   std::string handle_value_string =
856       CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
857           kEventToTriggerHandleSwitch);
858   CHECK(!handle_value_string.empty());
859 
860   uint64_t handle_value_uint64;
861   CHECK(StringToUint64(handle_value_string, &handle_value_uint64));
862   // Give ownership of the handle to |event|.
863   WaitableEvent event(
864       win::ScopedHandle(reinterpret_cast<HANDLE>(handle_value_uint64)));
865 
866   event.Signal();
867 
868   return 0;
869 }
870 
TEST_F(ProcessUtilTest,InheritSpecifiedHandles)871 TEST_F(ProcessUtilTest, InheritSpecifiedHandles) {
872   // Manually create the event, so that it can be inheritable.
873   SECURITY_ATTRIBUTES security_attributes = {};
874   security_attributes.nLength = static_cast<DWORD>(sizeof(security_attributes));
875   security_attributes.lpSecurityDescriptor = NULL;
876   security_attributes.bInheritHandle = true;
877 
878   // Takes ownership of the event handle.
879   WaitableEvent event(
880       win::ScopedHandle(CreateEvent(&security_attributes, true, false, NULL)));
881   LaunchOptions options;
882   options.handles_to_inherit.emplace_back(event.handle());
883 
884   CommandLine cmd_line = MakeCmdLine("TriggerEventChildProcess");
885   cmd_line.AppendSwitchASCII(
886       kEventToTriggerHandleSwitch,
887       NumberToString(reinterpret_cast<uint64_t>(event.handle())));
888 
889   // Launch the process and wait for it to trigger the event.
890   ASSERT_TRUE(LaunchProcess(cmd_line, options).IsValid());
891   EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
892 }
893 #endif  // BUILDFLAG(IS_WIN)
894 
TEST_F(ProcessUtilTest,GetAppOutput)895 TEST_F(ProcessUtilTest, GetAppOutput) {
896   CommandLine command(test_helper_path_);
897   command.AppendArg("hello");
898   command.AppendArg("there");
899   command.AppendArg("good");
900   command.AppendArg("people");
901   std::string output;
902   EXPECT_TRUE(GetAppOutput(command, &output));
903   EXPECT_EQ("hello there good people", output);
904   output.clear();
905 
906   const char* kEchoMessage = "blah";
907   command = CommandLine(test_helper_path_);
908   command.AppendArg("-x");
909   command.AppendArg("28");
910   command.AppendArg(kEchoMessage);
911   EXPECT_FALSE(GetAppOutput(command, &output));
912   EXPECT_EQ(kEchoMessage, output);
913 }
914 
TEST_F(ProcessUtilTest,GetAppOutputWithExitCode)915 TEST_F(ProcessUtilTest, GetAppOutputWithExitCode) {
916   const char* kEchoMessage1 = "doge";
917   int exit_code = -1;
918   CommandLine command(test_helper_path_);
919   command.AppendArg(kEchoMessage1);
920   std::string output;
921   EXPECT_TRUE(GetAppOutputWithExitCode(command, &output, &exit_code));
922   EXPECT_EQ(kEchoMessage1, output);
923   EXPECT_EQ(0, exit_code);
924   output.clear();
925 
926   const char* kEchoMessage2 = "pupper";
927   const int kExpectedExitCode = 42;
928   command = CommandLine(test_helper_path_);
929   command.AppendArg("-x");
930   command.AppendArg(NumberToString(kExpectedExitCode));
931   command.AppendArg(kEchoMessage2);
932 #if BUILDFLAG(IS_WIN)
933   // On Windows, anything that quits with a nonzero status code is handled as a
934   // "crash", so just ignore GetAppOutputWithExitCode's return value.
935   GetAppOutputWithExitCode(command, &output, &exit_code);
936 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
937   EXPECT_TRUE(GetAppOutputWithExitCode(command, &output, &exit_code));
938 #endif
939   EXPECT_EQ(kEchoMessage2, output);
940   EXPECT_EQ(kExpectedExitCode, exit_code);
941 }
942 
943 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
944 
945 namespace {
946 
947 // Returns the maximum number of files that a process can have open.
948 // Returns 0 on error.
GetMaxFilesOpenInProcess()949 int GetMaxFilesOpenInProcess() {
950 #if BUILDFLAG(IS_FUCHSIA)
951   return FDIO_MAX_FD;
952 #else
953   struct rlimit rlim;
954   if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
955     return 0;
956   }
957 
958   // rlim_t is a uint64_t - clip to maxint. We do this since FD #s are ints
959   // which are all 32 bits on the supported platforms.
960   rlim_t max_int = static_cast<rlim_t>(std::numeric_limits<int32_t>::max());
961   if (rlim.rlim_cur > max_int) {
962     return max_int;
963   }
964 
965   return rlim.rlim_cur;
966 #endif  // BUILDFLAG(IS_FUCHSIA)
967 }
968 
969 const int kChildPipe = 20;  // FD # for write end of pipe in child process.
970 
971 #if BUILDFLAG(IS_APPLE)
972 
973 // Declarations from 12.3 xnu-8020.101.4/bsd/sys/guarded.h (not in the SDK).
974 extern "C" {
975 
976 using guardid_t = uint64_t;
977 
978 #define GUARD_DUP (1u << 1)
979 
980 int change_fdguard_np(int fd,
981                       const guardid_t* guard,
982                       unsigned int guardflags,
983                       const guardid_t* nguard,
984                       unsigned int nguardflags,
985                       int* fdflagsp);
986 
987 }  // extern "C"
988 
989 // Attempt to set a file-descriptor guard on |fd|.  In case of success, remove
990 // it and return |true| to indicate that it can be guarded.  Returning |false|
991 // means either that |fd| is guarded by some other code, or more likely EBADF.
992 //
993 // Starting with 10.9, libdispatch began setting GUARD_DUP on a file descriptor.
994 // Unfortunately, it is spun up as part of +[NSApplication initialize], which is
995 // not really something that Chromium can avoid using on OSX.  See
996 // <http://crbug.com/338157>.  This function allows querying whether the file
997 // descriptor is guarded before attempting to close it.
CanGuardFd(int fd)998 bool CanGuardFd(int fd) {
999   // Saves the original flags to reset later.
1000   int original_fdflags = 0;
1001 
1002   // This can be any value at all, it just has to match up between the two
1003   // calls.
1004   const guardid_t kGuard = 15;
1005 
1006   // Attempt to change the guard.  This can fail with EBADF if the file
1007   // descriptor is bad, or EINVAL if the fd already has a guard set.
1008   int ret =
1009       change_fdguard_np(fd, NULL, 0, &kGuard, GUARD_DUP, &original_fdflags);
1010   if (ret == -1)
1011     return false;
1012 
1013   // Remove the guard.  It should not be possible to fail in removing the guard
1014   // just added.
1015   ret = change_fdguard_np(fd, &kGuard, GUARD_DUP, NULL, 0, &original_fdflags);
1016   DPCHECK(ret == 0);
1017 
1018   return true;
1019 }
1020 #endif  // BUILDFLAG(IS_APPLE)
1021 
1022 }  // namespace
1023 
MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess)1024 MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess) {
1025   // This child process counts the number of open FDs, it then writes that
1026   // number out to a pipe connected to the parent.
1027   int num_open_files = 0;
1028   int write_pipe = kChildPipe;
1029   int max_files = GetMaxFilesOpenInProcess();
1030   for (int i = STDERR_FILENO + 1; i < max_files; i++) {
1031 #if BUILDFLAG(IS_APPLE)
1032     // Ignore guarded or invalid file descriptors.
1033     if (!CanGuardFd(i))
1034       continue;
1035 #endif
1036 
1037     if (i != kChildPipe) {
1038       int fd;
1039       if ((fd = HANDLE_EINTR(dup(i))) != -1) {
1040         close(fd);
1041         num_open_files += 1;
1042       }
1043     }
1044   }
1045 
1046   int written =
1047       HANDLE_EINTR(write(write_pipe, &num_open_files, sizeof(num_open_files)));
1048   DCHECK_EQ(static_cast<size_t>(written), sizeof(num_open_files));
1049   int ret = IGNORE_EINTR(close(write_pipe));
1050   DPCHECK(ret == 0);
1051 
1052   return 0;
1053 }
1054 
CountOpenFDsInChild()1055 int ProcessUtilTest::CountOpenFDsInChild() {
1056   int fds[2];
1057   if (pipe(fds) < 0)
1058     NOTREACHED();
1059 
1060   LaunchOptions options;
1061   options.fds_to_remap.emplace_back(fds[1], kChildPipe);
1062   Process process =
1063       SpawnChildWithOptions("ProcessUtilsLeakFDChildProcess", options);
1064   CHECK(process.IsValid());
1065   int ret = IGNORE_EINTR(close(fds[1]));
1066   DPCHECK(ret == 0);
1067 
1068   // Read number of open files in client process from pipe;
1069   int num_open_files = -1;
1070   ssize_t bytes_read =
1071       HANDLE_EINTR(read(fds[0], &num_open_files, sizeof(num_open_files)));
1072   CHECK_EQ(bytes_read, static_cast<ssize_t>(sizeof(num_open_files)));
1073 
1074 #if defined(THREAD_SANITIZER)
1075   // Compiler-based ThreadSanitizer makes this test slow.
1076   TimeDelta timeout = Seconds(3);
1077 #else
1078   TimeDelta timeout = Seconds(1);
1079 #endif
1080   int exit_code;
1081   CHECK(process.WaitForExitWithTimeout(timeout, &exit_code));
1082   ret = IGNORE_EINTR(close(fds[0]));
1083   DPCHECK(ret == 0);
1084 
1085   return num_open_files;
1086 }
1087 
TEST_F(ProcessUtilTest,FDRemapping)1088 TEST_F(ProcessUtilTest, FDRemapping) {
1089   int fds_before = CountOpenFDsInChild();
1090 
1091   // Open some dummy fds to make sure they don't propagate over to the
1092   // child process.
1093 #if BUILDFLAG(IS_FUCHSIA)
1094   ScopedFD dev_null(fdio_fd_create_null());
1095 #else
1096   ScopedFD dev_null(open("/dev/null", O_RDONLY));
1097 #endif  // BUILDFLAG(IS_FUCHSIA)
1098 
1099   DPCHECK(dev_null.get() > 0);
1100   int sockets[2];
1101   int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
1102   DPCHECK(ret == 0);
1103 
1104   int fds_after = CountOpenFDsInChild();
1105 
1106   ASSERT_EQ(fds_after, fds_before);
1107 
1108   ret = IGNORE_EINTR(close(sockets[0]));
1109   DPCHECK(ret == 0);
1110   ret = IGNORE_EINTR(close(sockets[1]));
1111   DPCHECK(ret == 0);
1112 }
1113 
1114 const char kPipeValue = '\xcc';
MULTIPROCESS_TEST_MAIN(ProcessUtilsVerifyStdio)1115 MULTIPROCESS_TEST_MAIN(ProcessUtilsVerifyStdio) {
1116   // Write to stdio so the parent process can observe output.
1117   CHECK_EQ(1, HANDLE_EINTR(write(STDOUT_FILENO, &kPipeValue, 1)));
1118 
1119   // Close all of the handles, to verify they are valid.
1120   CHECK_EQ(0, IGNORE_EINTR(close(STDIN_FILENO)));
1121   CHECK_EQ(0, IGNORE_EINTR(close(STDOUT_FILENO)));
1122   CHECK_EQ(0, IGNORE_EINTR(close(STDERR_FILENO)));
1123   return 0;
1124 }
1125 
TEST_F(ProcessUtilTest,FDRemappingIncludesStdio)1126 TEST_F(ProcessUtilTest, FDRemappingIncludesStdio) {
1127 #if BUILDFLAG(IS_FUCHSIA)
1128   // The fd obtained from fdio_fd_create_null cannot be cloned while spawning a
1129   // child proc, so open a true file in a transient temp dir.
1130   ScopedTempDir temp_dir;
1131   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1132   FilePath temp_file_path;
1133   ASSERT_TRUE(CreateTemporaryFileInDir(temp_dir.GetPath(), &temp_file_path));
1134   File temp_file(temp_file_path,
1135                  File::FLAG_CREATE_ALWAYS | File::FLAG_READ | File::FLAG_WRITE);
1136   ASSERT_TRUE(temp_file.IsValid());
1137   ScopedFD some_fd(temp_file.TakePlatformFile());
1138 #else   // BUILDFLAG(IS_FUCHSIA)
1139   ScopedFD some_fd(open("/dev/null", O_RDONLY));
1140 #endif  // BUILDFLAG(IS_FUCHSIA)
1141   ASSERT_LT(2, some_fd.get());
1142 
1143   // Backup stdio and replace it with the write end of a pipe, for our
1144   // child process to inherit.
1145   int pipe_fds[2];
1146   int result = pipe(pipe_fds);
1147   ASSERT_EQ(0, result);
1148   int backup_stdio = HANDLE_EINTR(dup(STDOUT_FILENO));
1149   ASSERT_LE(0, backup_stdio);
1150   result = dup2(pipe_fds[1], STDOUT_FILENO);
1151   ASSERT_EQ(STDOUT_FILENO, result);
1152 
1153   // Launch the test process, which should inherit our pipe stdio.
1154   LaunchOptions options;
1155   options.fds_to_remap.emplace_back(some_fd.get(), some_fd.get());
1156   Process process = SpawnChildWithOptions("ProcessUtilsVerifyStdio", options);
1157   ASSERT_TRUE(process.IsValid());
1158 
1159   // Restore stdio, so we can output stuff.
1160   result = dup2(backup_stdio, STDOUT_FILENO);
1161   ASSERT_EQ(STDOUT_FILENO, result);
1162 
1163   // Close our copy of the write end of the pipe, so that the read()
1164   // from the other end will see EOF if it wasn't copied to the child.
1165   result = IGNORE_EINTR(close(pipe_fds[1]));
1166   ASSERT_EQ(0, result);
1167 
1168   result = IGNORE_EINTR(close(backup_stdio));
1169   ASSERT_EQ(0, result);
1170   // Also close the remapped descriptor.
1171   some_fd.reset();
1172 
1173   // Read from the pipe to verify that it is connected to the child
1174   // process' stdio.
1175   char buf[16] = {};
1176   EXPECT_EQ(1, HANDLE_EINTR(read(pipe_fds[0], buf, sizeof(buf))));
1177   EXPECT_EQ(kPipeValue, buf[0]);
1178 
1179   result = IGNORE_EINTR(close(pipe_fds[0]));
1180   ASSERT_EQ(0, result);
1181 
1182   int exit_code;
1183   ASSERT_TRUE(process.WaitForExitWithTimeout(Seconds(5), &exit_code));
1184   EXPECT_EQ(0, exit_code);
1185 }
1186 
1187 #if BUILDFLAG(IS_FUCHSIA)
1188 
1189 const uint16_t kStartupHandleId = 43;
MULTIPROCESS_TEST_MAIN(ProcessUtilsVerifyHandle)1190 MULTIPROCESS_TEST_MAIN(ProcessUtilsVerifyHandle) {
1191   zx_handle_t handle =
1192       zx_take_startup_handle(PA_HND(PA_USER0, kStartupHandleId));
1193   CHECK_NE(ZX_HANDLE_INVALID, handle);
1194 
1195   // Write to the pipe so the parent process can observe output.
1196   size_t bytes_written = 0;
1197   zx_status_t result = zx_socket_write(handle, 0, &kPipeValue,
1198                                        sizeof(kPipeValue), &bytes_written);
1199   CHECK_EQ(ZX_OK, result);
1200   CHECK_EQ(1u, bytes_written);
1201 
1202   CHECK_EQ(ZX_OK, zx_handle_close(handle));
1203   return 0;
1204 }
1205 
TEST_F(ProcessUtilTest,LaunchWithHandleTransfer)1206 TEST_F(ProcessUtilTest, LaunchWithHandleTransfer) {
1207   // Create a pipe to pass to the child process.
1208   zx_handle_t handles[2];
1209   zx_status_t result =
1210       zx_socket_create(ZX_SOCKET_STREAM, &handles[0], &handles[1]);
1211   ASSERT_EQ(ZX_OK, result);
1212 
1213   // Launch the test process, and pass it one end of the pipe.
1214   LaunchOptions options;
1215   options.handles_to_transfer.push_back(
1216       {PA_HND(PA_USER0, kStartupHandleId), handles[0]});
1217   Process process = SpawnChildWithOptions("ProcessUtilsVerifyHandle", options);
1218   ASSERT_TRUE(process.IsValid());
1219 
1220   // Read from the pipe to verify that the child received it.
1221   zx_signals_t signals = 0;
1222   result = zx_object_wait_one(
1223       handles[1], ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED,
1224       (TimeTicks::Now() + TestTimeouts::action_timeout()).ToZxTime(), &signals);
1225   ASSERT_EQ(ZX_OK, result);
1226   ASSERT_TRUE(signals & ZX_SOCKET_READABLE);
1227 
1228   size_t bytes_read = 0;
1229   char buf[16] = {0};
1230   result = zx_socket_read(handles[1], 0, buf, sizeof(buf), &bytes_read);
1231   EXPECT_EQ(ZX_OK, result);
1232   EXPECT_EQ(1u, bytes_read);
1233   EXPECT_EQ(kPipeValue, buf[0]);
1234 
1235   CHECK_EQ(ZX_OK, zx_handle_close(handles[1]));
1236 
1237   int exit_code;
1238   ASSERT_TRUE(process.WaitForExitWithTimeout(TestTimeouts::action_timeout(),
1239                                              &exit_code));
1240   EXPECT_EQ(0, exit_code);
1241 }
1242 
1243 #endif  // BUILDFLAG(IS_FUCHSIA)
1244 
1245 // There's no such thing as a parent process id on Fuchsia.
1246 #if !BUILDFLAG(IS_FUCHSIA)
TEST_F(ProcessUtilTest,GetParentProcessId)1247 TEST_F(ProcessUtilTest, GetParentProcessId) {
1248   ProcessId ppid = GetParentProcessId(GetCurrentProcessHandle());
1249   EXPECT_EQ(ppid, static_cast<ProcessId>(getppid()));
1250 }
1251 #endif  // !BUILDFLAG(IS_FUCHSIA)
1252 
1253 #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA) && !BUILDFLAG(IS_APPLE)
1254 class WriteToPipeDelegate : public LaunchOptions::PreExecDelegate {
1255  public:
WriteToPipeDelegate(int fd)1256   explicit WriteToPipeDelegate(int fd) : fd_(fd) {}
1257 
1258   WriteToPipeDelegate(const WriteToPipeDelegate&) = delete;
1259   WriteToPipeDelegate& operator=(const WriteToPipeDelegate&) = delete;
1260 
1261   ~WriteToPipeDelegate() override = default;
RunAsyncSafe()1262   void RunAsyncSafe() override {
1263     RAW_CHECK(HANDLE_EINTR(write(fd_, &kPipeValue, 1)) == 1);
1264     RAW_CHECK(IGNORE_EINTR(close(fd_)) == 0);
1265   }
1266 
1267  private:
1268   int fd_;
1269 };
1270 
TEST_F(ProcessUtilTest,PreExecHook)1271 TEST_F(ProcessUtilTest, PreExecHook) {
1272   int pipe_fds[2];
1273   ASSERT_EQ(0, pipe(pipe_fds));
1274 
1275   ScopedFD read_fd(pipe_fds[0]);
1276   ScopedFD write_fd(pipe_fds[1]);
1277 
1278   WriteToPipeDelegate write_to_pipe_delegate(write_fd.get());
1279   LaunchOptions options;
1280   options.fds_to_remap.emplace_back(write_fd.get(), write_fd.get());
1281   options.pre_exec_delegate = &write_to_pipe_delegate;
1282   Process process(SpawnChildWithOptions("SimpleChildProcess", options));
1283   ASSERT_TRUE(process.IsValid());
1284 
1285   write_fd.reset();
1286   char c;
1287   ASSERT_EQ(1, HANDLE_EINTR(read(read_fd.get(), &c, 1)));
1288   EXPECT_EQ(c, kPipeValue);
1289 
1290   int exit_code = 42;
1291   EXPECT_TRUE(process.WaitForExit(&exit_code));
1292   EXPECT_EQ(0, exit_code);
1293 }
1294 #endif  // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_FUCHSIA)
1295 
1296 #endif  // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
1297 
1298 // There's no such thing as a parent process id on Fuchsia.
1299 #if !BUILDFLAG(IS_FUCHSIA)
TEST_F(ProcessUtilTest,GetParentProcessId2)1300 TEST_F(ProcessUtilTest, GetParentProcessId2) {
1301   ProcessId id1 = GetCurrentProcId();
1302   Process process = SpawnChild("SimpleChildProcess");
1303   ASSERT_TRUE(process.IsValid());
1304   ProcessId ppid = GetParentProcessId(process.Handle());
1305   EXPECT_EQ(ppid, id1);
1306 }
1307 #endif  // !BUILDFLAG(IS_FUCHSIA)
1308 
1309 namespace {
1310 
TestLaunchProcess(const CommandLine & cmdline,const EnvironmentMap & env_changes,const bool clear_environment,const int clone_flags)1311 std::string TestLaunchProcess(const CommandLine& cmdline,
1312                               const EnvironmentMap& env_changes,
1313                               const bool clear_environment,
1314                               const int clone_flags) {
1315   LaunchOptions options;
1316   options.wait = true;
1317   options.environment = env_changes;
1318   options.clear_environment = clear_environment;
1319 
1320 #if BUILDFLAG(IS_WIN)
1321   HANDLE read_handle, write_handle;
1322   PCHECK(CreatePipe(&read_handle, &write_handle, nullptr, 0));
1323   File read_pipe(read_handle);
1324   File write_pipe(write_handle);
1325   options.stdin_handle = INVALID_HANDLE_VALUE;
1326   options.stdout_handle = write_handle;
1327   options.stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
1328   options.handles_to_inherit.push_back(write_handle);
1329 #else
1330   int fds[2];
1331   PCHECK(pipe(fds) == 0);
1332   File read_pipe(fds[0]);
1333   File write_pipe(fds[1]);
1334   options.fds_to_remap.emplace_back(fds[1], STDOUT_FILENO);
1335 #endif  // BUILDFLAG(IS_WIN)
1336 
1337 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1338   options.clone_flags = clone_flags;
1339 #else
1340   CHECK_EQ(0, clone_flags);
1341 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1342 
1343   EXPECT_TRUE(LaunchProcess(cmdline, options).IsValid());
1344   write_pipe.Close();
1345 
1346   char buf[512];
1347   int n = read_pipe.ReadAtCurrentPos(buf, sizeof(buf));
1348 #if BUILDFLAG(IS_WIN)
1349   // Closed pipes fail with ERROR_BROKEN_PIPE on Windows, rather than
1350   // successfully reporting EOF.
1351   if (n < 0 && GetLastError() == ERROR_BROKEN_PIPE) {
1352     n = 0;
1353   }
1354 #endif  // BUILDFLAG(IS_WIN)
1355   PCHECK(n >= 0);
1356 
1357   return std::string(buf, n);
1358 }
1359 
1360 const char kLargeString[] =
1361     "0123456789012345678901234567890123456789012345678901234567890123456789"
1362     "0123456789012345678901234567890123456789012345678901234567890123456789"
1363     "0123456789012345678901234567890123456789012345678901234567890123456789"
1364     "0123456789012345678901234567890123456789012345678901234567890123456789"
1365     "0123456789012345678901234567890123456789012345678901234567890123456789"
1366     "0123456789012345678901234567890123456789012345678901234567890123456789"
1367     "0123456789012345678901234567890123456789012345678901234567890123456789";
1368 
1369 }  // namespace
1370 
TEST_F(ProcessUtilTest,LaunchProcess)1371 TEST_F(ProcessUtilTest, LaunchProcess) {
1372   const int no_clone_flags = 0;
1373   const bool no_clear_environ = false;
1374   const FilePath::CharType kBaseTest[] = FILE_PATH_LITERAL("BASE_TEST");
1375   const CommandLine kPrintEnvCommand(CommandLine::StringVector(
1376       {test_helper_path_.value(), FILE_PATH_LITERAL("-e"), kBaseTest}));
1377   std::unique_ptr<Environment> env = Environment::Create();
1378 
1379   EnvironmentMap env_changes;
1380   env_changes[kBaseTest] = FILE_PATH_LITERAL("bar");
1381   EXPECT_EQ("bar", TestLaunchProcess(kPrintEnvCommand, env_changes,
1382                                      no_clear_environ, no_clone_flags));
1383   env_changes.clear();
1384 
1385   EXPECT_TRUE(env->SetVar("BASE_TEST", "testing"));
1386   EXPECT_EQ("testing", TestLaunchProcess(kPrintEnvCommand, env_changes,
1387                                          no_clear_environ, no_clone_flags));
1388 
1389   env_changes[kBaseTest] = FilePath::StringType();
1390   EXPECT_EQ("", TestLaunchProcess(kPrintEnvCommand, env_changes,
1391                                   no_clear_environ, no_clone_flags));
1392 
1393   env_changes[kBaseTest] = FILE_PATH_LITERAL("foo");
1394   EXPECT_EQ("foo", TestLaunchProcess(kPrintEnvCommand, env_changes,
1395                                      no_clear_environ, no_clone_flags));
1396 
1397   env_changes.clear();
1398   EXPECT_TRUE(env->SetVar("BASE_TEST", kLargeString));
1399   EXPECT_EQ(std::string(kLargeString),
1400             TestLaunchProcess(kPrintEnvCommand, env_changes, no_clear_environ,
1401                               no_clone_flags));
1402 
1403   env_changes[kBaseTest] = FILE_PATH_LITERAL("wibble");
1404   EXPECT_EQ("wibble", TestLaunchProcess(kPrintEnvCommand, env_changes,
1405                                         no_clear_environ, no_clone_flags));
1406 
1407 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1408   // Test a non-trival value for clone_flags.
1409   EXPECT_EQ("wibble", TestLaunchProcess(kPrintEnvCommand, env_changes,
1410                                         no_clear_environ, CLONE_FS));
1411 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1412 
1413   EXPECT_EQ("wibble",
1414             TestLaunchProcess(kPrintEnvCommand, env_changes,
1415                               true /* clear_environ */, no_clone_flags));
1416   env_changes.clear();
1417   EXPECT_EQ("", TestLaunchProcess(kPrintEnvCommand, env_changes,
1418                                   true /* clear_environ */, no_clone_flags));
1419 }
1420 
1421 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
MULTIPROCESS_TEST_MAIN(CheckPidProcess)1422 MULTIPROCESS_TEST_MAIN(CheckPidProcess) {
1423   const pid_t kInitPid = 1;
1424   const pid_t pid = syscall(__NR_getpid);
1425   CHECK(pid == kInitPid);
1426   CHECK(getpid() == pid);
1427   return kSuccess;
1428 }
1429 
1430 #if defined(CLONE_NEWUSER) && defined(CLONE_NEWPID)
TEST_F(ProcessUtilTest,CloneFlags)1431 TEST_F(ProcessUtilTest, CloneFlags) {
1432   if (!PathExists(FilePath("/proc/self/ns/user")) ||
1433       !PathExists(FilePath("/proc/self/ns/pid"))) {
1434     // User or PID namespaces are not supported.
1435     return;
1436   }
1437 
1438   LaunchOptions options;
1439   options.clone_flags = CLONE_NEWUSER | CLONE_NEWPID;
1440 
1441   Process process(SpawnChildWithOptions("CheckPidProcess", options));
1442   ASSERT_TRUE(process.IsValid());
1443 
1444   int exit_code = 42;
1445   EXPECT_TRUE(process.WaitForExit(&exit_code));
1446   EXPECT_EQ(kSuccess, exit_code);
1447 }
1448 #endif  // defined(CLONE_NEWUSER) && defined(CLONE_NEWPID)
1449 
TEST(ForkWithFlagsTest,UpdatesPidCache)1450 TEST(ForkWithFlagsTest, UpdatesPidCache) {
1451   // Warm up the libc pid cache, if there is one.
1452   ASSERT_EQ(syscall(__NR_getpid), getpid());
1453 
1454   pid_t ctid = 0;
1455   const pid_t pid = ForkWithFlags(SIGCHLD | CLONE_CHILD_SETTID, nullptr, &ctid);
1456   if (pid == 0) {
1457     // In child.  Check both the raw getpid syscall and the libc getpid wrapper
1458     // (which may rely on a pid cache).
1459     RAW_CHECK(syscall(__NR_getpid) == ctid);
1460     RAW_CHECK(getpid() == ctid);
1461     _exit(kSuccess);
1462   }
1463 
1464   ASSERT_NE(-1, pid);
1465   int status = 42;
1466   ASSERT_EQ(pid, HANDLE_EINTR(waitpid(pid, &status, 0)));
1467   ASSERT_TRUE(WIFEXITED(status));
1468   EXPECT_EQ(kSuccess, WEXITSTATUS(status));
1469 }
1470 
TEST_F(ProcessUtilTest,InvalidCurrentDirectory)1471 TEST_F(ProcessUtilTest, InvalidCurrentDirectory) {
1472   LaunchOptions options;
1473   options.current_directory = FilePath("/dev/null");
1474 
1475   Process process(SpawnChildWithOptions("SimpleChildProcess", options));
1476   ASSERT_TRUE(process.IsValid());
1477 
1478   int exit_code = kSuccess;
1479   EXPECT_TRUE(process.WaitForExit(&exit_code));
1480   EXPECT_NE(kSuccess, exit_code);
1481 }
1482 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
1483 
1484 }  // namespace base
1485