blob: e14e4094f66c3df60ee54167e54030ef07b69706 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- ObjectFileMachO.cpp -------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Kate Stoneb9c1b512016-09-06 20:57:50 +000010#include "llvm/ADT/StringRef.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011
Kate Stoneb9c1b512016-09-06 20:57:50 +000012#include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
13#include "Plugins/Process/Utility/RegisterContextDarwin_arm64.h"
14#include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
15#include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
Jason Molendaf6ce26f2013-04-10 05:58:57 +000016#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include "lldb/Core/FileSpecList.h"
18#include "lldb/Core/Module.h"
Greg Claytonf4d6de62013-04-24 22:29:28 +000019#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/PluginManager.h"
Greg Clayton1eac0c72012-04-24 03:06:13 +000021#include "lldb/Core/RangeMap.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/Section.h"
23#include "lldb/Core/StreamFile.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000024#include "lldb/Host/Host.h"
Jason Molenda5635f772013-03-21 03:36:01 +000025#include "lldb/Symbol/DWARFCallFrameInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Symbol/ObjectFile.h"
Jason Molenda13becd42016-07-29 00:18:39 +000027#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000028#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton26b47e22012-04-18 05:19:20 +000029#include "lldb/Target/Platform.h"
Greg Claytonc9660542012-02-05 02:38:54 +000030#include "lldb/Target/Process.h"
Greg Clayton7524e092014-02-06 20:10:16 +000031#include "lldb/Target/SectionLoadList.h"
Greg Clayton26b47e22012-04-18 05:19:20 +000032#include "lldb/Target/Target.h"
Greg Claytona2715cf2014-06-13 00:54:12 +000033#include "lldb/Target/Thread.h"
34#include "lldb/Target/ThreadList.h"
Pavel Labath5f19b902017-11-13 16:16:33 +000035#include "lldb/Utility/ArchSpec.h"
Pavel Labath50251fc2017-12-21 10:54:30 +000036#include "lldb/Utility/DataBuffer.h"
Zachary Turner5713a052017-03-22 18:40:07 +000037#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000038#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000039#include "lldb/Utility/RegisterValue.h"
Zachary Turner97206d52017-05-12 04:51:55 +000040#include "lldb/Utility/Status.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000041#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000042#include "lldb/Utility/Timer.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000043#include "lldb/Utility/UUID.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
Pavel Labath77044732018-09-12 12:26:05 +000045#include "lldb/Host/SafeMachO.h"
Jim Ingham46d005d2014-04-02 22:53:21 +000046
Zachary Turner3f4a4b32017-02-24 18:56:49 +000047#include "llvm/Support/MemoryBuffer.h"
48
Jim Ingham46d005d2014-04-02 22:53:21 +000049#include "ObjectFileMachO.h"
50
Kate Stoneb9c1b512016-09-06 20:57:50 +000051#if defined(__APPLE__) && \
52 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Jason Molenda0e0954c2013-04-16 06:24:42 +000053// GetLLDBSharedCacheUUID() needs to call dlsym()
54#include <dlfcn.h>
55#endif
56
Daniel Maleaffeb4b62013-04-17 19:24:22 +000057#ifndef __APPLE__
58#include "Utility/UuidCompatibility.h"
Jason Molenda9b7fcdc2017-04-12 23:33:30 +000059#else
60#include <uuid/uuid.h>
Daniel Maleaffeb4b62013-04-17 19:24:22 +000061#endif
62
Greg Claytonb887da12015-07-16 19:50:57 +000063#define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
Chris Lattner30fdc8d2010-06-08 16:52:24 +000064using namespace lldb;
65using namespace lldb_private;
Greg Claytone1a916a2010-07-21 22:12:05 +000066using namespace llvm::MachO;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067
Jason Molenda649a6072015-11-10 05:21:54 +000068// Some structure definitions needed for parsing the dyld shared cache files
69// found on iOS devices.
70
Kate Stoneb9c1b512016-09-06 20:57:50 +000071struct lldb_copy_dyld_cache_header_v1 {
72 char magic[16]; // e.g. "dyld_v0 i386", "dyld_v1 armv7", etc.
73 uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info
74 uint32_t mappingCount; // number of dyld_cache_mapping_info entries
75 uint32_t imagesOffset;
76 uint32_t imagesCount;
77 uint64_t dyldBaseAddress;
78 uint64_t codeSignatureOffset;
79 uint64_t codeSignatureSize;
80 uint64_t slideInfoOffset;
81 uint64_t slideInfoSize;
82 uint64_t localSymbolsOffset;
83 uint64_t localSymbolsSize;
84 uint8_t uuid[16]; // v1 and above, also recorded in dyld_all_image_infos v13
85 // and later
Jason Molenda649a6072015-11-10 05:21:54 +000086};
87
Kate Stoneb9c1b512016-09-06 20:57:50 +000088struct lldb_copy_dyld_cache_mapping_info {
89 uint64_t address;
90 uint64_t size;
91 uint64_t fileOffset;
92 uint32_t maxProt;
93 uint32_t initProt;
Jason Molenda649a6072015-11-10 05:21:54 +000094};
95
Kate Stoneb9c1b512016-09-06 20:57:50 +000096struct lldb_copy_dyld_cache_local_symbols_info {
97 uint32_t nlistOffset;
98 uint32_t nlistCount;
99 uint32_t stringsOffset;
100 uint32_t stringsSize;
101 uint32_t entriesOffset;
102 uint32_t entriesCount;
Jason Molenda649a6072015-11-10 05:21:54 +0000103};
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104struct lldb_copy_dyld_cache_local_symbols_entry {
105 uint32_t dylibOffset;
106 uint32_t nlistStartIndex;
107 uint32_t nlistCount;
Jason Molenda649a6072015-11-10 05:21:54 +0000108};
109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000111public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread,
113 const DataExtractor &data)
114 : RegisterContextDarwin_x86_64(thread, 0) {
115 SetRegisterDataFrom_LC_THREAD(data);
116 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 void InvalidateAllRegisters() override {
119 // Do nothing... registers are always valid...
120 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000121
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
123 lldb::offset_t offset = 0;
124 SetError(GPRRegSet, Read, -1);
125 SetError(FPURegSet, Read, -1);
126 SetError(EXCRegSet, Read, -1);
127 bool done = false;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 while (!done) {
130 int flavor = data.GetU32(&offset);
131 if (flavor == 0)
132 done = true;
133 else {
134 uint32_t i;
135 uint32_t count = data.GetU32(&offset);
136 switch (flavor) {
137 case GPRRegSet:
138 for (i = 0; i < count; ++i)
139 (&gpr.rax)[i] = data.GetU64(&offset);
140 SetError(GPRRegSet, Read, 0);
141 done = true;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 break;
144 case FPURegSet:
145 // TODO: fill in FPU regs....
146 // SetError (FPURegSet, Read, -1);
147 done = true;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 break;
150 case EXCRegSet:
151 exc.trapno = data.GetU32(&offset);
152 exc.err = data.GetU32(&offset);
153 exc.faultvaddr = data.GetU64(&offset);
154 SetError(EXCRegSet, Read, 0);
155 done = true;
156 break;
157 case 7:
158 case 8:
159 case 9:
Adrian Prantl05097242018-04-30 16:49:04 +0000160 // fancy flavors that encapsulate of the above flavors...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000162
Greg Clayton9aae0a12013-05-15 19:52:08 +0000163 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 done = true;
165 break;
166 }
167 }
Greg Clayton9aae0a12013-05-15 19:52:08 +0000168 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169 }
170
171 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
172 const char *alt_name, size_t reg_byte_size,
173 Stream &data) {
174 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
175 if (reg_info == NULL)
176 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
177 if (reg_info) {
178 lldb_private::RegisterValue reg_value;
179 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
180 if (reg_info->byte_size >= reg_byte_size)
181 data.Write(reg_value.GetBytes(), reg_byte_size);
182 else {
183 data.Write(reg_value.GetBytes(), reg_info->byte_size);
184 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
185 ++i)
186 data.PutChar(0);
187 }
188 return reg_byte_size;
189 }
190 }
191 // Just write zeros if all else fails
192 for (size_t i = 0; i < reg_byte_size; ++i)
193 data.PutChar(0);
194 return reg_byte_size;
195 }
196
197 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
198 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
199 if (reg_ctx_sp) {
200 RegisterContext *reg_ctx = reg_ctx_sp.get();
201
202 data.PutHex32(GPRRegSet); // Flavor
203 data.PutHex32(GPRWordCount);
204 WriteRegister(reg_ctx, "rax", NULL, 8, data);
205 WriteRegister(reg_ctx, "rbx", NULL, 8, data);
206 WriteRegister(reg_ctx, "rcx", NULL, 8, data);
207 WriteRegister(reg_ctx, "rdx", NULL, 8, data);
208 WriteRegister(reg_ctx, "rdi", NULL, 8, data);
209 WriteRegister(reg_ctx, "rsi", NULL, 8, data);
210 WriteRegister(reg_ctx, "rbp", NULL, 8, data);
211 WriteRegister(reg_ctx, "rsp", NULL, 8, data);
212 WriteRegister(reg_ctx, "r8", NULL, 8, data);
213 WriteRegister(reg_ctx, "r9", NULL, 8, data);
214 WriteRegister(reg_ctx, "r10", NULL, 8, data);
215 WriteRegister(reg_ctx, "r11", NULL, 8, data);
216 WriteRegister(reg_ctx, "r12", NULL, 8, data);
217 WriteRegister(reg_ctx, "r13", NULL, 8, data);
218 WriteRegister(reg_ctx, "r14", NULL, 8, data);
219 WriteRegister(reg_ctx, "r15", NULL, 8, data);
220 WriteRegister(reg_ctx, "rip", NULL, 8, data);
221 WriteRegister(reg_ctx, "rflags", NULL, 8, data);
222 WriteRegister(reg_ctx, "cs", NULL, 8, data);
223 WriteRegister(reg_ctx, "fs", NULL, 8, data);
224 WriteRegister(reg_ctx, "gs", NULL, 8, data);
225
226 // // Write out the FPU registers
227 // const size_t fpu_byte_size = sizeof(FPU);
228 // size_t bytes_written = 0;
229 // data.PutHex32 (FPURegSet);
230 // data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
231 // bytes_written += data.PutHex32(0); // uint32_t pad[0]
232 // bytes_written += data.PutHex32(0); // uint32_t pad[1]
233 // bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
234 // data); // uint16_t fcw; // "fctrl"
235 // bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
236 // data); // uint16_t fsw; // "fstat"
237 // bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
238 // data); // uint8_t ftw; // "ftag"
239 // bytes_written += data.PutHex8 (0); // uint8_t pad1;
240 // bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
241 // data); // uint16_t fop; // "fop"
242 // bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
243 // data); // uint32_t ip; // "fioff"
244 // bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
245 // data); // uint16_t cs; // "fiseg"
246 // bytes_written += data.PutHex16 (0); // uint16_t pad2;
247 // bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
248 // data); // uint32_t dp; // "fooff"
249 // bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
250 // data); // uint16_t ds; // "foseg"
251 // bytes_written += data.PutHex16 (0); // uint16_t pad3;
252 // bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
253 // data); // uint32_t mxcsr;
254 // bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
255 // 4, data);// uint32_t mxcsrmask;
256 // bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
257 // sizeof(MMSReg), data);
258 // bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
259 // sizeof(MMSReg), data);
260 // bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
261 // sizeof(MMSReg), data);
262 // bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
263 // sizeof(MMSReg), data);
264 // bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
265 // sizeof(MMSReg), data);
266 // bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
267 // sizeof(MMSReg), data);
268 // bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
269 // sizeof(MMSReg), data);
270 // bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
271 // sizeof(MMSReg), data);
272 // bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
273 // sizeof(XMMReg), data);
274 // bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
275 // sizeof(XMMReg), data);
276 // bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
277 // sizeof(XMMReg), data);
278 // bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
279 // sizeof(XMMReg), data);
280 // bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
281 // sizeof(XMMReg), data);
282 // bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
283 // sizeof(XMMReg), data);
284 // bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
285 // sizeof(XMMReg), data);
286 // bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
287 // sizeof(XMMReg), data);
288 // bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
289 // sizeof(XMMReg), data);
290 // bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
291 // sizeof(XMMReg), data);
292 // bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
293 // sizeof(XMMReg), data);
294 // bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
295 // sizeof(XMMReg), data);
296 // bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
297 // sizeof(XMMReg), data);
298 // bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
299 // sizeof(XMMReg), data);
300 // bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
301 // sizeof(XMMReg), data);
302 // bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
303 // sizeof(XMMReg), data);
304 //
305 // // Fill rest with zeros
306 // for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
307 // i)
308 // data.PutChar(0);
309
310 // Write out the EXC registers
311 data.PutHex32(EXCRegSet);
312 data.PutHex32(EXCWordCount);
313 WriteRegister(reg_ctx, "trapno", NULL, 4, data);
314 WriteRegister(reg_ctx, "err", NULL, 4, data);
315 WriteRegister(reg_ctx, "faultvaddr", NULL, 8, data);
316 return true;
317 }
318 return false;
319 }
320
321protected:
322 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
323
324 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
325
326 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
327
328 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
Greg Clayton9aae0a12013-05-15 19:52:08 +0000329 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 }
331
332 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
333 return 0;
334 }
335
336 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
337 return 0;
338 }
339};
340
341class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 {
342public:
343 RegisterContextDarwin_i386_Mach(lldb_private::Thread &thread,
344 const DataExtractor &data)
345 : RegisterContextDarwin_i386(thread, 0) {
346 SetRegisterDataFrom_LC_THREAD(data);
347 }
348
349 void InvalidateAllRegisters() override {
350 // Do nothing... registers are always valid...
351 }
352
353 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
354 lldb::offset_t offset = 0;
355 SetError(GPRRegSet, Read, -1);
356 SetError(FPURegSet, Read, -1);
357 SetError(EXCRegSet, Read, -1);
358 bool done = false;
359
360 while (!done) {
361 int flavor = data.GetU32(&offset);
362 if (flavor == 0)
363 done = true;
364 else {
365 uint32_t i;
366 uint32_t count = data.GetU32(&offset);
367 switch (flavor) {
368 case GPRRegSet:
369 for (i = 0; i < count; ++i)
370 (&gpr.eax)[i] = data.GetU32(&offset);
371 SetError(GPRRegSet, Read, 0);
372 done = true;
373
374 break;
375 case FPURegSet:
376 // TODO: fill in FPU regs....
377 // SetError (FPURegSet, Read, -1);
378 done = true;
379
380 break;
381 case EXCRegSet:
382 exc.trapno = data.GetU32(&offset);
383 exc.err = data.GetU32(&offset);
384 exc.faultvaddr = data.GetU32(&offset);
385 SetError(EXCRegSet, Read, 0);
386 done = true;
387 break;
388 case 7:
389 case 8:
390 case 9:
Adrian Prantl05097242018-04-30 16:49:04 +0000391 // fancy flavors that encapsulate of the above flavors...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 break;
393
394 default:
395 done = true;
396 break;
397 }
398 }
399 }
400 }
401
402 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
403 const char *alt_name, size_t reg_byte_size,
404 Stream &data) {
405 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
406 if (reg_info == NULL)
407 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
408 if (reg_info) {
409 lldb_private::RegisterValue reg_value;
410 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
411 if (reg_info->byte_size >= reg_byte_size)
412 data.Write(reg_value.GetBytes(), reg_byte_size);
413 else {
414 data.Write(reg_value.GetBytes(), reg_info->byte_size);
415 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
416 ++i)
417 data.PutChar(0);
418 }
419 return reg_byte_size;
420 }
421 }
422 // Just write zeros if all else fails
423 for (size_t i = 0; i < reg_byte_size; ++i)
424 data.PutChar(0);
425 return reg_byte_size;
426 }
427
428 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
429 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
430 if (reg_ctx_sp) {
431 RegisterContext *reg_ctx = reg_ctx_sp.get();
432
433 data.PutHex32(GPRRegSet); // Flavor
434 data.PutHex32(GPRWordCount);
435 WriteRegister(reg_ctx, "eax", NULL, 4, data);
436 WriteRegister(reg_ctx, "ebx", NULL, 4, data);
437 WriteRegister(reg_ctx, "ecx", NULL, 4, data);
438 WriteRegister(reg_ctx, "edx", NULL, 4, data);
439 WriteRegister(reg_ctx, "edi", NULL, 4, data);
440 WriteRegister(reg_ctx, "esi", NULL, 4, data);
441 WriteRegister(reg_ctx, "ebp", NULL, 4, data);
442 WriteRegister(reg_ctx, "esp", NULL, 4, data);
443 WriteRegister(reg_ctx, "ss", NULL, 4, data);
444 WriteRegister(reg_ctx, "eflags", NULL, 4, data);
445 WriteRegister(reg_ctx, "eip", NULL, 4, data);
446 WriteRegister(reg_ctx, "cs", NULL, 4, data);
447 WriteRegister(reg_ctx, "ds", NULL, 4, data);
448 WriteRegister(reg_ctx, "es", NULL, 4, data);
449 WriteRegister(reg_ctx, "fs", NULL, 4, data);
450 WriteRegister(reg_ctx, "gs", NULL, 4, data);
451
452 // Write out the EXC registers
453 data.PutHex32(EXCRegSet);
454 data.PutHex32(EXCWordCount);
455 WriteRegister(reg_ctx, "trapno", NULL, 4, data);
456 WriteRegister(reg_ctx, "err", NULL, 4, data);
457 WriteRegister(reg_ctx, "faultvaddr", NULL, 4, data);
458 return true;
459 }
460 return false;
461 }
462
463protected:
464 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
465
466 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
467
468 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
469
470 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
471 return 0;
472 }
473
474 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
475 return 0;
476 }
477
478 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
479 return 0;
480 }
481};
482
483class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm {
484public:
485 RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread,
486 const DataExtractor &data)
487 : RegisterContextDarwin_arm(thread, 0) {
488 SetRegisterDataFrom_LC_THREAD(data);
489 }
490
491 void InvalidateAllRegisters() override {
492 // Do nothing... registers are always valid...
493 }
494
495 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
496 lldb::offset_t offset = 0;
497 SetError(GPRRegSet, Read, -1);
498 SetError(FPURegSet, Read, -1);
499 SetError(EXCRegSet, Read, -1);
500 bool done = false;
501
502 while (!done) {
503 int flavor = data.GetU32(&offset);
504 uint32_t count = data.GetU32(&offset);
505 lldb::offset_t next_thread_state = offset + (count * 4);
506 switch (flavor) {
507 case GPRAltRegSet:
508 case GPRRegSet:
509 for (uint32_t i = 0; i < count; ++i) {
510 gpr.r[i] = data.GetU32(&offset);
511 }
512
513 // Note that gpr.cpsr is also copied by the above loop; this loop
Adrian Prantl05097242018-04-30 16:49:04 +0000514 // technically extends one element past the end of the gpr.r[] array.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515
516 SetError(GPRRegSet, Read, 0);
517 offset = next_thread_state;
518 break;
519
520 case FPURegSet: {
521 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats.s[0];
522 const int fpu_reg_buf_size = sizeof(fpu.floats);
523 if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
524 fpu_reg_buf) == fpu_reg_buf_size) {
525 offset += fpu_reg_buf_size;
526 fpu.fpscr = data.GetU32(&offset);
527 SetError(FPURegSet, Read, 0);
528 } else {
529 done = true;
530 }
531 }
532 offset = next_thread_state;
533 break;
534
535 case EXCRegSet:
536 if (count == 3) {
537 exc.exception = data.GetU32(&offset);
538 exc.fsr = data.GetU32(&offset);
539 exc.far = data.GetU32(&offset);
540 SetError(EXCRegSet, Read, 0);
541 }
542 done = true;
543 offset = next_thread_state;
544 break;
545
546 // Unknown register set flavor, stop trying to parse.
547 default:
548 done = true;
549 }
550 }
551 }
552
553 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
554 const char *alt_name, size_t reg_byte_size,
555 Stream &data) {
556 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
557 if (reg_info == NULL)
558 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
559 if (reg_info) {
560 lldb_private::RegisterValue reg_value;
561 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
562 if (reg_info->byte_size >= reg_byte_size)
563 data.Write(reg_value.GetBytes(), reg_byte_size);
564 else {
565 data.Write(reg_value.GetBytes(), reg_info->byte_size);
566 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
567 ++i)
568 data.PutChar(0);
569 }
570 return reg_byte_size;
571 }
572 }
573 // Just write zeros if all else fails
574 for (size_t i = 0; i < reg_byte_size; ++i)
575 data.PutChar(0);
576 return reg_byte_size;
577 }
578
579 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
580 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
581 if (reg_ctx_sp) {
582 RegisterContext *reg_ctx = reg_ctx_sp.get();
583
584 data.PutHex32(GPRRegSet); // Flavor
585 data.PutHex32(GPRWordCount);
586 WriteRegister(reg_ctx, "r0", NULL, 4, data);
587 WriteRegister(reg_ctx, "r1", NULL, 4, data);
588 WriteRegister(reg_ctx, "r2", NULL, 4, data);
589 WriteRegister(reg_ctx, "r3", NULL, 4, data);
590 WriteRegister(reg_ctx, "r4", NULL, 4, data);
591 WriteRegister(reg_ctx, "r5", NULL, 4, data);
592 WriteRegister(reg_ctx, "r6", NULL, 4, data);
593 WriteRegister(reg_ctx, "r7", NULL, 4, data);
594 WriteRegister(reg_ctx, "r8", NULL, 4, data);
595 WriteRegister(reg_ctx, "r9", NULL, 4, data);
596 WriteRegister(reg_ctx, "r10", NULL, 4, data);
597 WriteRegister(reg_ctx, "r11", NULL, 4, data);
598 WriteRegister(reg_ctx, "r12", NULL, 4, data);
599 WriteRegister(reg_ctx, "sp", NULL, 4, data);
600 WriteRegister(reg_ctx, "lr", NULL, 4, data);
601 WriteRegister(reg_ctx, "pc", NULL, 4, data);
602 WriteRegister(reg_ctx, "cpsr", NULL, 4, data);
603
604 // Write out the EXC registers
605 // data.PutHex32 (EXCRegSet);
606 // data.PutHex32 (EXCWordCount);
607 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
608 // WriteRegister (reg_ctx, "fsr", NULL, 4, data);
609 // WriteRegister (reg_ctx, "far", NULL, 4, data);
610 return true;
611 }
612 return false;
613 }
614
615protected:
616 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
617
618 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
619
620 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
621
622 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
623
624 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
625 return 0;
626 }
627
628 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
629 return 0;
630 }
631
632 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
633 return 0;
634 }
635
636 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
637 return -1;
638 }
639};
640
641class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 {
642public:
643 RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread,
644 const DataExtractor &data)
645 : RegisterContextDarwin_arm64(thread, 0) {
646 SetRegisterDataFrom_LC_THREAD(data);
647 }
648
649 void InvalidateAllRegisters() override {
650 // Do nothing... registers are always valid...
651 }
652
653 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
654 lldb::offset_t offset = 0;
655 SetError(GPRRegSet, Read, -1);
656 SetError(FPURegSet, Read, -1);
657 SetError(EXCRegSet, Read, -1);
658 bool done = false;
659 while (!done) {
660 int flavor = data.GetU32(&offset);
661 uint32_t count = data.GetU32(&offset);
662 lldb::offset_t next_thread_state = offset + (count * 4);
663 switch (flavor) {
664 case GPRRegSet:
665 // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
666 // 32-bit register)
667 if (count >= (33 * 2) + 1) {
Vedant Kumar6ba1db92016-11-07 02:39:37 +0000668 for (uint32_t i = 0; i < 29; ++i)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 gpr.x[i] = data.GetU64(&offset);
Vedant Kumar6ba1db92016-11-07 02:39:37 +0000670 gpr.fp = data.GetU64(&offset);
671 gpr.lr = data.GetU64(&offset);
672 gpr.sp = data.GetU64(&offset);
673 gpr.pc = data.GetU64(&offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 gpr.cpsr = data.GetU32(&offset);
675 SetError(GPRRegSet, Read, 0);
676 }
677 offset = next_thread_state;
678 break;
679 case FPURegSet: {
680 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
681 const int fpu_reg_buf_size = sizeof(fpu);
Jason Molenda4f346142017-11-16 00:50:29 +0000682 if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683 data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
684 fpu_reg_buf) == fpu_reg_buf_size) {
685 SetError(FPURegSet, Read, 0);
686 } else {
687 done = true;
688 }
689 }
690 offset = next_thread_state;
691 break;
692 case EXCRegSet:
693 if (count == 4) {
694 exc.far = data.GetU64(&offset);
695 exc.esr = data.GetU32(&offset);
696 exc.exception = data.GetU32(&offset);
697 SetError(EXCRegSet, Read, 0);
698 }
699 offset = next_thread_state;
700 break;
701 default:
702 done = true;
703 break;
704 }
705 }
706 }
707
708 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
709 const char *alt_name, size_t reg_byte_size,
710 Stream &data) {
711 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
712 if (reg_info == NULL)
713 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
714 if (reg_info) {
715 lldb_private::RegisterValue reg_value;
716 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
717 if (reg_info->byte_size >= reg_byte_size)
718 data.Write(reg_value.GetBytes(), reg_byte_size);
719 else {
720 data.Write(reg_value.GetBytes(), reg_info->byte_size);
721 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
722 ++i)
723 data.PutChar(0);
724 }
725 return reg_byte_size;
726 }
727 }
728 // Just write zeros if all else fails
729 for (size_t i = 0; i < reg_byte_size; ++i)
730 data.PutChar(0);
731 return reg_byte_size;
732 }
733
734 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
735 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
736 if (reg_ctx_sp) {
737 RegisterContext *reg_ctx = reg_ctx_sp.get();
738
739 data.PutHex32(GPRRegSet); // Flavor
740 data.PutHex32(GPRWordCount);
741 WriteRegister(reg_ctx, "x0", NULL, 8, data);
742 WriteRegister(reg_ctx, "x1", NULL, 8, data);
743 WriteRegister(reg_ctx, "x2", NULL, 8, data);
744 WriteRegister(reg_ctx, "x3", NULL, 8, data);
745 WriteRegister(reg_ctx, "x4", NULL, 8, data);
746 WriteRegister(reg_ctx, "x5", NULL, 8, data);
747 WriteRegister(reg_ctx, "x6", NULL, 8, data);
748 WriteRegister(reg_ctx, "x7", NULL, 8, data);
749 WriteRegister(reg_ctx, "x8", NULL, 8, data);
750 WriteRegister(reg_ctx, "x9", NULL, 8, data);
751 WriteRegister(reg_ctx, "x10", NULL, 8, data);
752 WriteRegister(reg_ctx, "x11", NULL, 8, data);
753 WriteRegister(reg_ctx, "x12", NULL, 8, data);
754 WriteRegister(reg_ctx, "x13", NULL, 8, data);
755 WriteRegister(reg_ctx, "x14", NULL, 8, data);
756 WriteRegister(reg_ctx, "x15", NULL, 8, data);
757 WriteRegister(reg_ctx, "x16", NULL, 8, data);
758 WriteRegister(reg_ctx, "x17", NULL, 8, data);
759 WriteRegister(reg_ctx, "x18", NULL, 8, data);
760 WriteRegister(reg_ctx, "x19", NULL, 8, data);
761 WriteRegister(reg_ctx, "x20", NULL, 8, data);
762 WriteRegister(reg_ctx, "x21", NULL, 8, data);
763 WriteRegister(reg_ctx, "x22", NULL, 8, data);
764 WriteRegister(reg_ctx, "x23", NULL, 8, data);
765 WriteRegister(reg_ctx, "x24", NULL, 8, data);
766 WriteRegister(reg_ctx, "x25", NULL, 8, data);
767 WriteRegister(reg_ctx, "x26", NULL, 8, data);
768 WriteRegister(reg_ctx, "x27", NULL, 8, data);
769 WriteRegister(reg_ctx, "x28", NULL, 8, data);
770 WriteRegister(reg_ctx, "fp", NULL, 8, data);
771 WriteRegister(reg_ctx, "lr", NULL, 8, data);
772 WriteRegister(reg_ctx, "sp", NULL, 8, data);
773 WriteRegister(reg_ctx, "pc", NULL, 8, data);
774 WriteRegister(reg_ctx, "cpsr", NULL, 4, data);
775
776 // Write out the EXC registers
777 // data.PutHex32 (EXCRegSet);
778 // data.PutHex32 (EXCWordCount);
779 // WriteRegister (reg_ctx, "far", NULL, 8, data);
780 // WriteRegister (reg_ctx, "esr", NULL, 4, data);
781 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
782 return true;
783 }
784 return false;
785 }
786
787protected:
788 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
789
790 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
791
792 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
793
794 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
795
796 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
797 return 0;
798 }
799
800 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
801 return 0;
802 }
803
804 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
805 return 0;
806 }
807
808 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
809 return -1;
810 }
811};
812
813static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
814 switch (magic) {
815 case MH_MAGIC:
816 case MH_CIGAM:
817 return sizeof(struct mach_header);
818
819 case MH_MAGIC_64:
820 case MH_CIGAM_64:
821 return sizeof(struct mach_header_64);
822 break;
823
824 default:
825 break;
826 }
827 return 0;
Greg Clayton9aae0a12013-05-15 19:52:08 +0000828}
829
Greg Claytonded470d2011-03-19 01:12:21 +0000830#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832void ObjectFileMachO::Initialize() {
833 PluginManager::RegisterPlugin(
834 GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
835 CreateMemoryInstance, GetModuleSpecifications, SaveCore);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000836}
837
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838void ObjectFileMachO::Terminate() {
839 PluginManager::UnregisterPlugin(CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000840}
841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842lldb_private::ConstString ObjectFileMachO::GetPluginNameStatic() {
843 static ConstString g_name("mach-o");
844 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845}
846
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847const char *ObjectFileMachO::GetPluginDescriptionStatic() {
848 return "Mach-o object file reader (32 and 64 bit)";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000849}
850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851ObjectFile *ObjectFileMachO::CreateInstance(const lldb::ModuleSP &module_sp,
852 DataBufferSP &data_sp,
853 lldb::offset_t data_offset,
854 const FileSpec *file,
855 lldb::offset_t file_offset,
856 lldb::offset_t length) {
857 if (!data_sp) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000858 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000859 if (!data_sp)
860 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000861 data_offset = 0;
862 }
863
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000864 if (!ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
865 return nullptr;
866
867 // Update the data to contain the entire file if it doesn't already
868 if (data_sp->GetByteSize() < length) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000869 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000870 if (!data_sp)
871 return nullptr;
872 data_offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 }
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000874 auto objfile_ap = llvm::make_unique<ObjectFileMachO>(
875 module_sp, data_sp, data_offset, file, file_offset, length);
876 if (!objfile_ap || !objfile_ap->ParseHeader())
877 return nullptr;
878
879 return objfile_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880}
881
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882ObjectFile *ObjectFileMachO::CreateMemoryInstance(
883 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
884 const ProcessSP &process_sp, lldb::addr_t header_addr) {
885 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
886 std::unique_ptr<ObjectFile> objfile_ap(
887 new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
888 if (objfile_ap.get() && objfile_ap->ParseHeader())
889 return objfile_ap.release();
890 }
891 return NULL;
Greg Claytonc9660542012-02-05 02:38:54 +0000892}
893
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894size_t ObjectFileMachO::GetModuleSpecifications(
895 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
896 lldb::offset_t data_offset, lldb::offset_t file_offset,
897 lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
898 const size_t initial_count = specs.GetSize();
Oleksiy Vyalov63acdfd2015-03-10 01:15:28 +0000899
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
Greg Clayton44435ed2012-01-12 05:25:17 +0000901 DataExtractor data;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 data.SetData(data_sp);
903 llvm::MachO::mach_header header;
904 if (ParseHeader(data, &data_offset, header)) {
905 size_t header_and_load_cmds =
906 header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
907 if (header_and_load_cmds >= data_sp->GetByteSize()) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000908 data_sp = MapFileData(file, header_and_load_cmds, file_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 data.SetData(data_sp);
910 data_offset = MachHeaderSizeFromMagic(header.magic);
911 }
912 if (data_sp) {
913 ModuleSpec spec;
914 spec.GetFileSpec() = file;
915 spec.SetObjectOffset(file_offset);
916 spec.SetObjectSize(length);
917
918 if (GetArchitecture(header, data, data_offset,
919 spec.GetArchitecture())) {
920 if (spec.GetArchitecture().IsValid()) {
921 GetUUID(header, data, data_offset, spec.GetUUID());
922 specs.Append(spec);
923 }
924 }
925 }
926 }
927 }
928 return specs.GetSize() - initial_count;
929}
930
931const ConstString &ObjectFileMachO::GetSegmentNameTEXT() {
932 static ConstString g_segment_name_TEXT("__TEXT");
933 return g_segment_name_TEXT;
934}
935
936const ConstString &ObjectFileMachO::GetSegmentNameDATA() {
937 static ConstString g_segment_name_DATA("__DATA");
938 return g_segment_name_DATA;
939}
940
941const ConstString &ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
942 static ConstString g_segment_name("__DATA_DIRTY");
943 return g_segment_name;
944}
945
946const ConstString &ObjectFileMachO::GetSegmentNameDATA_CONST() {
947 static ConstString g_segment_name("__DATA_CONST");
948 return g_segment_name;
949}
950
951const ConstString &ObjectFileMachO::GetSegmentNameOBJC() {
952 static ConstString g_segment_name_OBJC("__OBJC");
953 return g_segment_name_OBJC;
954}
955
956const ConstString &ObjectFileMachO::GetSegmentNameLINKEDIT() {
957 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
958 return g_section_name_LINKEDIT;
959}
960
961const ConstString &ObjectFileMachO::GetSectionNameEHFrame() {
962 static ConstString g_section_name_eh_frame("__eh_frame");
963 return g_section_name_eh_frame;
964}
965
966bool ObjectFileMachO::MagicBytesMatch(DataBufferSP &data_sp,
967 lldb::addr_t data_offset,
968 lldb::addr_t data_length) {
969 DataExtractor data;
970 data.SetData(data_sp, data_offset, data_length);
971 lldb::offset_t offset = 0;
972 uint32_t magic = data.GetU32(&offset);
973 return MachHeaderSizeFromMagic(magic) != 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974}
975
Greg Clayton5ce9c562013-02-06 17:22:03 +0000976ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 DataBufferSP &data_sp,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000978 lldb::offset_t data_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979 const FileSpec *file,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000980 lldb::offset_t file_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 lldb::offset_t length)
982 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
983 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
984 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
985 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
986 ::memset(&m_header, 0, sizeof(m_header));
987 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000988}
989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
991 lldb::DataBufferSP &header_data_sp,
992 const lldb::ProcessSP &process_sp,
993 lldb::addr_t header_addr)
994 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
995 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
996 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
997 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
998 ::memset(&m_header, 0, sizeof(m_header));
999 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Greg Claytonc9660542012-02-05 02:38:54 +00001000}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002bool ObjectFileMachO::ParseHeader(DataExtractor &data,
1003 lldb::offset_t *data_offset_ptr,
1004 llvm::MachO::mach_header &header) {
1005 data.SetByteOrder(endian::InlHostByteOrder());
1006 // Leave magic in the original byte order
1007 header.magic = data.GetU32(data_offset_ptr);
1008 bool can_parse = false;
1009 bool is_64_bit = false;
1010 switch (header.magic) {
1011 case MH_MAGIC:
1012 data.SetByteOrder(endian::InlHostByteOrder());
1013 data.SetAddressByteSize(4);
1014 can_parse = true;
1015 break;
1016
1017 case MH_MAGIC_64:
1018 data.SetByteOrder(endian::InlHostByteOrder());
1019 data.SetAddressByteSize(8);
1020 can_parse = true;
1021 is_64_bit = true;
1022 break;
1023
1024 case MH_CIGAM:
1025 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1026 ? eByteOrderLittle
1027 : eByteOrderBig);
1028 data.SetAddressByteSize(4);
1029 can_parse = true;
1030 break;
1031
1032 case MH_CIGAM_64:
1033 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1034 ? eByteOrderLittle
1035 : eByteOrderBig);
1036 data.SetAddressByteSize(8);
1037 is_64_bit = true;
1038 can_parse = true;
1039 break;
1040
1041 default:
1042 break;
1043 }
1044
1045 if (can_parse) {
1046 data.GetU32(data_offset_ptr, &header.cputype, 6);
1047 if (is_64_bit)
1048 *data_offset_ptr += 4;
1049 return true;
1050 } else {
1051 memset(&header, 0, sizeof(header));
1052 }
1053 return false;
1054}
1055
1056bool ObjectFileMachO::ParseHeader() {
1057 ModuleSP module_sp(GetModule());
1058 if (module_sp) {
1059 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Greg Claytonf4d6de62013-04-24 22:29:28 +00001060 bool can_parse = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 lldb::offset_t offset = 0;
1062 m_data.SetByteOrder(endian::InlHostByteOrder());
1063 // Leave magic in the original byte order
1064 m_header.magic = m_data.GetU32(&offset);
1065 switch (m_header.magic) {
1066 case MH_MAGIC:
1067 m_data.SetByteOrder(endian::InlHostByteOrder());
1068 m_data.SetAddressByteSize(4);
1069 can_parse = true;
1070 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 case MH_MAGIC_64:
1073 m_data.SetByteOrder(endian::InlHostByteOrder());
1074 m_data.SetAddressByteSize(8);
1075 can_parse = true;
1076 break;
Greg Claytona1743492012-03-13 23:14:29 +00001077
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 case MH_CIGAM:
1079 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1080 ? eByteOrderLittle
1081 : eByteOrderBig);
1082 m_data.SetAddressByteSize(4);
1083 can_parse = true;
1084 break;
Greg Claytona1743492012-03-13 23:14:29 +00001085
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 case MH_CIGAM_64:
1087 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1088 ? eByteOrderLittle
1089 : eByteOrderBig);
1090 m_data.SetAddressByteSize(8);
1091 can_parse = true;
1092 break;
Greg Claytona1743492012-03-13 23:14:29 +00001093
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094 default:
1095 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 }
1097
Kate Stoneb9c1b512016-09-06 20:57:50 +00001098 if (can_parse) {
1099 m_data.GetU32(&offset, &m_header.cputype, 6);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 ArchSpec mach_arch;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 if (GetArchitecture(mach_arch)) {
1104 // Check if the module has a required architecture
1105 const ArchSpec &module_arch = module_sp->GetArchitecture();
1106 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1107 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 if (SetModulesArchitecture(mach_arch)) {
1110 const size_t header_and_lc_size =
1111 m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1112 if (m_data.GetByteSize() < header_and_lc_size) {
1113 DataBufferSP data_sp;
1114 ProcessSP process_sp(m_process_wp.lock());
1115 if (process_sp) {
1116 data_sp =
1117 ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1118 } else {
1119 // Read in all only the load command data from the file on disk
Pavel Labath50251fc2017-12-21 10:54:30 +00001120 data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 if (data_sp->GetByteSize() != header_and_lc_size)
Greg Clayton8f265f72015-10-28 20:49:34 +00001122 return false;
1123 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 if (data_sp)
1125 m_data.SetData(data_sp);
1126 }
Greg Clayton9191db42013-10-21 18:40:51 +00001127 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 return true;
1129 }
1130 } else {
1131 memset(&m_header, 0, sizeof(struct mach_header));
1132 }
1133 }
1134 return false;
1135}
1136
1137ByteOrder ObjectFileMachO::GetByteOrder() const {
1138 return m_data.GetByteOrder();
1139}
1140
1141bool ObjectFileMachO::IsExecutable() const {
1142 return m_header.filetype == MH_EXECUTE;
1143}
1144
1145uint32_t ObjectFileMachO::GetAddressByteSize() const {
1146 return m_data.GetAddressByteSize();
1147}
1148
1149AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
1150 Symtab *symtab = GetSymtab();
1151 if (symtab) {
1152 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1153 if (symbol) {
1154 if (symbol->ValueIsAddress()) {
1155 SectionSP section_sp(symbol->GetAddressRef().GetSection());
1156 if (section_sp) {
1157 const lldb::SectionType section_type = section_sp->GetType();
1158 switch (section_type) {
1159 case eSectionTypeInvalid:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001160 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161
1162 case eSectionTypeCode:
1163 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001164 // For ARM we have a bit in the n_desc field of the symbol that
1165 // tells us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001167 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001169 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170
1171 case eSectionTypeContainer:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001172 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173
1174 case eSectionTypeData:
1175 case eSectionTypeDataCString:
1176 case eSectionTypeDataCStringPointers:
1177 case eSectionTypeDataSymbolAddress:
1178 case eSectionTypeData4:
1179 case eSectionTypeData8:
1180 case eSectionTypeData16:
1181 case eSectionTypeDataPointers:
1182 case eSectionTypeZeroFill:
1183 case eSectionTypeDataObjCMessageRefs:
1184 case eSectionTypeDataObjCCFStrings:
1185 case eSectionTypeGoSymtab:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001186 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001187
1188 case eSectionTypeDebug:
1189 case eSectionTypeDWARFDebugAbbrev:
1190 case eSectionTypeDWARFDebugAddr:
1191 case eSectionTypeDWARFDebugAranges:
Tamas Berghammer963ce482017-08-25 13:56:14 +00001192 case eSectionTypeDWARFDebugCuIndex:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 case eSectionTypeDWARFDebugFrame:
1194 case eSectionTypeDWARFDebugInfo:
1195 case eSectionTypeDWARFDebugLine:
George Rimarc6c7bfc2018-09-13 17:06:47 +00001196 case eSectionTypeDWARFDebugLineStr:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 case eSectionTypeDWARFDebugLoc:
George Rimare4dee262018-10-23 09:46:15 +00001198 case eSectionTypeDWARFDebugLocLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 case eSectionTypeDWARFDebugMacInfo:
1200 case eSectionTypeDWARFDebugMacro:
Pavel Labatha041d842018-06-01 12:06:45 +00001201 case eSectionTypeDWARFDebugNames:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 case eSectionTypeDWARFDebugPubNames:
1203 case eSectionTypeDWARFDebugPubTypes:
1204 case eSectionTypeDWARFDebugRanges:
George Rimar6e357122018-10-10 08:11:15 +00001205 case eSectionTypeDWARFDebugRngLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 case eSectionTypeDWARFDebugStr:
1207 case eSectionTypeDWARFDebugStrOffsets:
Greg Clayton2550ca12018-05-08 17:19:24 +00001208 case eSectionTypeDWARFDebugTypes:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 case eSectionTypeDWARFAppleNames:
1210 case eSectionTypeDWARFAppleTypes:
1211 case eSectionTypeDWARFAppleNamespaces:
1212 case eSectionTypeDWARFAppleObjC:
Jan Kratochvile4777a92018-04-29 19:47:48 +00001213 case eSectionTypeDWARFGNUDebugAltLink:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001214 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215
1216 case eSectionTypeEHFrame:
1217 case eSectionTypeARMexidx:
1218 case eSectionTypeARMextab:
1219 case eSectionTypeCompactUnwind:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001220 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221
1222 case eSectionTypeAbsoluteAddress:
1223 case eSectionTypeELFSymbolTable:
1224 case eSectionTypeELFDynamicSymbols:
1225 case eSectionTypeELFRelocationEntries:
1226 case eSectionTypeELFDynamicLinkInfo:
1227 case eSectionTypeOther:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001228 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 }
1230 }
1231 }
1232
1233 const SymbolType symbol_type = symbol->GetType();
1234 switch (symbol_type) {
1235 case eSymbolTypeAny:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001236 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001237 case eSymbolTypeAbsolute:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001238 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239
1240 case eSymbolTypeCode:
1241 case eSymbolTypeTrampoline:
1242 case eSymbolTypeResolver:
1243 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001244 // For ARM we have a bit in the n_desc field of the symbol that tells
1245 // us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001247 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001248 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001249 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250
1251 case eSymbolTypeData:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001252 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 case eSymbolTypeRuntime:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001254 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 case eSymbolTypeException:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001256 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 case eSymbolTypeSourceFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001258 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259 case eSymbolTypeHeaderFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001260 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 case eSymbolTypeObjectFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001262 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 case eSymbolTypeCommonBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001264 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 case eSymbolTypeBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001266 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267 case eSymbolTypeLocal:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001268 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 case eSymbolTypeParam:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001270 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 case eSymbolTypeVariable:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001272 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 case eSymbolTypeVariableType:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001274 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001275 case eSymbolTypeLineEntry:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001276 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277 case eSymbolTypeLineHeader:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001278 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 case eSymbolTypeScopeBegin:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001280 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 case eSymbolTypeScopeEnd:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001282 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283 case eSymbolTypeAdditional:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001284 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 case eSymbolTypeCompiler:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001286 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 case eSymbolTypeInstrumentation:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001288 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 case eSymbolTypeUndefined:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001290 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 case eSymbolTypeObjCClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001292 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 case eSymbolTypeObjCMetaClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001294 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001295 case eSymbolTypeObjCIVar:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001296 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297 case eSymbolTypeReExported:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001298 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 }
1300 }
1301 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001302 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303}
1304
1305Symtab *ObjectFileMachO::GetSymtab() {
1306 ModuleSP module_sp(GetModule());
1307 if (module_sp) {
1308 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1309 if (m_symtab_ap.get() == NULL) {
1310 m_symtab_ap.reset(new Symtab(this));
1311 std::lock_guard<std::recursive_mutex> symtab_guard(
1312 m_symtab_ap->GetMutex());
1313 ParseSymtab();
Davide Italiano407c6912018-11-02 21:59:14 +00001314 m_symtab_ap->Finalize();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 }
1316 }
1317 return m_symtab_ap.get();
1318}
1319
1320bool ObjectFileMachO::IsStripped() {
1321 if (m_dysymtab.cmd == 0) {
1322 ModuleSP module_sp(GetModule());
1323 if (module_sp) {
1324 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1325 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1326 const lldb::offset_t load_cmd_offset = offset;
1327
1328 load_command lc;
1329 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
1330 break;
1331 if (lc.cmd == LC_DYSYMTAB) {
1332 m_dysymtab.cmd = lc.cmd;
1333 m_dysymtab.cmdsize = lc.cmdsize;
1334 if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1335 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1336 NULL) {
1337 // Clear m_dysymtab if we were unable to read all items from the
1338 // load command
1339 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1340 }
1341 }
1342 offset = load_cmd_offset + lc.cmdsize;
1343 }
1344 }
1345 }
1346 if (m_dysymtab.cmd)
1347 return m_dysymtab.nlocalsym <= 1;
1348 return false;
1349}
1350
Pavel Labathb417eea2018-03-06 13:53:26 +00001351ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
1352 EncryptedFileRanges result;
Pavel Labathf90054d2018-03-03 22:07:47 +00001353 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labathb417eea2018-03-06 13:53:26 +00001354
Pavel Labathf90054d2018-03-03 22:07:47 +00001355 encryption_info_command encryption_cmd;
Pavel Labathb417eea2018-03-06 13:53:26 +00001356 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001357 const lldb::offset_t load_cmd_offset = offset;
1358 if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL)
1359 break;
1360
Adrian Prantl05097242018-04-30 16:49:04 +00001361 // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1362 // 3 fields we care about, so treat them the same.
Pavel Labathf90054d2018-03-03 22:07:47 +00001363 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1364 encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1365 if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1366 if (encryption_cmd.cryptid != 0) {
1367 EncryptedFileRanges::Entry entry;
1368 entry.SetRangeBase(encryption_cmd.cryptoff);
1369 entry.SetByteSize(encryption_cmd.cryptsize);
Pavel Labathb417eea2018-03-06 13:53:26 +00001370 result.Append(entry);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 }
1372 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 }
Pavel Labathf90054d2018-03-03 22:07:47 +00001374 offset = load_cmd_offset + encryption_cmd.cmdsize;
1375 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376
Pavel Labathb417eea2018-03-06 13:53:26 +00001377 return result;
1378}
1379
1380void ObjectFileMachO::SanitizeSegmentCommand(segment_command_64 &seg_cmd,
1381 uint32_t cmd_idx) {
1382 if (m_length == 0 || seg_cmd.filesize == 0)
1383 return;
1384
1385 if (seg_cmd.fileoff > m_length) {
1386 // We have a load command that says it extends past the end of the file.
1387 // This is likely a corrupt file. We don't have any way to return an error
1388 // condition here (this method was likely invoked from something like
1389 // ObjectFile::GetSectionList()), so we just null out the section contents,
1390 // and dump a message to stdout. The most common case here is core file
1391 // debugging with a truncated file.
1392 const char *lc_segment_name =
1393 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1394 GetModule()->ReportWarning(
1395 "load command %u %s has a fileoff (0x%" PRIx64
1396 ") that extends beyond the end of the file (0x%" PRIx64
1397 "), ignoring this section",
1398 cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
1399
1400 seg_cmd.fileoff = 0;
1401 seg_cmd.filesize = 0;
1402 }
1403
1404 if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1405 // We have a load command that says it extends past the end of the file.
1406 // This is likely a corrupt file. We don't have any way to return an error
1407 // condition here (this method was likely invoked from something like
1408 // ObjectFile::GetSectionList()), so we just null out the section contents,
1409 // and dump a message to stdout. The most common case here is core file
1410 // debugging with a truncated file.
1411 const char *lc_segment_name =
1412 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1413 GetModule()->ReportWarning(
1414 "load command %u %s has a fileoff + filesize (0x%" PRIx64
1415 ") that extends beyond the end of the file (0x%" PRIx64
1416 "), the segment will be truncated to match",
1417 cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
1418
1419 // Truncate the length
1420 seg_cmd.filesize = m_length - seg_cmd.fileoff;
1421 }
1422}
1423
1424static uint32_t GetSegmentPermissions(const segment_command_64 &seg_cmd) {
1425 uint32_t result = 0;
1426 if (seg_cmd.initprot & VM_PROT_READ)
1427 result |= ePermissionsReadable;
1428 if (seg_cmd.initprot & VM_PROT_WRITE)
1429 result |= ePermissionsWritable;
1430 if (seg_cmd.initprot & VM_PROT_EXECUTE)
1431 result |= ePermissionsExecutable;
1432 return result;
1433}
1434
1435static lldb::SectionType GetSectionType(uint32_t flags,
1436 ConstString section_name) {
1437
1438 if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1439 return eSectionTypeCode;
1440
1441 uint32_t mach_sect_type = flags & SECTION_TYPE;
1442 static ConstString g_sect_name_objc_data("__objc_data");
1443 static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1444 static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1445 static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
1446 static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
1447 static ConstString g_sect_name_objc_const("__objc_const");
1448 static ConstString g_sect_name_objc_classlist("__objc_classlist");
1449 static ConstString g_sect_name_cfstring("__cfstring");
1450
1451 static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
1452 static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1453 static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1454 static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1455 static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1456 static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
George Rimare4dee262018-10-23 09:46:15 +00001457 static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
Pavel Labathb417eea2018-03-06 13:53:26 +00001458 static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
Pavel Labatha041d842018-06-01 12:06:45 +00001459 static ConstString g_sect_name_dwarf_debug_names("__debug_names");
Pavel Labathb417eea2018-03-06 13:53:26 +00001460 static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1461 static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1462 static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1463 static ConstString g_sect_name_dwarf_debug_str("__debug_str");
Greg Clayton2550ca12018-05-08 17:19:24 +00001464 static ConstString g_sect_name_dwarf_debug_types("__debug_types");
Pavel Labathb417eea2018-03-06 13:53:26 +00001465 static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1466 static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1467 static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1468 static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1469 static ConstString g_sect_name_eh_frame("__eh_frame");
1470 static ConstString g_sect_name_compact_unwind("__unwind_info");
1471 static ConstString g_sect_name_text("__text");
1472 static ConstString g_sect_name_data("__data");
1473 static ConstString g_sect_name_go_symtab("__gosymtab");
1474
1475 if (section_name == g_sect_name_dwarf_debug_abbrev)
1476 return eSectionTypeDWARFDebugAbbrev;
1477 if (section_name == g_sect_name_dwarf_debug_aranges)
1478 return eSectionTypeDWARFDebugAranges;
1479 if (section_name == g_sect_name_dwarf_debug_frame)
1480 return eSectionTypeDWARFDebugFrame;
1481 if (section_name == g_sect_name_dwarf_debug_info)
1482 return eSectionTypeDWARFDebugInfo;
1483 if (section_name == g_sect_name_dwarf_debug_line)
1484 return eSectionTypeDWARFDebugLine;
1485 if (section_name == g_sect_name_dwarf_debug_loc)
1486 return eSectionTypeDWARFDebugLoc;
George Rimare4dee262018-10-23 09:46:15 +00001487 if (section_name == g_sect_name_dwarf_debug_loclists)
1488 return eSectionTypeDWARFDebugLocLists;
Pavel Labathb417eea2018-03-06 13:53:26 +00001489 if (section_name == g_sect_name_dwarf_debug_macinfo)
1490 return eSectionTypeDWARFDebugMacInfo;
Pavel Labatha041d842018-06-01 12:06:45 +00001491 if (section_name == g_sect_name_dwarf_debug_names)
1492 return eSectionTypeDWARFDebugNames;
Pavel Labathb417eea2018-03-06 13:53:26 +00001493 if (section_name == g_sect_name_dwarf_debug_pubnames)
1494 return eSectionTypeDWARFDebugPubNames;
1495 if (section_name == g_sect_name_dwarf_debug_pubtypes)
1496 return eSectionTypeDWARFDebugPubTypes;
1497 if (section_name == g_sect_name_dwarf_debug_ranges)
George Rimar6e357122018-10-10 08:11:15 +00001498 return eSectionTypeDWARFDebugRanges;
Pavel Labathb417eea2018-03-06 13:53:26 +00001499 if (section_name == g_sect_name_dwarf_debug_str)
1500 return eSectionTypeDWARFDebugStr;
Greg Clayton2550ca12018-05-08 17:19:24 +00001501 if (section_name == g_sect_name_dwarf_debug_types)
1502 return eSectionTypeDWARFDebugTypes;
Pavel Labathb417eea2018-03-06 13:53:26 +00001503 if (section_name == g_sect_name_dwarf_apple_names)
1504 return eSectionTypeDWARFAppleNames;
1505 if (section_name == g_sect_name_dwarf_apple_types)
1506 return eSectionTypeDWARFAppleTypes;
1507 if (section_name == g_sect_name_dwarf_apple_namespaces)
1508 return eSectionTypeDWARFAppleNamespaces;
1509 if (section_name == g_sect_name_dwarf_apple_objc)
1510 return eSectionTypeDWARFAppleObjC;
1511 if (section_name == g_sect_name_objc_selrefs)
1512 return eSectionTypeDataCStringPointers;
1513 if (section_name == g_sect_name_objc_msgrefs)
1514 return eSectionTypeDataObjCMessageRefs;
1515 if (section_name == g_sect_name_eh_frame)
1516 return eSectionTypeEHFrame;
1517 if (section_name == g_sect_name_compact_unwind)
1518 return eSectionTypeCompactUnwind;
1519 if (section_name == g_sect_name_cfstring)
1520 return eSectionTypeDataObjCCFStrings;
1521 if (section_name == g_sect_name_go_symtab)
1522 return eSectionTypeGoSymtab;
1523 if (section_name == g_sect_name_objc_data ||
1524 section_name == g_sect_name_objc_classrefs ||
1525 section_name == g_sect_name_objc_superrefs ||
1526 section_name == g_sect_name_objc_const ||
1527 section_name == g_sect_name_objc_classlist) {
1528 return eSectionTypeDataPointers;
1529 }
1530
1531 switch (mach_sect_type) {
1532 // TODO: categorize sections by other flags for regular sections
1533 case S_REGULAR:
1534 if (section_name == g_sect_name_text)
1535 return eSectionTypeCode;
1536 if (section_name == g_sect_name_data)
1537 return eSectionTypeData;
1538 return eSectionTypeOther;
1539 case S_ZEROFILL:
1540 return eSectionTypeZeroFill;
1541 case S_CSTRING_LITERALS: // section with only literal C strings
1542 return eSectionTypeDataCString;
1543 case S_4BYTE_LITERALS: // section with only 4 byte literals
1544 return eSectionTypeData4;
1545 case S_8BYTE_LITERALS: // section with only 8 byte literals
1546 return eSectionTypeData8;
1547 case S_LITERAL_POINTERS: // section with only pointers to literals
1548 return eSectionTypeDataPointers;
1549 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1550 return eSectionTypeDataPointers;
1551 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1552 return eSectionTypeDataPointers;
1553 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1554 // the reserved2 field
1555 return eSectionTypeCode;
1556 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1557 // initialization
1558 return eSectionTypeDataPointers;
1559 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1560 // termination
1561 return eSectionTypeDataPointers;
1562 case S_COALESCED:
1563 return eSectionTypeOther;
1564 case S_GB_ZEROFILL:
1565 return eSectionTypeZeroFill;
1566 case S_INTERPOSING: // section with only pairs of function pointers for
1567 // interposing
1568 return eSectionTypeCode;
1569 case S_16BYTE_LITERALS: // section with only 16 byte literals
1570 return eSectionTypeData16;
1571 case S_DTRACE_DOF:
1572 return eSectionTypeDebug;
1573 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1574 return eSectionTypeDataPointers;
1575 default:
1576 return eSectionTypeOther;
1577 }
1578}
1579
1580struct ObjectFileMachO::SegmentParsingContext {
1581 const EncryptedFileRanges EncryptedRanges;
1582 lldb_private::SectionList &UnifiedList;
1583 uint32_t NextSegmentIdx = 0;
1584 uint32_t NextSectionIdx = 0;
1585 bool FileAddressesChanged = false;
1586
1587 SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
1588 lldb_private::SectionList &UnifiedList)
1589 : EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
1590};
1591
1592void ObjectFileMachO::ProcessSegmentCommand(const load_command &load_cmd_,
1593 lldb::offset_t offset,
1594 uint32_t cmd_idx,
1595 SegmentParsingContext &context) {
1596 segment_command_64 load_cmd;
1597 memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1598
1599 if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1600 return;
1601
1602 ModuleSP module_sp = GetModule();
1603 const bool is_core = GetType() == eTypeCoreFile;
1604 const bool is_dsym = (m_header.filetype == MH_DSYM);
1605 bool add_section = true;
1606 bool add_to_unified = true;
1607 ConstString const_segname(
1608 load_cmd.segname,
1609 std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname)));
1610
1611 SectionSP unified_section_sp(
1612 context.UnifiedList.FindSectionByName(const_segname));
1613 if (is_dsym && unified_section_sp) {
1614 if (const_segname == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001615 // We need to keep the __LINKEDIT segment private to this object file
1616 // only
Pavel Labathb417eea2018-03-06 13:53:26 +00001617 add_to_unified = false;
1618 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001619 // This is the dSYM file and this section has already been created by the
1620 // object file, no need to create it.
Pavel Labathb417eea2018-03-06 13:53:26 +00001621 add_section = false;
1622 }
1623 }
1624 load_cmd.vmaddr = m_data.GetAddress(&offset);
1625 load_cmd.vmsize = m_data.GetAddress(&offset);
1626 load_cmd.fileoff = m_data.GetAddress(&offset);
1627 load_cmd.filesize = m_data.GetAddress(&offset);
1628 if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1629 return;
1630
1631 SanitizeSegmentCommand(load_cmd, cmd_idx);
1632
1633 const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1634 const bool segment_is_encrypted =
1635 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1636
Adrian Prantl05097242018-04-30 16:49:04 +00001637 // Keep a list of mach segments around in case we need to get at data that
1638 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001639 m_mach_segments.push_back(load_cmd);
1640
Adrian Prantl05097242018-04-30 16:49:04 +00001641 // Use a segment ID of the segment index shifted left by 8 so they never
1642 // conflict with any of the sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001643 SectionSP segment_sp;
1644 if (add_section && (const_segname || is_core)) {
1645 segment_sp.reset(new Section(
1646 module_sp, // Module to which this section belongs
1647 this, // Object file to which this sections belongs
1648 ++context.NextSegmentIdx
1649 << 8, // Section ID is the 1 based segment index
Adrian Prantl05097242018-04-30 16:49:04 +00001650 // shifted right by 8 bits as not to collide with any of the 256
1651 // section IDs that are possible
Pavel Labathb417eea2018-03-06 13:53:26 +00001652 const_segname, // Name of this section
1653 eSectionTypeContainer, // This section is a container of other
1654 // sections.
1655 load_cmd.vmaddr, // File VM address == addresses as they are
1656 // found in the object file
1657 load_cmd.vmsize, // VM size in bytes of this section
1658 load_cmd.fileoff, // Offset to the data for this section in
1659 // the file
1660 load_cmd.filesize, // Size in bytes of this section as found
1661 // in the file
1662 0, // Segments have no alignment information
1663 load_cmd.flags)); // Flags for this section
1664
1665 segment_sp->SetIsEncrypted(segment_is_encrypted);
1666 m_sections_ap->AddSection(segment_sp);
1667 segment_sp->SetPermissions(segment_permissions);
1668 if (add_to_unified)
1669 context.UnifiedList.AddSection(segment_sp);
1670 } else if (unified_section_sp) {
1671 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1672 // Check to see if the module was read from memory?
1673 if (module_sp->GetObjectFile()->GetHeaderAddress().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001674 // We have a module that is in memory and needs to have its file
1675 // address adjusted. We need to do this because when we load a file
1676 // from memory, its addresses will be slid already, yet the addresses
1677 // in the new symbol file will still be unslid. Since everything is
1678 // stored as section offset, this shouldn't cause any problems.
Pavel Labathb417eea2018-03-06 13:53:26 +00001679
Adrian Prantl05097242018-04-30 16:49:04 +00001680 // Make sure we've parsed the symbol table from the ObjectFile before
1681 // we go around changing its Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001682 module_sp->GetObjectFile()->GetSymtab();
Adrian Prantl05097242018-04-30 16:49:04 +00001683 // eh_frame would present the same problems but we parse that on a per-
1684 // function basis as-needed so it's more difficult to remove its use of
1685 // the Sections. Realistically, the environments where this code path
1686 // will be taken will not have eh_frame sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001687
1688 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1689
Adrian Prantl05097242018-04-30 16:49:04 +00001690 // Notify the module that the section addresses have been changed once
1691 // we're done so any file-address caches can be updated.
Pavel Labathb417eea2018-03-06 13:53:26 +00001692 context.FileAddressesChanged = true;
1693 }
1694 }
1695 m_sections_ap->AddSection(unified_section_sp);
1696 }
1697
1698 struct section_64 sect64;
1699 ::memset(&sect64, 0, sizeof(sect64));
Adrian Prantl05097242018-04-30 16:49:04 +00001700 // Push a section into our mach sections for the section at index zero
1701 // (NO_SECT) if we don't have any mach sections yet...
Pavel Labathb417eea2018-03-06 13:53:26 +00001702 if (m_mach_sections.empty())
1703 m_mach_sections.push_back(sect64);
1704 uint32_t segment_sect_idx;
1705 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1706
1707 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1708 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1709 ++segment_sect_idx) {
1710 if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1711 sizeof(sect64.sectname)) == NULL)
1712 break;
1713 if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1714 sizeof(sect64.segname)) == NULL)
1715 break;
1716 sect64.addr = m_data.GetAddress(&offset);
1717 sect64.size = m_data.GetAddress(&offset);
1718
1719 if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
1720 break;
1721
Adrian Prantl05097242018-04-30 16:49:04 +00001722 // Keep a list of mach sections around in case we need to get at data that
1723 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001724 m_mach_sections.push_back(sect64);
1725
1726 if (add_section) {
1727 ConstString section_name(
1728 sect64.sectname,
1729 std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname)));
1730 if (!const_segname) {
Adrian Prantl05097242018-04-30 16:49:04 +00001731 // We have a segment with no name so we need to conjure up segments
1732 // that correspond to the section's segname if there isn't already such
1733 // a section. If there is such a section, we resize the section so that
1734 // it spans all sections. We also mark these sections as fake so
1735 // address matches don't hit if they land in the gaps between the child
1736 // sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001737 const_segname.SetTrimmedCStringWithLength(sect64.segname,
1738 sizeof(sect64.segname));
1739 segment_sp = context.UnifiedList.FindSectionByName(const_segname);
1740 if (segment_sp.get()) {
1741 Section *segment = segment_sp.get();
1742 // Grow the section size as needed.
1743 const lldb::addr_t sect64_min_addr = sect64.addr;
1744 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1745 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1746 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1747 const lldb::addr_t curr_seg_max_addr =
1748 curr_seg_min_addr + curr_seg_byte_size;
1749 if (sect64_min_addr >= curr_seg_min_addr) {
1750 const lldb::addr_t new_seg_byte_size =
1751 sect64_max_addr - curr_seg_min_addr;
1752 // Only grow the section size if needed
1753 if (new_seg_byte_size > curr_seg_byte_size)
1754 segment->SetByteSize(new_seg_byte_size);
1755 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001756 // We need to change the base address of the segment and adjust the
1757 // child section offsets for all existing children.
Pavel Labathb417eea2018-03-06 13:53:26 +00001758 const lldb::addr_t slide_amount =
1759 sect64_min_addr - curr_seg_min_addr;
1760 segment->Slide(slide_amount, false);
1761 segment->GetChildren().Slide(-slide_amount, false);
1762 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1763 }
1764
1765 // Grow the section size as needed.
1766 if (sect64.offset) {
1767 const lldb::addr_t segment_min_file_offset =
1768 segment->GetFileOffset();
1769 const lldb::addr_t segment_max_file_offset =
1770 segment_min_file_offset + segment->GetFileSize();
1771
1772 const lldb::addr_t section_min_file_offset = sect64.offset;
1773 const lldb::addr_t section_max_file_offset =
1774 section_min_file_offset + sect64.size;
1775 const lldb::addr_t new_file_offset =
1776 std::min(section_min_file_offset, segment_min_file_offset);
1777 const lldb::addr_t new_file_size =
1778 std::max(section_max_file_offset, segment_max_file_offset) -
1779 new_file_offset;
1780 segment->SetFileOffset(new_file_offset);
1781 segment->SetFileSize(new_file_size);
1782 }
1783 } else {
1784 // Create a fake section for the section's named segment
1785 segment_sp.reset(new Section(
1786 segment_sp, // Parent section
1787 module_sp, // Module to which this section belongs
1788 this, // Object file to which this section belongs
1789 ++context.NextSegmentIdx
1790 << 8, // Section ID is the 1 based segment index
1791 // shifted right by 8 bits as not to
1792 // collide with any of the 256 section IDs
1793 // that are possible
1794 const_segname, // Name of this section
1795 eSectionTypeContainer, // This section is a container of
1796 // other sections.
1797 sect64.addr, // File VM address == addresses as they are
1798 // found in the object file
1799 sect64.size, // VM size in bytes of this section
1800 sect64.offset, // Offset to the data for this section in
1801 // the file
1802 sect64.offset ? sect64.size : 0, // Size in bytes of
1803 // this section as
1804 // found in the file
1805 sect64.align,
1806 load_cmd.flags)); // Flags for this section
1807 segment_sp->SetIsFake(true);
1808 segment_sp->SetPermissions(segment_permissions);
1809 m_sections_ap->AddSection(segment_sp);
1810 if (add_to_unified)
1811 context.UnifiedList.AddSection(segment_sp);
1812 segment_sp->SetIsEncrypted(segment_is_encrypted);
1813 }
1814 }
1815 assert(segment_sp.get());
1816
1817 lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1818
1819 SectionSP section_sp(new Section(
1820 segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1821 sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1822 sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1823 sect64.flags));
1824 // Set the section to be encrypted to match the segment
1825
1826 bool section_is_encrypted = false;
1827 if (!segment_is_encrypted && load_cmd.filesize != 0)
1828 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1829 sect64.offset) != NULL;
1830
1831 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1832 section_sp->SetPermissions(segment_permissions);
1833 segment_sp->GetChildren().AddSection(section_sp);
1834
1835 if (segment_sp->IsFake()) {
1836 segment_sp.reset();
1837 const_segname.Clear();
1838 }
1839 }
1840 }
1841 if (segment_sp && is_dsym) {
1842 if (first_segment_sectID <= context.NextSectionIdx) {
1843 lldb::user_id_t sect_uid;
1844 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1845 ++sect_uid) {
1846 SectionSP curr_section_sp(
1847 segment_sp->GetChildren().FindSectionByID(sect_uid));
1848 SectionSP next_section_sp;
1849 if (sect_uid + 1 <= context.NextSectionIdx)
1850 next_section_sp =
1851 segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1852
1853 if (curr_section_sp.get()) {
1854 if (curr_section_sp->GetByteSize() == 0) {
1855 if (next_section_sp.get() != NULL)
1856 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1857 curr_section_sp->GetFileAddress());
1858 else
1859 curr_section_sp->SetByteSize(load_cmd.vmsize);
1860 }
1861 }
1862 }
1863 }
1864 }
1865}
1866
1867void ObjectFileMachO::ProcessDysymtabCommand(const load_command &load_cmd,
1868 lldb::offset_t offset) {
1869 m_dysymtab.cmd = load_cmd.cmd;
1870 m_dysymtab.cmdsize = load_cmd.cmdsize;
1871 m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1872 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1873}
1874
1875void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1876 if (m_sections_ap)
1877 return;
1878
1879 m_sections_ap.reset(new SectionList());
1880
1881 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1882 // bool dump_sections = false;
1883 ModuleSP module_sp(GetModule());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001884
Pavel Labathf90054d2018-03-03 22:07:47 +00001885 offset = MachHeaderSizeFromMagic(m_header.magic);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001886
Pavel Labathb417eea2018-03-06 13:53:26 +00001887 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1888 struct load_command load_cmd;
1889 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001890 const lldb::offset_t load_cmd_offset = offset;
1891 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
1892 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001893
Pavel Labathb417eea2018-03-06 13:53:26 +00001894 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1895 ProcessSegmentCommand(load_cmd, offset, i, context);
1896 else if (load_cmd.cmd == LC_DYSYMTAB)
1897 ProcessDysymtabCommand(load_cmd, offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001898
Pavel Labathf90054d2018-03-03 22:07:47 +00001899 offset = load_cmd_offset + load_cmd.cmdsize;
1900 }
1901
Pavel Labathb417eea2018-03-06 13:53:26 +00001902 if (context.FileAddressesChanged && module_sp)
Pavel Labathf90054d2018-03-03 22:07:47 +00001903 module_sp->SectionFileAddressesChanged();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904}
1905
1906class MachSymtabSectionInfo {
1907public:
1908 MachSymtabSectionInfo(SectionList *section_list)
1909 : m_section_list(section_list), m_section_infos() {
Adrian Prantl05097242018-04-30 16:49:04 +00001910 // Get the number of sections down to a depth of 1 to include all segments
1911 // and their sections, but no other sections that may be added for debug
1912 // map or
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913 m_section_infos.resize(section_list->GetNumSections(1));
1914 }
1915
1916 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1917 if (n_sect == 0)
1918 return SectionSP();
1919 if (n_sect < m_section_infos.size()) {
1920 if (!m_section_infos[n_sect].section_sp) {
1921 SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1922 m_section_infos[n_sect].section_sp = section_sp;
1923 if (section_sp) {
1924 m_section_infos[n_sect].vm_range.SetBaseAddress(
1925 section_sp->GetFileAddress());
1926 m_section_infos[n_sect].vm_range.SetByteSize(
1927 section_sp->GetByteSize());
1928 } else {
1929 Host::SystemLog(Host::eSystemLogError,
1930 "error: unable to find section for section %u\n",
1931 n_sect);
1932 }
1933 }
1934 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1935 // Symbol is in section.
1936 return m_section_infos[n_sect].section_sp;
1937 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1938 m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1939 file_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001940 // Symbol is in section with zero size, but has the same start address
1941 // as the section. This can happen with linker symbols (symbols that
1942 // start with the letter 'l' or 'L'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001943 return m_section_infos[n_sect].section_sp;
1944 }
1945 }
1946 return m_section_list->FindSectionContainingFileAddress(file_addr);
1947 }
1948
1949protected:
1950 struct SectionInfo {
1951 SectionInfo() : vm_range(), section_sp() {}
1952
1953 VMRange vm_range;
1954 SectionSP section_sp;
1955 };
1956 SectionList *m_section_list;
1957 std::vector<SectionInfo> m_section_infos;
1958};
1959
1960struct TrieEntry {
1961 TrieEntry()
1962 : name(), address(LLDB_INVALID_ADDRESS), flags(0), other(0),
1963 import_name() {}
1964
1965 void Clear() {
1966 name.Clear();
1967 address = LLDB_INVALID_ADDRESS;
1968 flags = 0;
1969 other = 0;
1970 import_name.Clear();
1971 }
1972
1973 void Dump() const {
1974 printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
1975 static_cast<unsigned long long>(address),
1976 static_cast<unsigned long long>(flags),
1977 static_cast<unsigned long long>(other), name.GetCString());
1978 if (import_name)
1979 printf(" -> \"%s\"\n", import_name.GetCString());
1980 else
1981 printf("\n");
1982 }
1983 ConstString name;
1984 uint64_t address;
1985 uint64_t flags;
1986 uint64_t other;
1987 ConstString import_name;
1988};
1989
1990struct TrieEntryWithOffset {
1991 lldb::offset_t nodeOffset;
1992 TrieEntry entry;
1993
1994 TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
1995
1996 void Dump(uint32_t idx) const {
1997 printf("[%3u] 0x%16.16llx: ", idx,
1998 static_cast<unsigned long long>(nodeOffset));
1999 entry.Dump();
2000 }
2001
2002 bool operator<(const TrieEntryWithOffset &other) const {
2003 return (nodeOffset < other.nodeOffset);
2004 }
2005};
2006
2007static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
2008 const bool is_arm,
2009 std::vector<llvm::StringRef> &nameSlices,
2010 std::set<lldb::addr_t> &resolver_addresses,
2011 std::vector<TrieEntryWithOffset> &output) {
2012 if (!data.ValidOffset(offset))
Greg Clayton8f265f72015-10-28 20:49:34 +00002013 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002014
2015 const uint64_t terminalSize = data.GetULEB128(&offset);
2016 lldb::offset_t children_offset = offset + terminalSize;
2017 if (terminalSize != 0) {
2018 TrieEntryWithOffset e(offset);
2019 e.entry.flags = data.GetULEB128(&offset);
2020 const char *import_name = NULL;
2021 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2022 e.entry.address = 0;
2023 e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2024 import_name = data.GetCStr(&offset);
2025 } else {
2026 e.entry.address = data.GetULEB128(&offset);
2027 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2028 e.entry.other = data.GetULEB128(&offset);
2029 uint64_t resolver_addr = e.entry.other;
2030 if (is_arm)
2031 resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2032 resolver_addresses.insert(resolver_addr);
2033 } else
2034 e.entry.other = 0;
2035 }
2036 // Only add symbols that are reexport symbols with a valid import name
2037 if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name &&
2038 import_name[0]) {
2039 std::string name;
2040 if (!nameSlices.empty()) {
2041 for (auto name_slice : nameSlices)
2042 name.append(name_slice.data(), name_slice.size());
2043 }
2044 if (name.size() > 1) {
2045 // Skip the leading '_'
2046 e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2047 }
2048 if (import_name) {
2049 // Skip the leading '_'
2050 e.entry.import_name.SetCString(import_name + 1);
2051 }
2052 output.push_back(e);
2053 }
2054 }
2055
2056 const uint8_t childrenCount = data.GetU8(&children_offset);
2057 for (uint8_t i = 0; i < childrenCount; ++i) {
2058 const char *cstr = data.GetCStr(&children_offset);
2059 if (cstr)
2060 nameSlices.push_back(llvm::StringRef(cstr));
2061 else
2062 return false; // Corrupt data
2063 lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2064 if (childNodeOffset) {
2065 if (!ParseTrieEntries(data, childNodeOffset, is_arm, nameSlices,
2066 resolver_addresses, output)) {
2067 return false;
2068 }
2069 }
2070 nameSlices.pop_back();
2071 }
2072 return true;
Greg Clayton9191db42013-10-21 18:40:51 +00002073}
2074
Jason Molenda649a6072015-11-10 05:21:54 +00002075// Read the UUID out of a dyld_shared_cache file on-disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002076UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
2077 const ByteOrder byte_order,
2078 const uint32_t addr_byte_size) {
2079 UUID dsc_uuid;
Pavel Labath50251fc2017-12-21 10:54:30 +00002080 DataBufferSP DscData = MapFileData(
2081 dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002082 if (!DscData)
2083 return dsc_uuid;
2084 DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
Jason Molenda649a6072015-11-10 05:21:54 +00002085
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002086 char version_str[7];
2087 lldb::offset_t offset = 0;
2088 memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
2089 version_str[6] = '\0';
2090 if (strcmp(version_str, "dyld_v") == 0) {
2091 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
Pavel Labath2f93fd12018-06-26 15:12:20 +00002092 dsc_uuid = UUID::fromOptionalData(
2093 dsc_header_data.GetData(&offset, sizeof(uuid_t)), sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094 }
Jason Molendafd443e92018-02-07 01:28:29 +00002095 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2096 if (log && dsc_uuid.IsValid()) {
2097 log->Printf("Shared cache %s has UUID %s", dyld_shared_cache.GetPath().c_str(),
2098 dsc_uuid.GetAsString().c_str());
2099 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100 return dsc_uuid;
Jason Molenda649a6072015-11-10 05:21:54 +00002101}
2102
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103size_t ObjectFileMachO::ParseSymtab() {
Pavel Labathf9d16472017-05-15 13:02:37 +00002104 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2105 Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 m_file.GetFilename().AsCString(""));
2107 ModuleSP module_sp(GetModule());
2108 if (!module_sp)
2109 return 0;
2110
2111 struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2112 struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2113 struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2114 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2115 FunctionStarts function_starts;
2116 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2117 uint32_t i;
2118 FileSpecList dylib_files;
2119 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2120 static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2121 static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2122 static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2123
2124 for (i = 0; i < m_header.ncmds; ++i) {
2125 const lldb::offset_t cmd_offset = offset;
2126 // Read in the load command and load command size
2127 struct load_command lc;
2128 if (m_data.GetU32(&offset, &lc, 2) == NULL)
2129 break;
2130 // Watch for the symbol table load command
2131 switch (lc.cmd) {
2132 case LC_SYMTAB:
2133 symtab_load_command.cmd = lc.cmd;
2134 symtab_load_command.cmdsize = lc.cmdsize;
2135 // Read in the rest of the symtab load command
2136 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2137 0) // fill in symoff, nsyms, stroff, strsize fields
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002138 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 if (symtab_load_command.symoff == 0) {
2140 if (log)
2141 module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2142 return 0;
2143 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002144
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145 if (symtab_load_command.stroff == 0) {
2146 if (log)
2147 module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2148 return 0;
2149 }
Greg Clayton77ccca72011-12-30 00:32:24 +00002150
Kate Stoneb9c1b512016-09-06 20:57:50 +00002151 if (symtab_load_command.nsyms == 0) {
2152 if (log)
2153 module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
2154 return 0;
2155 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002156
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157 if (symtab_load_command.strsize == 0) {
2158 if (log)
2159 module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2160 return 0;
2161 }
2162 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002163
Kate Stoneb9c1b512016-09-06 20:57:50 +00002164 case LC_DYLD_INFO:
2165 case LC_DYLD_INFO_ONLY:
2166 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2167 dyld_info.cmd = lc.cmd;
2168 dyld_info.cmdsize = lc.cmdsize;
2169 } else {
2170 memset(&dyld_info, 0, sizeof(dyld_info));
2171 }
2172 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002173
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 case LC_LOAD_DYLIB:
2175 case LC_LOAD_WEAK_DYLIB:
2176 case LC_REEXPORT_DYLIB:
2177 case LC_LOADFVMLIB:
2178 case LC_LOAD_UPWARD_DYLIB: {
2179 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2180 const char *path = m_data.PeekCStr(name_offset);
2181 if (path) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002182 FileSpec file_spec(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 // Strip the path if there is @rpath, @executable, etc so we just use
2184 // the basename
2185 if (path[0] == '@')
2186 file_spec.GetDirectory().Clear();
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002187
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188 if (lc.cmd == LC_REEXPORT_DYLIB) {
2189 m_reexported_dylibs.AppendIfUnique(file_spec);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002190 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002191
2192 dylib_files.Append(file_spec);
2193 }
2194 } break;
2195
2196 case LC_FUNCTION_STARTS:
2197 function_starts_load_command.cmd = lc.cmd;
2198 function_starts_load_command.cmdsize = lc.cmdsize;
2199 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2200 NULL) // fill in symoff, nsyms, stroff, strsize fields
2201 memset(&function_starts_load_command, 0,
2202 sizeof(function_starts_load_command));
2203 break;
2204
2205 default:
2206 break;
2207 }
2208 offset = cmd_offset + lc.cmdsize;
2209 }
2210
2211 if (symtab_load_command.cmd) {
2212 Symtab *symtab = m_symtab_ap.get();
2213 SectionList *section_list = GetSectionList();
2214 if (section_list == NULL)
2215 return 0;
2216
2217 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2218 const ByteOrder byte_order = m_data.GetByteOrder();
2219 bool bit_width_32 = addr_byte_size == 4;
2220 const size_t nlist_byte_size =
2221 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2222
2223 DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size);
2224 DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size);
2225 DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size);
2226 DataExtractor indirect_symbol_index_data(NULL, 0, byte_order,
2227 addr_byte_size);
2228 DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size);
2229
2230 const addr_t nlist_data_byte_size =
2231 symtab_load_command.nsyms * nlist_byte_size;
2232 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2233 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2234
2235 ProcessSP process_sp(m_process_wp.lock());
2236 Process *process = process_sp.get();
2237
2238 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2239
2240 if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2241 Target &target = process->GetTarget();
2242
2243 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2244
2245 SectionSP linkedit_section_sp(
2246 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2247 // Reading mach file from memory in a process or core file...
2248
2249 if (linkedit_section_sp) {
2250 addr_t linkedit_load_addr =
2251 linkedit_section_sp->GetLoadBaseAddress(&target);
2252 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2253 // We might be trying to access the symbol table before the
Adrian Prantl05097242018-04-30 16:49:04 +00002254 // __LINKEDIT's load address has been set in the target. We can't
2255 // fail to read the symbol table, so calculate the right address
2256 // manually
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2258 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2259 }
2260
2261 const addr_t linkedit_file_offset =
2262 linkedit_section_sp->GetFileOffset();
2263 const addr_t symoff_addr = linkedit_load_addr +
2264 symtab_load_command.symoff -
2265 linkedit_file_offset;
2266 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2267 linkedit_file_offset;
2268
2269 bool data_was_read = false;
2270
2271#if defined(__APPLE__) && \
2272 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2273 if (m_header.flags & 0x80000000u &&
2274 process->GetAddressByteSize() == sizeof(void *)) {
2275 // This mach-o memory file is in the dyld shared cache. If this
2276 // program is not remote and this is iOS, then this process will
Adrian Prantl05097242018-04-30 16:49:04 +00002277 // share the same shared cache as the process we are debugging and we
2278 // can read the entire __LINKEDIT from the address space in this
Kate Stoneb9c1b512016-09-06 20:57:50 +00002279 // process. This is a needed optimization that is used for local iOS
2280 // debugging only since all shared libraries in the shared cache do
2281 // not have corresponding files that exist in the file system of the
2282 // device. They have been combined into a single file. This means we
2283 // always have to load these files from memory. All of the symbol and
2284 // string tables from all of the __LINKEDIT sections from the shared
2285 // libraries in the shared cache have been merged into a single large
2286 // symbol and string table. Reading all of this symbol and string
Adrian Prantl05097242018-04-30 16:49:04 +00002287 // table data across can slow down debug launch times, so we optimize
2288 // this by reading the memory for the __LINKEDIT section from this
2289 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290
Jason Molenda07580ff2018-05-04 00:59:37 +00002291 UUID lldb_shared_cache;
2292 addr_t lldb_shared_cache_addr;
2293 GetLLDBSharedCacheUUID (lldb_shared_cache_addr, lldb_shared_cache);
2294 UUID process_shared_cache;
2295 addr_t process_shared_cache_addr;
2296 GetProcessSharedCacheUUID(process, process_shared_cache_addr, process_shared_cache);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297 bool use_lldb_cache = true;
2298 if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
Jason Molenda07580ff2018-05-04 00:59:37 +00002299 (lldb_shared_cache != process_shared_cache
2300 || process_shared_cache_addr != lldb_shared_cache_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301 use_lldb_cache = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302 }
2303
2304 PlatformSP platform_sp(target.GetPlatform());
2305 if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2306 data_was_read = true;
2307 nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2308 eByteOrderLittle);
2309 strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2310 eByteOrderLittle);
2311 if (function_starts_load_command.cmd) {
2312 const addr_t func_start_addr =
2313 linkedit_load_addr + function_starts_load_command.dataoff -
2314 linkedit_file_offset;
2315 function_starts_data.SetData(
2316 (void *)func_start_addr,
2317 function_starts_load_command.datasize, eByteOrderLittle);
2318 }
2319 }
2320 }
2321#endif
2322
2323 if (!data_was_read) {
2324 // Always load dyld - the dynamic linker - from memory if we didn't
Adrian Prantl05097242018-04-30 16:49:04 +00002325 // find a binary anywhere else. lldb will not register
2326 // dylib/framework/bundle loads/unloads if we don't have the dyld
2327 // symbols, we force dyld to load from memory despite the user's
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328 // target.memory-module-load-level setting.
2329 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2330 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2331 DataBufferSP nlist_data_sp(
2332 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2333 if (nlist_data_sp)
2334 nlist_data.SetData(nlist_data_sp, 0,
2335 nlist_data_sp->GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336 if (m_dysymtab.nindirectsyms != 0) {
2337 const addr_t indirect_syms_addr = linkedit_load_addr +
2338 m_dysymtab.indirectsymoff -
2339 linkedit_file_offset;
2340 DataBufferSP indirect_syms_data_sp(
2341 ReadMemory(process_sp, indirect_syms_addr,
2342 m_dysymtab.nindirectsyms * 4));
2343 if (indirect_syms_data_sp)
2344 indirect_symbol_index_data.SetData(
2345 indirect_syms_data_sp, 0,
2346 indirect_syms_data_sp->GetByteSize());
Jason Molendab0d33e92018-09-06 00:55:27 +00002347 // If this binary is outside the shared cache,
2348 // cache the string table.
2349 // Binaries in the shared cache all share a giant string table, and
2350 // we can't share the string tables across multiple ObjectFileMachO's,
2351 // so we'd end up re-reading this mega-strtab for every binary
2352 // in the shared cache - it would be a big perf problem.
2353 // For binaries outside the shared cache, it's faster to read the
2354 // entire strtab at once instead of piece-by-piece as we process
2355 // the nlist records.
2356 if ((m_header.flags & 0x80000000u) == 0) {
2357 DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr,
2358 strtab_data_byte_size));
2359 if (strtab_data_sp) {
2360 strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
2361 }
2362 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002363 }
Jim Ingham8a5d7a22018-08-15 23:10:32 +00002364 }
2365 if (memory_module_load_level >=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366 eMemoryModuleLoadLevelPartial) {
2367 if (function_starts_load_command.cmd) {
2368 const addr_t func_start_addr =
2369 linkedit_load_addr + function_starts_load_command.dataoff -
2370 linkedit_file_offset;
2371 DataBufferSP func_start_data_sp(
2372 ReadMemory(process_sp, func_start_addr,
2373 function_starts_load_command.datasize));
2374 if (func_start_data_sp)
2375 function_starts_data.SetData(func_start_data_sp, 0,
2376 func_start_data_sp->GetByteSize());
2377 }
2378 }
2379 }
2380 }
2381 } else {
2382 nlist_data.SetData(m_data, symtab_load_command.symoff,
2383 nlist_data_byte_size);
2384 strtab_data.SetData(m_data, symtab_load_command.stroff,
2385 strtab_data_byte_size);
2386
2387 if (dyld_info.export_size > 0) {
2388 dyld_trie_data.SetData(m_data, dyld_info.export_off,
2389 dyld_info.export_size);
2390 }
2391
2392 if (m_dysymtab.nindirectsyms != 0) {
2393 indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2394 m_dysymtab.nindirectsyms * 4);
2395 }
2396 if (function_starts_load_command.cmd) {
2397 function_starts_data.SetData(m_data,
2398 function_starts_load_command.dataoff,
2399 function_starts_load_command.datasize);
2400 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002401 }
2402
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 if (nlist_data.GetByteSize() == 0 &&
2404 memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2405 if (log)
2406 module_sp->LogMessage(log, "failed to read nlist data");
2407 return 0;
2408 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2411 if (!have_strtab_data) {
2412 if (process) {
2413 if (strtab_addr == LLDB_INVALID_ADDRESS) {
2414 if (log)
2415 module_sp->LogMessage(log, "failed to locate the strtab in memory");
2416 return 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002417 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 } else {
2419 if (log)
2420 module_sp->LogMessage(log, "failed to read strtab data");
2421 return 0;
2422 }
2423 }
Greg Clayton9191db42013-10-21 18:40:51 +00002424
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2426 const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2427 const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2428 const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2429 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2430 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2431 SectionSP text_section_sp(
2432 section_list->FindSectionByName(g_segment_name_TEXT));
2433 SectionSP data_section_sp(
2434 section_list->FindSectionByName(g_segment_name_DATA));
2435 SectionSP data_dirty_section_sp(
2436 section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2437 SectionSP data_const_section_sp(
2438 section_list->FindSectionByName(g_segment_name_DATA_CONST));
2439 SectionSP objc_section_sp(
2440 section_list->FindSectionByName(g_segment_name_OBJC));
2441 SectionSP eh_frame_section_sp;
2442 if (text_section_sp.get())
2443 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2444 g_section_name_eh_frame);
2445 else
2446 eh_frame_section_sp =
2447 section_list->FindSectionByName(g_section_name_eh_frame);
Greg Clayton77ccca72011-12-30 00:32:24 +00002448
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
Greg Clayton86eac942013-08-13 21:32:34 +00002450
Kate Stoneb9c1b512016-09-06 20:57:50 +00002451 // lldb works best if it knows the start address of all functions in a
Adrian Prantl05097242018-04-30 16:49:04 +00002452 // module. Linker symbols or debug info are normally the best source of
2453 // information for start addr / size but they may be stripped in a released
2454 // binary. Two additional sources of information exist in Mach-O binaries:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002455 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2456 // function's start address in the
2457 // binary, relative to the text section.
2458 // eh_frame - the eh_frame FDEs have the start addr & size of
2459 // each function
2460 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2461 // all modern binaries.
2462 // Binaries built to run on older releases may need to use eh_frame
2463 // information.
Greg Clayton4c82d422012-05-18 23:20:01 +00002464
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465 if (text_section_sp && function_starts_data.GetByteSize()) {
2466 FunctionStarts::Entry function_start_entry;
2467 function_start_entry.data = false;
2468 lldb::offset_t function_start_offset = 0;
2469 function_start_entry.addr = text_section_sp->GetFileAddress();
2470 uint64_t delta;
2471 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2472 0) {
2473 // Now append the current entry
2474 function_start_entry.addr += delta;
2475 function_starts.Append(function_start_entry);
2476 }
2477 } else {
2478 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
Adrian Prantl05097242018-04-30 16:49:04 +00002479 // load command claiming an eh_frame but it doesn't actually have the
2480 // eh_frame content. And if we have a dSYM, we don't need to do any of
2481 // this fill-in-the-missing-symbols works anyway - the debug info should
2482 // give us all the functions in the module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002483 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2484 m_type != eTypeDebugInfo) {
2485 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
Pavel Labath3f2a0812017-06-28 09:09:19 +00002486 DWARFCallFrameInfo::EH);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002487 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2488 eh_frame.GetFunctionAddressAndSizeVector(functions);
2489 addr_t text_base_addr = text_section_sp->GetFileAddress();
2490 size_t count = functions.GetSize();
2491 for (size_t i = 0; i < count; ++i) {
2492 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2493 functions.GetEntryAtIndex(i);
2494 if (func) {
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002495 FunctionStarts::Entry function_start_entry;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002496 function_start_entry.addr = func->base - text_base_addr;
2497 function_starts.Append(function_start_entry);
2498 }
Jason Molendad63d3c72013-04-16 00:18:44 +00002499 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 }
2501 }
2502
2503 const size_t function_starts_count = function_starts.GetSize();
2504
2505 // For user process binaries (executables, dylibs, frameworks, bundles), if
Adrian Prantl05097242018-04-30 16:49:04 +00002506 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2507 // going to assume the binary has been stripped. Don't allow assembly
2508 // language instruction emulation because we don't know proper function
2509 // start boundaries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002510 //
2511 // For all other types of binaries (kernels, stand-alone bare board
Adrian Prantl05097242018-04-30 16:49:04 +00002512 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2513 // sections - we should not make any assumptions about them based on that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2515 m_allow_assembly_emulation_unwind_plans = false;
2516 Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2517 LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2518
2519 if (unwind_or_symbol_log)
2520 module_sp->LogMessage(
2521 unwind_or_symbol_log,
2522 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2523 }
2524
2525 const user_id_t TEXT_eh_frame_sectID =
2526 eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2527 : static_cast<user_id_t>(NO_SECT);
2528
2529 lldb::offset_t nlist_data_offset = 0;
2530
2531 uint32_t N_SO_index = UINT32_MAX;
2532
2533 MachSymtabSectionInfo section_info(section_list);
2534 std::vector<uint32_t> N_FUN_indexes;
2535 std::vector<uint32_t> N_NSYM_indexes;
2536 std::vector<uint32_t> N_INCL_indexes;
2537 std::vector<uint32_t> N_BRAC_indexes;
2538 std::vector<uint32_t> N_COMM_indexes;
2539 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2540 typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2541 typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2542 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2543 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2544 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00002545 // Any symbols that get merged into another will get an entry in this map
2546 // so we know
Kate Stoneb9c1b512016-09-06 20:57:50 +00002547 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2548 uint32_t nlist_idx = 0;
2549 Symbol *symbol_ptr = NULL;
2550
2551 uint32_t sym_idx = 0;
2552 Symbol *sym = NULL;
2553 size_t num_syms = 0;
2554 std::string memory_symbol_name;
2555 uint32_t unmapped_local_symbols_found = 0;
2556
2557 std::vector<TrieEntryWithOffset> trie_entries;
2558 std::set<lldb::addr_t> resolver_addresses;
2559
2560 if (dyld_trie_data.GetByteSize() > 0) {
2561 std::vector<llvm::StringRef> nameSlices;
2562 ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2563 resolver_addresses, trie_entries);
2564
2565 ConstString text_segment_name("__TEXT");
2566 SectionSP text_segment_sp =
2567 GetSectionList()->FindSectionByName(text_segment_name);
2568 if (text_segment_sp) {
2569 const lldb::addr_t text_segment_file_addr =
2570 text_segment_sp->GetFileAddress();
2571 if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2572 for (auto &e : trie_entries)
2573 e.entry.address += text_segment_file_addr;
2574 }
2575 }
2576 }
2577
2578 typedef std::set<ConstString> IndirectSymbols;
2579 IndirectSymbols indirect_symbol_names;
2580
2581#if defined(__APPLE__) && \
2582 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2583
2584 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
Adrian Prantl05097242018-04-30 16:49:04 +00002585 // optimized by moving LOCAL symbols out of the memory mapped portion of
2586 // the DSC. The symbol information has all been retained, but it isn't
2587 // available in the normal nlist data. However, there *are* duplicate
2588 // entries of *some*
Kate Stoneb9c1b512016-09-06 20:57:50 +00002589 // LOCAL symbols in the normal nlist data. To handle this situation
2590 // correctly, we must first attempt
2591 // to parse any DSC unmapped symbol information. If we find any, we set a
Adrian Prantl05097242018-04-30 16:49:04 +00002592 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593
2594 if (m_header.flags & 0x80000000u) {
Adrian Prantl05097242018-04-30 16:49:04 +00002595 // Before we can start mapping the DSC, we need to make certain the
2596 // target process is actually using the cache we can find.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002597
2598 // Next we need to determine the correct path for the dyld shared cache.
2599
2600 ArchSpec header_arch;
2601 GetArchitecture(header_arch);
2602 char dsc_path[PATH_MAX];
2603 char dsc_path_development[PATH_MAX];
2604
2605 snprintf(
2606 dsc_path, sizeof(dsc_path), "%s%s%s",
2607 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2608 */
2609 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2610 header_arch.GetArchitectureName());
2611
2612 snprintf(
2613 dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2614 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2615 */
2616 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
Ilia K4f730dc2016-09-12 05:25:33 +00002617 header_arch.GetArchitectureName(), ".development");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002618
2619 FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2620 FileSpec dsc_development_filespec(dsc_path_development, false);
2621 FileSpec dsc_filespec;
2622
2623 UUID dsc_uuid;
2624 UUID process_shared_cache_uuid;
Jason Molenda07580ff2018-05-04 00:59:37 +00002625 addr_t process_shared_cache_base_addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002626
2627 if (process) {
Jason Molenda07580ff2018-05-04 00:59:37 +00002628 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, process_shared_cache_uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629 }
2630
Adrian Prantl05097242018-04-30 16:49:04 +00002631 // First see if we can find an exact match for the inferior process
2632 // shared cache UUID in the development or non-development shared caches
2633 // on disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634 if (process_shared_cache_uuid.IsValid()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002635 if (FileSystem::Instance().Exists(dsc_development_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002636 UUID dsc_development_uuid = GetSharedCacheUUID(
2637 dsc_development_filespec, byte_order, addr_byte_size);
2638 if (dsc_development_uuid.IsValid() &&
2639 dsc_development_uuid == process_shared_cache_uuid) {
2640 dsc_filespec = dsc_development_filespec;
2641 dsc_uuid = dsc_development_uuid;
2642 }
2643 }
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002644 if (!dsc_uuid.IsValid() &&
2645 FileSystem::Instance().Exists(dsc_nondevelopment_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002646 UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2647 dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2648 if (dsc_nondevelopment_uuid.IsValid() &&
2649 dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2650 dsc_filespec = dsc_nondevelopment_filespec;
2651 dsc_uuid = dsc_nondevelopment_uuid;
2652 }
2653 }
2654 }
2655
2656 // Failing a UUID match, prefer the development dyld_shared cache if both
2657 // are present.
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002658 if (!FileSystem::Instance().Exists(dsc_filespec)) {
2659 if (FileSystem::Instance().Exists(dsc_development_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002660 dsc_filespec = dsc_development_filespec;
2661 } else {
2662 dsc_filespec = dsc_nondevelopment_filespec;
2663 }
2664 }
2665
2666 /* The dyld_cache_header has a pointer to the
2667 dyld_cache_local_symbols_info structure (localSymbolsOffset).
2668 The dyld_cache_local_symbols_info structure gives us three things:
2669 1. The start and count of the nlist records in the dyld_shared_cache
2670 file
2671 2. The start and size of the strings for these nlist records
2672 3. The start and count of dyld_cache_local_symbols_entry entries
2673
2674 There is one dyld_cache_local_symbols_entry per dylib/framework in the
2675 dyld shared cache.
2676 The "dylibOffset" field is the Mach-O header of this dylib/framework in
2677 the dyld shared cache.
2678 The dyld_cache_local_symbols_entry also lists the start of this
2679 dylib/framework's nlist records
2680 and the count of how many nlist records there are for this
2681 dylib/framework.
2682 */
2683
2684 // Process the dyld shared cache header to find the unmapped symbols
2685
Pavel Labath50251fc2017-12-21 10:54:30 +00002686 DataBufferSP dsc_data_sp = MapFileData(
2687 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002688 if (!dsc_uuid.IsValid()) {
2689 dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2690 }
2691 if (dsc_data_sp) {
2692 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2693
2694 bool uuid_match = true;
2695 if (dsc_uuid.IsValid() && process) {
2696 if (process_shared_cache_uuid.IsValid() &&
2697 dsc_uuid != process_shared_cache_uuid) {
2698 // The on-disk dyld_shared_cache file is not the same as the one in
Adrian Prantl05097242018-04-30 16:49:04 +00002699 // this process' memory, don't use it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002700 uuid_match = false;
2701 ModuleSP module_sp(GetModule());
2702 if (module_sp)
2703 module_sp->ReportWarning("process shared cache does not match "
2704 "on-disk dyld_shared_cache file, some "
2705 "symbol names will be missing.");
2706 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002707 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00002708
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002710
Kate Stoneb9c1b512016-09-06 20:57:50 +00002711 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
Jason Molenda955dcf22016-05-04 03:09:40 +00002712
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 // If the mappingOffset points to a location inside the header, we've
2714 // opened an old dyld shared cache, and should not proceed further.
2715 if (uuid_match &&
2716 mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
Jason Molenda955dcf22016-05-04 03:09:40 +00002717
Pavel Labath50251fc2017-12-21 10:54:30 +00002718 DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2719 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2720 mappingOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002721
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2723 byte_order, addr_byte_size);
2724 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002725
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726 // The File addresses (from the in-memory Mach-O load commands) for
Adrian Prantl05097242018-04-30 16:49:04 +00002727 // the shared libraries in the shared library cache need to be
2728 // adjusted by an offset to match up with the dylibOffset identifying
2729 // field in the dyld_cache_local_symbol_entry's. This offset is
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 // recorded in mapping_offset_value.
2731 const uint64_t mapping_offset_value =
2732 dsc_mapping_info_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002733
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2735 localSymbolsOffset);
2736 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2737 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002738
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739 if (localSymbolsOffset && localSymbolsSize) {
2740 // Map the local symbols
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002741 DataBufferSP dsc_local_symbols_data_sp =
Pavel Labath50251fc2017-12-21 10:54:30 +00002742 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002743
2744 if (dsc_local_symbols_data_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2746 byte_order, addr_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002747
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002749
Kate Stoneb9c1b512016-09-06 20:57:50 +00002750 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2751 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2752 UndefinedNameToDescMap undefined_name_to_desc;
2753 SymbolIndexToName reexport_shlib_needs_fixup;
Jim Inghamea3ac272014-01-10 22:55:37 +00002754
Kate Stoneb9c1b512016-09-06 20:57:50 +00002755 // Read the local_symbols_infos struct in one shot
2756 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2757 dsc_local_symbols_data.GetU32(&offset,
2758 &local_symbols_info.nlistOffset, 6);
Jim Inghamea3ac272014-01-10 22:55:37 +00002759
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 SectionSP text_section_sp(
2761 section_list->FindSectionByName(GetSegmentNameTEXT()));
Greg Claytonb65c6292015-02-20 22:20:05 +00002762
Kate Stoneb9c1b512016-09-06 20:57:50 +00002763 uint32_t header_file_offset =
2764 (text_section_sp->GetFileAddress() - mapping_offset_value);
Jason Molendaa5609c82012-06-21 01:51:02 +00002765
Kate Stoneb9c1b512016-09-06 20:57:50 +00002766 offset = local_symbols_info.entriesOffset;
2767 for (uint32_t entry_index = 0;
2768 entry_index < local_symbols_info.entriesCount;
2769 entry_index++) {
2770 struct lldb_copy_dyld_cache_local_symbols_entry
2771 local_symbols_entry;
2772 local_symbols_entry.dylibOffset =
2773 dsc_local_symbols_data.GetU32(&offset);
2774 local_symbols_entry.nlistStartIndex =
2775 dsc_local_symbols_data.GetU32(&offset);
2776 local_symbols_entry.nlistCount =
2777 dsc_local_symbols_data.GetU32(&offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002778
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 if (header_file_offset == local_symbols_entry.dylibOffset) {
2780 unmapped_local_symbols_found = local_symbols_entry.nlistCount;
Jason Molendaa5609c82012-06-21 01:51:02 +00002781
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 // The normal nlist code cannot correctly size the Symbols
2783 // array, we need to allocate it here.
2784 sym = symtab->Resize(
2785 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2786 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2787 num_syms = symtab->GetNumSymbols();
Jason Molendaa5609c82012-06-21 01:51:02 +00002788
Kate Stoneb9c1b512016-09-06 20:57:50 +00002789 nlist_data_offset =
2790 local_symbols_info.nlistOffset +
2791 (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2792 uint32_t string_table_offset =
2793 local_symbols_info.stringsOffset;
Jason Molendaa5609c82012-06-21 01:51:02 +00002794
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 for (uint32_t nlist_index = 0;
2796 nlist_index < local_symbols_entry.nlistCount;
2797 nlist_index++) {
2798 /////////////////////////////
Jason Molenda649a6072015-11-10 05:21:54 +00002799 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 struct nlist_64 nlist;
2801 if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(
2802 nlist_data_offset, nlist_byte_size))
2803 break;
Eugene Zelenko8157a882015-10-23 16:56:07 +00002804
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(
2806 &nlist_data_offset);
2807 nlist.n_type = dsc_local_symbols_data.GetU8_unchecked(
2808 &nlist_data_offset);
2809 nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked(
2810 &nlist_data_offset);
2811 nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked(
2812 &nlist_data_offset);
2813 nlist.n_value =
2814 dsc_local_symbols_data.GetAddress_unchecked(
2815 &nlist_data_offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002816
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 SymbolType type = eSymbolTypeInvalid;
2818 const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2819 string_table_offset + nlist.n_strx);
Jason Molendaf8130862012-06-22 03:28:35 +00002820
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002822 // No symbol should be NULL, even the symbols with no
Adrian Prantl05097242018-04-30 16:49:04 +00002823 // string values should have an offset zero which
2824 // points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00002825 Host::SystemLog(
2826 Host::eSystemLogError,
2827 "error: DSC unmapped local symbol[%u] has invalid "
2828 "string table offset 0x%x in %s, ignoring symbol\n",
2829 entry_index, nlist.n_strx,
2830 module_sp->GetFileSpec().GetPath().c_str());
Greg Claytonfd814c52013-08-13 01:42:25 +00002831 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832 }
2833 if (symbol_name[0] == '\0')
Greg Claytonfd814c52013-08-13 01:42:25 +00002834 symbol_name = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002835
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836 const char *symbol_name_non_abi_mangled = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002837
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 SectionSP symbol_section;
2839 uint32_t symbol_byte_size = 0;
2840 bool add_nlist = true;
2841 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2842 bool demangled_is_synthesized = false;
2843 bool is_gsym = false;
2844 bool set_value = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00002845
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 assert(sym_idx < num_syms);
Jason Molenda4e7511e2013-03-06 23:19:17 +00002847
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 sym[sym_idx].SetDebug(is_debug);
Greg Clayton29e08cb2012-03-14 01:53:24 +00002849
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 if (is_debug) {
2851 switch (nlist.n_type) {
2852 case N_GSYM:
2853 // global symbol: name,,NO_SECT,type,0
2854 // Sometimes the N_GSYM value contains the address.
2855
2856 // FIXME: In the .o files, we have a GSYM and a debug
2857 // symbol for all the ObjC data. They
2858 // have the same address, but we want to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +00002859 // we always find only the real symbol, 'cause we
2860 // don't currently correctly attribute the
Kate Stoneb9c1b512016-09-06 20:57:50 +00002861 // GSYM one to the ObjCClass/Ivar/MetaClass
Adrian Prantl05097242018-04-30 16:49:04 +00002862 // symbol type. This is a temporary hack to make
2863 // sure the ObjectiveC symbols get treated correctly.
2864 // To do this right, we should coalesce all the GSYM
2865 // & global symbols that have the same address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866
2867 is_gsym = true;
2868 sym[sym_idx].SetExternal(true);
2869
2870 if (symbol_name && symbol_name[0] == '_' &&
2871 symbol_name[1] == 'O') {
Greg Clayton1e28adf2015-02-25 17:25:02 +00002872 llvm::StringRef symbol_name_ref(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002873 if (symbol_name_ref.startswith(
2874 g_objc_v2_prefix_class)) {
2875 symbol_name_non_abi_mangled = symbol_name + 1;
2876 symbol_name =
2877 symbol_name + g_objc_v2_prefix_class.size();
2878 type = eSymbolTypeObjCClass;
2879 demangled_is_synthesized = true;
2880
2881 } else if (symbol_name_ref.startswith(
2882 g_objc_v2_prefix_metaclass)) {
2883 symbol_name_non_abi_mangled = symbol_name + 1;
2884 symbol_name = symbol_name +
2885 g_objc_v2_prefix_metaclass.size();
2886 type = eSymbolTypeObjCMetaClass;
2887 demangled_is_synthesized = true;
2888 } else if (symbol_name_ref.startswith(
2889 g_objc_v2_prefix_ivar)) {
2890 symbol_name_non_abi_mangled = symbol_name + 1;
2891 symbol_name =
2892 symbol_name + g_objc_v2_prefix_ivar.size();
2893 type = eSymbolTypeObjCIVar;
2894 demangled_is_synthesized = true;
Greg Clayton1e28adf2015-02-25 17:25:02 +00002895 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002897 if (nlist.n_value != 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898 symbol_section = section_info.GetSection(
2899 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002900 type = eSymbolTypeData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 }
2902 break;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002903
Kate Stoneb9c1b512016-09-06 20:57:50 +00002904 case N_FNAME:
2905 // procedure name (f77 kludge): name,,NO_SECT,0,0
2906 type = eSymbolTypeCompiler;
2907 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002908
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909 case N_FUN:
2910 // procedure: name,,n_sect,linenumber,address
2911 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002912 type = eSymbolTypeCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 symbol_section = section_info.GetSection(
2914 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002915
Kate Stoneb9c1b512016-09-06 20:57:50 +00002916 N_FUN_addr_to_sym_idx.insert(
2917 std::make_pair(nlist.n_value, sym_idx));
2918 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00002919 // symbol table in lieu of using nlist_idx in case
2920 // we ever start trimming entries out
Greg Claytonfd814c52013-08-13 01:42:25 +00002921 N_FUN_indexes.push_back(sym_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002922 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002923 type = eSymbolTypeCompiler;
2924
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00002926 // Copy the size of the function into the
2927 // original
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 // STAB entry so we don't have
2929 // to hunt for it later
2930 symtab->SymbolAtIndex(N_FUN_indexes.back())
2931 ->SetByteSize(nlist.n_value);
2932 N_FUN_indexes.pop_back();
2933 // We don't really need the end function STAB as
Adrian Prantl05097242018-04-30 16:49:04 +00002934 // it contains the size which we already placed
2935 // with the original symbol, so don't add it if
2936 // we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 add_nlist = false;
Greg Claytondacc4a92013-05-14 22:19:37 +00002938 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 }
2940 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002941
Kate Stoneb9c1b512016-09-06 20:57:50 +00002942 case N_STSYM:
2943 // static symbol: name,,n_sect,type,address
2944 N_STSYM_addr_to_sym_idx.insert(
2945 std::make_pair(nlist.n_value, sym_idx));
2946 symbol_section = section_info.GetSection(
2947 nlist.n_sect, nlist.n_value);
2948 if (symbol_name && symbol_name[0]) {
2949 type = ObjectFile::GetSymbolTypeFromName(
2950 symbol_name + 1, eSymbolTypeData);
2951 }
2952 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002953
Kate Stoneb9c1b512016-09-06 20:57:50 +00002954 case N_LCSYM:
2955 // .lcomm symbol: name,,n_sect,type,address
2956 symbol_section = section_info.GetSection(
2957 nlist.n_sect, nlist.n_value);
2958 type = eSymbolTypeCommonBlock;
2959 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002960
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961 case N_BNSYM:
2962 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00002963 // table in lieu of using nlist_idx in case we ever
2964 // start trimming entries out Skip these if we want
2965 // minimal symbol tables
Kate Stoneb9c1b512016-09-06 20:57:50 +00002966 add_nlist = false;
2967 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002968
Kate Stoneb9c1b512016-09-06 20:57:50 +00002969 case N_ENSYM:
2970 // Set the size of the N_BNSYM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002971 // index of this N_ENSYM so that we can always skip
2972 // the entire symbol if we need to navigate more
2973 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974 // Skip these if we want minimal symbol tables
2975 add_nlist = false;
2976 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002977
Kate Stoneb9c1b512016-09-06 20:57:50 +00002978 case N_OPT:
2979 // emitted with gcc2_compiled and in gcc source
2980 type = eSymbolTypeCompiler;
2981 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002982
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983 case N_RSYM:
2984 // register sym: name,,NO_SECT,type,register
2985 type = eSymbolTypeVariable;
2986 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002987
Kate Stoneb9c1b512016-09-06 20:57:50 +00002988 case N_SLINE:
2989 // src line: 0,,n_sect,linenumber,address
2990 symbol_section = section_info.GetSection(
2991 nlist.n_sect, nlist.n_value);
2992 type = eSymbolTypeLineEntry;
2993 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002994
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 case N_SSYM:
2996 // structure elt: name,,NO_SECT,type,struct_offset
2997 type = eSymbolTypeVariableType;
2998 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002999
Kate Stoneb9c1b512016-09-06 20:57:50 +00003000 case N_SO:
3001 // source file name
3002 type = eSymbolTypeSourceFile;
3003 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003004 add_nlist = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005 if (N_SO_index != UINT32_MAX) {
3006 // Set the size of the N_SO to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003007 // index of this N_SO so that we can always skip
3008 // the entire N_SO if we need to navigate more
3009 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3011 symbol_ptr->SetByteSize(sym_idx);
3012 symbol_ptr->SetSizeIsSibling(true);
Greg Claytonfd814c52013-08-13 01:42:25 +00003013 }
3014 N_NSYM_indexes.clear();
3015 N_INCL_indexes.clear();
3016 N_BRAC_indexes.clear();
3017 N_COMM_indexes.clear();
3018 N_FUN_indexes.clear();
3019 N_SO_index = UINT32_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003020 } else {
3021 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00003022 // symbol table in lieu of using nlist_idx in case
3023 // we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003024 const bool N_SO_has_full_path =
3025 symbol_name[0] == '/';
3026 if (N_SO_has_full_path) {
3027 if ((N_SO_index == sym_idx - 1) &&
3028 ((sym_idx - 1) < num_syms)) {
3029 // We have two consecutive N_SO entries where
Adrian Prantl05097242018-04-30 16:49:04 +00003030 // the first contains a directory and the
3031 // second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 sym[sym_idx - 1].GetMangled().SetValue(
3033 ConstString(symbol_name), false);
3034 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3035 add_nlist = false;
3036 } else {
3037 // This is the first entry in a N_SO that
3038 // contains a directory or
3039 // a full path to the source file
Greg Claytonfd814c52013-08-13 01:42:25 +00003040 N_SO_index = sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041 }
3042 } else if ((N_SO_index == sym_idx - 1) &&
3043 ((sym_idx - 1) < num_syms)) {
3044 // This is usually the second N_SO entry that
Adrian Prantl05097242018-04-30 16:49:04 +00003045 // contains just the filename, so here we combine
3046 // it with the first one if we are minimizing the
3047 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 const char *so_path =
3049 sym[sym_idx - 1]
3050 .GetMangled()
3051 .GetDemangledName(
3052 lldb::eLanguageTypeUnknown)
3053 .AsCString();
3054 if (so_path && so_path[0]) {
3055 std::string full_so_path(so_path);
3056 const size_t double_slash_pos =
3057 full_so_path.find("//");
3058 if (double_slash_pos != std::string::npos) {
3059 // The linker has been generating bad N_SO
3060 // entries with doubled up paths
Adrian Prantl05097242018-04-30 16:49:04 +00003061 // in the format "%s%s" where the first
3062 // string in the DW_AT_comp_dir, and the
3063 // second is the directory for the source
3064 // file so you end up with a path that looks
3065 // like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066 FileSpec so_dir(so_path, false);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00003067 if (!FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068 so_dir.SetFile(
3069 &full_so_path[double_slash_pos + 1],
3070 false);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00003071 if (FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003072 // Trim off the incorrect path
3073 full_so_path.erase(0,
3074 double_slash_pos + 1);
3075 }
3076 }
3077 }
3078 if (*full_so_path.rbegin() != '/')
3079 full_so_path += '/';
3080 full_so_path += symbol_name;
3081 sym[sym_idx - 1].GetMangled().SetValue(
3082 ConstString(full_so_path.c_str()), false);
3083 add_nlist = false;
3084 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3085 }
3086 } else {
3087 // This could be a relative path to a N_SO
3088 N_SO_index = sym_idx;
Greg Claytonfd814c52013-08-13 01:42:25 +00003089 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090 }
3091 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003092
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 case N_OSO:
3094 // object file name: name,,0,0,st_mtime
3095 type = eSymbolTypeObjectFile;
3096 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003097
Kate Stoneb9c1b512016-09-06 20:57:50 +00003098 case N_LSYM:
3099 // local sym: name,,NO_SECT,type,offset
3100 type = eSymbolTypeLocal;
3101 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003102
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103 //----------------------------------------------------------------------
3104 // INCL scopes
3105 //----------------------------------------------------------------------
3106 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00003107 // include file beginning: name,,NO_SECT,0,sum We use
3108 // the current number of symbols in the symbol table
3109 // in lieu of using nlist_idx in case we ever start
3110 // trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003111 N_INCL_indexes.push_back(sym_idx);
3112 type = eSymbolTypeScopeBegin;
3113 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003114
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 case N_EINCL:
3116 // include file end: name,,NO_SECT,0,0
3117 // Set the size of the N_BINCL to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003118 // index of this N_EINCL so that we can always skip
3119 // the entire symbol if we need to navigate more
3120 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121 if (!N_INCL_indexes.empty()) {
3122 symbol_ptr =
3123 symtab->SymbolAtIndex(N_INCL_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003124 symbol_ptr->SetByteSize(sym_idx + 1);
3125 symbol_ptr->SetSizeIsSibling(true);
3126 N_INCL_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003127 }
3128 type = eSymbolTypeScopeEnd;
3129 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003130
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131 case N_SOL:
3132 // #included file name: name,,n_sect,0,address
3133 type = eSymbolTypeHeaderFile;
Greg Claytonfd814c52013-08-13 01:42:25 +00003134
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135 // We currently don't use the header files on darwin
3136 add_nlist = false;
3137 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003138
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 case N_PARAMS:
3140 // compiler parameters: name,,NO_SECT,0,0
3141 type = eSymbolTypeCompiler;
3142 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003143
Kate Stoneb9c1b512016-09-06 20:57:50 +00003144 case N_VERSION:
3145 // compiler version: name,,NO_SECT,0,0
3146 type = eSymbolTypeCompiler;
3147 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003148
Kate Stoneb9c1b512016-09-06 20:57:50 +00003149 case N_OLEVEL:
3150 // compiler -O level: name,,NO_SECT,0,0
3151 type = eSymbolTypeCompiler;
3152 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003153
Kate Stoneb9c1b512016-09-06 20:57:50 +00003154 case N_PSYM:
3155 // parameter: name,,NO_SECT,type,offset
3156 type = eSymbolTypeVariable;
3157 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003158
Kate Stoneb9c1b512016-09-06 20:57:50 +00003159 case N_ENTRY:
3160 // alternate entry: name,,n_sect,linenumber,address
3161 symbol_section = section_info.GetSection(
3162 nlist.n_sect, nlist.n_value);
3163 type = eSymbolTypeLineEntry;
3164 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003165
Kate Stoneb9c1b512016-09-06 20:57:50 +00003166 //----------------------------------------------------------------------
3167 // Left and Right Braces
3168 //----------------------------------------------------------------------
3169 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00003170 // left bracket: 0,,NO_SECT,nesting level,address We
3171 // use the current number of symbols in the symbol
3172 // table in lieu of using nlist_idx in case we ever
3173 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003174 symbol_section = section_info.GetSection(
3175 nlist.n_sect, nlist.n_value);
3176 N_BRAC_indexes.push_back(sym_idx);
3177 type = eSymbolTypeScopeBegin;
3178 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003179
Kate Stoneb9c1b512016-09-06 20:57:50 +00003180 case N_RBRAC:
3181 // right bracket: 0,,NO_SECT,nesting level,address
3182 // Set the size of the N_LBRAC to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003183 // index of this N_RBRAC so that we can always skip
3184 // the entire symbol if we need to navigate more
3185 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003186 symbol_section = section_info.GetSection(
3187 nlist.n_sect, nlist.n_value);
3188 if (!N_BRAC_indexes.empty()) {
3189 symbol_ptr =
3190 symtab->SymbolAtIndex(N_BRAC_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003191 symbol_ptr->SetByteSize(sym_idx + 1);
3192 symbol_ptr->SetSizeIsSibling(true);
3193 N_BRAC_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003194 }
3195 type = eSymbolTypeScopeEnd;
3196 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003197
Kate Stoneb9c1b512016-09-06 20:57:50 +00003198 case N_EXCL:
3199 // deleted include file: name,,NO_SECT,0,sum
3200 type = eSymbolTypeHeaderFile;
3201 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003202
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 //----------------------------------------------------------------------
3204 // COMM scopes
3205 //----------------------------------------------------------------------
3206 case N_BCOMM:
3207 // begin common: name,,NO_SECT,0,0
3208 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00003209 // table in lieu of using nlist_idx in case we ever
3210 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003211 type = eSymbolTypeScopeBegin;
3212 N_COMM_indexes.push_back(sym_idx);
3213 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003214
Kate Stoneb9c1b512016-09-06 20:57:50 +00003215 case N_ECOML:
3216 // end common (local name): 0,,n_sect,0,address
3217 symbol_section = section_info.GetSection(
3218 nlist.n_sect, nlist.n_value);
3219 // Fall through
Greg Claytonfd814c52013-08-13 01:42:25 +00003220
Kate Stoneb9c1b512016-09-06 20:57:50 +00003221 case N_ECOMM:
3222 // end common: name,,n_sect,0,0
3223 // Set the size of the N_BCOMM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003224 // index of this N_ECOMM/N_ECOML so that we can
3225 // always skip the entire symbol if we need to
3226 // navigate more quickly at the source level when
3227 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228 if (!N_COMM_indexes.empty()) {
3229 symbol_ptr =
3230 symtab->SymbolAtIndex(N_COMM_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003231 symbol_ptr->SetByteSize(sym_idx + 1);
3232 symbol_ptr->SetSizeIsSibling(true);
3233 N_COMM_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003234 }
3235 type = eSymbolTypeScopeEnd;
3236 break;
3237
3238 case N_LENG:
3239 // second stab entry with length information
3240 type = eSymbolTypeAdditional;
3241 break;
3242
3243 default:
3244 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003245 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003246 } else {
3247 // uint8_t n_pext = N_PEXT & nlist.n_type;
3248 uint8_t n_type = N_TYPE & nlist.n_type;
3249 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
Greg Claytonfd814c52013-08-13 01:42:25 +00003250
Kate Stoneb9c1b512016-09-06 20:57:50 +00003251 switch (n_type) {
3252 case N_INDR: {
3253 const char *reexport_name_cstr =
3254 strtab_data.PeekCStr(nlist.n_value);
3255 if (reexport_name_cstr && reexport_name_cstr[0]) {
3256 type = eSymbolTypeReExported;
3257 ConstString reexport_name(
3258 reexport_name_cstr +
3259 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3260 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3261 set_value = false;
3262 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3263 indirect_symbol_names.insert(
3264 ConstString(symbol_name +
3265 ((symbol_name[0] == '_') ? 1 : 0)));
3266 } else
3267 type = eSymbolTypeUndefined;
3268 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003269
Kate Stoneb9c1b512016-09-06 20:57:50 +00003270 case N_UNDF:
3271 if (symbol_name && symbol_name[0]) {
3272 ConstString undefined_name(
3273 symbol_name +
3274 ((symbol_name[0] == '_') ? 1 : 0));
3275 undefined_name_to_desc[undefined_name] =
3276 nlist.n_desc;
3277 }
3278 // Fall through
3279 case N_PBUD:
3280 type = eSymbolTypeUndefined;
3281 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003282
Kate Stoneb9c1b512016-09-06 20:57:50 +00003283 case N_ABS:
3284 type = eSymbolTypeAbsolute;
3285 break;
Greg Clayton60038be2015-02-14 00:51:13 +00003286
Kate Stoneb9c1b512016-09-06 20:57:50 +00003287 case N_SECT: {
3288 symbol_section = section_info.GetSection(
3289 nlist.n_sect, nlist.n_value);
Jason Molenda62e06812016-02-16 04:14:33 +00003290
Kate Stoneb9c1b512016-09-06 20:57:50 +00003291 if (symbol_section == NULL) {
3292 // TODO: warn about this?
3293 add_nlist = false;
3294 break;
3295 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003296
Kate Stoneb9c1b512016-09-06 20:57:50 +00003297 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3298 type = eSymbolTypeException;
3299 } else {
3300 uint32_t section_type =
3301 symbol_section->Get() & SECTION_TYPE;
Greg Claytonfd814c52013-08-13 01:42:25 +00003302
Kate Stoneb9c1b512016-09-06 20:57:50 +00003303 switch (section_type) {
3304 case S_CSTRING_LITERALS:
3305 type = eSymbolTypeData;
3306 break; // section with only literal C strings
3307 case S_4BYTE_LITERALS:
3308 type = eSymbolTypeData;
3309 break; // section with only 4 byte literals
3310 case S_8BYTE_LITERALS:
3311 type = eSymbolTypeData;
3312 break; // section with only 8 byte literals
3313 case S_LITERAL_POINTERS:
3314 type = eSymbolTypeTrampoline;
3315 break; // section with only pointers to literals
3316 case S_NON_LAZY_SYMBOL_POINTERS:
3317 type = eSymbolTypeTrampoline;
3318 break; // section with only non-lazy symbol
3319 // pointers
3320 case S_LAZY_SYMBOL_POINTERS:
3321 type = eSymbolTypeTrampoline;
3322 break; // section with only lazy symbol pointers
3323 case S_SYMBOL_STUBS:
3324 type = eSymbolTypeTrampoline;
3325 break; // section with only symbol stubs, byte
3326 // size of stub in the reserved2 field
3327 case S_MOD_INIT_FUNC_POINTERS:
3328 type = eSymbolTypeCode;
3329 break; // section with only function pointers for
3330 // initialization
3331 case S_MOD_TERM_FUNC_POINTERS:
3332 type = eSymbolTypeCode;
3333 break; // section with only function pointers for
3334 // termination
3335 case S_INTERPOSING:
3336 type = eSymbolTypeTrampoline;
3337 break; // section with only pairs of function
3338 // pointers for interposing
3339 case S_16BYTE_LITERALS:
3340 type = eSymbolTypeData;
3341 break; // section with only 16 byte literals
3342 case S_DTRACE_DOF:
3343 type = eSymbolTypeInstrumentation;
3344 break;
3345 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3346 type = eSymbolTypeTrampoline;
3347 break;
3348 default:
3349 switch (symbol_section->GetType()) {
3350 case lldb::eSectionTypeCode:
3351 type = eSymbolTypeCode;
Greg Claytonfd814c52013-08-13 01:42:25 +00003352 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003353 case eSectionTypeData:
3354 case eSectionTypeDataCString: // Inlined C string
3355 // data
3356 case eSectionTypeDataCStringPointers: // Pointers
3357 // to C
3358 // string
3359 // data
3360 case eSectionTypeDataSymbolAddress: // Address of
3361 // a symbol in
3362 // the symbol
3363 // table
3364 case eSectionTypeData4:
3365 case eSectionTypeData8:
3366 case eSectionTypeData16:
3367 type = eSymbolTypeData;
3368 break;
3369 default:
3370 break;
3371 }
3372 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003373 }
3374
Kate Stoneb9c1b512016-09-06 20:57:50 +00003375 if (type == eSymbolTypeInvalid) {
3376 const char *symbol_sect_name =
3377 symbol_section->GetName().AsCString();
3378 if (symbol_section->IsDescendant(
3379 text_section_sp.get())) {
3380 if (symbol_section->IsClear(
3381 S_ATTR_PURE_INSTRUCTIONS |
3382 S_ATTR_SELF_MODIFYING_CODE |
3383 S_ATTR_SOME_INSTRUCTIONS))
3384 type = eSymbolTypeData;
3385 else
3386 type = eSymbolTypeCode;
3387 } else if (symbol_section->IsDescendant(
3388 data_section_sp.get()) ||
3389 symbol_section->IsDescendant(
3390 data_dirty_section_sp.get()) ||
3391 symbol_section->IsDescendant(
3392 data_const_section_sp.get())) {
3393 if (symbol_sect_name &&
3394 ::strstr(symbol_sect_name, "__objc") ==
3395 symbol_sect_name) {
3396 type = eSymbolTypeRuntime;
Greg Claytonfd814c52013-08-13 01:42:25 +00003397
Kate Stoneb9c1b512016-09-06 20:57:50 +00003398 if (symbol_name) {
3399 llvm::StringRef symbol_name_ref(
3400 symbol_name);
3401 if (symbol_name_ref.startswith("_OBJC_")) {
3402 static const llvm::StringRef
3403 g_objc_v2_prefix_class(
3404 "_OBJC_CLASS_$_");
3405 static const llvm::StringRef
3406 g_objc_v2_prefix_metaclass(
3407 "_OBJC_METACLASS_$_");
3408 static const llvm::StringRef
3409 g_objc_v2_prefix_ivar(
3410 "_OBJC_IVAR_$_");
3411 if (symbol_name_ref.startswith(
3412 g_objc_v2_prefix_class)) {
3413 symbol_name_non_abi_mangled =
3414 symbol_name + 1;
3415 symbol_name =
3416 symbol_name +
3417 g_objc_v2_prefix_class.size();
3418 type = eSymbolTypeObjCClass;
3419 demangled_is_synthesized = true;
3420 } else if (
3421 symbol_name_ref.startswith(
3422 g_objc_v2_prefix_metaclass)) {
3423 symbol_name_non_abi_mangled =
3424 symbol_name + 1;
3425 symbol_name =
3426 symbol_name +
3427 g_objc_v2_prefix_metaclass.size();
3428 type = eSymbolTypeObjCMetaClass;
3429 demangled_is_synthesized = true;
3430 } else if (symbol_name_ref.startswith(
3431 g_objc_v2_prefix_ivar)) {
3432 symbol_name_non_abi_mangled =
3433 symbol_name + 1;
3434 symbol_name =
3435 symbol_name +
3436 g_objc_v2_prefix_ivar.size();
3437 type = eSymbolTypeObjCIVar;
3438 demangled_is_synthesized = true;
3439 }
Greg Clayton38f9cc42014-06-16 22:53:16 +00003440 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003441 }
3442 } else if (symbol_sect_name &&
3443 ::strstr(symbol_sect_name,
3444 "__gcc_except_tab") ==
3445 symbol_sect_name) {
3446 type = eSymbolTypeException;
3447 } else {
3448 type = eSymbolTypeData;
Greg Claytonfd814c52013-08-13 01:42:25 +00003449 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003450 } else if (symbol_sect_name &&
3451 ::strstr(symbol_sect_name,
3452 "__IMPORT") ==
3453 symbol_sect_name) {
3454 type = eSymbolTypeTrampoline;
3455 } else if (symbol_section->IsDescendant(
3456 objc_section_sp.get())) {
3457 type = eSymbolTypeRuntime;
3458 if (symbol_name && symbol_name[0] == '.') {
3459 llvm::StringRef symbol_name_ref(symbol_name);
3460 static const llvm::StringRef
3461 g_objc_v1_prefix_class(
3462 ".objc_class_name_");
3463 if (symbol_name_ref.startswith(
3464 g_objc_v1_prefix_class)) {
3465 symbol_name_non_abi_mangled = symbol_name;
3466 symbol_name = symbol_name +
3467 g_objc_v1_prefix_class.size();
3468 type = eSymbolTypeObjCClass;
3469 demangled_is_synthesized = true;
3470 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003471 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003472 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003473 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003474 }
3475 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003476 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003477 }
Greg Claytondacc4a92013-05-14 22:19:37 +00003478
Kate Stoneb9c1b512016-09-06 20:57:50 +00003479 if (add_nlist) {
3480 uint64_t symbol_value = nlist.n_value;
3481 if (symbol_name_non_abi_mangled) {
3482 sym[sym_idx].GetMangled().SetMangledName(
3483 ConstString(symbol_name_non_abi_mangled));
3484 sym[sym_idx].GetMangled().SetDemangledName(
3485 ConstString(symbol_name));
3486 } else {
3487 bool symbol_name_is_mangled = false;
Greg Claytonfd814c52013-08-13 01:42:25 +00003488
Kate Stoneb9c1b512016-09-06 20:57:50 +00003489 if (symbol_name && symbol_name[0] == '_') {
Greg Claytonfd814c52013-08-13 01:42:25 +00003490 symbol_name_is_mangled = symbol_name[1] == '_';
Kate Stoneb9c1b512016-09-06 20:57:50 +00003491 symbol_name++; // Skip the leading underscore
3492 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003493
Kate Stoneb9c1b512016-09-06 20:57:50 +00003494 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003495 ConstString const_symbol_name(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003496 sym[sym_idx].GetMangled().SetValue(
3497 const_symbol_name, symbol_name_is_mangled);
3498 if (is_gsym && is_debug) {
3499 const char *gsym_name =
3500 sym[sym_idx]
3501 .GetMangled()
3502 .GetName(lldb::eLanguageTypeUnknown,
3503 Mangled::ePreferMangled)
3504 .GetCString();
3505 if (gsym_name)
3506 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3507 }
3508 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003509 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003510 if (symbol_section) {
3511 const addr_t section_file_addr =
3512 symbol_section->GetFileAddress();
3513 if (symbol_byte_size == 0 &&
3514 function_starts_count > 0) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003515 addr_t symbol_lookup_file_addr = nlist.n_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003516 // Do an exact address match for non-ARM addresses,
Adrian Prantl05097242018-04-30 16:49:04 +00003517 // else get the closest since the symbol might be a
3518 // thumb symbol which has an address with bit zero
3519 // set
Kate Stoneb9c1b512016-09-06 20:57:50 +00003520 FunctionStarts::Entry *func_start_entry =
3521 function_starts.FindEntry(
3522 symbol_lookup_file_addr, !is_arm);
3523 if (is_arm && func_start_entry) {
3524 // Verify that the function start address is the
Adrian Prantl05097242018-04-30 16:49:04 +00003525 // symbol address (ARM) or the symbol address + 1
3526 // (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003527 if (func_start_entry->addr !=
3528 symbol_lookup_file_addr &&
3529 func_start_entry->addr !=
3530 (symbol_lookup_file_addr + 1)) {
3531 // Not the right entry, NULL it out...
3532 func_start_entry = NULL;
3533 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003534 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003535 if (func_start_entry) {
3536 func_start_entry->data = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00003537
Kate Stoneb9c1b512016-09-06 20:57:50 +00003538 addr_t symbol_file_addr = func_start_entry->addr;
3539 uint32_t symbol_flags = 0;
3540 if (is_arm) {
3541 if (symbol_file_addr & 1)
3542 symbol_flags =
3543 MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3544 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3545 }
3546
3547 const FunctionStarts::Entry
3548 *next_func_start_entry =
3549 function_starts.FindNextEntry(
3550 func_start_entry);
3551 const addr_t section_end_file_addr =
3552 section_file_addr +
3553 symbol_section->GetByteSize();
3554 if (next_func_start_entry) {
3555 addr_t next_symbol_file_addr =
3556 next_func_start_entry->addr;
3557 // Be sure the clear the Thumb address bit when
Adrian Prantl05097242018-04-30 16:49:04 +00003558 // we calculate the size from the current and
3559 // next address
Greg Claytonfd814c52013-08-13 01:42:25 +00003560 if (is_arm)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003561 next_symbol_file_addr &=
3562 THUMB_ADDRESS_BIT_MASK;
3563 symbol_byte_size = std::min<lldb::addr_t>(
3564 next_symbol_file_addr - symbol_file_addr,
3565 section_end_file_addr - symbol_file_addr);
3566 } else {
3567 symbol_byte_size =
3568 section_end_file_addr - symbol_file_addr;
3569 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003570 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003571 }
3572 symbol_value -= section_file_addr;
Greg Claytonfd814c52013-08-13 01:42:25 +00003573 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003574
Kate Stoneb9c1b512016-09-06 20:57:50 +00003575 if (is_debug == false) {
3576 if (type == eSymbolTypeCode) {
3577 // See if we can find a N_FUN entry for any code
Adrian Prantl05097242018-04-30 16:49:04 +00003578 // symbols. If we do find a match, and the name
3579 // matches, then we can merge the two into just the
3580 // function symbol to avoid duplicate entries in
3581 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003582 std::pair<ValueToSymbolIndexMap::const_iterator,
3583 ValueToSymbolIndexMap::const_iterator>
3584 range;
3585 range = N_FUN_addr_to_sym_idx.equal_range(
3586 nlist.n_value);
3587 if (range.first != range.second) {
3588 bool found_it = false;
3589 for (ValueToSymbolIndexMap::const_iterator pos =
3590 range.first;
3591 pos != range.second; ++pos) {
3592 if (sym[sym_idx].GetMangled().GetName(
3593 lldb::eLanguageTypeUnknown,
3594 Mangled::ePreferMangled) ==
3595 sym[pos->second].GetMangled().GetName(
3596 lldb::eLanguageTypeUnknown,
3597 Mangled::ePreferMangled)) {
3598 m_nlist_idx_to_sym_idx[nlist_idx] =
3599 pos->second;
3600 // We just need the flags from the linker
3601 // symbol, so put these flags
3602 // into the N_FUN flags to avoid duplicate
3603 // symbols in the symbol table
3604 sym[pos->second].SetExternal(
3605 sym[sym_idx].IsExternal());
3606 sym[pos->second].SetFlags(nlist.n_type << 16 |
3607 nlist.n_desc);
3608 if (resolver_addresses.find(nlist.n_value) !=
3609 resolver_addresses.end())
3610 sym[pos->second].SetType(
3611 eSymbolTypeResolver);
3612 sym[sym_idx].Clear();
3613 found_it = true;
3614 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003616 }
3617 if (found_it)
3618 continue;
3619 } else {
3620 if (resolver_addresses.find(nlist.n_value) !=
3621 resolver_addresses.end())
3622 type = eSymbolTypeResolver;
Greg Claytonfd814c52013-08-13 01:42:25 +00003623 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003624 } else if (type == eSymbolTypeData ||
3625 type == eSymbolTypeObjCClass ||
3626 type == eSymbolTypeObjCMetaClass ||
3627 type == eSymbolTypeObjCIVar) {
3628 // See if we can find a N_STSYM entry for any data
Adrian Prantl05097242018-04-30 16:49:04 +00003629 // symbols. If we do find a match, and the name
3630 // matches, then we can merge the two into just the
3631 // Static symbol to avoid duplicate entries in the
3632 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003633 std::pair<ValueToSymbolIndexMap::const_iterator,
3634 ValueToSymbolIndexMap::const_iterator>
3635 range;
3636 range = N_STSYM_addr_to_sym_idx.equal_range(
3637 nlist.n_value);
3638 if (range.first != range.second) {
3639 bool found_it = false;
3640 for (ValueToSymbolIndexMap::const_iterator pos =
3641 range.first;
3642 pos != range.second; ++pos) {
3643 if (sym[sym_idx].GetMangled().GetName(
3644 lldb::eLanguageTypeUnknown,
3645 Mangled::ePreferMangled) ==
3646 sym[pos->second].GetMangled().GetName(
3647 lldb::eLanguageTypeUnknown,
3648 Mangled::ePreferMangled)) {
3649 m_nlist_idx_to_sym_idx[nlist_idx] =
3650 pos->second;
3651 // We just need the flags from the linker
3652 // symbol, so put these flags
3653 // into the N_STSYM flags to avoid duplicate
3654 // symbols in the symbol table
3655 sym[pos->second].SetExternal(
3656 sym[sym_idx].IsExternal());
3657 sym[pos->second].SetFlags(nlist.n_type << 16 |
3658 nlist.n_desc);
3659 sym[sym_idx].Clear();
3660 found_it = true;
3661 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003662 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003663 }
3664 if (found_it)
3665 continue;
3666 } else {
3667 const char *gsym_name =
3668 sym[sym_idx]
3669 .GetMangled()
3670 .GetName(lldb::eLanguageTypeUnknown,
3671 Mangled::ePreferMangled)
3672 .GetCString();
3673 if (gsym_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00003674 // Combine N_GSYM stab entries with the non
3675 // stab symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00003676 ConstNameToSymbolIndexMap::const_iterator pos =
3677 N_GSYM_name_to_sym_idx.find(gsym_name);
3678 if (pos != N_GSYM_name_to_sym_idx.end()) {
3679 const uint32_t GSYM_sym_idx = pos->second;
3680 m_nlist_idx_to_sym_idx[nlist_idx] =
3681 GSYM_sym_idx;
3682 // Copy the address, because often the N_GSYM
3683 // address has an invalid address of zero
3684 // when the global is a common symbol
3685 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3686 symbol_section);
3687 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3688 symbol_value);
3689 // We just need the flags from the linker
3690 // symbol, so put these flags
3691 // into the N_GSYM flags to avoid duplicate
3692 // symbols in the symbol table
3693 sym[GSYM_sym_idx].SetFlags(
3694 nlist.n_type << 16 | nlist.n_desc);
3695 sym[sym_idx].Clear();
3696 continue;
3697 }
3698 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003699 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003700 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003701 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003702
Kate Stoneb9c1b512016-09-06 20:57:50 +00003703 sym[sym_idx].SetID(nlist_idx);
3704 sym[sym_idx].SetType(type);
3705 if (set_value) {
3706 sym[sym_idx].GetAddressRef().SetSection(
3707 symbol_section);
3708 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
Greg Clayton29e08cb2012-03-14 01:53:24 +00003709 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003710 sym[sym_idx].SetFlags(nlist.n_type << 16 |
3711 nlist.n_desc);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003712
Kate Stoneb9c1b512016-09-06 20:57:50 +00003713 if (symbol_byte_size > 0)
3714 sym[sym_idx].SetByteSize(symbol_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003715
Kate Stoneb9c1b512016-09-06 20:57:50 +00003716 if (demangled_is_synthesized)
3717 sym[sym_idx].SetDemangledNameIsSynthesized(true);
Greg Clayton60038be2015-02-14 00:51:13 +00003718 ++sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003719 } else {
3720 sym[sym_idx].Clear();
3721 }
Greg Clayton9191db42013-10-21 18:40:51 +00003722 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723 /////////////////////////////
3724 }
3725 break; // No more entries to consider
Greg Clayton9191db42013-10-21 18:40:51 +00003726 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003727 }
3728
3729 for (const auto &pos : reexport_shlib_needs_fixup) {
3730 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3731 if (undef_pos != undefined_name_to_desc.end()) {
3732 const uint8_t dylib_ordinal =
3733 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3734 if (dylib_ordinal > 0 &&
3735 dylib_ordinal < dylib_files.GetSize())
3736 sym[pos.first].SetReExportedSymbolSharedLibrary(
3737 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3738 }
3739 }
Greg Clayton9191db42013-10-21 18:40:51 +00003740 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003741 }
Greg Clayton9191db42013-10-21 18:40:51 +00003742 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003743 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003744 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003745
3746 // Must reset this in case it was mutated above!
3747 nlist_data_offset = 0;
3748#endif
3749
3750 if (nlist_data.GetByteSize() > 0) {
3751
3752 // If the sym array was not created while parsing the DSC unmapped
3753 // symbols, create it now.
3754 if (sym == NULL) {
3755 sym = symtab->Resize(symtab_load_command.nsyms +
3756 m_dysymtab.nindirectsyms);
3757 num_syms = symtab->GetNumSymbols();
3758 }
3759
3760 if (unmapped_local_symbols_found) {
3761 assert(m_dysymtab.ilocalsym == 0);
3762 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3763 nlist_idx = m_dysymtab.nlocalsym;
3764 } else {
3765 nlist_idx = 0;
3766 }
3767
3768 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3769 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3770 UndefinedNameToDescMap undefined_name_to_desc;
3771 SymbolIndexToName reexport_shlib_needs_fixup;
3772 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
3773 struct nlist_64 nlist;
3774 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset,
3775 nlist_byte_size))
3776 break;
3777
3778 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
3779 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
3780 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
3781 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
3782 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
3783
3784 SymbolType type = eSymbolTypeInvalid;
3785 const char *symbol_name = NULL;
3786
3787 if (have_strtab_data) {
3788 symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3789
3790 if (symbol_name == NULL) {
Adrian Prantl05097242018-04-30 16:49:04 +00003791 // No symbol should be NULL, even the symbols with no string values
3792 // should have an offset zero which points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793 Host::SystemLog(Host::eSystemLogError,
3794 "error: symbol[%u] has invalid string table offset "
3795 "0x%x in %s, ignoring symbol\n",
3796 nlist_idx, nlist.n_strx,
3797 module_sp->GetFileSpec().GetPath().c_str());
3798 continue;
3799 }
3800 if (symbol_name[0] == '\0')
3801 symbol_name = NULL;
3802 } else {
3803 const addr_t str_addr = strtab_addr + nlist.n_strx;
Zachary Turner97206d52017-05-12 04:51:55 +00003804 Status str_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003805 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3806 str_error))
3807 symbol_name = memory_symbol_name.c_str();
3808 }
3809 const char *symbol_name_non_abi_mangled = NULL;
3810
3811 SectionSP symbol_section;
3812 lldb::addr_t symbol_byte_size = 0;
3813 bool add_nlist = true;
3814 bool is_gsym = false;
3815 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3816 bool demangled_is_synthesized = false;
3817 bool set_value = true;
3818 assert(sym_idx < num_syms);
3819
3820 sym[sym_idx].SetDebug(is_debug);
3821
3822 if (is_debug) {
3823 switch (nlist.n_type) {
3824 case N_GSYM:
3825 // global symbol: name,,NO_SECT,type,0
3826 // Sometimes the N_GSYM value contains the address.
3827
3828 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3829 // the ObjC data. They
3830 // have the same address, but we want to ensure that we always find
Adrian Prantl05097242018-04-30 16:49:04 +00003831 // only the real symbol, 'cause we don't currently correctly
3832 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3833 // type. This is a temporary hack to make sure the ObjectiveC
3834 // symbols get treated correctly. To do this right, we should
3835 // coalesce all the GSYM & global symbols that have the same
3836 // address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003837 is_gsym = true;
3838 sym[sym_idx].SetExternal(true);
3839
3840 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3841 llvm::StringRef symbol_name_ref(symbol_name);
3842 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3843 symbol_name_non_abi_mangled = symbol_name + 1;
3844 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3845 type = eSymbolTypeObjCClass;
3846 demangled_is_synthesized = true;
3847
3848 } else if (symbol_name_ref.startswith(
3849 g_objc_v2_prefix_metaclass)) {
3850 symbol_name_non_abi_mangled = symbol_name + 1;
3851 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3852 type = eSymbolTypeObjCMetaClass;
3853 demangled_is_synthesized = true;
3854 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3855 symbol_name_non_abi_mangled = symbol_name + 1;
3856 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3857 type = eSymbolTypeObjCIVar;
3858 demangled_is_synthesized = true;
3859 }
3860 } else {
3861 if (nlist.n_value != 0)
3862 symbol_section =
3863 section_info.GetSection(nlist.n_sect, nlist.n_value);
3864 type = eSymbolTypeData;
3865 }
3866 break;
3867
3868 case N_FNAME:
3869 // procedure name (f77 kludge): name,,NO_SECT,0,0
3870 type = eSymbolTypeCompiler;
3871 break;
3872
3873 case N_FUN:
3874 // procedure: name,,n_sect,linenumber,address
3875 if (symbol_name) {
3876 type = eSymbolTypeCode;
3877 symbol_section =
3878 section_info.GetSection(nlist.n_sect, nlist.n_value);
3879
3880 N_FUN_addr_to_sym_idx.insert(
3881 std::make_pair(nlist.n_value, sym_idx));
3882 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003883 // lieu of using nlist_idx in case we ever start trimming entries
3884 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003885 N_FUN_indexes.push_back(sym_idx);
3886 } else {
3887 type = eSymbolTypeCompiler;
3888
3889 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003890 // Copy the size of the function into the original STAB entry
3891 // so we don't have to hunt for it later
Kate Stoneb9c1b512016-09-06 20:57:50 +00003892 symtab->SymbolAtIndex(N_FUN_indexes.back())
3893 ->SetByteSize(nlist.n_value);
3894 N_FUN_indexes.pop_back();
Adrian Prantl05097242018-04-30 16:49:04 +00003895 // We don't really need the end function STAB as it contains
3896 // the size which we already placed with the original symbol,
3897 // so don't add it if we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003898 add_nlist = false;
3899 }
3900 }
3901 break;
3902
3903 case N_STSYM:
3904 // static symbol: name,,n_sect,type,address
3905 N_STSYM_addr_to_sym_idx.insert(
3906 std::make_pair(nlist.n_value, sym_idx));
3907 symbol_section =
3908 section_info.GetSection(nlist.n_sect, nlist.n_value);
3909 if (symbol_name && symbol_name[0]) {
3910 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3911 eSymbolTypeData);
3912 }
3913 break;
3914
3915 case N_LCSYM:
3916 // .lcomm symbol: name,,n_sect,type,address
3917 symbol_section =
3918 section_info.GetSection(nlist.n_sect, nlist.n_value);
3919 type = eSymbolTypeCommonBlock;
3920 break;
3921
3922 case N_BNSYM:
3923 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00003924 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003925 // Skip these if we want minimal symbol tables
3926 add_nlist = false;
3927 break;
3928
3929 case N_ENSYM:
3930 // Set the size of the N_BNSYM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003931 // N_ENSYM so that we can always skip the entire symbol if we need
3932 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003933 // Skip these if we want minimal symbol tables
3934 add_nlist = false;
3935 break;
3936
3937 case N_OPT:
3938 // emitted with gcc2_compiled and in gcc source
3939 type = eSymbolTypeCompiler;
3940 break;
3941
3942 case N_RSYM:
3943 // register sym: name,,NO_SECT,type,register
3944 type = eSymbolTypeVariable;
3945 break;
3946
3947 case N_SLINE:
3948 // src line: 0,,n_sect,linenumber,address
3949 symbol_section =
3950 section_info.GetSection(nlist.n_sect, nlist.n_value);
3951 type = eSymbolTypeLineEntry;
3952 break;
3953
3954 case N_SSYM:
3955 // structure elt: name,,NO_SECT,type,struct_offset
3956 type = eSymbolTypeVariableType;
3957 break;
3958
3959 case N_SO:
3960 // source file name
3961 type = eSymbolTypeSourceFile;
3962 if (symbol_name == NULL) {
3963 add_nlist = false;
3964 if (N_SO_index != UINT32_MAX) {
3965 // Set the size of the N_SO to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003966 // N_SO so that we can always skip the entire N_SO if we need
3967 // to navigate more quickly at the source level when parsing
3968 // STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003969 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3970 symbol_ptr->SetByteSize(sym_idx);
3971 symbol_ptr->SetSizeIsSibling(true);
3972 }
3973 N_NSYM_indexes.clear();
3974 N_INCL_indexes.clear();
3975 N_BRAC_indexes.clear();
3976 N_COMM_indexes.clear();
3977 N_FUN_indexes.clear();
3978 N_SO_index = UINT32_MAX;
3979 } else {
3980 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003981 // lieu of using nlist_idx in case we ever start trimming entries
3982 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983 const bool N_SO_has_full_path = symbol_name[0] == '/';
3984 if (N_SO_has_full_path) {
3985 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3986 // We have two consecutive N_SO entries where the first
Adrian Prantl05097242018-04-30 16:49:04 +00003987 // contains a directory and the second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003988 sym[sym_idx - 1].GetMangled().SetValue(
3989 ConstString(symbol_name), false);
3990 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3991 add_nlist = false;
3992 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003993 // This is the first entry in a N_SO that contains a
3994 // directory or a full path to the source file
Kate Stoneb9c1b512016-09-06 20:57:50 +00003995 N_SO_index = sym_idx;
3996 }
3997 } else if ((N_SO_index == sym_idx - 1) &&
3998 ((sym_idx - 1) < num_syms)) {
3999 // This is usually the second N_SO entry that contains just the
Adrian Prantl05097242018-04-30 16:49:04 +00004000 // filename, so here we combine it with the first one if we are
4001 // minimizing the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004002 const char *so_path =
4003 sym[sym_idx - 1]
4004 .GetMangled()
4005 .GetDemangledName(lldb::eLanguageTypeUnknown)
4006 .AsCString();
4007 if (so_path && so_path[0]) {
4008 std::string full_so_path(so_path);
4009 const size_t double_slash_pos = full_so_path.find("//");
4010 if (double_slash_pos != std::string::npos) {
4011 // The linker has been generating bad N_SO entries with
Adrian Prantl05097242018-04-30 16:49:04 +00004012 // doubled up paths in the format "%s%s" where the first
4013 // string in the DW_AT_comp_dir, and the second is the
4014 // directory for the source file so you end up with a path
4015 // that looks like "/tmp/src//tmp/src/"
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004016 FileSpec so_dir(so_path);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00004017 if (!FileSystem::Instance().Exists(so_dir)) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004018 so_dir.SetFile(&full_so_path[double_slash_pos + 1],
Jonas Devlieghere937348c2018-06-13 22:08:14 +00004019 FileSpec::Style::native);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00004020 if (FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004021 // Trim off the incorrect path
4022 full_so_path.erase(0, double_slash_pos + 1);
4023 }
4024 }
4025 }
4026 if (*full_so_path.rbegin() != '/')
4027 full_so_path += '/';
4028 full_so_path += symbol_name;
4029 sym[sym_idx - 1].GetMangled().SetValue(
4030 ConstString(full_so_path.c_str()), false);
4031 add_nlist = false;
4032 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4033 }
4034 } else {
4035 // This could be a relative path to a N_SO
4036 N_SO_index = sym_idx;
4037 }
4038 }
4039 break;
4040
4041 case N_OSO:
4042 // object file name: name,,0,0,st_mtime
4043 type = eSymbolTypeObjectFile;
4044 break;
4045
4046 case N_LSYM:
4047 // local sym: name,,NO_SECT,type,offset
4048 type = eSymbolTypeLocal;
4049 break;
4050
4051 //----------------------------------------------------------------------
4052 // INCL scopes
4053 //----------------------------------------------------------------------
4054 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00004055 // include file beginning: name,,NO_SECT,0,sum We use the current
4056 // number of symbols in the symbol table in lieu of using nlist_idx
4057 // in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004058 N_INCL_indexes.push_back(sym_idx);
4059 type = eSymbolTypeScopeBegin;
4060 break;
4061
4062 case N_EINCL:
4063 // include file end: name,,NO_SECT,0,0
4064 // Set the size of the N_BINCL to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004065 // N_EINCL so that we can always skip the entire symbol if we need
4066 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004067 if (!N_INCL_indexes.empty()) {
4068 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
4069 symbol_ptr->SetByteSize(sym_idx + 1);
4070 symbol_ptr->SetSizeIsSibling(true);
4071 N_INCL_indexes.pop_back();
4072 }
4073 type = eSymbolTypeScopeEnd;
4074 break;
4075
4076 case N_SOL:
4077 // #included file name: name,,n_sect,0,address
4078 type = eSymbolTypeHeaderFile;
4079
4080 // We currently don't use the header files on darwin
4081 add_nlist = false;
4082 break;
4083
4084 case N_PARAMS:
4085 // compiler parameters: name,,NO_SECT,0,0
4086 type = eSymbolTypeCompiler;
4087 break;
4088
4089 case N_VERSION:
4090 // compiler version: name,,NO_SECT,0,0
4091 type = eSymbolTypeCompiler;
4092 break;
4093
4094 case N_OLEVEL:
4095 // compiler -O level: name,,NO_SECT,0,0
4096 type = eSymbolTypeCompiler;
4097 break;
4098
4099 case N_PSYM:
4100 // parameter: name,,NO_SECT,type,offset
4101 type = eSymbolTypeVariable;
4102 break;
4103
4104 case N_ENTRY:
4105 // alternate entry: name,,n_sect,linenumber,address
4106 symbol_section =
4107 section_info.GetSection(nlist.n_sect, nlist.n_value);
4108 type = eSymbolTypeLineEntry;
4109 break;
4110
4111 //----------------------------------------------------------------------
4112 // Left and Right Braces
4113 //----------------------------------------------------------------------
4114 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004115 // left bracket: 0,,NO_SECT,nesting level,address We use the
4116 // current number of symbols in the symbol table in lieu of using
4117 // nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004118 symbol_section =
4119 section_info.GetSection(nlist.n_sect, nlist.n_value);
4120 N_BRAC_indexes.push_back(sym_idx);
4121 type = eSymbolTypeScopeBegin;
4122 break;
4123
4124 case N_RBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004125 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4126 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4127 // can always skip the entire symbol if we need to navigate more
4128 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004129 symbol_section =
4130 section_info.GetSection(nlist.n_sect, nlist.n_value);
4131 if (!N_BRAC_indexes.empty()) {
4132 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4133 symbol_ptr->SetByteSize(sym_idx + 1);
4134 symbol_ptr->SetSizeIsSibling(true);
4135 N_BRAC_indexes.pop_back();
4136 }
4137 type = eSymbolTypeScopeEnd;
4138 break;
4139
4140 case N_EXCL:
4141 // deleted include file: name,,NO_SECT,0,sum
4142 type = eSymbolTypeHeaderFile;
4143 break;
4144
4145 //----------------------------------------------------------------------
4146 // COMM scopes
4147 //----------------------------------------------------------------------
4148 case N_BCOMM:
4149 // begin common: name,,NO_SECT,0,0
4150 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00004151 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004152 type = eSymbolTypeScopeBegin;
4153 N_COMM_indexes.push_back(sym_idx);
4154 break;
4155
4156 case N_ECOML:
4157 // end common (local name): 0,,n_sect,0,address
4158 symbol_section =
4159 section_info.GetSection(nlist.n_sect, nlist.n_value);
4160 LLVM_FALLTHROUGH;
4161
4162 case N_ECOMM:
4163 // end common: name,,n_sect,0,0
4164 // Set the size of the N_BCOMM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004165 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4166 // we need to navigate more quickly at the source level when
4167 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004168 if (!N_COMM_indexes.empty()) {
4169 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4170 symbol_ptr->SetByteSize(sym_idx + 1);
4171 symbol_ptr->SetSizeIsSibling(true);
4172 N_COMM_indexes.pop_back();
4173 }
4174 type = eSymbolTypeScopeEnd;
4175 break;
4176
4177 case N_LENG:
4178 // second stab entry with length information
4179 type = eSymbolTypeAdditional;
4180 break;
4181
4182 default:
4183 break;
4184 }
4185 } else {
4186 // uint8_t n_pext = N_PEXT & nlist.n_type;
4187 uint8_t n_type = N_TYPE & nlist.n_type;
4188 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4189
4190 switch (n_type) {
4191 case N_INDR: {
4192 const char *reexport_name_cstr =
4193 strtab_data.PeekCStr(nlist.n_value);
4194 if (reexport_name_cstr && reexport_name_cstr[0]) {
4195 type = eSymbolTypeReExported;
4196 ConstString reexport_name(
4197 reexport_name_cstr +
4198 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4199 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4200 set_value = false;
4201 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4202 indirect_symbol_names.insert(
4203 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4204 } else
4205 type = eSymbolTypeUndefined;
4206 } break;
4207
4208 case N_UNDF:
4209 if (symbol_name && symbol_name[0]) {
4210 ConstString undefined_name(symbol_name +
4211 ((symbol_name[0] == '_') ? 1 : 0));
4212 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4213 }
4214 LLVM_FALLTHROUGH;
4215
4216 case N_PBUD:
4217 type = eSymbolTypeUndefined;
4218 break;
4219
4220 case N_ABS:
4221 type = eSymbolTypeAbsolute;
4222 break;
4223
4224 case N_SECT: {
4225 symbol_section =
4226 section_info.GetSection(nlist.n_sect, nlist.n_value);
4227
4228 if (!symbol_section) {
4229 // TODO: warn about this?
4230 add_nlist = false;
4231 break;
4232 }
4233
4234 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4235 type = eSymbolTypeException;
4236 } else {
4237 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4238
4239 switch (section_type) {
4240 case S_CSTRING_LITERALS:
4241 type = eSymbolTypeData;
4242 break; // section with only literal C strings
4243 case S_4BYTE_LITERALS:
4244 type = eSymbolTypeData;
4245 break; // section with only 4 byte literals
4246 case S_8BYTE_LITERALS:
4247 type = eSymbolTypeData;
4248 break; // section with only 8 byte literals
4249 case S_LITERAL_POINTERS:
4250 type = eSymbolTypeTrampoline;
4251 break; // section with only pointers to literals
4252 case S_NON_LAZY_SYMBOL_POINTERS:
4253 type = eSymbolTypeTrampoline;
4254 break; // section with only non-lazy symbol pointers
4255 case S_LAZY_SYMBOL_POINTERS:
4256 type = eSymbolTypeTrampoline;
4257 break; // section with only lazy symbol pointers
4258 case S_SYMBOL_STUBS:
4259 type = eSymbolTypeTrampoline;
4260 break; // section with only symbol stubs, byte size of stub in
4261 // the reserved2 field
4262 case S_MOD_INIT_FUNC_POINTERS:
4263 type = eSymbolTypeCode;
4264 break; // section with only function pointers for initialization
4265 case S_MOD_TERM_FUNC_POINTERS:
4266 type = eSymbolTypeCode;
4267 break; // section with only function pointers for termination
4268 case S_INTERPOSING:
4269 type = eSymbolTypeTrampoline;
4270 break; // section with only pairs of function pointers for
4271 // interposing
4272 case S_16BYTE_LITERALS:
4273 type = eSymbolTypeData;
4274 break; // section with only 16 byte literals
4275 case S_DTRACE_DOF:
4276 type = eSymbolTypeInstrumentation;
4277 break;
4278 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4279 type = eSymbolTypeTrampoline;
4280 break;
4281 default:
4282 switch (symbol_section->GetType()) {
4283 case lldb::eSectionTypeCode:
4284 type = eSymbolTypeCode;
4285 break;
4286 case eSectionTypeData:
4287 case eSectionTypeDataCString: // Inlined C string data
4288 case eSectionTypeDataCStringPointers: // Pointers to C string
4289 // data
4290 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4291 // the symbol table
4292 case eSectionTypeData4:
4293 case eSectionTypeData8:
4294 case eSectionTypeData16:
4295 type = eSymbolTypeData;
4296 break;
4297 default:
4298 break;
4299 }
4300 break;
4301 }
4302
4303 if (type == eSymbolTypeInvalid) {
4304 const char *symbol_sect_name =
4305 symbol_section->GetName().AsCString();
4306 if (symbol_section->IsDescendant(text_section_sp.get())) {
4307 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4308 S_ATTR_SELF_MODIFYING_CODE |
4309 S_ATTR_SOME_INSTRUCTIONS))
4310 type = eSymbolTypeData;
4311 else
4312 type = eSymbolTypeCode;
4313 } else if (symbol_section->IsDescendant(
4314 data_section_sp.get()) ||
4315 symbol_section->IsDescendant(
4316 data_dirty_section_sp.get()) ||
4317 symbol_section->IsDescendant(
4318 data_const_section_sp.get())) {
4319 if (symbol_sect_name &&
4320 ::strstr(symbol_sect_name, "__objc") ==
4321 symbol_sect_name) {
4322 type = eSymbolTypeRuntime;
4323
4324 if (symbol_name) {
4325 llvm::StringRef symbol_name_ref(symbol_name);
4326 if (symbol_name_ref.startswith("_OBJC_")) {
4327 static const llvm::StringRef g_objc_v2_prefix_class(
4328 "_OBJC_CLASS_$_");
4329 static const llvm::StringRef g_objc_v2_prefix_metaclass(
4330 "_OBJC_METACLASS_$_");
4331 static const llvm::StringRef g_objc_v2_prefix_ivar(
4332 "_OBJC_IVAR_$_");
4333 if (symbol_name_ref.startswith(
4334 g_objc_v2_prefix_class)) {
4335 symbol_name_non_abi_mangled = symbol_name + 1;
4336 symbol_name =
4337 symbol_name + g_objc_v2_prefix_class.size();
4338 type = eSymbolTypeObjCClass;
4339 demangled_is_synthesized = true;
4340 } else if (symbol_name_ref.startswith(
4341 g_objc_v2_prefix_metaclass)) {
4342 symbol_name_non_abi_mangled = symbol_name + 1;
4343 symbol_name =
4344 symbol_name + g_objc_v2_prefix_metaclass.size();
4345 type = eSymbolTypeObjCMetaClass;
4346 demangled_is_synthesized = true;
4347 } else if (symbol_name_ref.startswith(
4348 g_objc_v2_prefix_ivar)) {
4349 symbol_name_non_abi_mangled = symbol_name + 1;
4350 symbol_name =
4351 symbol_name + g_objc_v2_prefix_ivar.size();
4352 type = eSymbolTypeObjCIVar;
4353 demangled_is_synthesized = true;
4354 }
4355 }
4356 }
4357 } else if (symbol_sect_name &&
4358 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4359 symbol_sect_name) {
4360 type = eSymbolTypeException;
4361 } else {
4362 type = eSymbolTypeData;
4363 }
4364 } else if (symbol_sect_name &&
4365 ::strstr(symbol_sect_name, "__IMPORT") ==
4366 symbol_sect_name) {
4367 type = eSymbolTypeTrampoline;
4368 } else if (symbol_section->IsDescendant(
4369 objc_section_sp.get())) {
4370 type = eSymbolTypeRuntime;
4371 if (symbol_name && symbol_name[0] == '.') {
4372 llvm::StringRef symbol_name_ref(symbol_name);
4373 static const llvm::StringRef g_objc_v1_prefix_class(
4374 ".objc_class_name_");
4375 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4376 symbol_name_non_abi_mangled = symbol_name;
4377 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4378 type = eSymbolTypeObjCClass;
4379 demangled_is_synthesized = true;
4380 }
4381 }
4382 }
4383 }
4384 }
4385 } break;
4386 }
4387 }
4388
4389 if (add_nlist) {
4390 uint64_t symbol_value = nlist.n_value;
4391
4392 if (symbol_name_non_abi_mangled) {
4393 sym[sym_idx].GetMangled().SetMangledName(
4394 ConstString(symbol_name_non_abi_mangled));
4395 sym[sym_idx].GetMangled().SetDemangledName(
4396 ConstString(symbol_name));
4397 } else {
4398 bool symbol_name_is_mangled = false;
4399
4400 if (symbol_name && symbol_name[0] == '_') {
4401 symbol_name_is_mangled = symbol_name[1] == '_';
4402 symbol_name++; // Skip the leading underscore
4403 }
4404
4405 if (symbol_name) {
4406 ConstString const_symbol_name(symbol_name);
4407 sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4408 symbol_name_is_mangled);
4409 }
4410 }
4411
4412 if (is_gsym) {
4413 const char *gsym_name = sym[sym_idx]
4414 .GetMangled()
4415 .GetName(lldb::eLanguageTypeUnknown,
4416 Mangled::ePreferMangled)
4417 .GetCString();
4418 if (gsym_name)
4419 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4420 }
4421
4422 if (symbol_section) {
4423 const addr_t section_file_addr = symbol_section->GetFileAddress();
4424 if (symbol_byte_size == 0 && function_starts_count > 0) {
4425 addr_t symbol_lookup_file_addr = nlist.n_value;
4426 // Do an exact address match for non-ARM addresses, else get the
Adrian Prantl05097242018-04-30 16:49:04 +00004427 // closest since the symbol might be a thumb symbol which has an
4428 // address with bit zero set
Kate Stoneb9c1b512016-09-06 20:57:50 +00004429 FunctionStarts::Entry *func_start_entry =
4430 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4431 if (is_arm && func_start_entry) {
4432 // Verify that the function start address is the symbol address
Adrian Prantl05097242018-04-30 16:49:04 +00004433 // (ARM) or the symbol address + 1 (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004434 if (func_start_entry->addr != symbol_lookup_file_addr &&
4435 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4436 // Not the right entry, NULL it out...
4437 func_start_entry = NULL;
4438 }
4439 }
4440 if (func_start_entry) {
4441 func_start_entry->data = true;
4442
4443 addr_t symbol_file_addr = func_start_entry->addr;
4444 if (is_arm)
4445 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4446
4447 const FunctionStarts::Entry *next_func_start_entry =
4448 function_starts.FindNextEntry(func_start_entry);
4449 const addr_t section_end_file_addr =
4450 section_file_addr + symbol_section->GetByteSize();
4451 if (next_func_start_entry) {
4452 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4453 // Be sure the clear the Thumb address bit when we calculate
Adrian Prantl05097242018-04-30 16:49:04 +00004454 // the size from the current and next address
Kate Stoneb9c1b512016-09-06 20:57:50 +00004455 if (is_arm)
4456 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4457 symbol_byte_size = std::min<lldb::addr_t>(
4458 next_symbol_file_addr - symbol_file_addr,
4459 section_end_file_addr - symbol_file_addr);
4460 } else {
4461 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4462 }
4463 }
4464 }
4465 symbol_value -= section_file_addr;
4466 }
4467
4468 if (is_debug == false) {
4469 if (type == eSymbolTypeCode) {
Adrian Prantl05097242018-04-30 16:49:04 +00004470 // See if we can find a N_FUN entry for any code symbols. If we
4471 // do find a match, and the name matches, then we can merge the
4472 // two into just the function symbol to avoid duplicate entries
4473 // in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474 std::pair<ValueToSymbolIndexMap::const_iterator,
4475 ValueToSymbolIndexMap::const_iterator>
4476 range;
4477 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4478 if (range.first != range.second) {
4479 bool found_it = false;
4480 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4481 pos != range.second; ++pos) {
4482 if (sym[sym_idx].GetMangled().GetName(
4483 lldb::eLanguageTypeUnknown,
4484 Mangled::ePreferMangled) ==
4485 sym[pos->second].GetMangled().GetName(
4486 lldb::eLanguageTypeUnknown,
4487 Mangled::ePreferMangled)) {
4488 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4489 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004490 // these flags into the N_FUN flags to avoid duplicate
4491 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004492 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4493 sym[pos->second].SetFlags(nlist.n_type << 16 |
4494 nlist.n_desc);
4495 if (resolver_addresses.find(nlist.n_value) !=
4496 resolver_addresses.end())
4497 sym[pos->second].SetType(eSymbolTypeResolver);
4498 sym[sym_idx].Clear();
4499 found_it = true;
4500 break;
4501 }
4502 }
4503 if (found_it)
4504 continue;
4505 } else {
4506 if (resolver_addresses.find(nlist.n_value) !=
4507 resolver_addresses.end())
4508 type = eSymbolTypeResolver;
4509 }
4510 } else if (type == eSymbolTypeData ||
4511 type == eSymbolTypeObjCClass ||
4512 type == eSymbolTypeObjCMetaClass ||
4513 type == eSymbolTypeObjCIVar) {
Adrian Prantl05097242018-04-30 16:49:04 +00004514 // See if we can find a N_STSYM entry for any data symbols. If we
4515 // do find a match, and the name matches, then we can merge the
4516 // two into just the Static symbol to avoid duplicate entries in
4517 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004518 std::pair<ValueToSymbolIndexMap::const_iterator,
4519 ValueToSymbolIndexMap::const_iterator>
4520 range;
4521 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4522 if (range.first != range.second) {
4523 bool found_it = false;
4524 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4525 pos != range.second; ++pos) {
4526 if (sym[sym_idx].GetMangled().GetName(
4527 lldb::eLanguageTypeUnknown,
4528 Mangled::ePreferMangled) ==
4529 sym[pos->second].GetMangled().GetName(
4530 lldb::eLanguageTypeUnknown,
4531 Mangled::ePreferMangled)) {
4532 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4533 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004534 // these flags into the N_STSYM flags to avoid duplicate
4535 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004536 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4537 sym[pos->second].SetFlags(nlist.n_type << 16 |
4538 nlist.n_desc);
4539 sym[sym_idx].Clear();
4540 found_it = true;
4541 break;
4542 }
4543 }
4544 if (found_it)
4545 continue;
4546 } else {
4547 // Combine N_GSYM stab entries with the non stab symbol
4548 const char *gsym_name = sym[sym_idx]
4549 .GetMangled()
4550 .GetName(lldb::eLanguageTypeUnknown,
4551 Mangled::ePreferMangled)
4552 .GetCString();
4553 if (gsym_name) {
4554 ConstNameToSymbolIndexMap::const_iterator pos =
4555 N_GSYM_name_to_sym_idx.find(gsym_name);
4556 if (pos != N_GSYM_name_to_sym_idx.end()) {
4557 const uint32_t GSYM_sym_idx = pos->second;
4558 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00004559 // Copy the address, because often the N_GSYM address has
4560 // an invalid address of zero when the global is a common
4561 // symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00004562 sym[GSYM_sym_idx].GetAddressRef().SetSection(
4563 symbol_section);
4564 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4565 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004566 // these flags into the N_GSYM flags to avoid duplicate
4567 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004568 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
4569 nlist.n_desc);
4570 sym[sym_idx].Clear();
4571 continue;
4572 }
4573 }
4574 }
4575 }
4576 }
4577
4578 sym[sym_idx].SetID(nlist_idx);
4579 sym[sym_idx].SetType(type);
4580 if (set_value) {
4581 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4582 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4583 }
4584 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4585
4586 if (symbol_byte_size > 0)
4587 sym[sym_idx].SetByteSize(symbol_byte_size);
4588
4589 if (demangled_is_synthesized)
4590 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4591
4592 ++sym_idx;
4593 } else {
4594 sym[sym_idx].Clear();
4595 }
4596 }
4597
4598 for (const auto &pos : reexport_shlib_needs_fixup) {
4599 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4600 if (undef_pos != undefined_name_to_desc.end()) {
4601 const uint8_t dylib_ordinal =
4602 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4603 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4604 sym[pos.first].SetReExportedSymbolSharedLibrary(
4605 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4606 }
4607 }
4608 }
4609
4610 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4611
4612 if (function_starts_count > 0) {
4613 uint32_t num_synthetic_function_symbols = 0;
4614 for (i = 0; i < function_starts_count; ++i) {
4615 if (function_starts.GetEntryRef(i).data == false)
4616 ++num_synthetic_function_symbols;
4617 }
4618
4619 if (num_synthetic_function_symbols > 0) {
4620 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4621 num_syms = sym_idx + num_synthetic_function_symbols;
4622 sym = symtab->Resize(num_syms);
4623 }
4624 for (i = 0; i < function_starts_count; ++i) {
4625 const FunctionStarts::Entry *func_start_entry =
4626 function_starts.GetEntryAtIndex(i);
4627 if (func_start_entry->data == false) {
4628 addr_t symbol_file_addr = func_start_entry->addr;
4629 uint32_t symbol_flags = 0;
4630 if (is_arm) {
4631 if (symbol_file_addr & 1)
4632 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4633 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4634 }
4635 Address symbol_addr;
4636 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4637 SectionSP symbol_section(symbol_addr.GetSection());
4638 uint32_t symbol_byte_size = 0;
4639 if (symbol_section) {
4640 const addr_t section_file_addr =
4641 symbol_section->GetFileAddress();
4642 const FunctionStarts::Entry *next_func_start_entry =
4643 function_starts.FindNextEntry(func_start_entry);
4644 const addr_t section_end_file_addr =
4645 section_file_addr + symbol_section->GetByteSize();
4646 if (next_func_start_entry) {
4647 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4648 if (is_arm)
4649 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4650 symbol_byte_size = std::min<lldb::addr_t>(
4651 next_symbol_file_addr - symbol_file_addr,
4652 section_end_file_addr - symbol_file_addr);
4653 } else {
4654 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4655 }
4656 sym[sym_idx].SetID(synthetic_sym_id++);
4657 sym[sym_idx].GetMangled().SetDemangledName(
4658 GetNextSyntheticSymbolName());
4659 sym[sym_idx].SetType(eSymbolTypeCode);
4660 sym[sym_idx].SetIsSynthetic(true);
4661 sym[sym_idx].GetAddressRef() = symbol_addr;
4662 if (symbol_flags)
4663 sym[sym_idx].SetFlags(symbol_flags);
4664 if (symbol_byte_size)
4665 sym[sym_idx].SetByteSize(symbol_byte_size);
4666 ++sym_idx;
4667 }
4668 }
4669 }
4670 }
4671 }
4672 }
4673
Adrian Prantl05097242018-04-30 16:49:04 +00004674 // Trim our symbols down to just what we ended up with after removing any
4675 // symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004676 if (sym_idx < num_syms) {
4677 num_syms = sym_idx;
4678 sym = symtab->Resize(num_syms);
4679 }
4680
4681 // Now synthesize indirect symbols
4682 if (m_dysymtab.nindirectsyms != 0) {
4683 if (indirect_symbol_index_data.GetByteSize()) {
4684 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4685 m_nlist_idx_to_sym_idx.end();
4686
4687 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4688 ++sect_idx) {
4689 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4690 S_SYMBOL_STUBS) {
4691 uint32_t symbol_stub_byte_size =
4692 m_mach_sections[sect_idx].reserved2;
4693 if (symbol_stub_byte_size == 0)
4694 continue;
4695
4696 const uint32_t num_symbol_stubs =
4697 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4698
4699 if (num_symbol_stubs == 0)
4700 continue;
4701
4702 const uint32_t symbol_stub_index_offset =
4703 m_mach_sections[sect_idx].reserved1;
4704 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs;
4705 ++stub_idx) {
4706 const uint32_t symbol_stub_index =
4707 symbol_stub_index_offset + stub_idx;
4708 const lldb::addr_t symbol_stub_addr =
4709 m_mach_sections[sect_idx].addr +
4710 (stub_idx * symbol_stub_byte_size);
4711 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4712 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4713 symbol_stub_offset, 4)) {
4714 const uint32_t stub_sym_id =
4715 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4716 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4717 continue;
4718
4719 NListIndexToSymbolIndexMap::const_iterator index_pos =
4720 m_nlist_idx_to_sym_idx.find(stub_sym_id);
4721 Symbol *stub_symbol = NULL;
4722 if (index_pos != end_index_pos) {
Adrian Prantl05097242018-04-30 16:49:04 +00004723 // We have a remapping from the original nlist index to a
4724 // current symbol index, so just look this up by index
Kate Stoneb9c1b512016-09-06 20:57:50 +00004725 stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4726 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004727 // We need to lookup a symbol using the original nlist symbol
4728 // index since this index is coming from the S_SYMBOL_STUBS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004729 stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4730 }
4731
4732 if (stub_symbol) {
4733 Address so_addr(symbol_stub_addr, section_list);
4734
4735 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4736 // Change the external symbol into a trampoline that makes
Adrian Prantl05097242018-04-30 16:49:04 +00004737 // sense These symbols were N_UNDF N_EXT, and are useless
4738 // to us, so we can re-use them so we don't have to make up
4739 // a synthetic symbol for no good reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004740 if (resolver_addresses.find(symbol_stub_addr) ==
4741 resolver_addresses.end())
4742 stub_symbol->SetType(eSymbolTypeTrampoline);
4743 else
4744 stub_symbol->SetType(eSymbolTypeResolver);
4745 stub_symbol->SetExternal(false);
4746 stub_symbol->GetAddressRef() = so_addr;
4747 stub_symbol->SetByteSize(symbol_stub_byte_size);
4748 } else {
4749 // Make a synthetic symbol to describe the trampoline stub
4750 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4751 if (sym_idx >= num_syms) {
4752 sym = symtab->Resize(++num_syms);
4753 stub_symbol = NULL; // this pointer no longer valid
4754 }
4755 sym[sym_idx].SetID(synthetic_sym_id++);
4756 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4757 if (resolver_addresses.find(symbol_stub_addr) ==
4758 resolver_addresses.end())
4759 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4760 else
4761 sym[sym_idx].SetType(eSymbolTypeResolver);
4762 sym[sym_idx].SetIsSynthetic(true);
4763 sym[sym_idx].GetAddressRef() = so_addr;
4764 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4765 ++sym_idx;
4766 }
4767 } else {
4768 if (log)
4769 log->Warning("symbol stub referencing symbol table symbol "
4770 "%u that isn't in our minimal symbol table, "
4771 "fix this!!!",
4772 stub_sym_id);
4773 }
4774 }
4775 }
4776 }
4777 }
4778 }
4779 }
4780
4781 if (!trie_entries.empty()) {
4782 for (const auto &e : trie_entries) {
4783 if (e.entry.import_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00004784 // Only add indirect symbols from the Trie entries if we didn't have
4785 // a N_INDR nlist entry for this already
Kate Stoneb9c1b512016-09-06 20:57:50 +00004786 if (indirect_symbol_names.find(e.entry.name) ==
4787 indirect_symbol_names.end()) {
4788 // Make a synthetic symbol to describe re-exported symbol.
4789 if (sym_idx >= num_syms)
4790 sym = symtab->Resize(++num_syms);
4791 sym[sym_idx].SetID(synthetic_sym_id++);
4792 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4793 sym[sym_idx].SetType(eSymbolTypeReExported);
4794 sym[sym_idx].SetIsSynthetic(true);
4795 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4796 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4797 sym[sym_idx].SetReExportedSymbolSharedLibrary(
4798 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4799 }
4800 ++sym_idx;
4801 }
4802 }
4803 }
4804 }
4805
Davide Italiano407c6912018-11-02 21:59:14 +00004806 // StreamFile s(stdout, false);
4807 // s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4808 // symtab->Dump(&s, NULL, eSortOrderNone);
4809 // Set symbol byte sizes correctly since mach-o nlist entries don't have
4810 // sizes
4811 symtab->CalculateSymbolSizes();
4812
4813 // s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4814 // symtab->Dump(&s, NULL, eSortOrderNone);
4815
Kate Stoneb9c1b512016-09-06 20:57:50 +00004816 return symtab->GetNumSymbols();
4817 }
4818 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004819}
4820
Kate Stoneb9c1b512016-09-06 20:57:50 +00004821void ObjectFileMachO::Dump(Stream *s) {
4822 ModuleSP module_sp(GetModule());
4823 if (module_sp) {
4824 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4825 s->Printf("%p: ", static_cast<void *>(this));
4826 s->Indent();
4827 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4828 s->PutCString("ObjectFileMachO64");
4829 else
4830 s->PutCString("ObjectFileMachO32");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004831
Kate Stoneb9c1b512016-09-06 20:57:50 +00004832 ArchSpec header_arch;
4833 GetArchitecture(header_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004834
Kate Stoneb9c1b512016-09-06 20:57:50 +00004835 *s << ", file = '" << m_file
Adrian Prantl9702c962018-05-11 00:41:20 +00004836 << "', triple = " << header_arch.GetTriple().getTriple() << "\n";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004837
Kate Stoneb9c1b512016-09-06 20:57:50 +00004838 SectionList *sections = GetSectionList();
4839 if (sections)
4840 sections->Dump(s, NULL, true, UINT32_MAX);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004841
Kate Stoneb9c1b512016-09-06 20:57:50 +00004842 if (m_symtab_ap.get())
4843 m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4844 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004845}
4846
Kate Stoneb9c1b512016-09-06 20:57:50 +00004847bool ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4848 const lldb_private::DataExtractor &data,
4849 lldb::offset_t lc_offset,
4850 lldb_private::UUID &uuid) {
4851 uint32_t i;
4852 struct uuid_command load_cmd;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004853
Kate Stoneb9c1b512016-09-06 20:57:50 +00004854 lldb::offset_t offset = lc_offset;
4855 for (i = 0; i < header.ncmds; ++i) {
4856 const lldb::offset_t cmd_offset = offset;
4857 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4858 break;
4859
4860 if (load_cmd.cmd == LC_UUID) {
4861 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4862
4863 if (uuid_bytes) {
4864 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4865 // We pretend these object files have no UUID to prevent crashing.
4866
4867 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4868 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4869 0xbb, 0x14, 0xf0, 0x0d};
4870
4871 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4872 return false;
4873
Pavel Labath2f93fd12018-06-26 15:12:20 +00004874 uuid = UUID::fromOptionalData(uuid_bytes, 16);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004875 return true;
4876 }
4877 return false;
4878 }
4879 offset = cmd_offset + load_cmd.cmdsize;
4880 }
4881 return false;
4882}
4883
Jason Molenda32762fd2018-10-11 00:28:35 +00004884static llvm::StringRef GetOSName(uint32_t cmd) {
Adrian Prantl9702c962018-05-11 00:41:20 +00004885 switch (cmd) {
4886 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004887 return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004888 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Jason Molenda32762fd2018-10-11 00:28:35 +00004889 return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
Adrian Prantl9702c962018-05-11 00:41:20 +00004890 case llvm::MachO::LC_VERSION_MIN_TVOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004891 return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004892 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004893 return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004894 default:
4895 llvm_unreachable("unexpected LC_VERSION load command");
4896 }
4897}
4898
Jason Molenda32762fd2018-10-11 00:28:35 +00004899namespace {
4900 struct OSEnv {
4901 llvm::StringRef os_type;
4902 llvm::StringRef environment;
4903 OSEnv(uint32_t cmd) {
4904 switch (cmd) {
4905 case PLATFORM_MACOS:
4906 os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4907 return;
4908 case PLATFORM_IOS:
4909 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4910 return;
4911 case PLATFORM_TVOS:
4912 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4913 return;
4914 case PLATFORM_WATCHOS:
4915 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4916 return;
4917// NEED_BRIDGEOS_TRIPLE case PLATFORM_BRIDGEOS:
4918// NEED_BRIDGEOS_TRIPLE os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4919// NEED_BRIDGEOS_TRIPLE return;
4920#if defined (PLATFORM_IOSSIMULATOR) && defined (PLATFORM_TVOSSIMULATOR) && defined (PLATFORM_WATCHOSSIMULATOR)
4921 case PLATFORM_IOSSIMULATOR:
4922 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4923 environment =
4924 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4925 return;
4926 case PLATFORM_TVOSSIMULATOR:
4927 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4928 environment =
4929 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4930 return;
4931 case PLATFORM_WATCHOSSIMULATOR:
4932 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4933 environment =
4934 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4935 return;
4936#endif
4937 default: {
4938 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
4939 LIBLLDB_LOG_PROCESS));
4940 if (log)
4941 log->Printf("unsupported platform in LC_BUILD_VERSION");
4942 }
4943 }
4944 }
4945 };
4946
4947 struct MinOS {
Eric Liu7d2f7832018-10-11 14:44:12 +00004948 uint32_t major_version, minor_version, patch_version;
Jason Molenda32762fd2018-10-11 00:28:35 +00004949 MinOS(uint32_t version)
Eric Liu7d2f7832018-10-11 14:44:12 +00004950 : major_version(version >> 16),
4951 minor_version((version >> 8) & 0xffu),
4952 patch_version(version & 0xffu) {}
Jason Molenda32762fd2018-10-11 00:28:35 +00004953 };
4954} // namespace
4955
Kate Stoneb9c1b512016-09-06 20:57:50 +00004956bool ObjectFileMachO::GetArchitecture(const llvm::MachO::mach_header &header,
4957 const lldb_private::DataExtractor &data,
4958 lldb::offset_t lc_offset,
4959 ArchSpec &arch) {
4960 arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4961
4962 if (arch.IsValid()) {
4963 llvm::Triple &triple = arch.GetTriple();
4964
4965 // Set OS to an unspecified unknown or a "*" so it can match any OS
4966 triple.setOS(llvm::Triple::UnknownOS);
4967 triple.setOSName(llvm::StringRef());
4968
4969 if (header.filetype == MH_PRELOAD) {
4970 if (header.cputype == CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00004971 // If this is a 32-bit arm binary, and it's a standalone binary, force
4972 // the Vendor to Apple so we don't accidentally pick up the generic
4973 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4974 // frame pointer register; most other armv7 ABIs use a combination of
4975 // r7 and r11.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004976 triple.setVendor(llvm::Triple::Apple);
4977 } else {
4978 // Set vendor to an unspecified unknown or a "*" so it can match any
Adrian Prantl05097242018-04-30 16:49:04 +00004979 // vendor This is required for correct behavior of EFI debugging on
4980 // x86_64
Kate Stoneb9c1b512016-09-06 20:57:50 +00004981 triple.setVendor(llvm::Triple::UnknownVendor);
4982 triple.setVendorName(llvm::StringRef());
4983 }
4984 return true;
4985 } else {
4986 struct load_command load_cmd;
Jason Molenda32762fd2018-10-11 00:28:35 +00004987 llvm::SmallString<16> os_name;
4988 llvm::raw_svector_ostream os(os_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004989
Jason Molenda32762fd2018-10-11 00:28:35 +00004990 // See if there is an LC_VERSION_MIN_* load command that can give
4991 // us the OS type.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004992 lldb::offset_t offset = lc_offset;
4993 for (uint32_t i = 0; i < header.ncmds; ++i) {
Greg Claytonf4d6de62013-04-24 22:29:28 +00004994 const lldb::offset_t cmd_offset = offset;
4995 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996 break;
4997
Adrian Prantl9702c962018-05-11 00:41:20 +00004998 struct version_min_command version_min;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004999 switch (load_cmd.cmd) {
5000 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005001 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005002 case llvm::MachO::LC_VERSION_MIN_TVOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00005003 case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
Adrian Prantl9702c962018-05-11 00:41:20 +00005004 if (load_cmd.cmdsize != sizeof(version_min))
5005 break;
Jason Molenda32762fd2018-10-11 00:28:35 +00005006 if (data.ExtractBytes(cmd_offset, sizeof(version_min),
5007 data.GetByteOrder(), &version_min) == 0)
5008 break;
5009 MinOS min_os(version_min.version);
Eric Liu7d2f7832018-10-11 14:44:12 +00005010 os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
5011 << min_os.minor_version << '.' << min_os.patch_version;
Adrian Prantl9702c962018-05-11 00:41:20 +00005012 triple.setOSName(os.str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005013 return true;
Jason Molenda32762fd2018-10-11 00:28:35 +00005014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005015 default:
5016 break;
Greg Claytonf4d6de62013-04-24 22:29:28 +00005017 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005018
Greg Claytonf4d6de62013-04-24 22:29:28 +00005019 offset = cmd_offset + load_cmd.cmdsize;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005020 }
5021
Jason Molenda32762fd2018-10-11 00:28:35 +00005022 // See if there is an LC_BUILD_VERSION load command that can give
5023 // us the OS type.
5024
5025 offset = lc_offset;
5026 for (uint32_t i = 0; i < header.ncmds; ++i) {
5027 const lldb::offset_t cmd_offset = offset;
5028 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
5029 break;
Adrian Prantl874e32d2018-11-13 23:14:37 +00005030 do {
5031 if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
5032 struct build_version_command build_version;
5033 if (load_cmd.cmdsize < sizeof(build_version)) {
5034 // Malformed load command.
5035 break;
5036 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005037 if (data.ExtractBytes(cmd_offset, sizeof(build_version),
5038 data.GetByteOrder(), &build_version) == 0)
Adrian Prantl874e32d2018-11-13 23:14:37 +00005039 break;
5040 MinOS min_os(build_version.minos);
5041 OSEnv os_env(build_version.platform);
5042 if (os_env.os_type.empty())
5043 break;
5044 os << os_env.os_type << min_os.major_version << '.'
5045 << min_os.minor_version << '.' << min_os.patch_version;
5046 triple.setOSName(os.str());
5047 if (!os_env.environment.empty())
5048 triple.setEnvironmentName(os_env.environment);
5049 return true;
5050 }
5051 } while (0);
Jason Molenda32762fd2018-10-11 00:28:35 +00005052 offset = cmd_offset + load_cmd.cmdsize;
5053 }
5054
Kate Stoneb9c1b512016-09-06 20:57:50 +00005055 if (header.filetype != MH_KEXT_BUNDLE) {
5056 // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
5057 // so lets not say our Vendor is Apple, leave it as an unspecified
5058 // unknown
5059 triple.setVendor(llvm::Triple::UnknownVendor);
5060 triple.setVendorName(llvm::StringRef());
5061 }
Greg Claytonf4d6de62013-04-24 22:29:28 +00005062 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005063 }
5064 return arch.IsValid();
Greg Claytonf4d6de62013-04-24 22:29:28 +00005065}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005066
Kate Stoneb9c1b512016-09-06 20:57:50 +00005067bool ObjectFileMachO::GetUUID(lldb_private::UUID *uuid) {
5068 ModuleSP module_sp(GetModule());
5069 if (module_sp) {
5070 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5071 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5072 return GetUUID(m_header, m_data, offset, *uuid);
5073 }
5074 return false;
Greg Clayton7ab7f892014-05-29 21:33:45 +00005075}
5076
Kate Stoneb9c1b512016-09-06 20:57:50 +00005077uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
5078 uint32_t count = 0;
5079 ModuleSP module_sp(GetModule());
5080 if (module_sp) {
5081 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5082 struct load_command load_cmd;
5083 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5084 std::vector<std::string> rpath_paths;
5085 std::vector<std::string> rpath_relative_paths;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005086 std::vector<std::string> at_exec_relative_paths;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005087 uint32_t i;
5088 for (i = 0; i < m_header.ncmds; ++i) {
5089 const uint32_t cmd_offset = offset;
5090 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5091 break;
5092
5093 switch (load_cmd.cmd) {
5094 case LC_RPATH:
5095 case LC_LOAD_DYLIB:
5096 case LC_LOAD_WEAK_DYLIB:
5097 case LC_REEXPORT_DYLIB:
5098 case LC_LOAD_DYLINKER:
5099 case LC_LOADFVMLIB:
5100 case LC_LOAD_UPWARD_DYLIB: {
5101 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5102 const char *path = m_data.PeekCStr(name_offset);
5103 if (path) {
5104 if (load_cmd.cmd == LC_RPATH)
5105 rpath_paths.push_back(path);
5106 else {
5107 if (path[0] == '@') {
5108 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5109 rpath_relative_paths.push_back(path + strlen("@rpath"));
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005110 else if (strncmp(path, "@executable_path",
5111 strlen("@executable_path")) == 0)
5112 at_exec_relative_paths.push_back(path
5113 + strlen("@executable_path"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005114 } else {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005115 FileSpec file_spec(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005116 if (files.AppendIfUnique(file_spec))
5117 count++;
5118 }
5119 }
5120 }
5121 } break;
5122
5123 default:
5124 break;
5125 }
5126 offset = cmd_offset + load_cmd.cmdsize;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005127 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005128
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005129 FileSpec this_file_spec(m_file);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005130 FileSystem::Instance().Resolve(this_file_spec);
5131
Kate Stoneb9c1b512016-09-06 20:57:50 +00005132 if (!rpath_paths.empty()) {
5133 // Fixup all LC_RPATH values to be absolute paths
Kate Stoneb9c1b512016-09-06 20:57:50 +00005134 std::string loader_path("@loader_path");
5135 std::string executable_path("@executable_path");
5136 for (auto &rpath : rpath_paths) {
5137 if (rpath.find(loader_path) == 0) {
5138 rpath.erase(0, loader_path.size());
5139 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5140 } else if (rpath.find(executable_path) == 0) {
5141 rpath.erase(0, executable_path.size());
5142 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5143 }
5144 }
5145
5146 for (const auto &rpath_relative_path : rpath_relative_paths) {
5147 for (const auto &rpath : rpath_paths) {
5148 std::string path = rpath;
5149 path += rpath_relative_path;
Adrian Prantl05097242018-04-30 16:49:04 +00005150 // It is OK to resolve this path because we must find a file on disk
5151 // for us to accept it anyway if it is rpath relative.
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005152 FileSpec file_spec(path);
5153 FileSystem::Instance().Resolve(file_spec);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00005154 if (FileSystem::Instance().Exists(file_spec) &&
5155 files.AppendIfUnique(file_spec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005156 count++;
5157 break;
5158 }
5159 }
5160 }
5161 }
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005162
5163 // We may have @executable_paths but no RPATHS. Figure those out here.
5164 // Only do this if this object file is the executable. We have no way to
5165 // get back to the actual executable otherwise, so we won't get the right
5166 // path.
5167 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5168 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5169 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5170 FileSpec file_spec =
5171 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00005172 if (FileSystem::Instance().Exists(file_spec) &&
5173 files.AppendIfUnique(file_spec))
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005174 count++;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005175 }
5176 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005177 }
5178 return count;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005179}
5180
Kate Stoneb9c1b512016-09-06 20:57:50 +00005181lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5182 // If the object file is not an executable it can't hold the entry point.
Adrian Prantl05097242018-04-30 16:49:04 +00005183 // m_entry_point_address is initialized to an invalid address, so we can just
5184 // return that. If m_entry_point_address is valid it means we've found it
5185 // already, so return the cached value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005186
Kate Stoneb9c1b512016-09-06 20:57:50 +00005187 if (!IsExecutable() || m_entry_point_address.IsValid())
Jim Ingham672e6f52011-03-07 23:44:08 +00005188 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00005189
Kate Stoneb9c1b512016-09-06 20:57:50 +00005190 // Otherwise, look for the UnixThread or Thread command. The data for the
Adrian Prantl05097242018-04-30 16:49:04 +00005191 // Thread command is given in /usr/include/mach-o.h, but it is basically:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005192 //
5193 // uint32_t flavor - this is the flavor argument you would pass to
5194 // thread_get_state
5195 // uint32_t count - this is the count of longs in the thread state data
5196 // struct XXX_thread_state state - this is the structure from
5197 // <machine/thread_status.h> corresponding to the flavor.
5198 // <repeat this trio>
5199 //
5200 // So we just keep reading the various register flavors till we find the GPR
5201 // one, then read the PC out of there.
5202 // FIXME: We will need to have a "RegisterContext data provider" class at some
5203 // point that can get all the registers
5204 // out of data in this form & attach them to a given thread. That should
Adrian Prantl05097242018-04-30 16:49:04 +00005205 // underlie the MacOS X User process plugin, and we'll also need it for the
5206 // MacOS X Core File process plugin. When we have that we can also use it
5207 // here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005208 //
5209 // For now we hard-code the offsets and flavors we need:
5210 //
5211 //
Greg Claytonc9660542012-02-05 02:38:54 +00005212
Kate Stoneb9c1b512016-09-06 20:57:50 +00005213 ModuleSP module_sp(GetModule());
5214 if (module_sp) {
5215 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5216 struct load_command load_cmd;
5217 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5218 uint32_t i;
5219 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5220 bool done = false;
5221
5222 for (i = 0; i < m_header.ncmds; ++i) {
5223 const lldb::offset_t cmd_offset = offset;
5224 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5225 break;
5226
5227 switch (load_cmd.cmd) {
5228 case LC_UNIXTHREAD:
5229 case LC_THREAD: {
5230 while (offset < cmd_offset + load_cmd.cmdsize) {
5231 uint32_t flavor = m_data.GetU32(&offset);
5232 uint32_t count = m_data.GetU32(&offset);
5233 if (count == 0) {
5234 // We've gotten off somehow, log and exit;
5235 return m_entry_point_address;
5236 }
5237
5238 switch (m_header.cputype) {
5239 case llvm::MachO::CPU_TYPE_ARM:
5240 if (flavor == 1 ||
5241 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 from
5242 // mach/arm/thread_status.h
Greg Claytonc3776bf2012-02-09 06:16:32 +00005243 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005244 offset += 60; // This is the offset of pc in the GPR thread state
5245 // data structure.
5246 start_address = m_data.GetU32(&offset);
5247 done = true;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005249 break;
5250 case llvm::MachO::CPU_TYPE_ARM64:
5251 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5252 {
5253 offset += 256; // This is the offset of pc in the GPR thread state
5254 // data structure.
5255 start_address = m_data.GetU64(&offset);
5256 done = true;
5257 }
5258 break;
5259 case llvm::MachO::CPU_TYPE_I386:
5260 if (flavor ==
5261 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5262 {
5263 offset += 40; // This is the offset of eip in the GPR thread state
5264 // data structure.
5265 start_address = m_data.GetU32(&offset);
5266 done = true;
5267 }
5268 break;
5269 case llvm::MachO::CPU_TYPE_X86_64:
5270 if (flavor ==
5271 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5272 {
5273 offset += 16 * 8; // This is the offset of rip in the GPR thread
5274 // state data structure.
5275 start_address = m_data.GetU64(&offset);
5276 done = true;
5277 }
5278 break;
5279 default:
5280 return m_entry_point_address;
5281 }
5282 // Haven't found the GPR flavor yet, skip over the data for this
5283 // flavor:
5284 if (done)
5285 break;
5286 offset += count * 4;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005287 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005288 } break;
5289 case LC_MAIN: {
5290 ConstString text_segment_name("__TEXT");
5291 uint64_t entryoffset = m_data.GetU64(&offset);
5292 SectionSP text_segment_sp =
5293 GetSectionList()->FindSectionByName(text_segment_name);
5294 if (text_segment_sp) {
5295 done = true;
5296 start_address = text_segment_sp->GetFileAddress() + entryoffset;
5297 }
5298 } break;
5299
5300 default:
5301 break;
5302 }
5303 if (done)
5304 break;
5305
5306 // Go to the next load command:
5307 offset = cmd_offset + load_cmd.cmdsize;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005308 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005309
5310 if (start_address != LLDB_INVALID_ADDRESS) {
5311 // We got the start address from the load commands, so now resolve that
Adrian Prantl05097242018-04-30 16:49:04 +00005312 // address in the sections of this ObjectFile:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005313 if (!m_entry_point_address.ResolveAddressUsingFileSections(
5314 start_address, GetSectionList())) {
5315 m_entry_point_address.Clear();
5316 }
5317 } else {
5318 // We couldn't read the UnixThread load command - maybe it wasn't there.
Adrian Prantl05097242018-04-30 16:49:04 +00005319 // As a fallback look for the "start" symbol in the main executable.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005320
5321 ModuleSP module_sp(GetModule());
5322
5323 if (module_sp) {
5324 SymbolContextList contexts;
5325 SymbolContext context;
5326 if (module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5327 eSymbolTypeCode, contexts)) {
5328 if (contexts.GetContextAtIndex(0, context))
5329 m_entry_point_address = context.symbol->GetAddress();
5330 }
5331 }
5332 }
5333 }
5334
5335 return m_entry_point_address;
5336}
5337
5338lldb_private::Address ObjectFileMachO::GetHeaderAddress() {
5339 lldb_private::Address header_addr;
5340 SectionList *section_list = GetSectionList();
5341 if (section_list) {
5342 SectionSP text_segment_sp(
5343 section_list->FindSectionByName(GetSegmentNameTEXT()));
5344 if (text_segment_sp) {
5345 header_addr.SetSection(text_segment_sp);
5346 header_addr.SetOffset(0);
5347 }
5348 }
5349 return header_addr;
5350}
5351
5352uint32_t ObjectFileMachO::GetNumThreadContexts() {
5353 ModuleSP module_sp(GetModule());
5354 if (module_sp) {
5355 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5356 if (!m_thread_context_offsets_valid) {
5357 m_thread_context_offsets_valid = true;
5358 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5359 FileRangeArray::Entry file_range;
5360 thread_command thread_cmd;
5361 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5362 const uint32_t cmd_offset = offset;
5363 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5364 break;
5365
5366 if (thread_cmd.cmd == LC_THREAD) {
5367 file_range.SetRangeBase(offset);
5368 file_range.SetByteSize(thread_cmd.cmdsize - 8);
5369 m_thread_context_offsets.Append(file_range);
5370 }
5371 offset = cmd_offset + thread_cmd.cmdsize;
5372 }
5373 }
5374 }
5375 return m_thread_context_offsets.GetSize();
Greg Claytonc3776bf2012-02-09 06:16:32 +00005376}
5377
Jason Molenda3533cec2017-04-06 01:50:11 +00005378std::string ObjectFileMachO::GetIdentifierString() {
5379 std::string result;
5380 ModuleSP module_sp(GetModule());
5381 if (module_sp) {
5382 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005383
Adrian Prantl05097242018-04-30 16:49:04 +00005384 // First, look over the load commands for an LC_NOTE load command with
5385 // data_owner string "kern ver str" & use that if found.
Jason Molenda3533cec2017-04-06 01:50:11 +00005386 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5387 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5388 const uint32_t cmd_offset = offset;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005389 load_command lc;
5390 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5391 break;
5392 if (lc.cmd == LC_NOTE)
5393 {
5394 char data_owner[17];
5395 m_data.CopyData (offset, 16, data_owner);
5396 data_owner[16] = '\0';
5397 offset += 16;
5398 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5399 uint64_t size = m_data.GetU64_unchecked (&offset);
5400
Adrian Prantl05097242018-04-30 16:49:04 +00005401 // "kern ver str" has a uint32_t version and then a nul terminated
5402 // c-string.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005403 if (strcmp ("kern ver str", data_owner) == 0)
5404 {
5405 offset = fileoff;
5406 uint32_t version;
5407 if (m_data.GetU32 (&offset, &version, 1) != nullptr)
5408 {
5409 if (version == 1)
5410 {
5411 uint32_t strsize = size - sizeof (uint32_t);
5412 char *buf = (char*) malloc (strsize);
5413 if (buf)
5414 {
5415 m_data.CopyData (offset, strsize, buf);
5416 buf[strsize - 1] = '\0';
5417 result = buf;
5418 if (buf)
5419 free (buf);
5420 return result;
5421 }
5422 }
5423 }
5424 }
5425 }
5426 offset = cmd_offset + lc.cmdsize;
5427 }
5428
Adrian Prantl05097242018-04-30 16:49:04 +00005429 // Second, make a pass over the load commands looking for an obsolete
5430 // LC_IDENT load command.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005431 offset = MachHeaderSizeFromMagic(m_header.magic);
5432 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5433 const uint32_t cmd_offset = offset;
Jason Molenda3533cec2017-04-06 01:50:11 +00005434 struct ident_command ident_command;
5435 if (m_data.GetU32(&offset, &ident_command, 2) == NULL)
5436 break;
5437 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005438 char *buf = (char *) malloc (ident_command.cmdsize);
Jason Molenda3533cec2017-04-06 01:50:11 +00005439 if (buf != nullptr
5440 && m_data.CopyData (offset, ident_command.cmdsize, buf) == ident_command.cmdsize) {
5441 buf[ident_command.cmdsize - 1] = '\0';
5442 result = buf;
5443 }
5444 if (buf)
5445 free (buf);
5446 }
5447 offset = cmd_offset + ident_command.cmdsize;
5448 }
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005449
Jason Molenda3533cec2017-04-06 01:50:11 +00005450 }
5451 return result;
5452}
5453
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005454bool ObjectFileMachO::GetCorefileMainBinaryInfo (addr_t &address, UUID &uuid) {
5455 address = LLDB_INVALID_ADDRESS;
5456 uuid.Clear();
5457 ModuleSP module_sp(GetModule());
5458 if (module_sp) {
5459 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5460 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5461 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5462 const uint32_t cmd_offset = offset;
5463 load_command lc;
5464 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5465 break;
5466 if (lc.cmd == LC_NOTE)
5467 {
5468 char data_owner[17];
5469 memset (data_owner, 0, sizeof (data_owner));
5470 m_data.CopyData (offset, 16, data_owner);
5471 offset += 16;
5472 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5473 uint64_t size = m_data.GetU64_unchecked (&offset);
5474
Adrian Prantl05097242018-04-30 16:49:04 +00005475 // "main bin spec" (main binary specification) data payload is
5476 // formatted:
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005477 // uint32_t version [currently 1]
5478 // uint32_t type [0 == unspecified, 1 == kernel, 2 == user process]
5479 // uint64_t address [ UINT64_MAX if address not specified ]
5480 // uuid_t uuid [ all zero's if uuid not specified ]
5481 // uint32_t log2_pagesize [ process page size in log base 2, e.g. 4k pages are 12. 0 for unspecified ]
5482
5483 if (strcmp ("main bin spec", data_owner) == 0 && size >= 32)
5484 {
5485 offset = fileoff;
5486 uint32_t version;
5487 if (m_data.GetU32 (&offset, &version, 1) != nullptr && version == 1)
5488 {
5489 uint32_t type = 0;
5490 uuid_t raw_uuid;
Jason Molenda3f608292017-04-13 02:12:32 +00005491 memset (raw_uuid, 0, sizeof (uuid_t));
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005492
Pavel Labath2f93fd12018-06-26 15:12:20 +00005493 if (m_data.GetU32(&offset, &type, 1) &&
5494 m_data.GetU64(&offset, &address, 1) &&
5495 m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
5496 uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t));
5497 return true;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005498 }
5499 }
5500 }
5501 }
5502 offset = cmd_offset + lc.cmdsize;
5503 }
5504 }
5505 return false;
5506}
5507
Greg Claytonc3776bf2012-02-09 06:16:32 +00005508lldb::RegisterContextSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005509ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5510 lldb_private::Thread &thread) {
5511 lldb::RegisterContextSP reg_ctx_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00005512
Kate Stoneb9c1b512016-09-06 20:57:50 +00005513 ModuleSP module_sp(GetModule());
5514 if (module_sp) {
5515 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5516 if (!m_thread_context_offsets_valid)
5517 GetNumThreadContexts();
Greg Claytona1743492012-03-13 23:14:29 +00005518
Kate Stoneb9c1b512016-09-06 20:57:50 +00005519 const FileRangeArray::Entry *thread_context_file_range =
5520 m_thread_context_offsets.GetEntryAtIndex(idx);
5521 if (thread_context_file_range) {
Jason Molenda4e7511e2013-03-06 23:19:17 +00005522
Kate Stoneb9c1b512016-09-06 20:57:50 +00005523 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5524 thread_context_file_range->GetByteSize());
Jim Ingham28eb5712012-10-12 17:34:26 +00005525
Kate Stoneb9c1b512016-09-06 20:57:50 +00005526 switch (m_header.cputype) {
5527 case llvm::MachO::CPU_TYPE_ARM64:
5528 reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data));
5529 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005530
Kate Stoneb9c1b512016-09-06 20:57:50 +00005531 case llvm::MachO::CPU_TYPE_ARM:
5532 reg_ctx_sp.reset(new RegisterContextDarwin_arm_Mach(thread, data));
5533 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005534
Kate Stoneb9c1b512016-09-06 20:57:50 +00005535 case llvm::MachO::CPU_TYPE_I386:
5536 reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data));
5537 break;
5538
5539 case llvm::MachO::CPU_TYPE_X86_64:
5540 reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data));
5541 break;
5542 }
Greg Claytonc3776bf2012-02-09 06:16:32 +00005543 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005544 }
5545 return reg_ctx_sp;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005546}
5547
Kate Stoneb9c1b512016-09-06 20:57:50 +00005548ObjectFile::Type ObjectFileMachO::CalculateType() {
5549 switch (m_header.filetype) {
5550 case MH_OBJECT: // 0x1u
5551 if (GetAddressByteSize() == 4) {
5552 // 32 bit kexts are just object files, but they do have a valid
5553 // UUID load command.
5554 UUID uuid;
5555 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005556 // this checking for the UUID load command is not enough we could
5557 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5558 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005559 if (m_strata == eStrataInvalid)
5560 m_strata = eStrataKernel;
5561 return eTypeSharedLibrary;
5562 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005563 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005564 return eTypeObjectFile;
5565
5566 case MH_EXECUTE:
5567 return eTypeExecutable; // 0x2u
5568 case MH_FVMLIB:
5569 return eTypeSharedLibrary; // 0x3u
5570 case MH_CORE:
5571 return eTypeCoreFile; // 0x4u
5572 case MH_PRELOAD:
5573 return eTypeSharedLibrary; // 0x5u
5574 case MH_DYLIB:
5575 return eTypeSharedLibrary; // 0x6u
5576 case MH_DYLINKER:
5577 return eTypeDynamicLinker; // 0x7u
5578 case MH_BUNDLE:
5579 return eTypeSharedLibrary; // 0x8u
5580 case MH_DYLIB_STUB:
5581 return eTypeStubLibrary; // 0x9u
5582 case MH_DSYM:
5583 return eTypeDebugInfo; // 0xAu
5584 case MH_KEXT_BUNDLE:
5585 return eTypeSharedLibrary; // 0xBu
5586 default:
5587 break;
5588 }
5589 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005590}
5591
Kate Stoneb9c1b512016-09-06 20:57:50 +00005592ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5593 switch (m_header.filetype) {
5594 case MH_OBJECT: // 0x1u
5595 {
5596 // 32 bit kexts are just object files, but they do have a valid
5597 // UUID load command.
5598 UUID uuid;
5599 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005600 // this checking for the UUID load command is not enough we could
5601 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5602 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005603 if (m_type == eTypeInvalid)
5604 m_type = eTypeSharedLibrary;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005605
Kate Stoneb9c1b512016-09-06 20:57:50 +00005606 return eStrataKernel;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005607 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005608 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005609 return eStrataUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005610
5611 case MH_EXECUTE: // 0x2u
5612 // Check for the MH_DYLDLINK bit in the flags
5613 if (m_header.flags & MH_DYLDLINK) {
5614 return eStrataUser;
5615 } else {
5616 SectionList *section_list = GetSectionList();
5617 if (section_list) {
5618 static ConstString g_kld_section_name("__KLD");
5619 if (section_list->FindSectionByName(g_kld_section_name))
5620 return eStrataKernel;
5621 }
5622 }
5623 return eStrataRawImage;
5624
5625 case MH_FVMLIB:
5626 return eStrataUser; // 0x3u
5627 case MH_CORE:
5628 return eStrataUnknown; // 0x4u
5629 case MH_PRELOAD:
5630 return eStrataRawImage; // 0x5u
5631 case MH_DYLIB:
5632 return eStrataUser; // 0x6u
5633 case MH_DYLINKER:
5634 return eStrataUser; // 0x7u
5635 case MH_BUNDLE:
5636 return eStrataUser; // 0x8u
5637 case MH_DYLIB_STUB:
5638 return eStrataUser; // 0x9u
5639 case MH_DSYM:
5640 return eStrataUnknown; // 0xAu
5641 case MH_KEXT_BUNDLE:
5642 return eStrataKernel; // 0xBu
5643 default:
5644 break;
5645 }
5646 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005647}
5648
Pavel Labath2272c482018-06-18 15:02:23 +00005649llvm::VersionTuple ObjectFileMachO::GetVersion() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005650 ModuleSP module_sp(GetModule());
5651 if (module_sp) {
5652 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5653 struct dylib_command load_cmd;
5654 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5655 uint32_t version_cmd = 0;
5656 uint64_t version = 0;
5657 uint32_t i;
5658 for (i = 0; i < m_header.ncmds; ++i) {
5659 const lldb::offset_t cmd_offset = offset;
5660 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5661 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005662
Kate Stoneb9c1b512016-09-06 20:57:50 +00005663 if (load_cmd.cmd == LC_ID_DYLIB) {
5664 if (version_cmd == 0) {
5665 version_cmd = load_cmd.cmd;
5666 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5667 break;
5668 version = load_cmd.dylib.current_version;
Greg Claytonc2ff9312012-02-22 19:41:02 +00005669 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005670 break; // Break for now unless there is another more complete version
5671 // number load command in the future.
5672 }
5673 offset = cmd_offset + load_cmd.cmdsize;
5674 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00005675
Kate Stoneb9c1b512016-09-06 20:57:50 +00005676 if (version_cmd == LC_ID_DYLIB) {
Pavel Labath2272c482018-06-18 15:02:23 +00005677 unsigned major = (version & 0xFFFF0000ull) >> 16;
5678 unsigned minor = (version & 0x0000FF00ull) >> 8;
5679 unsigned subminor = (version & 0x000000FFull);
5680 return llvm::VersionTuple(major, minor, subminor);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005681 }
5682 }
Pavel Labath2272c482018-06-18 15:02:23 +00005683 return llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005684}
5685
5686bool ObjectFileMachO::GetArchitecture(ArchSpec &arch) {
5687 ModuleSP module_sp(GetModule());
5688 if (module_sp) {
5689 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5690 return GetArchitecture(m_header, m_data,
5691 MachHeaderSizeFromMagic(m_header.magic), arch);
5692 }
5693 return false;
5694}
5695
Jason Molenda07580ff2018-05-04 00:59:37 +00005696void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process, addr_t &base_addr, UUID &uuid) {
5697 uuid.Clear();
5698 base_addr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005699 if (process && process->GetDynamicLoader()) {
5700 DynamicLoader *dl = process->GetDynamicLoader();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005701 LazyBool using_shared_cache;
5702 LazyBool private_shared_cache;
Jason Molenda07580ff2018-05-04 00:59:37 +00005703 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005704 private_shared_cache);
5705 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005706 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005707 if (log)
Jason Molenda07580ff2018-05-04 00:59:37 +00005708 log->Printf("inferior process shared cache has a UUID of %s, base address 0x%" PRIx64 , uuid.GetAsString().c_str(), base_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005709}
5710
Jason Molenda07580ff2018-05-04 00:59:37 +00005711// From dyld SPI header dyld_process_info.h
5712typedef void *dyld_process_info;
5713struct lldb_copy__dyld_process_cache_info {
5714 uuid_t cacheUUID; // UUID of cache used by process
5715 uint64_t cacheBaseAddress; // load address of dyld shared cache
5716 bool noCache; // process is running without a dyld cache
5717 bool privateCache; // process is using a private copy of its dyld cache
5718};
5719
5720// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with llvm
5721// enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile errors.
5722// So we need to use the actual underlying types of task_t and kern_return_t
5723// below.
5724extern "C" unsigned int /*task_t*/ mach_task_self();
5725
5726void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5727 uuid.Clear();
5728 base_addr = LLDB_INVALID_ADDRESS;
5729
Kate Stoneb9c1b512016-09-06 20:57:50 +00005730#if defined(__APPLE__) && \
5731 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5732 uint8_t *(*dyld_get_all_image_infos)(void);
5733 dyld_get_all_image_infos =
5734 (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5735 if (dyld_get_all_image_infos) {
5736 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5737 if (dyld_all_image_infos_address) {
5738 uint32_t *version = (uint32_t *)
5739 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5740 if (*version >= 13) {
5741 uuid_t *sharedCacheUUID_address = 0;
5742 int wordsize = sizeof(uint8_t *);
5743 if (wordsize == 8) {
5744 sharedCacheUUID_address =
5745 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5746 160); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005747 if (*version >= 15)
5748 base_addr = *(uint64_t *) ((uint8_t *) dyld_all_image_infos_address
5749 + 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +00005750 } else {
5751 sharedCacheUUID_address =
5752 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5753 84); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005754 if (*version >= 15) {
5755 base_addr = 0;
5756 base_addr = *(uint32_t *) ((uint8_t *) dyld_all_image_infos_address
5757 + 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5758 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005759 }
Pavel Labath2f93fd12018-06-26 15:12:20 +00005760 uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005761 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005762 }
Jason Molendafd443e92018-02-07 01:28:29 +00005763 } else {
5764 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
Jason Molenda07580ff2018-05-04 00:59:37 +00005765 dyld_process_info (*dyld_process_info_create)(unsigned int /* task_t */ task, uint64_t timestamp, unsigned int /*kern_return_t*/ *kernelError);
5766 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5767 void (*dyld_process_info_release)(dyld_process_info info);
5768
5769 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, unsigned int /*kern_return_t*/ *))
5770 dlsym (RTLD_DEFAULT, "_dyld_process_info_create");
5771 dyld_process_info_get_cache = (void (*)(void *, void *))
5772 dlsym (RTLD_DEFAULT, "_dyld_process_info_get_cache");
5773 dyld_process_info_release = (void (*)(void *))
5774 dlsym (RTLD_DEFAULT, "_dyld_process_info_release");
5775
5776 if (dyld_process_info_create && dyld_process_info_get_cache) {
5777 unsigned int /*kern_return_t */ kern_ret;
5778 dyld_process_info process_info = dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5779 if (process_info) {
5780 struct lldb_copy__dyld_process_cache_info sc_info;
5781 memset (&sc_info, 0, sizeof (struct lldb_copy__dyld_process_cache_info));
5782 dyld_process_info_get_cache (process_info, &sc_info);
5783 if (sc_info.cacheBaseAddress != 0) {
5784 base_addr = sc_info.cacheBaseAddress;
Pavel Labath2f93fd12018-06-26 15:12:20 +00005785 uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
Jason Molenda07580ff2018-05-04 00:59:37 +00005786 }
5787 dyld_process_info_release (process_info);
5788 }
Jason Molendafd443e92018-02-07 01:28:29 +00005789 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005790 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005791 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005792 if (log && uuid.IsValid())
Jason Molenda07580ff2018-05-04 00:59:37 +00005793 log->Printf("lldb's in-memory shared cache has a UUID of %s base address of 0x%" PRIx64, uuid.GetAsString().c_str(), base_addr);
Jason Molenda0e0954c2013-04-16 06:24:42 +00005794#endif
Jason Molenda0e0954c2013-04-16 06:24:42 +00005795}
5796
Pavel Labath2272c482018-06-18 15:02:23 +00005797llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5798 if (!m_min_os_version) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005799 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labath2272c482018-06-18 15:02:23 +00005800 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005801 const lldb::offset_t load_cmd_offset = offset;
5802
5803 version_min_command lc;
5804 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5805 break;
5806 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5807 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5808 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5809 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5810 if (m_data.GetU32(&offset, &lc.version,
5811 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5812 const uint32_t xxxx = lc.version >> 16;
5813 const uint32_t yy = (lc.version >> 8) & 0xffu;
5814 const uint32_t zz = lc.version & 0xffu;
5815 if (xxxx) {
Pavel Labath2272c482018-06-18 15:02:23 +00005816 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5817 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005818 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005819 }
5820 } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5821 // struct build_version_command {
5822 // uint32_t cmd; /* LC_BUILD_VERSION */
5823 // uint32_t cmdsize; /* sizeof(struct build_version_command) plus */
5824 // /* ntools * sizeof(struct build_tool_version) */
5825 // uint32_t platform; /* platform */
5826 // uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5827 // uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5828 // uint32_t ntools; /* number of tool entries following this */
5829 // };
5830
5831 offset += 4; // skip platform
5832 uint32_t minos = m_data.GetU32(&offset);
5833
5834 const uint32_t xxxx = minos >> 16;
5835 const uint32_t yy = (minos >> 8) & 0xffu;
5836 const uint32_t zz = minos & 0xffu;
5837 if (xxxx) {
5838 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5839 break;
Greg Clayton9b234982013-10-24 22:54:08 +00005840 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005841 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005842
Kate Stoneb9c1b512016-09-06 20:57:50 +00005843 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005844 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005845
Pavel Labath2272c482018-06-18 15:02:23 +00005846 if (!m_min_os_version) {
5847 // Set version to an empty value so we don't keep trying to
5848 m_min_os_version = llvm::VersionTuple();
Greg Clayton9b234982013-10-24 22:54:08 +00005849 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005850 }
5851
Pavel Labath2272c482018-06-18 15:02:23 +00005852 return *m_min_os_version;
Greg Clayton9b234982013-10-24 22:54:08 +00005853}
5854
Kate Stoneb9c1b512016-09-06 20:57:50 +00005855uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions,
5856 uint32_t num_versions) {
5857 if (m_sdk_versions.empty()) {
5858 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5859 bool success = false;
5860 for (uint32_t i = 0; success == false && i < m_header.ncmds; ++i) {
5861 const lldb::offset_t load_cmd_offset = offset;
5862
5863 version_min_command lc;
5864 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5865 break;
5866 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5867 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5868 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5869 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5870 if (m_data.GetU32(&offset, &lc.version,
5871 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5872 const uint32_t xxxx = lc.sdk >> 16;
5873 const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5874 const uint32_t zz = lc.sdk & 0xffu;
5875 if (xxxx) {
5876 m_sdk_versions.push_back(xxxx);
5877 m_sdk_versions.push_back(yy);
5878 m_sdk_versions.push_back(zz);
Jason Molenda32a91422018-06-25 23:45:39 +00005879 success = true;
5880 } else {
5881 GetModule()->ReportWarning(
5882 "minimum OS version load command with invalid (0) version found.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005883 }
Greg Clayton9b234982013-10-24 22:54:08 +00005884 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005885 }
5886 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005887 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005888
Jason Molenda32762fd2018-10-11 00:28:35 +00005889 if (success == false)
5890 {
5891 offset = MachHeaderSizeFromMagic(m_header.magic);
5892 for (uint32_t i = 0; success == false && i < m_header.ncmds; ++i)
5893 {
5894 const lldb::offset_t load_cmd_offset = offset;
5895
5896 version_min_command lc;
5897 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5898 break;
5899 if (lc.cmd == llvm::MachO::LC_BUILD_VERSION)
5900 {
5901 // struct build_version_command {
5902 // uint32_t cmd; /* LC_BUILD_VERSION */
5903 // uint32_t cmdsize; /* sizeof(struct build_version_command) plus */
5904 // /* ntools * sizeof(struct build_tool_version) */
5905 // uint32_t platform; /* platform */
5906 // uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5907 // uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5908 // uint32_t ntools; /* number of tool entries following this */
5909 // };
5910
5911 offset += 4; // skip platform
5912 uint32_t minos = m_data.GetU32(&offset);
5913
5914 const uint32_t xxxx = minos >> 16;
5915 const uint32_t yy = (minos >> 8) & 0xffu;
5916 const uint32_t zz = minos & 0xffu;
5917 if (xxxx)
5918 {
5919 m_sdk_versions.push_back (xxxx);
5920 m_sdk_versions.push_back (yy);
5921 m_sdk_versions.push_back (zz);
Jason Molendadcb3c282018-10-11 18:37:53 +00005922 success = true;
Jason Molenda32762fd2018-10-11 00:28:35 +00005923 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005924 }
5925 offset = load_cmd_offset + lc.cmdsize;
5926 }
5927 }
5928
Kate Stoneb9c1b512016-09-06 20:57:50 +00005929 if (success == false) {
Jason Molenda32a91422018-06-25 23:45:39 +00005930 // Push an invalid value so we don't try to find
5931 // the version # again on the next call to this
5932 // method.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005933 m_sdk_versions.push_back(UINT32_MAX);
Greg Clayton9b234982013-10-24 22:54:08 +00005934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005935 }
5936
Jason Molenda32a91422018-06-25 23:45:39 +00005937 // Legitimate version numbers will have 3 entries pushed
5938 // on to m_sdk_versions. If we only have one value, it's
5939 // the sentinel value indicating that this object file
5940 // does not have a valid minimum os version #.
5941 if (m_sdk_versions.size() > 1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005942 if (versions != NULL && num_versions > 0) {
5943 for (size_t i = 0; i < num_versions; ++i) {
5944 if (i < m_sdk_versions.size())
5945 versions[i] = m_sdk_versions[i];
5946 else
5947 versions[i] = 0;
5948 }
5949 }
5950 return m_sdk_versions.size();
5951 }
5952 // Call the superclasses version that will empty out the data
5953 return ObjectFile::GetSDKVersion(versions, num_versions);
Greg Clayton9b234982013-10-24 22:54:08 +00005954}
5955
Kate Stoneb9c1b512016-09-06 20:57:50 +00005956bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5957 return m_header.filetype == llvm::MachO::MH_DYLINKER;
Greg Clayton08928f32015-02-05 02:01:34 +00005958}
5959
Kate Stoneb9c1b512016-09-06 20:57:50 +00005960bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5961 return m_allow_assembly_emulation_unwind_plans;
Jason Molenda955dcf22016-05-04 03:09:40 +00005962}
5963
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005964//------------------------------------------------------------------
5965// PluginInterface protocol
5966//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00005967lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5968 return GetPluginNameStatic();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005969}
5970
Kate Stoneb9c1b512016-09-06 20:57:50 +00005971uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005972
Kate Stoneb9c1b512016-09-06 20:57:50 +00005973Section *ObjectFileMachO::GetMachHeaderSection() {
Adrian Prantl05097242018-04-30 16:49:04 +00005974 // Find the first address of the mach header which is the first non-zero file
5975 // sized section whose file offset is zero. This is the base file address of
5976 // the mach-o file which can be subtracted from the vmaddr of the other
Kate Stoneb9c1b512016-09-06 20:57:50 +00005977 // segments found in memory and added to the load address
5978 ModuleSP module_sp = GetModule();
5979 if (module_sp) {
5980 SectionList *section_list = GetSectionList();
5981 if (section_list) {
5982 lldb::addr_t mach_base_file_addr = LLDB_INVALID_ADDRESS;
5983 const size_t num_sections = section_list->GetSize();
Greg Clayton07347372015-06-08 21:53:11 +00005984
Kate Stoneb9c1b512016-09-06 20:57:50 +00005985 for (size_t sect_idx = 0; sect_idx < num_sections &&
5986 mach_base_file_addr == LLDB_INVALID_ADDRESS;
5987 ++sect_idx) {
5988 Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5989 if (section && section->GetFileSize() > 0 &&
5990 section->GetFileOffset() == 0 &&
5991 section->IsThreadSpecific() == false &&
5992 module_sp.get() == section->GetModule().get()) {
5993 return section;
Greg Clayton07347372015-06-08 21:53:11 +00005994 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005995 }
Greg Clayton07347372015-06-08 21:53:11 +00005996 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005997 }
5998 return nullptr;
Greg Clayton07347372015-06-08 21:53:11 +00005999}
6000
Kate Stoneb9c1b512016-09-06 20:57:50 +00006001lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
6002 lldb::addr_t mach_header_load_address, const Section *mach_header_section,
6003 const Section *section) {
6004 ModuleSP module_sp = GetModule();
6005 if (module_sp && mach_header_section && section &&
6006 mach_header_load_address != LLDB_INVALID_ADDRESS) {
6007 lldb::addr_t mach_header_file_addr = mach_header_section->GetFileAddress();
6008 if (mach_header_file_addr != LLDB_INVALID_ADDRESS) {
6009 if (section && section->GetFileSize() > 0 &&
6010 section->IsThreadSpecific() == false &&
6011 module_sp.get() == section->GetModule().get()) {
6012 // Ignore __LINKEDIT and __DWARF segments
6013 if (section->GetName() == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00006014 // Only map __LINKEDIT if we have an in memory image and this isn't a
6015 // kernel binary like a kext or mach_kernel.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006016 const bool is_memory_image = (bool)m_process_wp.lock();
6017 const Strata strata = GetStrata();
6018 if (is_memory_image == false || strata == eStrataKernel)
6019 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00006020 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006021 return section->GetFileAddress() - mach_header_file_addr +
6022 mach_header_load_address;
6023 }
Greg Clayton07347372015-06-08 21:53:11 +00006024 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006025 }
6026 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00006027}
6028
Kate Stoneb9c1b512016-09-06 20:57:50 +00006029bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
6030 bool value_is_offset) {
6031 ModuleSP module_sp = GetModule();
6032 if (module_sp) {
6033 size_t num_loaded_sections = 0;
6034 SectionList *section_list = GetSectionList();
6035 if (section_list) {
6036 const size_t num_sections = section_list->GetSize();
Greg Clayton7524e092014-02-06 20:10:16 +00006037
Kate Stoneb9c1b512016-09-06 20:57:50 +00006038 if (value_is_offset) {
6039 // "value" is an offset to apply to each top level segment
6040 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +00006041 // Iterate through the object file sections to find all of the
6042 // sections that size on disk (to avoid __PAGEZERO) and load them
Kate Stoneb9c1b512016-09-06 20:57:50 +00006043 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6044 if (section_sp && section_sp->GetFileSize() > 0 &&
6045 section_sp->IsThreadSpecific() == false &&
6046 module_sp.get() == section_sp->GetModule().get()) {
6047 // Ignore __LINKEDIT and __DWARF segments
6048 if (section_sp->GetName() == GetSegmentNameLINKEDIT()) {
6049 // Only map __LINKEDIT if we have an in memory image and this
Adrian Prantl05097242018-04-30 16:49:04 +00006050 // isn't a kernel binary like a kext or mach_kernel.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006051 const bool is_memory_image = (bool)m_process_wp.lock();
6052 const Strata strata = GetStrata();
6053 if (is_memory_image == false || strata == eStrataKernel)
6054 continue;
Greg Clayton7524e092014-02-06 20:10:16 +00006055 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006056 if (target.GetSectionLoadList().SetSectionLoadAddress(
6057 section_sp, section_sp->GetFileAddress() + value))
6058 ++num_loaded_sections;
6059 }
Greg Clayton7524e092014-02-06 20:10:16 +00006060 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006061 } else {
6062 // "value" is the new base address of the mach_header, adjust each
6063 // section accordingly
6064
6065 Section *mach_header_section = GetMachHeaderSection();
6066 if (mach_header_section) {
6067 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6068 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6069
6070 lldb::addr_t section_load_addr =
6071 CalculateSectionLoadAddressForMemoryImage(
6072 value, mach_header_section, section_sp.get());
6073 if (section_load_addr != LLDB_INVALID_ADDRESS) {
6074 if (target.GetSectionLoadList().SetSectionLoadAddress(
6075 section_sp, section_load_addr))
6076 ++num_loaded_sections;
6077 }
6078 }
6079 }
6080 }
Greg Clayton7524e092014-02-06 20:10:16 +00006081 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006082 return num_loaded_sections > 0;
6083 }
6084 return false;
Greg Clayton7524e092014-02-06 20:10:16 +00006085}
6086
Kate Stoneb9c1b512016-09-06 20:57:50 +00006087bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00006088 const FileSpec &outfile, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00006089 if (process_sp) {
6090 Target &target = process_sp->GetTarget();
6091 const ArchSpec target_arch = target.GetArchitecture();
6092 const llvm::Triple &target_triple = target_arch.GetTriple();
6093 if (target_triple.getVendor() == llvm::Triple::Apple &&
6094 (target_triple.getOS() == llvm::Triple::MacOSX ||
6095 target_triple.getOS() == llvm::Triple::IOS ||
6096 target_triple.getOS() == llvm::Triple::WatchOS ||
6097 target_triple.getOS() == llvm::Triple::TvOS)) {
Jason Molenda32762fd2018-10-11 00:28:35 +00006098 // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00006099 bool make_core = false;
6100 switch (target_arch.GetMachine()) {
6101 case llvm::Triple::aarch64:
6102 case llvm::Triple::arm:
6103 case llvm::Triple::thumb:
6104 case llvm::Triple::x86:
6105 case llvm::Triple::x86_64:
6106 make_core = true;
6107 break;
6108 default:
6109 error.SetErrorStringWithFormat("unsupported core architecture: %s",
6110 target_triple.str().c_str());
6111 break;
6112 }
6113
6114 if (make_core) {
6115 std::vector<segment_command_64> segment_load_commands;
6116 // uint32_t range_info_idx = 0;
6117 MemoryRegionInfo range_info;
Zachary Turner97206d52017-05-12 04:51:55 +00006118 Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006119 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6120 const ByteOrder byte_order = target_arch.GetByteOrder();
6121 if (range_error.Success()) {
6122 while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
6123 const addr_t addr = range_info.GetRange().GetRangeBase();
6124 const addr_t size = range_info.GetRange().GetByteSize();
6125
6126 if (size == 0)
6127 break;
6128
6129 // Calculate correct protections
6130 uint32_t prot = 0;
6131 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
6132 prot |= VM_PROT_READ;
6133 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
6134 prot |= VM_PROT_WRITE;
6135 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
6136 prot |= VM_PROT_EXECUTE;
6137
6138 // printf ("[%3u] [0x%16.16" PRIx64 " -
6139 // 0x%16.16" PRIx64 ") %c%c%c\n",
6140 // range_info_idx,
6141 // addr,
6142 // size,
6143 // (prot & VM_PROT_READ ) ? 'r' :
6144 // '-',
6145 // (prot & VM_PROT_WRITE ) ? 'w' :
6146 // '-',
6147 // (prot & VM_PROT_EXECUTE) ? 'x' :
6148 // '-');
6149
6150 if (prot != 0) {
6151 uint32_t cmd_type = LC_SEGMENT_64;
6152 uint32_t segment_size = sizeof(segment_command_64);
6153 if (addr_byte_size == 4) {
6154 cmd_type = LC_SEGMENT;
6155 segment_size = sizeof(segment_command);
6156 }
6157 segment_command_64 segment = {
6158 cmd_type, // uint32_t cmd;
6159 segment_size, // uint32_t cmdsize;
6160 {0}, // char segname[16];
6161 addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
6162 size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
6163 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
6164 size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
6165 prot, // uint32_t maxprot;
6166 prot, // uint32_t initprot;
6167 0, // uint32_t nsects;
6168 0}; // uint32_t flags;
6169 segment_load_commands.push_back(segment);
6170 } else {
6171 // No protections and a size of 1 used to be returned from old
6172 // debugservers when we asked about a region that was past the
6173 // last memory region and it indicates the end...
6174 if (size == 1)
6175 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006176 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006177
Kate Stoneb9c1b512016-09-06 20:57:50 +00006178 range_error = process_sp->GetMemoryRegionInfo(
6179 range_info.GetRange().GetRangeEnd(), range_info);
6180 if (range_error.Fail())
6181 break;
6182 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006183
Kate Stoneb9c1b512016-09-06 20:57:50 +00006184 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
Greg Claytona2715cf2014-06-13 00:54:12 +00006185
Kate Stoneb9c1b512016-09-06 20:57:50 +00006186 mach_header_64 mach_header;
6187 if (addr_byte_size == 8) {
6188 mach_header.magic = MH_MAGIC_64;
6189 } else {
6190 mach_header.magic = MH_MAGIC;
6191 }
6192 mach_header.cputype = target_arch.GetMachOCPUType();
6193 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6194 mach_header.filetype = MH_CORE;
6195 mach_header.ncmds = segment_load_commands.size();
6196 mach_header.flags = 0;
6197 mach_header.reserved = 0;
6198 ThreadList &thread_list = process_sp->GetThreadList();
6199 const uint32_t num_threads = thread_list.GetSize();
Greg Claytona2715cf2014-06-13 00:54:12 +00006200
Adrian Prantl05097242018-04-30 16:49:04 +00006201 // Make an array of LC_THREAD data items. Each one contains the
6202 // contents of the LC_THREAD load command. The data doesn't contain
6203 // the load command + load command size, we will add the load command
6204 // and load command size as we emit the data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006205 std::vector<StreamString> LC_THREAD_datas(num_threads);
6206 for (auto &LC_THREAD_data : LC_THREAD_datas) {
6207 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6208 LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6209 LC_THREAD_data.SetByteOrder(byte_order);
6210 }
6211 for (uint32_t thread_idx = 0; thread_idx < num_threads;
6212 ++thread_idx) {
6213 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6214 if (thread_sp) {
6215 switch (mach_header.cputype) {
6216 case llvm::MachO::CPU_TYPE_ARM64:
6217 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6218 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6219 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006220
Kate Stoneb9c1b512016-09-06 20:57:50 +00006221 case llvm::MachO::CPU_TYPE_ARM:
6222 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6223 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6224 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006225
Kate Stoneb9c1b512016-09-06 20:57:50 +00006226 case llvm::MachO::CPU_TYPE_I386:
6227 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6228 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6229 break;
Jason Molenda22952582014-11-12 01:11:36 +00006230
Kate Stoneb9c1b512016-09-06 20:57:50 +00006231 case llvm::MachO::CPU_TYPE_X86_64:
6232 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6233 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6234 break;
6235 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006236 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006237 }
6238
6239 // The size of the load command is the size of the segments...
6240 if (addr_byte_size == 8) {
6241 mach_header.sizeofcmds = segment_load_commands.size() *
6242 sizeof(struct segment_command_64);
6243 } else {
6244 mach_header.sizeofcmds =
6245 segment_load_commands.size() * sizeof(struct segment_command);
6246 }
6247
6248 // and the size of all LC_THREAD load command
6249 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6250 ++mach_header.ncmds;
6251 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6252 }
6253
6254 printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x "
6255 "0x%8.8x 0x%8.8x\n",
6256 mach_header.magic, mach_header.cputype, mach_header.cpusubtype,
6257 mach_header.filetype, mach_header.ncmds,
6258 mach_header.sizeofcmds, mach_header.flags,
6259 mach_header.reserved);
6260
6261 // Write the mach header
6262 buffer.PutHex32(mach_header.magic);
6263 buffer.PutHex32(mach_header.cputype);
6264 buffer.PutHex32(mach_header.cpusubtype);
6265 buffer.PutHex32(mach_header.filetype);
6266 buffer.PutHex32(mach_header.ncmds);
6267 buffer.PutHex32(mach_header.sizeofcmds);
6268 buffer.PutHex32(mach_header.flags);
6269 if (addr_byte_size == 8) {
6270 buffer.PutHex32(mach_header.reserved);
6271 }
6272
6273 // Skip the mach header and all load commands and align to the next
6274 // 0x1000 byte boundary
6275 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6276 if (file_offset & 0x00000fff) {
6277 file_offset += 0x00001000ull;
6278 file_offset &= (~0x00001000ull + 1);
6279 }
6280
6281 for (auto &segment : segment_load_commands) {
6282 segment.fileoff = file_offset;
6283 file_offset += segment.filesize;
6284 }
6285
6286 // Write out all of the LC_THREAD load commands
6287 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6288 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6289 buffer.PutHex32(LC_THREAD);
6290 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
Zachary Turnerc1564272016-11-16 21:15:24 +00006291 buffer.Write(LC_THREAD_data.GetString().data(),
6292 LC_THREAD_data_size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006293 }
6294
6295 // Write out all of the segment load commands
6296 for (const auto &segment : segment_load_commands) {
6297 printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6298 ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6299 ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6300 segment.cmd, segment.cmdsize, segment.vmaddr,
6301 segment.vmaddr + segment.vmsize, segment.fileoff,
6302 segment.filesize, segment.maxprot, segment.initprot,
6303 segment.nsects, segment.flags);
6304
6305 buffer.PutHex32(segment.cmd);
6306 buffer.PutHex32(segment.cmdsize);
6307 buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6308 if (addr_byte_size == 8) {
6309 buffer.PutHex64(segment.vmaddr);
6310 buffer.PutHex64(segment.vmsize);
6311 buffer.PutHex64(segment.fileoff);
6312 buffer.PutHex64(segment.filesize);
6313 } else {
6314 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6315 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6316 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6317 buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6318 }
6319 buffer.PutHex32(segment.maxprot);
6320 buffer.PutHex32(segment.initprot);
6321 buffer.PutHex32(segment.nsects);
6322 buffer.PutHex32(segment.flags);
6323 }
6324
6325 File core_file;
6326 std::string core_file_path(outfile.GetPath());
Jonas Devlieghere50bc1ed2018-11-02 22:34:51 +00006327 error = FileSystem::Instance().Open(core_file, outfile,
6328 File::eOpenOptionWrite |
6329 File::eOpenOptionTruncate |
6330 File::eOpenOptionCanCreate);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006331 if (error.Success()) {
6332 // Read 1 page at a time
6333 uint8_t bytes[0x1000];
6334 // Write the mach header and load commands out to the core file
6335 size_t bytes_written = buffer.GetString().size();
6336 error = core_file.Write(buffer.GetString().data(), bytes_written);
6337 if (error.Success()) {
6338 // Now write the file data for all memory segments in the process
6339 for (const auto &segment : segment_load_commands) {
6340 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6341 error.SetErrorStringWithFormat(
6342 "unable to seek to offset 0x%" PRIx64 " in '%s'",
6343 segment.fileoff, core_file_path.c_str());
6344 break;
6345 }
6346
6347 printf("Saving %" PRId64
6348 " bytes of data for memory region at 0x%" PRIx64 "\n",
6349 segment.vmsize, segment.vmaddr);
6350 addr_t bytes_left = segment.vmsize;
6351 addr_t addr = segment.vmaddr;
Zachary Turner97206d52017-05-12 04:51:55 +00006352 Status memory_read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006353 while (bytes_left > 0 && error.Success()) {
6354 const size_t bytes_to_read =
6355 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6356 const size_t bytes_read = process_sp->ReadMemory(
6357 addr, bytes, bytes_to_read, memory_read_error);
6358 if (bytes_read == bytes_to_read) {
6359 size_t bytes_written = bytes_read;
6360 error = core_file.Write(bytes, bytes_written);
6361 bytes_left -= bytes_read;
6362 addr += bytes_read;
6363 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00006364 // Some pages within regions are not readable, those should
6365 // be zero filled
Kate Stoneb9c1b512016-09-06 20:57:50 +00006366 memset(bytes, 0, bytes_to_read);
6367 size_t bytes_written = bytes_to_read;
6368 error = core_file.Write(bytes, bytes_written);
6369 bytes_left -= bytes_to_read;
6370 addr += bytes_to_read;
6371 }
6372 }
6373 }
6374 }
6375 }
6376 } else {
6377 error.SetErrorString(
6378 "process doesn't support getting memory region info");
Greg Claytona2715cf2014-06-13 00:54:12 +00006379 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006380 }
6381 return true; // This is the right plug to handle saving core files for
6382 // this process
Greg Claytona2715cf2014-06-13 00:54:12 +00006383 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006384 }
6385 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00006386}