summaryrefslogtreecommitdiff
path: root/base/test/multiprocess_test_android.cc
blob: f58b452d1cb316184884c6e7e19a196ed6a90c8c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/test/multiprocess_test.h"

#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#include <memory>
#include <utility>
#include <vector>

#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/containers/hash_tables.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/pickle.h"
#include "base/posix/global_descriptors.h"
#include "base/posix/unix_domain_socket_linux.h"
#include "testing/multiprocess_func_list.h"

namespace base {

namespace {

const int kMaxMessageSize = 1024 * 1024;
const int kFragmentSize = 4096;

// Message sent between parent process and helper child process.
enum class MessageType : uint32_t {
  START_REQUEST,
  START_RESPONSE,
  WAIT_REQUEST,
  WAIT_RESPONSE,
};

struct MessageHeader {
  uint32_t size;
  MessageType type;
};

struct StartProcessRequest {
  MessageHeader header =
      {sizeof(StartProcessRequest), MessageType::START_REQUEST};

  uint32_t num_args = 0;
  uint32_t num_fds = 0;
};

struct StartProcessResponse {
  MessageHeader header =
      {sizeof(StartProcessResponse), MessageType::START_RESPONSE};

  pid_t child_pid;
};

struct WaitProcessRequest {
  MessageHeader header =
      {sizeof(WaitProcessRequest), MessageType::WAIT_REQUEST};

  pid_t pid;
  uint64_t timeout_ms;
};

struct WaitProcessResponse {
  MessageHeader header =
      {sizeof(WaitProcessResponse), MessageType::WAIT_RESPONSE};

  bool success = false;
  int32_t exit_code = 0;
};

// Helper class that implements an alternate test child launcher for
// multi-process tests. The default implementation doesn't work if the child is
// launched after starting threads. However, for some tests (i.e. Mojo), this
// is necessary. This implementation works around that issue by forking a helper
// process very early in main(), before any real work is done. Then, when a
// child needs to be spawned, a message is sent to that helper process, which
// then forks and returns the result to the parent. The forked child then calls
// main() and things look as though a brand new process has been fork/exec'd.
class LaunchHelper {
 public:
  using MainFunction = int (*)(int, char**);

  LaunchHelper() {}

  // Initialise the alternate test child implementation.
  void Init(MainFunction main);

  // Starts a child test helper process.
  Process StartChildTestHelper(const std::string& procname,
                               const CommandLine& base_command_line,
                               const LaunchOptions& options);

  // Waits for a child test helper process.
  bool WaitForChildExitWithTimeout(const Process& process, TimeDelta timeout,
                                   int* exit_code);

  bool IsReady() const { return child_fd_ != -1; }
  bool IsChild() const { return is_child_; }

 private:
  // Wrappers around sendmsg/recvmsg that supports message fragmentation.
  void Send(int fd, const MessageHeader* msg, const std::vector<int>& fds);
  ssize_t Recv(int fd, void* buf, std::vector<ScopedFD>* fds);

  // Parent process implementation.
  void DoParent(int fd);
  // Helper process implementation.
  void DoHelper(int fd);

  void StartProcessInHelper(const StartProcessRequest* request,
                           std::vector<ScopedFD> fds);
  void WaitForChildInHelper(const WaitProcessRequest* request);

  bool is_child_ = false;

  // Parent vars.
  int child_fd_ = -1;

  // Helper vars.
  int parent_fd_ = -1;
  MainFunction main_ = nullptr;

  DISALLOW_COPY_AND_ASSIGN(LaunchHelper);
};

void LaunchHelper::Init(MainFunction main) {
  main_ = main;

  // Create a communication channel between the parent and child launch helper.
  // fd[0] belongs to the parent, fd[1] belongs to the child.
  int fds[2] = {-1, -1};
  int rv = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds);
  PCHECK(rv == 0);
  CHECK_NE(-1, fds[0]);
  CHECK_NE(-1, fds[1]);

  pid_t pid = fork();
  PCHECK(pid >= 0) << "Fork failed";
  if (pid) {
    // Parent.
    rv = close(fds[1]);
    PCHECK(rv == 0);
    DoParent(fds[0]);
  } else {
    // Helper.
    rv = close(fds[0]);
    PCHECK(rv == 0);
    DoHelper(fds[1]);
    NOTREACHED();
    _exit(0);
  }
}

void LaunchHelper::Send(
    int fd, const MessageHeader* msg, const std::vector<int>& fds) {
  uint32_t bytes_remaining = msg->size;
  const char* buf = reinterpret_cast<const char*>(msg);
  while (bytes_remaining) {
    size_t send_size =
        (bytes_remaining > kFragmentSize) ? kFragmentSize : bytes_remaining;
    bool success = UnixDomainSocket::SendMsg(
        fd, buf, send_size,
        (bytes_remaining == msg->size) ? fds : std::vector<int>());
    CHECK(success);
    bytes_remaining -= send_size;
    buf += send_size;
  }
}

ssize_t LaunchHelper::Recv(int fd, void* buf, std::vector<ScopedFD>* fds) {
  ssize_t size = UnixDomainSocket::RecvMsg(fd, buf, kFragmentSize, fds);
  if (size <= 0)
    return size;

  const MessageHeader* header = reinterpret_cast<const MessageHeader*>(buf);
  CHECK(header->size < kMaxMessageSize);
  uint32_t bytes_remaining = header->size - size;
  char* buffer = reinterpret_cast<char*>(buf);
  buffer += size;
  while (bytes_remaining) {
    std::vector<ScopedFD> dummy_fds;
    size = UnixDomainSocket::RecvMsg(fd, buffer, kFragmentSize, &dummy_fds);
    if (size <= 0)
      return size;

    CHECK(dummy_fds.empty());
    CHECK(size == kFragmentSize ||
          static_cast<size_t>(size) == bytes_remaining);
    bytes_remaining -= size;
    buffer += size;
  }
  return header->size;
}

void LaunchHelper::DoParent(int fd) {
  child_fd_ = fd;
}

void LaunchHelper::DoHelper(int fd) {
  parent_fd_ = fd;
  is_child_ = true;
  std::unique_ptr<char[]> buf(new char[kMaxMessageSize]);
  while (true) {
    // Wait for a message from the parent.
    std::vector<ScopedFD> fds;
    ssize_t size = Recv(parent_fd_, buf.get(), &fds);
    if (size == 0 || (size < 0 && errno == ECONNRESET)) {
      _exit(0);
    }
    PCHECK(size > 0);

    const MessageHeader* header =
        reinterpret_cast<const MessageHeader*>(buf.get());
    CHECK_EQ(static_cast<ssize_t>(header->size), size);
    switch (header->type) {
      case MessageType::START_REQUEST:
        StartProcessInHelper(
            reinterpret_cast<const StartProcessRequest*>(buf.get()),
            std::move(fds));
        break;
      case MessageType::WAIT_REQUEST:
        WaitForChildInHelper(
            reinterpret_cast<const WaitProcessRequest*>(buf.get()));
        break;
      default:
        LOG(FATAL) << "Unsupported message type: "
                   << static_cast<uint32_t>(header->type);
    }
  }
}

void LaunchHelper::StartProcessInHelper(const StartProcessRequest* request,
                                        std::vector<ScopedFD> fds) {
  pid_t pid = fork();
  PCHECK(pid >= 0) << "Fork failed";
  if (pid) {
    // Helper.
    StartProcessResponse resp;
    resp.child_pid = pid;
    Send(parent_fd_, reinterpret_cast<const MessageHeader*>(&resp),
         std::vector<int>());
  } else {
    // Child.
    PCHECK(close(parent_fd_) == 0);
    parent_fd_ = -1;
    CommandLine::Reset();

    Pickle serialised_extra(reinterpret_cast<const char*>(request + 1),
                            request->header.size - sizeof(StartProcessRequest));
    PickleIterator iter(serialised_extra);
    std::vector<std::string> args;
    for (size_t i = 0; i < request->num_args; i++) {
      std::string arg;
      CHECK(iter.ReadString(&arg));
      args.push_back(std::move(arg));
    }

    CHECK_EQ(request->num_fds, fds.size());
    for (size_t i = 0; i < request->num_fds; i++) {
      int new_fd;
      CHECK(iter.ReadInt(&new_fd));
      int old_fd = fds[i].release();
      if (new_fd != old_fd) {
        if (dup2(old_fd, new_fd) < 0) {
          PLOG(FATAL) << "dup2";
        }
        PCHECK(close(old_fd) == 0);
      }
    }

    // argv has argc+1 elements, where the last element is NULL.
    std::unique_ptr<char*[]> argv(new char*[args.size() + 1]);
    for (size_t i = 0; i < args.size(); i++) {
      argv[i] = const_cast<char*>(args[i].c_str());
    }
    argv[args.size()] = nullptr;
    _exit(main_(args.size(), argv.get()));
    NOTREACHED();
  }
}

void LaunchHelper::WaitForChildInHelper(const WaitProcessRequest* request) {
  Process process(request->pid);
  TimeDelta timeout = TimeDelta::FromMilliseconds(request->timeout_ms);
  int exit_code = -1;
  bool success = process.WaitForExitWithTimeout(timeout, &exit_code);

  WaitProcessResponse resp;
  resp.exit_code = exit_code;
  resp.success = success;
  Send(parent_fd_, reinterpret_cast<const MessageHeader*>(&resp),
       std::vector<int>());
}

Process LaunchHelper::StartChildTestHelper(const std::string& procname,
                                           const CommandLine& base_command_line,
                                           const LaunchOptions& options) {

  CommandLine command_line(base_command_line);
  if (!command_line.HasSwitch(switches::kTestChildProcess))
    command_line.AppendSwitchASCII(switches::kTestChildProcess, procname);

  StartProcessRequest request;
  Pickle serialised_extra;
  const CommandLine::StringVector& argv = command_line.argv();
  for (const auto& arg : argv)
    CHECK(serialised_extra.WriteString(arg));
  request.num_args = argv.size();

  std::vector<int> fds_to_send;
  if (options.fds_to_remap) {
    for (auto p : *options.fds_to_remap) {
      CHECK(serialised_extra.WriteInt(p.second));
      fds_to_send.push_back(p.first);
    }
    request.num_fds = options.fds_to_remap->size();
  }

  size_t buf_size = sizeof(StartProcessRequest) + serialised_extra.size();
  request.header.size = buf_size;
  std::unique_ptr<char[]> buffer(new char[buf_size]);
  memcpy(buffer.get(), &request, sizeof(StartProcessRequest));
  memcpy(buffer.get() + sizeof(StartProcessRequest), serialised_extra.data(),
         serialised_extra.size());

  // Send start message.
  Send(child_fd_, reinterpret_cast<const MessageHeader*>(buffer.get()),
       fds_to_send);

  // Synchronously get response.
  StartProcessResponse response;
  std::vector<ScopedFD> recv_fds;
  ssize_t resp_size = Recv(child_fd_, &response, &recv_fds);
  PCHECK(resp_size == sizeof(StartProcessResponse));

  return Process(response.child_pid);
}

bool LaunchHelper::WaitForChildExitWithTimeout(
    const Process& process, TimeDelta timeout, int* exit_code) {

  WaitProcessRequest request;
  request.pid = process.Handle();
  request.timeout_ms = timeout.InMilliseconds();

  Send(child_fd_, reinterpret_cast<const MessageHeader*>(&request),
       std::vector<int>());

  WaitProcessResponse response;
  std::vector<ScopedFD> recv_fds;
  ssize_t resp_size = Recv(child_fd_, &response, &recv_fds);
  PCHECK(resp_size == sizeof(WaitProcessResponse));

  if (!response.success)
    return false;

  *exit_code = response.exit_code;
  return true;
}

LazyInstance<LaunchHelper>::Leaky g_launch_helper;

}  // namespace

void InitAndroidMultiProcessTestHelper(int (*main)(int, char**)) {
  DCHECK(main);
  // Don't allow child processes to themselves create new child processes.
  if (g_launch_helper.Get().IsChild())
    return;
  g_launch_helper.Get().Init(main);
}

bool AndroidIsChildProcess() {
  return g_launch_helper.Get().IsChild();
}

bool AndroidWaitForChildExitWithTimeout(
    const Process& process, TimeDelta timeout, int* exit_code) {
  CHECK(g_launch_helper.Get().IsReady());
  return g_launch_helper.Get().WaitForChildExitWithTimeout(
      process, timeout, exit_code);
}

// A very basic implementation for Android. On Android tests can run in an APK
// and we don't have an executable to exec*. This implementation does the bare
// minimum to execute the method specified by procname (in the child process).
//  - All options except |fds_to_remap| are ignored.
Process SpawnMultiProcessTestChild(const std::string& procname,
                                   const CommandLine& base_command_line,
                                   const LaunchOptions& options) {
  if (g_launch_helper.Get().IsReady()) {
    return g_launch_helper.Get().StartChildTestHelper(
        procname, base_command_line, options);
  }

  // TODO(viettrungluu): The FD-remapping done below is wrong in the presence of
  // cycles (e.g., fd1 -> fd2, fd2 -> fd1). crbug.com/326576
  FileHandleMappingVector empty;
  const FileHandleMappingVector* fds_to_remap =
      options.fds_to_remap ? options.fds_to_remap : &empty;

  pid_t pid = fork();

  if (pid < 0) {
    PLOG(ERROR) << "fork";
    return Process();
  }
  if (pid > 0) {
    // Parent process.
    return Process(pid);
  }
  // Child process.
  base::hash_set<int> fds_to_keep_open;
  for (FileHandleMappingVector::const_iterator it = fds_to_remap->begin();
       it != fds_to_remap->end(); ++it) {
    fds_to_keep_open.insert(it->first);
  }
  // Keep standard FDs (stdin, stdout, stderr, etc.) open since this
  // is not meant to spawn a daemon.
  int base = GlobalDescriptors::kBaseDescriptor;
  for (int fd = base; fd < sysconf(_SC_OPEN_MAX); ++fd) {
    if (fds_to_keep_open.find(fd) == fds_to_keep_open.end()) {
      close(fd);
    }
  }
  for (FileHandleMappingVector::const_iterator it = fds_to_remap->begin();
       it != fds_to_remap->end(); ++it) {
    int old_fd = it->first;
    int new_fd = it->second;
    if (dup2(old_fd, new_fd) < 0) {
      PLOG(FATAL) << "dup2";
    }
    close(old_fd);
  }
  CommandLine::Reset();
  CommandLine::Init(0, nullptr);
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  command_line->InitFromArgv(base_command_line.argv());
  if (!command_line->HasSwitch(switches::kTestChildProcess))
    command_line->AppendSwitchASCII(switches::kTestChildProcess, procname);

  _exit(multi_process_function_list::InvokeChildProcessTest(procname));
  return Process();
}

}  // namespace base