blob: 9f4bc4dee48de8ff7a10d52e74dbe7cd986dd019 [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 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 "debugger.h"
18
Elliott Hughes3bb81562011-10-21 18:52:59 -070019#include <sys/uio.h>
20
Elliott Hughes6a5bd492011-10-28 14:33:57 -070021#include "ScopedLocalRef.h"
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -070022#include "ScopedPrimitiveArray.h"
Elliott Hughes47fce012011-10-25 18:37:19 -070023#include "stack_indirect_reference_table.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070024#include "thread_list.h"
25
Elliott Hughes6a5bd492011-10-28 14:33:57 -070026extern "C" void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*);
27#ifndef HAVE_ANDROID_OS
28void dlmalloc_walk_heap(void(*)(const void*, size_t, const void*, size_t, void*), void*) {
29 // No-op for glibc.
30}
31#endif
32
Elliott Hughes872d4ec2011-10-21 17:07:15 -070033namespace art {
34
Elliott Hughes475fc232011-10-25 15:00:35 -070035class ObjectRegistry {
36 public:
37 ObjectRegistry() : lock_("ObjectRegistry lock") {
38 }
39
40 JDWP::ObjectId Add(Object* o) {
41 if (o == NULL) {
42 return 0;
43 }
44 JDWP::ObjectId id = static_cast<JDWP::ObjectId>(reinterpret_cast<uintptr_t>(o));
45 MutexLock mu(lock_);
46 map_[id] = o;
47 return id;
48 }
49
Elliott Hughes234ab152011-10-26 14:02:26 -070050 void Clear() {
51 MutexLock mu(lock_);
52 LOG(DEBUG) << "Debugger has detached; object registry had " << map_.size() << " entries";
53 map_.clear();
54 }
55
Elliott Hughes475fc232011-10-25 15:00:35 -070056 bool Contains(JDWP::ObjectId id) {
57 MutexLock mu(lock_);
58 return map_.find(id) != map_.end();
59 }
60
Elliott Hughesbfe487b2011-10-26 15:48:55 -070061 void VisitRoots(Heap::RootVisitor* visitor, void* arg) {
62 MutexLock mu(lock_);
63 typedef std::map<JDWP::ObjectId, Object*>::iterator It; // C++0x auto
64 for (It it = map_.begin(); it != map_.end(); ++it) {
65 visitor(it->second, arg);
66 }
67 }
68
Elliott Hughes475fc232011-10-25 15:00:35 -070069 private:
70 Mutex lock_;
71 std::map<JDWP::ObjectId, Object*> map_;
72};
73
Elliott Hughes4ffd3132011-10-24 12:06:42 -070074// JDWP is allowed unless the Zygote forbids it.
75static bool gJdwpAllowed = true;
76
Elliott Hughes3bb81562011-10-21 18:52:59 -070077// Was there a -Xrunjdwp or -agent argument on the command-line?
78static bool gJdwpConfigured = false;
79
80// Broken-down JDWP options. (Only valid if gJdwpConfigured is true.)
Elliott Hughes376a7a02011-10-24 18:35:55 -070081static JDWP::JdwpOptions gJdwpOptions;
Elliott Hughes3bb81562011-10-21 18:52:59 -070082
83// Runtime JDWP state.
84static JDWP::JdwpState* gJdwpState = NULL;
85static bool gDebuggerConnected; // debugger or DDMS is connected.
86static bool gDebuggerActive; // debugger is making requests.
87
Elliott Hughes47fce012011-10-25 18:37:19 -070088static bool gDdmThreadNotification = false;
89
Elliott Hughes767a1472011-10-26 18:49:02 -070090// DDMS GC-related settings.
91static Dbg::HpifWhen gDdmHpifWhen = Dbg::HPIF_WHEN_NEVER;
92static Dbg::HpsgWhen gDdmHpsgWhen = Dbg::HPSG_WHEN_NEVER;
93static Dbg::HpsgWhat gDdmHpsgWhat;
94static Dbg::HpsgWhen gDdmNhsgWhen = Dbg::HPSG_WHEN_NEVER;
95static Dbg::HpsgWhat gDdmNhsgWhat;
96
Elliott Hughes475fc232011-10-25 15:00:35 -070097static ObjectRegistry* gRegistry = NULL;
98
Elliott Hughes3bb81562011-10-21 18:52:59 -070099/*
100 * Handle one of the JDWP name/value pairs.
101 *
102 * JDWP options are:
103 * help: if specified, show help message and bail
104 * transport: may be dt_socket or dt_shmem
105 * address: for dt_socket, "host:port", or just "port" when listening
106 * server: if "y", wait for debugger to attach; if "n", attach to debugger
107 * timeout: how long to wait for debugger to connect / listen
108 *
109 * Useful with server=n (these aren't supported yet):
110 * onthrow=<exception-name>: connect to debugger when exception thrown
111 * onuncaught=y|n: connect to debugger when uncaught exception thrown
112 * launch=<command-line>: launch the debugger itself
113 *
114 * The "transport" option is required, as is "address" if server=n.
115 */
116static bool ParseJdwpOption(const std::string& name, const std::string& value) {
117 if (name == "transport") {
118 if (value == "dt_socket") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700119 gJdwpOptions.transport = JDWP::kJdwpTransportSocket;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700120 } else if (value == "dt_android_adb") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700121 gJdwpOptions.transport = JDWP::kJdwpTransportAndroidAdb;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700122 } else {
123 LOG(ERROR) << "JDWP transport not supported: " << value;
124 return false;
125 }
126 } else if (name == "server") {
127 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700128 gJdwpOptions.server = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700129 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700130 gJdwpOptions.server = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700131 } else {
132 LOG(ERROR) << "JDWP option 'server' must be 'y' or 'n'";
133 return false;
134 }
135 } else if (name == "suspend") {
136 if (value == "n") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700137 gJdwpOptions.suspend = false;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700138 } else if (value == "y") {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700139 gJdwpOptions.suspend = true;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700140 } else {
141 LOG(ERROR) << "JDWP option 'suspend' must be 'y' or 'n'";
142 return false;
143 }
144 } else if (name == "address") {
145 /* this is either <port> or <host>:<port> */
146 std::string port_string;
Elliott Hughes376a7a02011-10-24 18:35:55 -0700147 gJdwpOptions.host.clear();
Elliott Hughes3bb81562011-10-21 18:52:59 -0700148 std::string::size_type colon = value.find(':');
149 if (colon != std::string::npos) {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700150 gJdwpOptions.host = value.substr(0, colon);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700151 port_string = value.substr(colon + 1);
152 } else {
153 port_string = value;
154 }
155 if (port_string.empty()) {
156 LOG(ERROR) << "JDWP address missing port: " << value;
157 return false;
158 }
159 char* end;
160 long port = strtol(port_string.c_str(), &end, 10);
161 if (*end != '\0') {
162 LOG(ERROR) << "JDWP address has junk in port field: " << value;
163 return false;
164 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700165 gJdwpOptions.port = port;
Elliott Hughes3bb81562011-10-21 18:52:59 -0700166 } else if (name == "launch" || name == "onthrow" || name == "oncaught" || name == "timeout") {
167 /* valid but unsupported */
168 LOG(INFO) << "Ignoring JDWP option '" << name << "'='" << value << "'";
169 } else {
170 LOG(INFO) << "Ignoring unrecognized JDWP option '" << name << "'='" << value << "'";
171 }
172
173 return true;
174}
175
176/*
177 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
178 * "transport=dt_socket,address=8000,server=y,suspend=n"
179 */
180bool Dbg::ParseJdwpOptions(const std::string& options) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700181 LOG(VERBOSE) << "ParseJdwpOptions: " << options;
182
Elliott Hughes3bb81562011-10-21 18:52:59 -0700183 std::vector<std::string> pairs;
184 Split(options, ',', pairs);
185
186 for (size_t i = 0; i < pairs.size(); ++i) {
187 std::string::size_type equals = pairs[i].find('=');
188 if (equals == std::string::npos) {
189 LOG(ERROR) << "Can't parse JDWP option '" << pairs[i] << "' in '" << options << "'";
190 return false;
191 }
192 ParseJdwpOption(pairs[i].substr(0, equals), pairs[i].substr(equals + 1));
193 }
194
Elliott Hughes376a7a02011-10-24 18:35:55 -0700195 if (gJdwpOptions.transport == JDWP::kJdwpTransportUnknown) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700196 LOG(ERROR) << "Must specify JDWP transport: " << options;
197 }
Elliott Hughes376a7a02011-10-24 18:35:55 -0700198 if (!gJdwpOptions.server && (gJdwpOptions.host.empty() || gJdwpOptions.port == 0)) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700199 LOG(ERROR) << "Must specify JDWP host and port when server=n: " << options;
200 return false;
201 }
202
203 gJdwpConfigured = true;
204 return true;
205}
206
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700207void Dbg::StartJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700208 if (!gJdwpAllowed || !gJdwpConfigured) {
209 // No JDWP for you!
210 return;
211 }
212
Elliott Hughes475fc232011-10-25 15:00:35 -0700213 CHECK(gRegistry == NULL);
214 gRegistry = new ObjectRegistry;
215
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700216 // Init JDWP if the debugger is enabled. This may connect out to a
217 // debugger, passively listen for a debugger, or block waiting for a
218 // debugger.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700219 gJdwpState = JDWP::JdwpState::Create(&gJdwpOptions);
220 if (gJdwpState == NULL) {
221 LOG(WARNING) << "debugger thread failed to initialize";
Elliott Hughes475fc232011-10-25 15:00:35 -0700222 return;
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700223 }
224
225 // If a debugger has already attached, send the "welcome" message.
226 // This may cause us to suspend all threads.
Elliott Hughes376a7a02011-10-24 18:35:55 -0700227 if (gJdwpState->IsActive()) {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700228 //ScopedThreadStateChange(Thread::Current(), Thread::kRunnable);
Elliott Hughes376a7a02011-10-24 18:35:55 -0700229 if (!gJdwpState->PostVMStart()) {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700230 LOG(WARNING) << "failed to post 'start' message to debugger";
231 }
232 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700233}
234
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700235void Dbg::StopJdwp() {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700236 delete gJdwpState;
Elliott Hughes475fc232011-10-25 15:00:35 -0700237 delete gRegistry;
238 gRegistry = NULL;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700239}
240
Elliott Hughes767a1472011-10-26 18:49:02 -0700241void Dbg::GcDidFinish() {
242 if (gDdmHpifWhen != HPIF_WHEN_NEVER) {
243 LOG(DEBUG) << "Sending VM heap info to DDM";
Elliott Hughes7162ad92011-10-27 14:08:42 -0700244 DdmSendHeapInfo(gDdmHpifWhen);
Elliott Hughes767a1472011-10-26 18:49:02 -0700245 }
246 if (gDdmHpsgWhen != HPSG_WHEN_NEVER) {
247 LOG(DEBUG) << "Dumping VM heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700248 DdmSendHeapSegments(false);
Elliott Hughes767a1472011-10-26 18:49:02 -0700249 }
250 if (gDdmNhsgWhen != HPSG_WHEN_NEVER) {
251 LOG(DEBUG) << "Dumping native heap to DDM";
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700252 DdmSendHeapSegments(true);
Elliott Hughes767a1472011-10-26 18:49:02 -0700253 }
254}
255
Elliott Hughes4ffd3132011-10-24 12:06:42 -0700256void Dbg::SetJdwpAllowed(bool allowed) {
257 gJdwpAllowed = allowed;
258}
259
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700260DebugInvokeReq* Dbg::GetInvokeReq() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700261 return Thread::Current()->GetInvokeReq();
262}
263
264Thread* Dbg::GetDebugThread() {
265 return (gJdwpState != NULL) ? gJdwpState->GetDebugThread() : NULL;
266}
267
268void Dbg::ClearWaitForEventThread() {
269 gJdwpState->ClearWaitForEventThread();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700270}
271
272void Dbg::Connected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700273 CHECK(!gDebuggerConnected);
274 LOG(VERBOSE) << "JDWP has attached";
275 gDebuggerConnected = true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700276}
277
278void Dbg::Active() {
279 UNIMPLEMENTED(FATAL);
280}
281
282void Dbg::Disconnected() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700283 CHECK(gDebuggerConnected);
284
285 gDebuggerActive = false;
286
287 //dvmDisableAllSubMode(kSubModeDebuggerActive);
288
289 gRegistry->Clear();
290 gDebuggerConnected = false;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700291}
292
293bool Dbg::IsDebuggerConnected() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700294 return gDebuggerActive;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700295}
296
297bool Dbg::IsDebuggingEnabled() {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700298 return gJdwpConfigured;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700299}
300
301int64_t Dbg::LastDebuggerActivity() {
302 UNIMPLEMENTED(WARNING);
303 return -1;
304}
305
306int Dbg::ThreadRunning() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700307 return static_cast<int>(Thread::Current()->SetState(Thread::kRunnable));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700308}
309
310int Dbg::ThreadWaiting() {
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700311 return static_cast<int>(Thread::Current()->SetState(Thread::kVmWait));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700312}
313
Elliott Hughes6ba581a2011-10-25 11:45:35 -0700314int Dbg::ThreadContinuing(int new_state) {
315 return static_cast<int>(Thread::Current()->SetState(static_cast<Thread::State>(new_state)));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700316}
317
318void Dbg::UndoDebuggerSuspensions() {
Elliott Hughes234ab152011-10-26 14:02:26 -0700319 Runtime::Current()->GetThreadList()->UndoDebuggerSuspensions();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700320}
321
322void Dbg::Exit(int status) {
323 UNIMPLEMENTED(FATAL);
324}
325
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700326void Dbg::VisitRoots(Heap::RootVisitor* visitor, void* arg) {
327 if (gRegistry != NULL) {
328 gRegistry->VisitRoots(visitor, arg);
329 }
330}
331
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700332const char* Dbg::GetClassDescriptor(JDWP::RefTypeId id) {
333 UNIMPLEMENTED(FATAL);
334 return NULL;
335}
336
337JDWP::ObjectId Dbg::GetClassObject(JDWP::RefTypeId id) {
338 UNIMPLEMENTED(FATAL);
339 return 0;
340}
341
342JDWP::RefTypeId Dbg::GetSuperclass(JDWP::RefTypeId id) {
343 UNIMPLEMENTED(FATAL);
344 return 0;
345}
346
347JDWP::ObjectId Dbg::GetClassLoader(JDWP::RefTypeId id) {
348 UNIMPLEMENTED(FATAL);
349 return 0;
350}
351
352uint32_t Dbg::GetAccessFlags(JDWP::RefTypeId id) {
353 UNIMPLEMENTED(FATAL);
354 return 0;
355}
356
357bool Dbg::IsInterface(JDWP::RefTypeId id) {
358 UNIMPLEMENTED(FATAL);
359 return false;
360}
361
362void Dbg::GetClassList(uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
363 UNIMPLEMENTED(FATAL);
364}
365
366void Dbg::GetVisibleClassList(JDWP::ObjectId classLoaderId, uint32_t* pNumClasses, JDWP::RefTypeId** pClassRefBuf) {
367 UNIMPLEMENTED(FATAL);
368}
369
370void Dbg::GetClassInfo(JDWP::RefTypeId classId, uint8_t* pTypeTag, uint32_t* pStatus, const char** pSignature) {
371 UNIMPLEMENTED(FATAL);
372}
373
374bool Dbg::FindLoadedClassBySignature(const char* classDescriptor, JDWP::RefTypeId* pRefTypeId) {
375 UNIMPLEMENTED(FATAL);
376 return false;
377}
378
379void Dbg::GetObjectType(JDWP::ObjectId objectId, uint8_t* pRefTypeTag, JDWP::RefTypeId* pRefTypeId) {
380 UNIMPLEMENTED(FATAL);
381}
382
383uint8_t Dbg::GetClassObjectType(JDWP::RefTypeId refTypeId) {
384 UNIMPLEMENTED(FATAL);
385 return 0;
386}
387
388const char* Dbg::GetSignature(JDWP::RefTypeId refTypeId) {
389 UNIMPLEMENTED(FATAL);
390 return NULL;
391}
392
393const char* Dbg::GetSourceFile(JDWP::RefTypeId refTypeId) {
394 UNIMPLEMENTED(FATAL);
395 return NULL;
396}
397
398const char* Dbg::GetObjectTypeName(JDWP::ObjectId objectId) {
399 UNIMPLEMENTED(FATAL);
400 return NULL;
401}
402
403uint8_t Dbg::GetObjectTag(JDWP::ObjectId objectId) {
404 UNIMPLEMENTED(FATAL);
405 return 0;
406}
407
408int Dbg::GetTagWidth(int tag) {
409 UNIMPLEMENTED(FATAL);
410 return 0;
411}
412
413int Dbg::GetArrayLength(JDWP::ObjectId arrayId) {
414 UNIMPLEMENTED(FATAL);
415 return 0;
416}
417
418uint8_t Dbg::GetArrayElementTag(JDWP::ObjectId arrayId) {
419 UNIMPLEMENTED(FATAL);
420 return 0;
421}
422
423bool Dbg::OutputArray(JDWP::ObjectId arrayId, int firstIndex, int count, JDWP::ExpandBuf* pReply) {
424 UNIMPLEMENTED(FATAL);
425 return false;
426}
427
428bool Dbg::SetArrayElements(JDWP::ObjectId arrayId, int firstIndex, int count, const uint8_t* buf) {
429 UNIMPLEMENTED(FATAL);
430 return false;
431}
432
433JDWP::ObjectId Dbg::CreateString(const char* str) {
434 UNIMPLEMENTED(FATAL);
435 return 0;
436}
437
438JDWP::ObjectId Dbg::CreateObject(JDWP::RefTypeId classId) {
439 UNIMPLEMENTED(FATAL);
440 return 0;
441}
442
443JDWP::ObjectId Dbg::CreateArrayObject(JDWP::RefTypeId arrayTypeId, uint32_t length) {
444 UNIMPLEMENTED(FATAL);
445 return 0;
446}
447
448bool Dbg::MatchType(JDWP::RefTypeId instClassId, JDWP::RefTypeId classId) {
449 UNIMPLEMENTED(FATAL);
450 return false;
451}
452
453const char* Dbg::GetMethodName(JDWP::RefTypeId refTypeId, JDWP::MethodId id) {
454 UNIMPLEMENTED(FATAL);
455 return NULL;
456}
457
458void Dbg::OutputAllFields(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
459 UNIMPLEMENTED(FATAL);
460}
461
462void Dbg::OutputAllMethods(JDWP::RefTypeId refTypeId, bool withGeneric, JDWP::ExpandBuf* pReply) {
463 UNIMPLEMENTED(FATAL);
464}
465
466void Dbg::OutputAllInterfaces(JDWP::RefTypeId refTypeId, JDWP::ExpandBuf* pReply) {
467 UNIMPLEMENTED(FATAL);
468}
469
470void Dbg::OutputLineTable(JDWP::RefTypeId refTypeId, JDWP::MethodId methodId, JDWP::ExpandBuf* pReply) {
471 UNIMPLEMENTED(FATAL);
472}
473
474void Dbg::OutputVariableTable(JDWP::RefTypeId refTypeId, JDWP::MethodId id, bool withGeneric, JDWP::ExpandBuf* pReply) {
475 UNIMPLEMENTED(FATAL);
476}
477
478uint8_t Dbg::GetFieldBasicTag(JDWP::ObjectId objId, JDWP::FieldId fieldId) {
479 UNIMPLEMENTED(FATAL);
480 return 0;
481}
482
483uint8_t Dbg::GetStaticFieldBasicTag(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId) {
484 UNIMPLEMENTED(FATAL);
485 return 0;
486}
487
488void Dbg::GetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
489 UNIMPLEMENTED(FATAL);
490}
491
492void Dbg::SetFieldValue(JDWP::ObjectId objectId, JDWP::FieldId fieldId, uint64_t value, int width) {
493 UNIMPLEMENTED(FATAL);
494}
495
496void Dbg::GetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, JDWP::ExpandBuf* pReply) {
497 UNIMPLEMENTED(FATAL);
498}
499
500void Dbg::SetStaticFieldValue(JDWP::RefTypeId refTypeId, JDWP::FieldId fieldId, uint64_t rawValue, int width) {
501 UNIMPLEMENTED(FATAL);
502}
503
504char* Dbg::StringToUtf8(JDWP::ObjectId strId) {
505 UNIMPLEMENTED(FATAL);
506 return NULL;
507}
508
509char* Dbg::GetThreadName(JDWP::ObjectId threadId) {
510 UNIMPLEMENTED(FATAL);
511 return NULL;
512}
513
514JDWP::ObjectId Dbg::GetThreadGroup(JDWP::ObjectId threadId) {
515 UNIMPLEMENTED(FATAL);
516 return 0;
517}
518
519char* Dbg::GetThreadGroupName(JDWP::ObjectId threadGroupId) {
520 UNIMPLEMENTED(FATAL);
521 return NULL;
522}
523
524JDWP::ObjectId Dbg::GetThreadGroupParent(JDWP::ObjectId threadGroupId) {
525 UNIMPLEMENTED(FATAL);
526 return 0;
527}
528
529JDWP::ObjectId Dbg::GetSystemThreadGroupId() {
530 UNIMPLEMENTED(FATAL);
531 return 0;
532}
533
534JDWP::ObjectId Dbg::GetMainThreadGroupId() {
535 UNIMPLEMENTED(FATAL);
536 return 0;
537}
538
539bool Dbg::GetThreadStatus(JDWP::ObjectId threadId, uint32_t* threadStatus, uint32_t* suspendStatus) {
540 UNIMPLEMENTED(FATAL);
541 return false;
542}
543
544uint32_t Dbg::GetThreadSuspendCount(JDWP::ObjectId threadId) {
545 UNIMPLEMENTED(FATAL);
546 return 0;
547}
548
549bool Dbg::ThreadExists(JDWP::ObjectId threadId) {
550 UNIMPLEMENTED(FATAL);
551 return false;
552}
553
554bool Dbg::IsSuspended(JDWP::ObjectId threadId) {
555 UNIMPLEMENTED(FATAL);
556 return false;
557}
558
559//void Dbg::WaitForSuspend(JDWP::ObjectId threadId);
560
561void Dbg::GetThreadGroupThreads(JDWP::ObjectId threadGroupId, JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
562 UNIMPLEMENTED(FATAL);
563}
564
565void Dbg::GetAllThreads(JDWP::ObjectId** ppThreadIds, uint32_t* pThreadCount) {
566 UNIMPLEMENTED(FATAL);
567}
568
569int Dbg::GetThreadFrameCount(JDWP::ObjectId threadId) {
570 UNIMPLEMENTED(FATAL);
571 return 0;
572}
573
574bool Dbg::GetThreadFrame(JDWP::ObjectId threadId, int num, JDWP::FrameId* pFrameId, JDWP::JdwpLocation* pLoc) {
575 UNIMPLEMENTED(FATAL);
576 return false;
577}
578
579JDWP::ObjectId Dbg::GetThreadSelfId() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700580 return gRegistry->Add(Thread::Current()->GetPeer());
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700581}
582
Elliott Hughes475fc232011-10-25 15:00:35 -0700583void Dbg::SuspendVM() {
584 Runtime::Current()->GetThreadList()->SuspendAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700585}
586
587void Dbg::ResumeVM() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700588 Runtime::Current()->GetThreadList()->ResumeAll(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700589}
590
591void Dbg::SuspendThread(JDWP::ObjectId threadId) {
592 UNIMPLEMENTED(FATAL);
593}
594
595void Dbg::ResumeThread(JDWP::ObjectId threadId) {
596 UNIMPLEMENTED(FATAL);
597}
598
599void Dbg::SuspendSelf() {
Elliott Hughes475fc232011-10-25 15:00:35 -0700600 Runtime::Current()->GetThreadList()->SuspendSelfForDebugger();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700601}
602
603bool Dbg::GetThisObject(JDWP::ObjectId threadId, JDWP::FrameId frameId, JDWP::ObjectId* pThisId) {
604 UNIMPLEMENTED(FATAL);
605 return false;
606}
607
608void Dbg::GetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint8_t* buf, int expectedLen) {
609 UNIMPLEMENTED(FATAL);
610}
611
612void Dbg::SetLocalValue(JDWP::ObjectId threadId, JDWP::FrameId frameId, int slot, uint8_t tag, uint64_t value, int width) {
613 UNIMPLEMENTED(FATAL);
614}
615
616void Dbg::PostLocationEvent(const Method* method, int pcOffset, Object* thisPtr, int eventFlags) {
617 UNIMPLEMENTED(FATAL);
618}
619
620void Dbg::PostException(void* throwFp, int throwRelPc, void* catchFp, int catchRelPc, Object* exception) {
621 UNIMPLEMENTED(FATAL);
622}
623
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700624void Dbg::PostClassPrepare(Class* c) {
625 UNIMPLEMENTED(FATAL);
626}
627
628bool Dbg::WatchLocation(const JDWP::JdwpLocation* pLoc) {
629 UNIMPLEMENTED(FATAL);
630 return false;
631}
632
633void Dbg::UnwatchLocation(const JDWP::JdwpLocation* pLoc) {
634 UNIMPLEMENTED(FATAL);
635}
636
637bool Dbg::ConfigureStep(JDWP::ObjectId threadId, JDWP::JdwpStepSize size, JDWP::JdwpStepDepth depth) {
638 UNIMPLEMENTED(FATAL);
639 return false;
640}
641
642void Dbg::UnconfigureStep(JDWP::ObjectId threadId) {
643 UNIMPLEMENTED(FATAL);
644}
645
646JDWP::JdwpError Dbg::InvokeMethod(JDWP::ObjectId threadId, JDWP::ObjectId objectId, JDWP::RefTypeId classId, JDWP::MethodId methodId, uint32_t numArgs, uint64_t* argArray, uint32_t options, uint8_t* pResultTag, uint64_t* pResultValue, JDWP::ObjectId* pExceptObj) {
647 UNIMPLEMENTED(FATAL);
648 return JDWP::ERR_NONE;
649}
650
651void Dbg::ExecuteMethod(DebugInvokeReq* pReq) {
652 UNIMPLEMENTED(FATAL);
653}
654
655void Dbg::RegisterObjectId(JDWP::ObjectId id) {
656 UNIMPLEMENTED(FATAL);
657}
658
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700659/*
660 * "buf" contains a full JDWP packet, possibly with multiple chunks. We
661 * need to process each, accumulate the replies, and ship the whole thing
662 * back.
663 *
664 * Returns "true" if we have a reply. The reply buffer is newly allocated,
665 * and includes the chunk type/length, followed by the data.
666 *
667 * TODO: we currently assume that the request and reply include a single
668 * chunk. If this becomes inconvenient we will need to adapt.
669 */
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700670bool Dbg::DdmHandlePacket(const uint8_t* buf, int dataLen, uint8_t** pReplyBuf, int* pReplyLen) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700671 CHECK_GE(dataLen, 0);
672
673 Thread* self = Thread::Current();
674 JNIEnv* env = self->GetJniEnv();
675
676 static jclass Chunk_class = env->FindClass("org/apache/harmony/dalvik/ddmc/Chunk");
677 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
678 static jmethodID dispatch_mid = env->GetStaticMethodID(DdmServer_class, "dispatch",
679 "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;");
680 static jfieldID data_fid = env->GetFieldID(Chunk_class, "data", "[B");
681 static jfieldID length_fid = env->GetFieldID(Chunk_class, "length", "I");
682 static jfieldID offset_fid = env->GetFieldID(Chunk_class, "offset", "I");
683 static jfieldID type_fid = env->GetFieldID(Chunk_class, "type", "I");
684
685 // Create a byte[] corresponding to 'buf'.
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700686 ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(dataLen));
687 if (dataArray.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700688 LOG(WARNING) << "byte[] allocation failed: " << dataLen;
689 env->ExceptionClear();
690 return false;
691 }
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700692 env->SetByteArrayRegion(dataArray.get(), 0, dataLen, reinterpret_cast<const jbyte*>(buf));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700693
694 const int kChunkHdrLen = 8;
695
696 // Run through and find all chunks. [Currently just find the first.]
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700697 ScopedByteArrayRO contents(env, dataArray.get());
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700698 jint type = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[0]));
699 jint length = JDWP::Get4BE(reinterpret_cast<const uint8_t*>(&contents[4]));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700700 jint offset = kChunkHdrLen;
701 if (offset + length > dataLen) {
702 LOG(WARNING) << StringPrintf("bad chunk found (len=%u pktLen=%d)", length, dataLen);
703 return false;
704 }
705
706 // Call "private static Chunk dispatch(int type, byte[] data, int offset, int length)".
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700707 ScopedLocalRef<jobject> chunk(env, env->CallStaticObjectMethod(DdmServer_class, dispatch_mid, type, dataArray.get(), offset, length));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700708 if (env->ExceptionCheck()) {
709 LOG(INFO) << StringPrintf("Exception thrown by dispatcher for 0x%08x", type);
710 env->ExceptionDescribe();
711 env->ExceptionClear();
712 return false;
713 }
714
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700715 if (chunk.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700716 return false;
717 }
718
719 /*
720 * Pull the pieces out of the chunk. We copy the results into a
721 * newly-allocated buffer that the caller can free. We don't want to
722 * continue using the Chunk object because nothing has a reference to it.
723 *
724 * We could avoid this by returning type/data/offset/length and having
725 * the caller be aware of the object lifetime issues, but that
726 * integrates the JDWP code more tightly into the VM, and doesn't work
727 * if we have responses for multiple chunks.
728 *
729 * So we're pretty much stuck with copying data around multiple times.
730 */
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700731 ScopedLocalRef<jbyteArray> replyData(env, reinterpret_cast<jbyteArray>(env->GetObjectField(chunk.get(), data_fid)));
732 length = env->GetIntField(chunk.get(), length_fid);
733 offset = env->GetIntField(chunk.get(), offset_fid);
734 type = env->GetIntField(chunk.get(), type_fid);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700735
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700736 LOG(VERBOSE) << StringPrintf("DDM reply: type=0x%08x data=%p offset=%d length=%d", type, replyData.get(), offset, length);
737 if (length == 0 || replyData.get() == NULL) {
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700738 return false;
739 }
740
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700741 jsize replyLength = env->GetArrayLength(replyData.get());
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700742 if (offset + length > replyLength) {
743 LOG(WARNING) << StringPrintf("chunk off=%d len=%d exceeds reply array len %d", offset, length, replyLength);
744 return false;
745 }
746
747 uint8_t* reply = new uint8_t[length + kChunkHdrLen];
748 if (reply == NULL) {
749 LOG(WARNING) << "malloc failed: " << (length + kChunkHdrLen);
750 return false;
751 }
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700752 JDWP::Set4BE(reply + 0, type);
753 JDWP::Set4BE(reply + 4, length);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700754 env->GetByteArrayRegion(replyData.get(), offset, length, reinterpret_cast<jbyte*>(reply + kChunkHdrLen));
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700755
756 *pReplyBuf = reply;
757 *pReplyLen = length + kChunkHdrLen;
758
759 LOG(VERBOSE) << StringPrintf("dvmHandleDdm returning type=%.4s buf=%p len=%d", (char*) reply, reply, length);
760 return true;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700761}
762
Elliott Hughes47fce012011-10-25 18:37:19 -0700763void DdmBroadcast(bool connect) {
764 LOG(VERBOSE) << "Broadcasting DDM " << (connect ? "connect" : "disconnect") << "...";
765
766 Thread* self = Thread::Current();
767 if (self->GetState() != Thread::kRunnable) {
768 LOG(ERROR) << "DDM broadcast in thread state " << self->GetState();
769 /* try anyway? */
770 }
771
772 JNIEnv* env = self->GetJniEnv();
773 static jclass DdmServer_class = env->FindClass("org/apache/harmony/dalvik/ddmc/DdmServer");
774 static jmethodID broadcast_mid = env->GetStaticMethodID(DdmServer_class, "broadcast", "(I)V");
775 jint event = connect ? 1 /*DdmServer.CONNECTED*/ : 2 /*DdmServer.DISCONNECTED*/;
776 env->CallStaticVoidMethod(DdmServer_class, broadcast_mid, event);
777 if (env->ExceptionCheck()) {
778 LOG(ERROR) << "DdmServer.broadcast " << event << " failed";
779 env->ExceptionDescribe();
780 env->ExceptionClear();
781 }
782}
783
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700784void Dbg::DdmConnected() {
Elliott Hughes47fce012011-10-25 18:37:19 -0700785 DdmBroadcast(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700786}
787
788void Dbg::DdmDisconnected() {
Elliott Hughes47fce012011-10-25 18:37:19 -0700789 DdmBroadcast(false);
790 gDdmThreadNotification = false;
791}
792
793/*
794 * Send a notification when a thread starts or stops.
795 *
796 * Because we broadcast the full set of threads when the notifications are
797 * first enabled, it's possible for "thread" to be actively executing.
798 */
799void DdmSendThreadNotification(Thread* t, bool started) {
800 if (!gDdmThreadNotification) {
801 return;
802 }
803
804 if (started) {
805 SirtRef<String> name(t->GetName());
806 size_t char_count = (name.get() != NULL) ? name->GetLength() : 0;
807
808 size_t byte_count = char_count*2 + sizeof(uint32_t)*2;
809 std::vector<uint8_t> buf(byte_count);
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700810 JDWP::Set4BE(&buf[0], t->GetThinLockId());
811 JDWP::Set4BE(&buf[4], char_count);
Elliott Hughes47fce012011-10-25 18:37:19 -0700812 if (char_count > 0) {
813 // Copy the UTF-16 string, transforming to big-endian.
814 const jchar* src = name->GetCharArray()->GetData();
815 jchar* dst = reinterpret_cast<jchar*>(&buf[8]);
816 while (char_count--) {
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700817 JDWP::Set2BE(reinterpret_cast<uint8_t*>(dst++), *src++);
Elliott Hughes47fce012011-10-25 18:37:19 -0700818 }
819 }
820 Dbg::DdmSendChunk(CHUNK_TYPE("THCR"), buf.size(), &buf[0]);
821 } else {
822 uint8_t buf[4];
Elliott Hughesf7c3b662011-10-27 12:04:56 -0700823 JDWP::Set4BE(&buf[0], t->GetThinLockId());
Elliott Hughes47fce012011-10-25 18:37:19 -0700824 Dbg::DdmSendChunk(CHUNK_TYPE("THDE"), 4, buf);
825 }
826}
827
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700828void DdmSendThreadStartCallback(Thread* t, void*) {
Elliott Hughes47fce012011-10-25 18:37:19 -0700829 DdmSendThreadNotification(t, true);
830}
831
832void Dbg::DdmSetThreadNotification(bool enable) {
833 // We lock the thread list to avoid sending duplicate events or missing
834 // a thread change. We should be okay holding this lock while sending
835 // the messages out. (We have to hold it while accessing a live thread.)
836 ThreadListLock lock;
837
838 gDdmThreadNotification = enable;
839 if (enable) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700840 Runtime::Current()->GetThreadList()->ForEach(DdmSendThreadStartCallback, NULL);
Elliott Hughes47fce012011-10-25 18:37:19 -0700841 }
842}
843
844void PostThreadStartOrStop(Thread* t, bool is_start) {
845 if (gDebuggerActive) {
846 JDWP::ObjectId id = gRegistry->Add(t->GetPeer());
847 gJdwpState->PostThreadChange(id, is_start);
848 }
849 DdmSendThreadNotification(t, is_start);
850}
851
852void Dbg::PostThreadStart(Thread* t) {
853 PostThreadStartOrStop(t, true);
854}
855
856void Dbg::PostThreadDeath(Thread* t) {
857 PostThreadStartOrStop(t, false);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700858}
859
Elliott Hughes3bb81562011-10-21 18:52:59 -0700860void Dbg::DdmSendChunk(int type, size_t byte_count, const uint8_t* buf) {
861 CHECK(buf != NULL);
862 iovec vec[1];
863 vec[0].iov_base = reinterpret_cast<void*>(const_cast<uint8_t*>(buf));
864 vec[0].iov_len = byte_count;
865 Dbg::DdmSendChunkV(type, vec, 1);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700866}
867
868void Dbg::DdmSendChunkV(int type, const struct iovec* iov, int iovcnt) {
Elliott Hughes3bb81562011-10-21 18:52:59 -0700869 if (gJdwpState == NULL) {
870 LOG(VERBOSE) << "Debugger thread not active, ignoring DDM send: " << type;
871 } else {
Elliott Hughes376a7a02011-10-24 18:35:55 -0700872 gJdwpState->DdmSendChunkV(type, iov, iovcnt);
Elliott Hughes3bb81562011-10-21 18:52:59 -0700873 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700874}
875
Elliott Hughes767a1472011-10-26 18:49:02 -0700876int Dbg::DdmHandleHpifChunk(HpifWhen when) {
877 if (when == HPIF_WHEN_NOW) {
Elliott Hughes7162ad92011-10-27 14:08:42 -0700878 DdmSendHeapInfo(when);
Elliott Hughes767a1472011-10-26 18:49:02 -0700879 return true;
880 }
881
882 if (when != HPIF_WHEN_NEVER && when != HPIF_WHEN_NEXT_GC && when != HPIF_WHEN_EVERY_GC) {
883 LOG(ERROR) << "invalid HpifWhen value: " << static_cast<int>(when);
884 return false;
885 }
886
887 gDdmHpifWhen = when;
888 return true;
889}
890
891bool Dbg::DdmHandleHpsgNhsgChunk(Dbg::HpsgWhen when, Dbg::HpsgWhat what, bool native) {
892 if (when != HPSG_WHEN_NEVER && when != HPSG_WHEN_EVERY_GC) {
893 LOG(ERROR) << "invalid HpsgWhen value: " << static_cast<int>(when);
894 return false;
895 }
896
897 if (what != HPSG_WHAT_MERGED_OBJECTS && what != HPSG_WHAT_DISTINCT_OBJECTS) {
898 LOG(ERROR) << "invalid HpsgWhat value: " << static_cast<int>(what);
899 return false;
900 }
901
902 if (native) {
903 gDdmNhsgWhen = when;
904 gDdmNhsgWhat = what;
905 } else {
906 gDdmHpsgWhen = when;
907 gDdmHpsgWhat = what;
908 }
909 return true;
910}
911
Elliott Hughes7162ad92011-10-27 14:08:42 -0700912void Dbg::DdmSendHeapInfo(HpifWhen reason) {
913 // If there's a one-shot 'when', reset it.
914 if (reason == gDdmHpifWhen) {
915 if (gDdmHpifWhen == HPIF_WHEN_NEXT_GC) {
916 gDdmHpifWhen = HPIF_WHEN_NEVER;
917 }
918 }
919
920 /*
921 * Chunk HPIF (client --> server)
922 *
923 * Heap Info. General information about the heap,
924 * suitable for a summary display.
925 *
926 * [u4]: number of heaps
927 *
928 * For each heap:
929 * [u4]: heap ID
930 * [u8]: timestamp in ms since Unix epoch
931 * [u1]: capture reason (same as 'when' value from server)
932 * [u4]: max heap size in bytes (-Xmx)
933 * [u4]: current heap size in bytes
934 * [u4]: current number of bytes allocated
935 * [u4]: current number of objects allocated
936 */
937 uint8_t heap_count = 1;
938 std::vector<uint8_t> bytes(4 + (heap_count * (4 + 8 + 1 + 4 + 4 + 4 + 4)));
939 uint8_t* dst = &bytes[0];
940 JDWP::Write4BE(&dst, heap_count);
941 JDWP::Write4BE(&dst, 1); // Heap id (bogus; we only have one heap).
942 JDWP::Write8BE(&dst, MilliTime());
943 JDWP::Write1BE(&dst, reason);
944 JDWP::Write4BE(&dst, Heap::GetMaxMemory()); // Max allowed heap size in bytes.
945 JDWP::Write4BE(&dst, Heap::GetTotalMemory()); // Current heap size in bytes.
946 JDWP::Write4BE(&dst, Heap::GetBytesAllocated());
947 JDWP::Write4BE(&dst, Heap::GetObjectsAllocated());
948 Dbg::DdmSendChunk(CHUNK_TYPE("HPIF"), bytes.size(), &bytes[0]);
Elliott Hughes767a1472011-10-26 18:49:02 -0700949}
950
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700951enum HpsgSolidity {
952 SOLIDITY_FREE = 0,
953 SOLIDITY_HARD = 1,
954 SOLIDITY_SOFT = 2,
955 SOLIDITY_WEAK = 3,
956 SOLIDITY_PHANTOM = 4,
957 SOLIDITY_FINALIZABLE = 5,
958 SOLIDITY_SWEEP = 6,
959};
960
961enum HpsgKind {
962 KIND_OBJECT = 0,
963 KIND_CLASS_OBJECT = 1,
964 KIND_ARRAY_1 = 2,
965 KIND_ARRAY_2 = 3,
966 KIND_ARRAY_4 = 4,
967 KIND_ARRAY_8 = 5,
968 KIND_UNKNOWN = 6,
969 KIND_NATIVE = 7,
970};
971
972#define HPSG_PARTIAL (1<<7)
973#define HPSG_STATE(solidity, kind) ((uint8_t)((((kind) & 0x7) << 3) | ((solidity) & 0x7)))
974
975struct HeapChunkContext {
976 std::vector<uint8_t> buf;
977 uint8_t* p;
978 uint8_t* pieceLenField;
979 size_t totalAllocationUnits;
980 int type;
981 bool merge;
982 bool needHeader;
983
984 // Maximum chunk size. Obtain this from the formula:
985 // (((maximum_heap_size / ALLOCATION_UNIT_SIZE) + 255) / 256) * 2
986 HeapChunkContext(bool merge, bool native)
987 : buf(16384 - 16),
988 type(0),
989 merge(merge) {
990 Reset();
991 if (native) {
992 type = CHUNK_TYPE("NHSG");
993 } else {
994 type = merge ? CHUNK_TYPE("HPSG") : CHUNK_TYPE("HPSO");
995 }
996 }
997
998 ~HeapChunkContext() {
999 if (p > &buf[0]) {
1000 Flush();
1001 }
1002 }
1003
1004 void EnsureHeader(const void* chunk_ptr) {
1005 if (!needHeader) {
1006 return;
1007 }
1008
1009 // Start a new HPSx chunk.
1010 JDWP::Write4BE(&p, 1); // Heap id (bogus; we only have one heap).
1011 JDWP::Write1BE(&p, 8); // Size of allocation unit, in bytes.
1012
1013 JDWP::Write4BE(&p, reinterpret_cast<uintptr_t>(chunk_ptr)); // virtual address of segment start.
1014 JDWP::Write4BE(&p, 0); // offset of this piece (relative to the virtual address).
1015 // [u4]: length of piece, in allocation units
1016 // We won't know this until we're done, so save the offset and stuff in a dummy value.
1017 pieceLenField = p;
1018 JDWP::Write4BE(&p, 0x55555555);
1019 needHeader = false;
1020 }
1021
1022 void Flush() {
1023 // Patch the "length of piece" field.
1024 CHECK_LE(&buf[0], pieceLenField);
1025 CHECK_LE(pieceLenField, p);
1026 JDWP::Set4BE(pieceLenField, totalAllocationUnits);
1027
1028 Dbg::DdmSendChunk(type, p - &buf[0], &buf[0]);
1029 Reset();
1030 }
1031
1032 private:
1033 void Reset() {
1034 p = &buf[0];
1035 totalAllocationUnits = 0;
1036 needHeader = true;
1037 pieceLenField = NULL;
1038 }
1039
1040 DISALLOW_COPY_AND_ASSIGN(HeapChunkContext);
1041};
1042
1043#define ALLOCATION_UNIT_SIZE 8
1044
1045uint8_t ExamineObject(const Object* o, bool is_native_heap) {
1046 if (o == NULL) {
1047 return HPSG_STATE(SOLIDITY_FREE, 0);
1048 }
1049
1050 // It's an allocated chunk. Figure out what it is.
1051
1052 // If we're looking at the native heap, we'll just return
1053 // (SOLIDITY_HARD, KIND_NATIVE) for all allocated chunks.
1054 if (is_native_heap || !Heap::IsLiveObjectLocked(o)) {
1055 return HPSG_STATE(SOLIDITY_HARD, KIND_NATIVE);
1056 }
1057
1058 Class* c = o->GetClass();
1059 if (c == NULL) {
1060 // The object was probably just created but hasn't been initialized yet.
1061 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1062 }
1063
1064 if (!Heap::IsHeapAddress(c)) {
1065 LOG(WARNING) << "invalid class for managed heap object: " << o << " " << c;
1066 return HPSG_STATE(SOLIDITY_HARD, KIND_UNKNOWN);
1067 }
1068
1069 if (c->IsClassClass()) {
1070 return HPSG_STATE(SOLIDITY_HARD, KIND_CLASS_OBJECT);
1071 }
1072
1073 if (c->IsArrayClass()) {
1074 if (o->IsObjectArray()) {
1075 return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1076 }
1077 switch (c->GetComponentSize()) {
1078 case 1: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_1);
1079 case 2: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_2);
1080 case 4: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_4);
1081 case 8: return HPSG_STATE(SOLIDITY_HARD, KIND_ARRAY_8);
1082 }
1083 }
1084
1085 return HPSG_STATE(SOLIDITY_HARD, KIND_OBJECT);
1086}
1087
1088static void HeapChunkCallback(const void* chunk_ptr, size_t chunk_len, const void* user_ptr, size_t user_len, void* arg) {
1089 HeapChunkContext* context = reinterpret_cast<HeapChunkContext*>(arg);
1090
1091 CHECK_EQ((chunk_len & (ALLOCATION_UNIT_SIZE-1)), 0U);
1092
1093 /* Make sure there's enough room left in the buffer.
1094 * We need to use two bytes for every fractional 256
1095 * allocation units used by the chunk.
1096 */
1097 {
1098 size_t needed = (((chunk_len/ALLOCATION_UNIT_SIZE + 255) / 256) * 2);
1099 size_t bytesLeft = context->buf.size() - (size_t)(context->p - &context->buf[0]);
1100 if (bytesLeft < needed) {
1101 context->Flush();
1102 }
1103
1104 bytesLeft = context->buf.size() - (size_t)(context->p - &context->buf[0]);
1105 if (bytesLeft < needed) {
1106 LOG(WARNING) << "chunk is too big to transmit (chunk_len=" << chunk_len << ", " << needed << " bytes)";
1107 return;
1108 }
1109 }
1110
1111 // OLD-TODO: notice when there's a gap and start a new heap, or at least a new range.
1112 context->EnsureHeader(chunk_ptr);
1113
1114 // Determine the type of this chunk.
1115 // OLD-TODO: if context.merge, see if this chunk is different from the last chunk.
1116 // If it's the same, we should combine them.
1117 uint8_t state = ExamineObject(reinterpret_cast<const Object*>(user_ptr), (context->type == CHUNK_TYPE("NHSG")));
1118
1119 // Write out the chunk description.
1120 chunk_len /= ALLOCATION_UNIT_SIZE; // convert to allocation units
1121 context->totalAllocationUnits += chunk_len;
1122 while (chunk_len > 256) {
1123 *context->p++ = state | HPSG_PARTIAL;
1124 *context->p++ = 255; // length - 1
1125 chunk_len -= 256;
1126 }
1127 *context->p++ = state;
1128 *context->p++ = chunk_len - 1;
1129}
1130
1131static void WalkHeap(bool merge, bool native) {
1132 HeapChunkContext context(merge, native);
1133 if (native) {
1134 dlmalloc_walk_heap(HeapChunkCallback, &context);
1135 } else {
1136 Heap::WalkHeap(HeapChunkCallback, &context);
1137 }
1138}
1139
1140void Dbg::DdmSendHeapSegments(bool native) {
1141 Dbg::HpsgWhen when;
1142 Dbg::HpsgWhat what;
1143 if (!native) {
1144 when = gDdmHpsgWhen;
1145 what = gDdmHpsgWhat;
1146 } else {
1147 when = gDdmNhsgWhen;
1148 what = gDdmNhsgWhat;
1149 }
1150 if (when == HPSG_WHEN_NEVER) {
1151 return;
1152 }
1153
1154 // Figure out what kind of chunks we'll be sending.
1155 CHECK(what == HPSG_WHAT_MERGED_OBJECTS || what == HPSG_WHAT_DISTINCT_OBJECTS) << static_cast<int>(what);
1156
1157 // First, send a heap start chunk.
1158 uint8_t heap_id[4];
1159 JDWP::Set4BE(&heap_id[0], 1); // Heap id (bogus; we only have one heap).
1160 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHST") : CHUNK_TYPE("HPST"), sizeof(heap_id), heap_id);
1161
1162 // Send a series of heap segment chunks.
1163 WalkHeap((what == HPSG_WHAT_MERGED_OBJECTS), native);
1164
1165 // Finally, send a heap end chunk.
1166 Dbg::DdmSendChunk(native ? CHUNK_TYPE("NHEN") : CHUNK_TYPE("HPEN"), sizeof(heap_id), heap_id);
Elliott Hughes767a1472011-10-26 18:49:02 -07001167}
1168
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001169} // namespace art