sandboxed-api/sandboxed_api/sandbox2/testcases/namespace.cc
Wiktor Garbacz d170bc3c80 Deflake namespace_test
When fetching exit status only lower 8-bits will be read.
Thus if getpid()&0xff == 0 the test can fail.

PiperOrigin-RevId: 257163766
Change-Id: I690c645fde33d1205578fd8873c5fc2974352ada
2019-07-09 04:11:07 -07:00

81 lines
2.2 KiB
C++

// Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Checks various things related to namespaces, depending on the first argument:
// ./binary 0 <file1> <file2> ... <fileN>:
// Make sure all provided files exist and are RO, return 0 on OK.
// Returns the index of the first non-existing file + 1 on failure.
// ./binary 1 <file1> <file2> ... <fileN>:
// Make sure all provided files exist and are RW, return 0 on OK.
// Returns the index of the first non-existing file + 1 on failure.
// ./binary 2
// Make sure that we run in a PID namespace (this implies getpid() == 1)
// Returns 0 on OK.
// ./binary 3 <uid> <gid>
// Make sure getuid()/getgid() returns the provided uid/gid (User namespace).
// Returns 0 on OK.
#include <fcntl.h>
#include <unistd.h>
#include <cstdlib>
int main(int argc, char* argv[]) {
if (argc < 2) {
return 0;
}
int mode = atoi(argv[1]); // NOLINT(runtime/deprecated_fn)
switch (mode) {
case 0: {
// Make sure file exist
for (int i = 2; i < argc; i++) {
if (access(argv[i], R_OK)) {
return i - 1;
}
}
} break;
case 1: {
for (int i = 2; i < argc; i++) {
if (access(argv[i], W_OK)) {
return i - 1;
}
}
} break;
case 2: {
if (getpid() != 2) {
return -1;
}
} break;
case 3: {
if (argc != 4) {
return 1;
}
if (getuid() != atoi(argv[2]) // NOLINT(runtime/deprecated_fn)
|| getgid() != atoi(argv[3])) { // NOLINT(runtime/deprecated_fn)
return -1;
}
} break;
default:
return 1;
}
return 0;
}