xref: /aosp_15_r20/external/perfetto/src/trace_processor/rpc/stdiod.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "src/trace_processor/rpc/stdiod.h"
18 
19 #include <cstddef>
20 #include <cstdint>
21 #include <memory>
22 #include <utility>
23 
24 #include "perfetto/base/build_config.h"
25 #include "perfetto/base/logging.h"
26 #include "perfetto/base/status.h"
27 #include "perfetto/ext/base/file_utils.h"
28 #include "perfetto/ext/base/utils.h"
29 #include "perfetto/trace_processor/trace_processor.h"
30 #include "src/trace_processor/rpc/rpc.h"
31 
32 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
33 #include <unistd.h>
34 #endif
35 
36 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) && !defined(STDIN_FILENO)
37 #define STDIN_FILENO 0
38 #define STDOUT_FILENO 1
39 #endif
40 
41 namespace perfetto::trace_processor {
42 
RunStdioRpcServer(std::unique_ptr<TraceProcessor> tp)43 base::Status RunStdioRpcServer(std::unique_ptr<TraceProcessor> tp) {
44   Rpc rpc(std::move(tp));
45   char buffer[4096];
46   for (;;) {
47     ssize_t ret = base::Read(STDIN_FILENO, buffer, base::ArraySize(buffer));
48     if (ret == -1) {
49       return base::ErrStatus("Failed while reading the buffer");
50     }
51     if (ret == 0) {
52       return base::OkStatus();
53     }
54     rpc.SetRpcResponseFunction([](const void* ptr, uint32_t size) {
55       ssize_t ret = base::WriteAll(STDOUT_FILENO, ptr, size);
56       if (ret < 0 || static_cast<uint32_t>(ret) != size) {
57         PERFETTO_FATAL("Failed to write response");
58       }
59     });
60     rpc.OnRpcRequest(buffer, static_cast<size_t>(ret));
61     rpc.SetRpcResponseFunction(nullptr);
62   }
63 }
64 
65 }  // namespace perfetto::trace_processor
66