File: agent.cc

package info (click to toggle)
android-platform-art 14.0.0%2Br15-4
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 96,788 kB
  • sloc: cpp: 522,217; java: 194,312; asm: 28,950; python: 14,910; xml: 5,087; sh: 4,528; ansic: 4,035; makefile: 111; perl: 77
file content (238 lines) | stat: -rw-r--r-- 8,800 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "agent.h"

#include "android-base/stringprintf.h"
#include "nativehelper/scoped_local_ref.h"
#include "nativeloader/native_loader.h"

#include "base/logging.h"
#include "jni/java_vm_ext.h"
#include "runtime.h"
#include "thread-current-inl.h"
#include "scoped_thread_state_change-inl.h"

namespace art {
namespace ti {

using android::base::StringPrintf;

const char* AGENT_ON_LOAD_FUNCTION_NAME = "Agent_OnLoad";
const char* AGENT_ON_ATTACH_FUNCTION_NAME = "Agent_OnAttach";
const char* AGENT_ON_UNLOAD_FUNCTION_NAME = "Agent_OnUnload";

AgentSpec::AgentSpec(const std::string& arg) {
  size_t eq = arg.find_first_of('=');
  if (eq == std::string::npos) {
    name_ = arg;
  } else {
    name_ = arg.substr(0, eq);
    args_ = arg.substr(eq + 1, arg.length());
  }
}

std::unique_ptr<Agent> AgentSpec::Load(/*out*/jint* call_res,
                                       /*out*/LoadError* error,
                                       /*out*/std::string* error_msg) {
  VLOG(agents) << "Loading agent: " << name_ << " " << args_;
  return DoLoadHelper(nullptr, false, nullptr, call_res, error, error_msg);
}

// Tries to attach the agent using its OnAttach method. Returns true on success.
std::unique_ptr<Agent> AgentSpec::Attach(JNIEnv* env,
                                         jobject class_loader,
                                         /*out*/jint* call_res,
                                         /*out*/LoadError* error,
                                         /*out*/std::string* error_msg) {
  VLOG(agents) << "Attaching agent: " << name_ << " " << args_;
  return DoLoadHelper(env, true, class_loader, call_res, error, error_msg);
}


// TODO We need to acquire some locks probably.
std::unique_ptr<Agent> AgentSpec::DoLoadHelper(JNIEnv* env,
                                               bool attaching,
                                               jobject class_loader,
                                               /*out*/jint* call_res,
                                               /*out*/LoadError* error,
                                               /*out*/std::string* error_msg) {
  ScopedThreadStateChange stsc(Thread::Current(), ThreadState::kNative);
  DCHECK(call_res != nullptr);
  DCHECK(error_msg != nullptr);

  std::unique_ptr<Agent> agent = DoDlOpen(env, class_loader, error, error_msg);
  if (agent == nullptr) {
    VLOG(agents) << "err: " << *error_msg;
    return nullptr;
  }
  AgentOnLoadFunction callback = attaching ? agent->onattach_ : agent->onload_;
  if (callback == nullptr) {
    *error_msg = StringPrintf("Unable to start agent %s: No %s callback found",
                              (attaching ? "attach" : "load"),
                              name_.c_str());
    VLOG(agents) << "err: " << *error_msg;
    *error = kLoadingError;
    return nullptr;
  }
  // Need to let the function fiddle with the array.
  std::unique_ptr<char[]> copied_args(new char[args_.size() + 1]);
  strlcpy(copied_args.get(), args_.c_str(), args_.size() + 1);
  // TODO Need to do some checks that we are at a good spot etc.
  *call_res = callback(Runtime::Current()->GetJavaVM(),
                       copied_args.get(),
                       nullptr);
  if (*call_res != 0) {
    *error_msg = StringPrintf("Initialization of %s returned non-zero value of %d",
                              name_.c_str(), *call_res);
    VLOG(agents) << "err: " << *error_msg;
    *error = kInitializationError;
    return nullptr;
  }
  return agent;
}

std::unique_ptr<Agent> AgentSpec::DoDlOpen(JNIEnv* env,
                                           jobject class_loader,
                                           /*out*/LoadError* error,
                                           /*out*/std::string* error_msg) {
  DCHECK(error_msg != nullptr);

  ScopedLocalRef<jstring> library_path(env,
                                       class_loader == nullptr
                                           ? nullptr
                                           : JavaVMExt::GetLibrarySearchPath(env, class_loader));

  bool needs_native_bridge = false;
  char* nativeloader_error_msg = nullptr;
  void* dlopen_handle = android::OpenNativeLibrary(env,
                                                   Runtime::Current()->GetTargetSdkVersion(),
                                                   name_.c_str(),
                                                   class_loader,
                                                   nullptr,
                                                   library_path.get(),
                                                   &needs_native_bridge,
                                                   &nativeloader_error_msg);
  if (dlopen_handle == nullptr) {
    *error_msg = StringPrintf("Unable to dlopen %s: %s",
                              name_.c_str(),
                              nativeloader_error_msg);
    android::NativeLoaderFreeErrorMessage(nativeloader_error_msg);
    *error = kLoadingError;
    return nullptr;
  }
  if (needs_native_bridge) {
    // TODO: Consider support?
    // The result of this call and error_msg is ignored because the most
    // relevant error is that native bridge is unsupported.
    android::CloseNativeLibrary(dlopen_handle, needs_native_bridge, &nativeloader_error_msg);
    android::NativeLoaderFreeErrorMessage(nativeloader_error_msg);
    *error_msg = StringPrintf("Native-bridge agents unsupported: %s", name_.c_str());
    *error = kLoadingError;
    return nullptr;
  }

  std::unique_ptr<Agent> agent(new Agent(name_, dlopen_handle));
  agent->PopulateFunctions();
  *error = kNoError;
  return agent;
}

std::ostream& operator<<(std::ostream &os, AgentSpec const& m) {
  return os << "AgentSpec { name=\"" << m.name_ << "\", args=\"" << m.args_ << "\" }";
}


void* Agent::FindSymbol(const std::string& name) const {
  CHECK(dlopen_handle_ != nullptr) << "Cannot find symbols in an unloaded agent library " << this;
  return dlsym(dlopen_handle_, name.c_str());
}

// TODO Lock some stuff probably.
void Agent::Unload() {
  if (dlopen_handle_ != nullptr) {
    if (onunload_ != nullptr) {
      onunload_(Runtime::Current()->GetJavaVM());
    }
    // Don't actually android::CloseNativeLibrary since some agents assume they will never get
    // unloaded. Since this only happens when the runtime is shutting down anyway this isn't a big
    // deal.
    dlopen_handle_ = nullptr;
    onload_ = nullptr;
    onattach_ = nullptr;
    onunload_ = nullptr;
  } else {
    VLOG(agents) << this << " is not currently loaded!";
  }
}

Agent::Agent(Agent&& other) noexcept
    : dlopen_handle_(nullptr),
      onload_(nullptr),
      onattach_(nullptr),
      onunload_(nullptr) {
  *this = std::move(other);
}

Agent& Agent::operator=(Agent&& other) noexcept {
  if (this != &other) {
    if (dlopen_handle_ != nullptr) {
      Unload();
    }
    name_ = std::move(other.name_);
    dlopen_handle_ = other.dlopen_handle_;
    onload_ = other.onload_;
    onattach_ = other.onattach_;
    onunload_ = other.onunload_;
    other.dlopen_handle_ = nullptr;
    other.onload_ = nullptr;
    other.onattach_ = nullptr;
    other.onunload_ = nullptr;
  }
  return *this;
}

void Agent::PopulateFunctions() {
  onload_ = reinterpret_cast<AgentOnLoadFunction>(FindSymbol(AGENT_ON_LOAD_FUNCTION_NAME));
  if (onload_ == nullptr) {
    VLOG(agents) << "Unable to find 'Agent_OnLoad' symbol in " << this;
  }
  onattach_ = reinterpret_cast<AgentOnLoadFunction>(FindSymbol(AGENT_ON_ATTACH_FUNCTION_NAME));
  if (onattach_ == nullptr) {
    VLOG(agents) << "Unable to find 'Agent_OnAttach' symbol in " << this;
  }
  onunload_ = reinterpret_cast<AgentOnUnloadFunction>(FindSymbol(AGENT_ON_UNLOAD_FUNCTION_NAME));
  if (onunload_ == nullptr) {
    VLOG(agents) << "Unable to find 'Agent_OnUnload' symbol in " << this;
  }
}

Agent::~Agent() {
  if (dlopen_handle_ != nullptr) {
    Unload();
  }
}

std::ostream& operator<<(std::ostream &os, const Agent* m) {
  return os << *m;
}

std::ostream& operator<<(std::ostream &os, Agent const& m) {
  return os << "Agent { name=\"" << m.name_ << "\", handle=" << m.dlopen_handle_ << " }";
}

}  // namespace ti
}  // namespace art