1 /*
2  * Copyright (C) 2017 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 #ifndef ART_RUNTIME_EXEC_UTILS_H_
18 #define ART_RUNTIME_EXEC_UTILS_H_
19 
20 #include <time.h>
21 
22 #include <cstdint>
23 #include <functional>
24 #include <optional>
25 #include <string>
26 #include <vector>
27 
28 #include "android-base/unique_fd.h"
29 #include "base/macros.h"
30 
31 namespace art HIDDEN {
32 
33 struct ProcessStat {
34   // The total wall time, in milliseconds, that the process spent, or 0 if failed to get the value.
35   int64_t wall_time_ms = 0;
36   // The total CPU time, in milliseconds, that the process and any waited-for children spent, or 0
37   // if failed to get the value.
38   int64_t cpu_time_ms = 0;
39 };
40 
41 struct ExecCallbacks {
42   // Called in the parent process as soon as the child process is forked.
43   std::function<void(pid_t pid)> on_start = [](pid_t) {};
44   // Called in the parent process after the child process exits while still in a waitable state, no
45   // matter the child process succeeds or not.
46   std::function<void(pid_t pid)> on_end = [](pid_t) {};
47 };
48 
49 struct ExecResult {
50   // This struct needs to be in sync with the ExecResultStatus enum contained within the
51   // OdrefreshReported atom in frameworks/proto_logging/atoms/art/odrefresh_extension_atoms.proto.
52   enum Status {
53     // Unable to get the status.
54     kUnknown = 0,
55     // Process exited normally with an exit code.
56     kExited = 1,
57     // Process terminated by a signal.
58     kSignaled = 2,
59     // Process timed out and killed.
60     kTimedOut = 3,
61     // Failed to start the process.
62     kStartFailed = 4,
63     kLast = kStartFailed
64   };
65 
66   Status status = kUnknown;
67 
68   // The process exit code, if `status` is `kExited`, or -1.
69   int exit_code = -1;
70 
71   // The signal that terminated the process, if `status` is `kSignaled`, or 0.
72   int signal = 0;
73 };
74 
75 // Wrapper on fork/execv to run a command in a subprocess.
76 // These spawn child processes using the environment as it was set when the single instance
77 // of the runtime (Runtime::Current()) was started.  If no instance of the runtime was started, it
78 // will use the current environment settings.
79 class EXPORT ExecUtils {
80  public:
81   virtual ~ExecUtils() = default;
82 
83   virtual bool Exec(const std::vector<std::string>& arg_vector,
84                     /*out*/ std::string* error_msg) const;
85 
86   virtual int ExecAndReturnCode(const std::vector<std::string>& arg_vector,
87                                 /*out*/ std::string* error_msg) const;
88 
89   // Executes the command specified in `arg_vector` in a subprocess with a timeout.
90   // If `timeout_sec` is negative, blocks until the subprocess exits.
91   // Returns a structured result. If the status is not `kExited`, also returns a non-empty
92   // `error_msg`.
93   virtual ExecResult ExecAndReturnResult(const std::vector<std::string>& arg_vector,
94                                          int timeout_sec,
95                                          /*out*/ std::string* error_msg) const;
96 
97   // Same as above, but also collects stat of the process, calls callbacks, and supports creating a
98   // new process group. The stat is collected no matter the child process succeeds or not.
99   //
100   // Programs used by artd (odrefresh, dex2oat, profman) should NOT set `new_process_group` to true
101   // when spawning child processes because artd needs to kill an entire process subtree by killing
102   // the process group.
103   virtual ExecResult ExecAndReturnResult(const std::vector<std::string>& arg_vector,
104                                          int timeout_sec,
105                                          const ExecCallbacks& callbacks,
106                                          bool new_process_group,
107                                          /*out*/ ProcessStat* stat,
108                                          /*out*/ std::string* error_msg) const;
109 
110  protected:
111   virtual android::base::unique_fd PidfdOpen(pid_t pid) const;
112 
113   // Returns the content of `/proc/<pid>/stat`, or an empty string if failed.
114   virtual std::string GetProcStat(pid_t pid) const;
115 
116   virtual std::optional<int64_t> GetUptimeMs(std::string* error_msg) const;
117 
118   virtual int64_t GetTicksPerSec() const;
119 
120  private:
121   bool GetStat(pid_t pid, /*out*/ ProcessStat* stat, /*out*/ std::string* error_msg) const;
122 };
123 
Exec(const std::vector<std::string> & arg_vector,std::string * error_msg)124 inline bool Exec(const std::vector<std::string>& arg_vector, /*out*/ std::string* error_msg) {
125   return ExecUtils().Exec(arg_vector, error_msg);
126 }
127 
ExecAndReturnCode(const std::vector<std::string> & arg_vector,std::string * error_msg)128 inline int ExecAndReturnCode(const std::vector<std::string>& arg_vector,
129                              /*out*/ std::string* error_msg) {
130   return ExecUtils().ExecAndReturnCode(arg_vector, error_msg);
131 }
132 
133 }  // namespace art
134 
135 #endif  // ART_RUNTIME_EXEC_UTILS_H_
136