summaryrefslogtreecommitdiff
path: root/test/process-test.cpp
blob: db13d0dd147a4c94ca7e79f8935a172e1414e23c (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
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <gtest/gtest.h>
#include <xorg/gtest/xorg-gtest.h>

#include <stdexcept>

using namespace xorg::testing;

TEST(Process, StartWithNULLArg)
{
  XORG_TESTCASE("invocation of 'ls' with no arguments");
  Process p;
  p.Start("ls", nullptr);
  ASSERT_GT(p.Pid(), 0);
}

TEST(Process, StartWithNULLTerminatedArg)
{
  XORG_TESTCASE("invocation of 'ls' with NULL-terminated argument list");

  Process p;
  p.Start("ls", "-l", nullptr);
  ASSERT_GT(p.Pid(), 0);
}

TEST(Process, ExitCodeSuccess)
{
  XORG_TESTCASE("invocation of 'echo -n', check for success exit status");

  Process p;
  ASSERT_EQ(p.GetState(), Process::NONE);

  /* Process:Start closes stdout, so we need something that doesn't print */
  p.Start("echo", "-n", nullptr);
  ASSERT_GT(p.Pid(), 0);
  ASSERT_EQ(p.GetState(), Process::RUNNING);

  /* ls shouldn't take longer terminate */
  for (int i = 0; i < 100; i++) {
    if (p.GetState() == Process::RUNNING)
      usleep(5000);
  }
  ASSERT_EQ(p.GetState(), Process::FINISHED_SUCCESS);
}

TEST(Process, ExitCodeFailure)
{
  XORG_TESTCASE("an invalid invocation of 'ls', check for error exit status");
  Process p;
  ASSERT_EQ(p.GetState(), Process::NONE);

  /* Process:Start closes stdout, so ls should fail with status 2, if not,
   * that file is unlikely to exists so we get status 1 */
  p.Start("ls", "asqwerq.aqerqw_rqwe", nullptr);
  ASSERT_GT(p.Pid(), 0);
  ASSERT_EQ(p.GetState(), Process::RUNNING);

  /* ls shouldn't take longer than 5s to terminate */
  for (int i = 0; i < 10; i++) {
    if (p.GetState() == Process::RUNNING)
      usleep(500);
  }
  ASSERT_EQ(p.GetState(), Process::FINISHED_FAILURE);
}

TEST(Process, ChildTearDown)
{
  XORG_TESTCASE("ensure child process dies when parent does");

  int pipefd[2];
  ASSERT_NE(pipe(pipefd), -1);

  /* Fork, the child will spawn a Process, write that Process's PID to a
     pipe and then kill itself. The parent checks that the child was
     terminated when the parent was killed.
   */
  pid_t pid = fork();
  if (pid == 0) { /* child */
    close(pipefd[0]);

    Process p;
    p.Start("sleep", "1000", nullptr); /* forks another child */
    ASSERT_GT(p.Pid(), 0);

    char *buffer;
    ASSERT_GT(asprintf(&buffer, "%d", p.Pid()), 0);
    ASSERT_EQ(write(pipefd[1], buffer, strlen(buffer)), static_cast<int>(strlen(buffer)));
    close(pipefd[1]);

    raise(SIGKILL);
  } else { /* parent */
    close(pipefd[1]);

    char buffer[20] = {0};
    ASSERT_GT(read(pipefd[0], buffer, sizeof(buffer)), 0);
    close(pipefd[0]);

    pid_t child_pid = atoi(buffer);
    for (int i = 0; i < 10; i++) {
      if (kill(child_pid, 0) != -1)
        usleep(100);

    }
    ASSERT_EQ(kill(child_pid, 0), -1);
    ASSERT_EQ(errno, ESRCH);
  }
}

TEST(Process, TerminationFailure)
{
  XORG_TESTCASE("if Process::Terminate() fails to terminate the \n"
                "child process, kill must terminate it it instead");

  sigset_t sig_mask;
  struct timespec sig_timeout = {0, 5000000L};

  sigemptyset(&sig_mask);
  sigaddset(&sig_mask, SIGUSR1);

  Process p;
  p.Start(TEST_ROOT_DIR "process-test-helper", nullptr);
  /* don't check error here, the helper may have sent the signal before we
     get here */
  sigtimedwait(&sig_mask, nullptr, &sig_timeout);

  ASSERT_GT(p.Pid(), 0);
  kill(p.Pid(), SIGSTOP);

  ASSERT_FALSE(p.Terminate(100));
  ASSERT_EQ(p.GetState(), Process::RUNNING);
  ASSERT_TRUE(p.Kill(100));
}

TEST(Process, KillExitStatus)
{
  XORG_TESTCASE("a child process killed must have a state of\n"
                "FINISHED_FAILURE");
  Process p;
  p.Start(TEST_ROOT_DIR "process-test-helper", nullptr);
  p.Kill(1000);
  ASSERT_EQ(p.GetState(), Process::FINISHED_FAILURE);
}

TEST(Process, DoubleStart)
{
  struct timespec sig_timeout = {0, 5000000L};

  XORG_TESTCASE("starting a process after it has been started\n"
                "fails. Re-starting a process succeeds\n");

  /* Process double-started must fail */
  Process p;
  p.Start("echo", "-n", nullptr);
  try {
    p.Start("echo", "-n", nullptr);
    FAIL() << "Expected exception";
  } catch (std::runtime_error &e) {
  }
  p.Terminate(1000);
  /* we sent it a SIGTERM, counts as failure */
  ASSERT_EQ(p.GetState(), Process::FINISHED_FAILURE);

  sigset_t sig_mask;
  sigemptyset(&sig_mask);
  sigaddset(&sig_mask, SIGCHLD);
  sigaddset(&sig_mask, SIGUSR1);
  sigprocmask(SIG_BLOCK, &sig_mask, 0);

  /* restart job after a failed one, must succeed */
  try {
    p.Start("echo", "-n", nullptr);
  } catch (std::runtime_error &e) {
    FAIL();
  }

  ASSERT_EQ(sigtimedwait(&sig_mask, nullptr, &sig_timeout), SIGCHLD);
  ASSERT_EQ(p.GetState(), Process::FINISHED_SUCCESS);

  /* restart job after successful one, must succeed */
  try {
    p.Start("echo", "-n", nullptr);
  } catch (std::runtime_error &e) {
    FAIL();
  }
  ASSERT_EQ(sigtimedwait(&sig_mask, nullptr, &sig_timeout), SIGCHLD);
  ASSERT_EQ(p.GetState(), Process::FINISHED_SUCCESS);

  /* job that must be killed, followed by job */
  sigemptyset(&sig_mask);
  sigaddset(&sig_mask, SIGUSR1);
  p.Start(TEST_ROOT_DIR "process-test-helper", nullptr);
  sigtimedwait(&sig_mask, nullptr, &sig_timeout);
  ASSERT_EQ(p.GetState(), Process::RUNNING);
  p.Kill(100);
  ASSERT_EQ(p.GetState(), Process::FINISHED_FAILURE);

  /* restart job after successful one, must succeed */
  try {
    p.Start("echo", "-n", nullptr);
  } catch (std::runtime_error &e) {
    FAIL();
  }
  sigemptyset(&sig_mask);
  sigaddset(&sig_mask, SIGCHLD);
  ASSERT_EQ(sigtimedwait(&sig_mask, nullptr, &sig_timeout), SIGCHLD);
  ASSERT_EQ(p.GetState(), Process::FINISHED_SUCCESS);

  /* job that fails to terminate, starting another one must fail */
  sigemptyset(&sig_mask);
  sigaddset(&sig_mask, SIGUSR1);
  p.Start(TEST_ROOT_DIR "process-test-helper", nullptr);
  sigtimedwait(&sig_mask, nullptr, &sig_timeout);
  ASSERT_EQ(p.GetState(), Process::RUNNING);
  ASSERT_FALSE(p.Terminate(100));

  try {
    p.Start("echo", "-n", nullptr);
    FAIL() << "exception expected";
  } catch (std::runtime_error &e) {
  }

  sigemptyset(&sig_mask);
  sigaddset(&sig_mask, SIGCHLD);
  sigaddset(&sig_mask, SIGUSR1);
  sigprocmask(SIG_UNBLOCK, &sig_mask, 0);
}

TEST(Process, ForkedParentStart)
{
  XORG_TESTCASE("Fork() and calling Start() on the parent causes an exception");
  Process p;
  if (p.Fork() > 0) {
    ASSERT_GT(p.Pid(), 0);
    ASSERT_EQ(p.GetState(), Process::RUNNING);
    ASSERT_THROW({ p.Start("ls", nullptr); }, std::runtime_error);
  }
}

TEST(Process, ForkedChildStart)
{
  XORG_TESTCASE("Fork() and calling Start() executes the process");
  Process p;
  if (p.Fork() == 0) {
    ASSERT_EQ(p.GetState(), Process::RUNNING);
    p.Start("ls", nullptr);
    ASSERT_GT(p.Pid(), 0);
  }
}

TEST(Process, ForkedChildDoubleStart)
{
  XORG_TESTCASE("Fork() and calling Start() twice causes an exception");
  Process p;
  if (p.Fork() == 0) {
    ASSERT_EQ(p.GetState(), Process::RUNNING);
    p.Start("ls", nullptr);
    ASSERT_THROW({
        p.Start("ls", nullptr);
    }, std::runtime_error);
  }
}

class ProcessValgrindWrapper : public ::testing::Test,
                               public ::testing::WithParamInterface<std::string> {
public:
  virtual void SetUp() {
    CheckForValgrind();
  }

  virtual void CheckForValgrind() {
    Process valgrind;

    /* check if valgrind actually exists */
    valgrind.Start("valgrind", "--version", nullptr);
    int status;
    ASSERT_EQ(waitpid(valgrind.Pid(), &status, 0), valgrind.Pid());
    ASSERT_TRUE(WIFEXITED(status));
    ASSERT_EQ(WEXITSTATUS(status), 0) << "valgrind failed to start\n";
  }
};

TEST_P(ProcessValgrindWrapper, ValgrindWrapper)
{
  XORG_TESTCASE("Use the valgrind wrapper to start valgrind");

  std::string executable = GetParam();

  /* now set the env and fire up valgrind */
  setenv("XORG_GTEST_USE_VALGRIND", executable.c_str(), 1);
  Process p;
  p.Start("ls", nullptr);
  unsetenv("XORG_GTEST_USE_VALGRIND");

  /* Check /proc/<pid>/comm to make sure valgrind
     was started. But comm takes a while to update, it's first our binary
     then valgrind, then memcheck-amd64 (or whatever applies)
  */
  char buff[1024] = {0};
  char fname[128];
  sprintf(fname, "/proc/%d/comm", p.Pid());

  do {
    FILE *fp = fopen(fname, "r");
    ASSERT_TRUE(fp);
    fgets(buff, sizeof(buff), fp);
    fclose(fp);
  } while(strstr(buff, program_invocation_short_name));

  if (executable.compare("valgrind") == 0)
    ASSERT_TRUE(strstr(buff, "memcheck") || strstr(buff, "valgrind"));
  else
    ASSERT_TRUE(strstr(buff, executable.c_str()));
}

class ProcessValgrindArgsWrapper : public ProcessValgrindWrapper {};

TEST_P(ProcessValgrindArgsWrapper, ValgrindWrapperWithArgs)
{
  XORG_TESTCASE("Use the valgrind wrapper with additional args to start valgrind");

  std::string vargs = GetParam();
  std::vector<std::string> valgrind_args;
  char *all_args = strdup(vargs.c_str());
  char *tok = strtok(all_args, " ");
  while(tok) {
    valgrind_args.push_back(std::string(tok));
    tok = strtok(nullptr, " ");
  }
  free(all_args);

  /* now set the env and fire up valgrind */
  setenv("XORG_GTEST_USE_VALGRIND", vargs.c_str(), 1);
  Process p;
  p.Start(TEST_ROOT_DIR "process-test-helper", nullptr);
  unsetenv("XORG_GTEST_USE_VALGRIND");

  ASSERT_EQ(p.GetState(), Process::RUNNING);

  char buff[1024] = {0};
  char fname[128];
  sprintf(fname, "/proc/%d/cmdline", p.Pid());

  do {
    FILE *fp = fopen(fname, "r");
    ASSERT_TRUE(fp);
    fgets(buff, sizeof(buff), fp);
    fclose(fp);
  } while(strstr(buff, program_invocation_short_name));

  const char * arg = buff + strlen(buff) + 1;

  /* accommodate the case that valgrind has a shell script wrapper */
  if (0 == strcmp(buff, "/bin/sh")) {
    if (0 == strcmp(arg, "-e")) {
      arg += strlen(arg) + 1;
    }
    arg += strlen(arg) + 1;
  }

  std::vector<std::string>::const_iterator it = valgrind_args.begin();

  it++; /* first one is "valgrind" */

  while(strlen(arg) && it != valgrind_args.end()) {
    ASSERT_EQ(it->compare(arg), 0);
    arg += strlen(arg) + 1;
    it++;
  }

  ASSERT_EQ(it, valgrind_args.end());
  p.Kill(100);
}

INSTANTIATE_TEST_CASE_P(, ProcessValgrindWrapper, ::testing::Values("valgrind", "ls"));
INSTANTIATE_TEST_CASE_P(, ProcessValgrindArgsWrapper,
                        ::testing::Values("valgrind --leak-check=full", "valgrind -q --trace-children=yes", "valgrind "));

int main(int argc, char *argv[]) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}