1 // Copyright 2020 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 <linux/futex.h>
16 #include <syscall.h>
17 #include <uv.h>
18
19 #include <iostream>
20
21 #include "absl/flags/flag.h"
22 #include "uv_sapi.sapi.h" // NOLINT(build/include)
23
24 namespace {
25
26 class UVSapiHelloworldSandbox : public uv::UVSandbox {
27 private:
ModifyPolicy(sandbox2::PolicyBuilder *)28 std::unique_ptr<sandbox2::Policy> ModifyPolicy(
29 sandbox2::PolicyBuilder*) override {
30 return sandbox2::PolicyBuilder()
31 .AllowDynamicStartup()
32 .AllowExit()
33 .AllowFutexOp(FUTEX_WAKE_PRIVATE)
34 .AllowSyscalls({__NR_epoll_create1, __NR_eventfd2, __NR_pipe2})
35 .AllowWrite()
36 .BuildOrDie();
37 }
38 };
39
HelloWorld()40 absl::Status HelloWorld() {
41 // Initialize sandbox2 and sapi
42 UVSapiHelloworldSandbox sandbox;
43 SAPI_RETURN_IF_ERROR(sandbox.Init());
44 uv::UVApi api(&sandbox);
45
46 // Allocate memory for the uv_loop_t object
47 void* loop_voidptr;
48 SAPI_RETURN_IF_ERROR(
49 sandbox.rpc_channel()->Allocate(sizeof(uv_loop_t), &loop_voidptr));
50 sapi::v::RemotePtr loop(loop_voidptr);
51
52 int return_code;
53
54 // Initialize loop
55 SAPI_ASSIGN_OR_RETURN(return_code, api.sapi_uv_loop_init(&loop));
56 if (return_code != 0) {
57 return absl::UnavailableError("uv_loop_init returned error " + return_code);
58 }
59
60 std::cout << "The loop is about to quit" << std::endl;
61
62 // Run loop
63 SAPI_ASSIGN_OR_RETURN(return_code, api.sapi_uv_run(&loop, UV_RUN_DEFAULT));
64 if (return_code != 0) {
65 return absl::UnavailableError("uv_run returned error " + return_code);
66 }
67
68 // Close loop
69 SAPI_ASSIGN_OR_RETURN(return_code, api.sapi_uv_loop_close(&loop));
70 if (return_code != 0) {
71 return absl::UnavailableError("uv_loop_close returned error " +
72 return_code);
73 }
74
75 return absl::OkStatus();
76 }
77
78 } // namespace
79
main(int argc,char * argv[])80 int main(int argc, char* argv[]) {
81 gflags::ParseCommandLineFlags(&argc, &argv, true);
82 sapi::InitLogging(argv[0]);
83
84 if (absl::Status status = HelloWorld(); !status.ok()) {
85 LOG(ERROR) << "HelloWorld failed: " << status.ToString();
86 return EXIT_FAILURE;
87 }
88
89 return EXIT_SUCCESS;
90 }
91