xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/sandbox2/testcases/starve.cc (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <sched.h>
16 #include <unistd.h>
17 
18 #include <csignal>
19 #include <cstdint>
20 
21 constexpr int kProcesses = 512;
22 constexpr int kThreads = 1;
23 constexpr int kSenders = 1;
24 constexpr int kStackSize = 4096;
25 
26 pid_t g_pids[kProcesses];
27 
28 uint8_t g_stacks[kThreads][kStackSize] __attribute__((aligned(4096)));
29 constexpr int kSignals[] = {
30     SIGPROF,
31 };
32 
SignalHandler(int)33 void SignalHandler(int) {}
34 
ChildFunc(void *)35 int ChildFunc(void*) {
36   for (;;) {
37     sleep(10);
38   }
39 }
40 
main()41 int main() {
42   for (int i = 0; i < kProcesses; ++i) {
43     int p[2] = {0, 0};
44     char c = ' ';
45     pipe(p);
46     g_pids[i] = fork();
47     if (g_pids[i] == 0) {
48       for (int sig : kSignals) {
49         signal(sig, SignalHandler);
50       }
51       for (int j = 0; j < kThreads; ++j) {
52         int flags = CLONE_FILES | CLONE_FS | CLONE_IO | CLONE_PARENT |
53                     CLONE_SIGHAND | CLONE_THREAD | CLONE_VM;
54         clone(&ChildFunc, g_stacks[j + 1], flags, nullptr, nullptr, nullptr,
55               nullptr);
56       }
57       close(p[0]);
58       write(p[1], &c, 1);
59       close(p[1]);
60       for (;;) {
61         sleep(10);
62       }
63     }
64     read(p[0], &c, 1);
65   }
66   for (int i = 0; i < kSenders; ++i) {
67     if (fork() == 0) {
68       break;
69     }
70   }
71   for (;;) {
72     for (int sig : kSignals) {
73       for (int pid : g_pids) {
74         kill(pid, sig);
75       }
76     }
77   }
78 }
79