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_ADBCONNECTION_ADBCONNECTION_H_
18 #define ART_ADBCONNECTION_ADBCONNECTION_H_
19 
20 #include <jni.h>
21 #include <stdint.h>
22 #include <sys/socket.h>
23 #include <sys/un.h>
24 
25 #include <limits>
26 #include <memory>
27 #include <string>
28 #include <vector>
29 
30 #include "adbconnection/client.h"
31 #include "base/array_ref.h"
32 #include "base/mutex.h"
33 #include "runtime_callbacks.h"
34 
35 namespace adbconnection {
36 
37 static constexpr char kAdbConnectionThreadName[] = "ADB-JDWP Connection Control Thread";
38 
39 // The default jdwp agent name.
40 static constexpr char kDefaultJdwpAgentName[] = "libjdwp.so";
41 
42 class AdbConnectionState;
43 
44 struct AdbConnectionDebuggerController : public art::DebuggerControlCallback {
AdbConnectionDebuggerControllerAdbConnectionDebuggerController45   explicit AdbConnectionDebuggerController(AdbConnectionState* connection)
46       : connection_(connection) {}
47 
48   // Begin running the debugger.
49   void StartDebugger() override;
50 
51   // The debugger should begin shutting down since the runtime is ending.
52   void StopDebugger() override;
53 
54   bool IsDebuggerConfigured() override;
55 
56  private:
57   AdbConnectionState* connection_;
58 };
59 
60 enum class DdmPacketType : uint8_t { kReply = 0x80, kCmd = 0x00, };
61 
62 struct AdbConnectionDdmCallback : public art::DdmCallback {
AdbConnectionDdmCallbackAdbConnectionDdmCallback63   explicit AdbConnectionDdmCallback(AdbConnectionState* connection) : connection_(connection) {}
64 
65   void DdmPublishChunk(uint32_t type,
66                        const art::ArrayRef<const uint8_t>& data)
67       REQUIRES_SHARED(art::Locks::mutator_lock_);
68 
69  private:
70   AdbConnectionState* connection_;
71 };
72 
73 struct AdbConnectionAppInfoCallback : public art::AppInfoCallback {
AdbConnectionAppInfoCallbackAdbConnectionAppInfoCallback74   explicit AdbConnectionAppInfoCallback(AdbConnectionState* connection) : connection_(connection) {}
75 
76   void AddApplication(const std::string& package_name) REQUIRES_SHARED(art::Locks::mutator_lock_);
77   void RemoveApplication(const std::string& package_name)
78       REQUIRES_SHARED(art::Locks::mutator_lock_);
79   void SetCurrentProcessName(const std::string& process_name)
80       REQUIRES_SHARED(art::Locks::mutator_lock_);
81   void SetWaitingForDebugger(bool waiting) REQUIRES_SHARED(art::Locks::mutator_lock_);
82   void SetUserId(int uid) REQUIRES_SHARED(art::Locks::mutator_lock_);
83 
84  private:
85   AdbConnectionState* connection_;
86 };
87 
88 class AdbConnectionState {
89  public:
90   explicit AdbConnectionState(const std::string& name);
91   ~AdbConnectionState();
92 
93   // Called on the listening thread to start dealing with new input. thr is used to attach the new
94   // thread to the runtime.
95   void RunPollLoop(art::Thread* self);
96 
97   // Sends ddms data over the socket, if there is one. This data is sent even if we haven't finished
98   // hand-shaking yet.
99   void PublishDdmData(uint32_t type, const art::ArrayRef<const uint8_t>& data);
100 
101   // Wake up the poll. Call this if the set of interesting event has changed. They will be
102   // recalculated and poll will be called again via fdevent write. This wakeup  relies on fdevent
103   // and should be ACKed via AcknowledgeWakeup.
104   void WakeupPollLoop();
105 
106   // After a call to WakeupPollLoop, the fdevent internal counter should be decreased via
107   // this method. This should be called after WakeupPollLoop was called and poll triggered.
108   void AcknowledgeWakeup();
109 
110   // Stops debugger threads during shutdown.
111   void StopDebuggerThreads();
112 
113   // If StartDebuggerThreads was called successfully.
DebuggerThreadsStarted()114   bool DebuggerThreadsStarted() {
115     return started_debugger_threads_;
116   }
117 
118   // Should be called by Framework when it changes its process name.
119   void SetCurrentProcessName(const std::string& process_name);
120 
121   // Should be called by Framework when it adds an app to a process.
122   // This can be called several times (see android:process)
123   void AddApplication(const std::string& package_name);
124 
125   // Should be called by Framework when it removes an app from a process.
126   void RemoveApplication(const std::string& package_name);
127 
128   // Should be called by Framework when its debugging state changes.
129   void SetWaitingForDebugger(bool waiting);
130 
131   // Should be called by Framework when the UserID is known.
132   void SetUserId(int uid);
133 
134  private:
135   uint32_t NextDdmId();
136 
137   void StartDebuggerThreads();
138 
139   // Tell adbd about the new runtime.
140   bool SetupAdbConnection();
141 
142   std::string MakeAgentArg();
143 
144   void SendAgentFds(bool require_handshake);
145 
146   void CloseFds();
147 
148   void HandleDataWithoutAgent(art::Thread* self);
149 
150   void PerformHandshake();
151 
152   void AttachJdwpAgent(art::Thread* self);
153 
154   void NotifyDdms(bool active);
155 
156   void SendDdmPacket(uint32_t id,
157                      DdmPacketType type,
158                      uint32_t ddm_type,
159                      art::ArrayRef<const uint8_t> data);
160 
161   std::string agent_name_;
162 
163   AdbConnectionDebuggerController controller_;
164   AdbConnectionDdmCallback ddm_callback_;
165   AdbConnectionAppInfoCallback appinfo_callback_;
166 
167   // Eventfd used to allow the StopDebuggerThreads function to wake up sleeping threads
168   android::base::unique_fd sleep_event_fd_;
169 
170   // Context which wraps the socket which we use to talk to adbd.
171   std::unique_ptr<AdbConnectionClientContext, void(*)(AdbConnectionClientContext*)> control_ctx_;
172 
173   // Socket that we use to talk to the agent (if it's loaded).
174   android::base::unique_fd local_agent_control_sock_;
175 
176   // The fd of the socket the agent uses to talk to us. We need to keep it around in order to clean
177   // it up when the runtime goes away.
178   android::base::unique_fd remote_agent_control_sock_;
179 
180   // The fd that is forwarded through adb to the client. This is guarded by the
181   // adb_write_event_fd_.
182   android::base::unique_fd adb_connection_socket_;
183 
184   // The fd we send to the agent to let us synchronize access to the shared adb_connection_socket_.
185   // This is also used as a general lock for the adb_connection_socket_ on any threads other than
186   // the poll thread.
187   android::base::unique_fd adb_write_event_fd_;
188 
189   std::atomic<bool> shutting_down_;
190 
191   // True if we have loaded the agent library.
192   std::atomic<bool> agent_loaded_;
193 
194   // True if the dt_fd_forward transport is listening for a new communication channel.
195   std::atomic<bool> agent_listening_;
196 
197   // True if the dt_fd_forward transport has the socket. If so we don't do anything to the agent or
198   // the adb connection socket until connection goes away.
199   std::atomic<bool> agent_has_socket_;
200 
201   std::atomic<bool> sent_agent_fds_;
202 
203   std::atomic<bool> performed_handshake_;
204 
205   bool notified_ddm_active_;
206 
207   std::atomic<uint32_t> next_ddm_id_;
208 
209   bool started_debugger_threads_;
210 
211   friend struct AdbConnectionDebuggerController;
212 };
213 
214 }  // namespace adbconnection
215 
216 #endif  // ART_ADBCONNECTION_ADBCONNECTION_H_
217