blob: 593a4e5cf22014ffdcf1b0173b07ced3bf2d299d [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
Greg Clayton57577c02018-12-21 17:04:18 +0000961const ConstString &ObjectFileMachO::GetSegmentNameDWARF() {
962 static ConstString g_section_name("__DWARF");
963 return g_section_name;
964}
965
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966const ConstString &ObjectFileMachO::GetSectionNameEHFrame() {
967 static ConstString g_section_name_eh_frame("__eh_frame");
968 return g_section_name_eh_frame;
969}
970
971bool ObjectFileMachO::MagicBytesMatch(DataBufferSP &data_sp,
972 lldb::addr_t data_offset,
973 lldb::addr_t data_length) {
974 DataExtractor data;
975 data.SetData(data_sp, data_offset, data_length);
976 lldb::offset_t offset = 0;
977 uint32_t magic = data.GetU32(&offset);
978 return MachHeaderSizeFromMagic(magic) != 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979}
980
Greg Clayton5ce9c562013-02-06 17:22:03 +0000981ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 DataBufferSP &data_sp,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000983 lldb::offset_t data_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 const FileSpec *file,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000985 lldb::offset_t file_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 lldb::offset_t length)
987 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
988 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
989 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
990 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
991 ::memset(&m_header, 0, sizeof(m_header));
992 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993}
994
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
996 lldb::DataBufferSP &header_data_sp,
997 const lldb::ProcessSP &process_sp,
998 lldb::addr_t header_addr)
999 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
1000 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
1001 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
1002 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
1003 ::memset(&m_header, 0, sizeof(m_header));
1004 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Greg Claytonc9660542012-02-05 02:38:54 +00001005}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007bool ObjectFileMachO::ParseHeader(DataExtractor &data,
1008 lldb::offset_t *data_offset_ptr,
1009 llvm::MachO::mach_header &header) {
1010 data.SetByteOrder(endian::InlHostByteOrder());
1011 // Leave magic in the original byte order
1012 header.magic = data.GetU32(data_offset_ptr);
1013 bool can_parse = false;
1014 bool is_64_bit = false;
1015 switch (header.magic) {
1016 case MH_MAGIC:
1017 data.SetByteOrder(endian::InlHostByteOrder());
1018 data.SetAddressByteSize(4);
1019 can_parse = true;
1020 break;
1021
1022 case MH_MAGIC_64:
1023 data.SetByteOrder(endian::InlHostByteOrder());
1024 data.SetAddressByteSize(8);
1025 can_parse = true;
1026 is_64_bit = true;
1027 break;
1028
1029 case MH_CIGAM:
1030 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1031 ? eByteOrderLittle
1032 : eByteOrderBig);
1033 data.SetAddressByteSize(4);
1034 can_parse = true;
1035 break;
1036
1037 case MH_CIGAM_64:
1038 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1039 ? eByteOrderLittle
1040 : eByteOrderBig);
1041 data.SetAddressByteSize(8);
1042 is_64_bit = true;
1043 can_parse = true;
1044 break;
1045
1046 default:
1047 break;
1048 }
1049
1050 if (can_parse) {
1051 data.GetU32(data_offset_ptr, &header.cputype, 6);
1052 if (is_64_bit)
1053 *data_offset_ptr += 4;
1054 return true;
1055 } else {
1056 memset(&header, 0, sizeof(header));
1057 }
1058 return false;
1059}
1060
1061bool ObjectFileMachO::ParseHeader() {
1062 ModuleSP module_sp(GetModule());
1063 if (module_sp) {
1064 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Greg Claytonf4d6de62013-04-24 22:29:28 +00001065 bool can_parse = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066 lldb::offset_t offset = 0;
1067 m_data.SetByteOrder(endian::InlHostByteOrder());
1068 // Leave magic in the original byte order
1069 m_header.magic = m_data.GetU32(&offset);
1070 switch (m_header.magic) {
1071 case MH_MAGIC:
1072 m_data.SetByteOrder(endian::InlHostByteOrder());
1073 m_data.SetAddressByteSize(4);
1074 can_parse = true;
1075 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 case MH_MAGIC_64:
1078 m_data.SetByteOrder(endian::InlHostByteOrder());
1079 m_data.SetAddressByteSize(8);
1080 can_parse = true;
1081 break;
Greg Claytona1743492012-03-13 23:14:29 +00001082
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 case MH_CIGAM:
1084 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1085 ? eByteOrderLittle
1086 : eByteOrderBig);
1087 m_data.SetAddressByteSize(4);
1088 can_parse = true;
1089 break;
Greg Claytona1743492012-03-13 23:14:29 +00001090
Kate Stoneb9c1b512016-09-06 20:57:50 +00001091 case MH_CIGAM_64:
1092 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1093 ? eByteOrderLittle
1094 : eByteOrderBig);
1095 m_data.SetAddressByteSize(8);
1096 can_parse = true;
1097 break;
Greg Claytona1743492012-03-13 23:14:29 +00001098
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099 default:
1100 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001101 }
1102
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 if (can_parse) {
1104 m_data.GetU32(&offset, &m_header.cputype, 6);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 ArchSpec mach_arch;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 if (GetArchitecture(mach_arch)) {
1109 // Check if the module has a required architecture
1110 const ArchSpec &module_arch = module_sp->GetArchitecture();
1111 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1112 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114 if (SetModulesArchitecture(mach_arch)) {
1115 const size_t header_and_lc_size =
1116 m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1117 if (m_data.GetByteSize() < header_and_lc_size) {
1118 DataBufferSP data_sp;
1119 ProcessSP process_sp(m_process_wp.lock());
1120 if (process_sp) {
1121 data_sp =
1122 ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1123 } else {
1124 // Read in all only the load command data from the file on disk
Pavel Labath50251fc2017-12-21 10:54:30 +00001125 data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 if (data_sp->GetByteSize() != header_and_lc_size)
Greg Clayton8f265f72015-10-28 20:49:34 +00001127 return false;
1128 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 if (data_sp)
1130 m_data.SetData(data_sp);
1131 }
Greg Clayton9191db42013-10-21 18:40:51 +00001132 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 return true;
1134 }
1135 } else {
1136 memset(&m_header, 0, sizeof(struct mach_header));
1137 }
1138 }
1139 return false;
1140}
1141
1142ByteOrder ObjectFileMachO::GetByteOrder() const {
1143 return m_data.GetByteOrder();
1144}
1145
1146bool ObjectFileMachO::IsExecutable() const {
1147 return m_header.filetype == MH_EXECUTE;
1148}
1149
1150uint32_t ObjectFileMachO::GetAddressByteSize() const {
1151 return m_data.GetAddressByteSize();
1152}
1153
1154AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
1155 Symtab *symtab = GetSymtab();
1156 if (symtab) {
1157 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1158 if (symbol) {
1159 if (symbol->ValueIsAddress()) {
1160 SectionSP section_sp(symbol->GetAddressRef().GetSection());
1161 if (section_sp) {
1162 const lldb::SectionType section_type = section_sp->GetType();
1163 switch (section_type) {
1164 case eSectionTypeInvalid:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001165 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166
1167 case eSectionTypeCode:
1168 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001169 // For ARM we have a bit in the n_desc field of the symbol that
1170 // tells us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001172 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001174 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175
1176 case eSectionTypeContainer:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001177 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178
1179 case eSectionTypeData:
1180 case eSectionTypeDataCString:
1181 case eSectionTypeDataCStringPointers:
1182 case eSectionTypeDataSymbolAddress:
1183 case eSectionTypeData4:
1184 case eSectionTypeData8:
1185 case eSectionTypeData16:
1186 case eSectionTypeDataPointers:
1187 case eSectionTypeZeroFill:
1188 case eSectionTypeDataObjCMessageRefs:
1189 case eSectionTypeDataObjCCFStrings:
1190 case eSectionTypeGoSymtab:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001191 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192
1193 case eSectionTypeDebug:
1194 case eSectionTypeDWARFDebugAbbrev:
George Rimar004bcb72018-11-14 13:01:15 +00001195 case eSectionTypeDWARFDebugAbbrevDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 case eSectionTypeDWARFDebugAddr:
1197 case eSectionTypeDWARFDebugAranges:
Tamas Berghammer963ce482017-08-25 13:56:14 +00001198 case eSectionTypeDWARFDebugCuIndex:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 case eSectionTypeDWARFDebugFrame:
1200 case eSectionTypeDWARFDebugInfo:
George Rimar004bcb72018-11-14 13:01:15 +00001201 case eSectionTypeDWARFDebugInfoDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 case eSectionTypeDWARFDebugLine:
George Rimarc6c7bfc2018-09-13 17:06:47 +00001203 case eSectionTypeDWARFDebugLineStr:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 case eSectionTypeDWARFDebugLoc:
George Rimare4dee262018-10-23 09:46:15 +00001205 case eSectionTypeDWARFDebugLocLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 case eSectionTypeDWARFDebugMacInfo:
1207 case eSectionTypeDWARFDebugMacro:
Pavel Labatha041d842018-06-01 12:06:45 +00001208 case eSectionTypeDWARFDebugNames:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 case eSectionTypeDWARFDebugPubNames:
1210 case eSectionTypeDWARFDebugPubTypes:
1211 case eSectionTypeDWARFDebugRanges:
George Rimar6e357122018-10-10 08:11:15 +00001212 case eSectionTypeDWARFDebugRngLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 case eSectionTypeDWARFDebugStr:
George Rimar004bcb72018-11-14 13:01:15 +00001214 case eSectionTypeDWARFDebugStrDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 case eSectionTypeDWARFDebugStrOffsets:
George Rimar004bcb72018-11-14 13:01:15 +00001216 case eSectionTypeDWARFDebugStrOffsetsDwo:
Greg Clayton2550ca12018-05-08 17:19:24 +00001217 case eSectionTypeDWARFDebugTypes:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 case eSectionTypeDWARFAppleNames:
1219 case eSectionTypeDWARFAppleTypes:
1220 case eSectionTypeDWARFAppleNamespaces:
1221 case eSectionTypeDWARFAppleObjC:
Jan Kratochvile4777a92018-04-29 19:47:48 +00001222 case eSectionTypeDWARFGNUDebugAltLink:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001223 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224
1225 case eSectionTypeEHFrame:
1226 case eSectionTypeARMexidx:
1227 case eSectionTypeARMextab:
1228 case eSectionTypeCompactUnwind:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001229 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230
1231 case eSectionTypeAbsoluteAddress:
1232 case eSectionTypeELFSymbolTable:
1233 case eSectionTypeELFDynamicSymbols:
1234 case eSectionTypeELFRelocationEntries:
1235 case eSectionTypeELFDynamicLinkInfo:
1236 case eSectionTypeOther:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001237 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 }
1239 }
1240 }
1241
1242 const SymbolType symbol_type = symbol->GetType();
1243 switch (symbol_type) {
1244 case eSymbolTypeAny:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001245 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 case eSymbolTypeAbsolute:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001247 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001248
1249 case eSymbolTypeCode:
1250 case eSymbolTypeTrampoline:
1251 case eSymbolTypeResolver:
1252 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001253 // For ARM we have a bit in the n_desc field of the symbol that tells
1254 // us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001256 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001258 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259
1260 case eSymbolTypeData:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001261 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 case eSymbolTypeRuntime:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001263 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264 case eSymbolTypeException:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001265 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 case eSymbolTypeSourceFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001267 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 case eSymbolTypeHeaderFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001269 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 case eSymbolTypeObjectFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001271 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 case eSymbolTypeCommonBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001273 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 case eSymbolTypeBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001275 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276 case eSymbolTypeLocal:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001277 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 case eSymbolTypeParam:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001279 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280 case eSymbolTypeVariable:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001281 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 case eSymbolTypeVariableType:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001283 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 case eSymbolTypeLineEntry:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001285 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 case eSymbolTypeLineHeader:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001287 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 case eSymbolTypeScopeBegin:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001289 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 case eSymbolTypeScopeEnd:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001291 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292 case eSymbolTypeAdditional:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001293 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 case eSymbolTypeCompiler:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001295 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 case eSymbolTypeInstrumentation:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001297 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 case eSymbolTypeUndefined:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001299 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 case eSymbolTypeObjCClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001301 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302 case eSymbolTypeObjCMetaClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001303 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 case eSymbolTypeObjCIVar:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001305 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001306 case eSymbolTypeReExported:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001307 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001308 }
1309 }
1310 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001311 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312}
1313
1314Symtab *ObjectFileMachO::GetSymtab() {
1315 ModuleSP module_sp(GetModule());
1316 if (module_sp) {
1317 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1318 if (m_symtab_ap.get() == NULL) {
1319 m_symtab_ap.reset(new Symtab(this));
1320 std::lock_guard<std::recursive_mutex> symtab_guard(
1321 m_symtab_ap->GetMutex());
1322 ParseSymtab();
Davide Italiano407c6912018-11-02 21:59:14 +00001323 m_symtab_ap->Finalize();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 }
1325 }
1326 return m_symtab_ap.get();
1327}
1328
1329bool ObjectFileMachO::IsStripped() {
1330 if (m_dysymtab.cmd == 0) {
1331 ModuleSP module_sp(GetModule());
1332 if (module_sp) {
1333 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1334 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1335 const lldb::offset_t load_cmd_offset = offset;
1336
1337 load_command lc;
1338 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
1339 break;
1340 if (lc.cmd == LC_DYSYMTAB) {
1341 m_dysymtab.cmd = lc.cmd;
1342 m_dysymtab.cmdsize = lc.cmdsize;
1343 if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1344 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1345 NULL) {
1346 // Clear m_dysymtab if we were unable to read all items from the
1347 // load command
1348 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1349 }
1350 }
1351 offset = load_cmd_offset + lc.cmdsize;
1352 }
1353 }
1354 }
1355 if (m_dysymtab.cmd)
1356 return m_dysymtab.nlocalsym <= 1;
1357 return false;
1358}
1359
Pavel Labathb417eea2018-03-06 13:53:26 +00001360ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
1361 EncryptedFileRanges result;
Pavel Labathf90054d2018-03-03 22:07:47 +00001362 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labathb417eea2018-03-06 13:53:26 +00001363
Pavel Labathf90054d2018-03-03 22:07:47 +00001364 encryption_info_command encryption_cmd;
Pavel Labathb417eea2018-03-06 13:53:26 +00001365 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001366 const lldb::offset_t load_cmd_offset = offset;
1367 if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL)
1368 break;
1369
Adrian Prantl05097242018-04-30 16:49:04 +00001370 // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1371 // 3 fields we care about, so treat them the same.
Pavel Labathf90054d2018-03-03 22:07:47 +00001372 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1373 encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1374 if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1375 if (encryption_cmd.cryptid != 0) {
1376 EncryptedFileRanges::Entry entry;
1377 entry.SetRangeBase(encryption_cmd.cryptoff);
1378 entry.SetByteSize(encryption_cmd.cryptsize);
Pavel Labathb417eea2018-03-06 13:53:26 +00001379 result.Append(entry);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380 }
1381 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 }
Pavel Labathf90054d2018-03-03 22:07:47 +00001383 offset = load_cmd_offset + encryption_cmd.cmdsize;
1384 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385
Pavel Labathb417eea2018-03-06 13:53:26 +00001386 return result;
1387}
1388
1389void ObjectFileMachO::SanitizeSegmentCommand(segment_command_64 &seg_cmd,
1390 uint32_t cmd_idx) {
1391 if (m_length == 0 || seg_cmd.filesize == 0)
1392 return;
1393
1394 if (seg_cmd.fileoff > m_length) {
1395 // We have a load command that says it extends past the end of the file.
1396 // This is likely a corrupt file. We don't have any way to return an error
1397 // condition here (this method was likely invoked from something like
1398 // ObjectFile::GetSectionList()), so we just null out the section contents,
1399 // and dump a message to stdout. The most common case here is core file
1400 // debugging with a truncated file.
1401 const char *lc_segment_name =
1402 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1403 GetModule()->ReportWarning(
1404 "load command %u %s has a fileoff (0x%" PRIx64
1405 ") that extends beyond the end of the file (0x%" PRIx64
1406 "), ignoring this section",
1407 cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
1408
1409 seg_cmd.fileoff = 0;
1410 seg_cmd.filesize = 0;
1411 }
1412
1413 if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1414 // We have a load command that says it extends past the end of the file.
1415 // This is likely a corrupt file. We don't have any way to return an error
1416 // condition here (this method was likely invoked from something like
1417 // ObjectFile::GetSectionList()), so we just null out the section contents,
1418 // and dump a message to stdout. The most common case here is core file
1419 // debugging with a truncated file.
1420 const char *lc_segment_name =
1421 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1422 GetModule()->ReportWarning(
1423 "load command %u %s has a fileoff + filesize (0x%" PRIx64
1424 ") that extends beyond the end of the file (0x%" PRIx64
1425 "), the segment will be truncated to match",
1426 cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
1427
1428 // Truncate the length
1429 seg_cmd.filesize = m_length - seg_cmd.fileoff;
1430 }
1431}
1432
1433static uint32_t GetSegmentPermissions(const segment_command_64 &seg_cmd) {
1434 uint32_t result = 0;
1435 if (seg_cmd.initprot & VM_PROT_READ)
1436 result |= ePermissionsReadable;
1437 if (seg_cmd.initprot & VM_PROT_WRITE)
1438 result |= ePermissionsWritable;
1439 if (seg_cmd.initprot & VM_PROT_EXECUTE)
1440 result |= ePermissionsExecutable;
1441 return result;
1442}
1443
1444static lldb::SectionType GetSectionType(uint32_t flags,
1445 ConstString section_name) {
1446
1447 if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1448 return eSectionTypeCode;
1449
1450 uint32_t mach_sect_type = flags & SECTION_TYPE;
1451 static ConstString g_sect_name_objc_data("__objc_data");
1452 static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1453 static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1454 static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
1455 static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
1456 static ConstString g_sect_name_objc_const("__objc_const");
1457 static ConstString g_sect_name_objc_classlist("__objc_classlist");
1458 static ConstString g_sect_name_cfstring("__cfstring");
1459
1460 static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
1461 static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1462 static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1463 static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1464 static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1465 static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
George Rimare4dee262018-10-23 09:46:15 +00001466 static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
Pavel Labathb417eea2018-03-06 13:53:26 +00001467 static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
Pavel Labatha041d842018-06-01 12:06:45 +00001468 static ConstString g_sect_name_dwarf_debug_names("__debug_names");
Pavel Labathb417eea2018-03-06 13:53:26 +00001469 static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1470 static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1471 static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1472 static ConstString g_sect_name_dwarf_debug_str("__debug_str");
Greg Clayton2550ca12018-05-08 17:19:24 +00001473 static ConstString g_sect_name_dwarf_debug_types("__debug_types");
Pavel Labathb417eea2018-03-06 13:53:26 +00001474 static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1475 static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1476 static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1477 static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1478 static ConstString g_sect_name_eh_frame("__eh_frame");
1479 static ConstString g_sect_name_compact_unwind("__unwind_info");
1480 static ConstString g_sect_name_text("__text");
1481 static ConstString g_sect_name_data("__data");
1482 static ConstString g_sect_name_go_symtab("__gosymtab");
1483
1484 if (section_name == g_sect_name_dwarf_debug_abbrev)
1485 return eSectionTypeDWARFDebugAbbrev;
1486 if (section_name == g_sect_name_dwarf_debug_aranges)
1487 return eSectionTypeDWARFDebugAranges;
1488 if (section_name == g_sect_name_dwarf_debug_frame)
1489 return eSectionTypeDWARFDebugFrame;
1490 if (section_name == g_sect_name_dwarf_debug_info)
1491 return eSectionTypeDWARFDebugInfo;
1492 if (section_name == g_sect_name_dwarf_debug_line)
1493 return eSectionTypeDWARFDebugLine;
1494 if (section_name == g_sect_name_dwarf_debug_loc)
1495 return eSectionTypeDWARFDebugLoc;
George Rimare4dee262018-10-23 09:46:15 +00001496 if (section_name == g_sect_name_dwarf_debug_loclists)
1497 return eSectionTypeDWARFDebugLocLists;
Pavel Labathb417eea2018-03-06 13:53:26 +00001498 if (section_name == g_sect_name_dwarf_debug_macinfo)
1499 return eSectionTypeDWARFDebugMacInfo;
Pavel Labatha041d842018-06-01 12:06:45 +00001500 if (section_name == g_sect_name_dwarf_debug_names)
1501 return eSectionTypeDWARFDebugNames;
Pavel Labathb417eea2018-03-06 13:53:26 +00001502 if (section_name == g_sect_name_dwarf_debug_pubnames)
1503 return eSectionTypeDWARFDebugPubNames;
1504 if (section_name == g_sect_name_dwarf_debug_pubtypes)
1505 return eSectionTypeDWARFDebugPubTypes;
1506 if (section_name == g_sect_name_dwarf_debug_ranges)
George Rimar6e357122018-10-10 08:11:15 +00001507 return eSectionTypeDWARFDebugRanges;
Pavel Labathb417eea2018-03-06 13:53:26 +00001508 if (section_name == g_sect_name_dwarf_debug_str)
1509 return eSectionTypeDWARFDebugStr;
Greg Clayton2550ca12018-05-08 17:19:24 +00001510 if (section_name == g_sect_name_dwarf_debug_types)
1511 return eSectionTypeDWARFDebugTypes;
Pavel Labathb417eea2018-03-06 13:53:26 +00001512 if (section_name == g_sect_name_dwarf_apple_names)
1513 return eSectionTypeDWARFAppleNames;
1514 if (section_name == g_sect_name_dwarf_apple_types)
1515 return eSectionTypeDWARFAppleTypes;
1516 if (section_name == g_sect_name_dwarf_apple_namespaces)
1517 return eSectionTypeDWARFAppleNamespaces;
1518 if (section_name == g_sect_name_dwarf_apple_objc)
1519 return eSectionTypeDWARFAppleObjC;
1520 if (section_name == g_sect_name_objc_selrefs)
1521 return eSectionTypeDataCStringPointers;
1522 if (section_name == g_sect_name_objc_msgrefs)
1523 return eSectionTypeDataObjCMessageRefs;
1524 if (section_name == g_sect_name_eh_frame)
1525 return eSectionTypeEHFrame;
1526 if (section_name == g_sect_name_compact_unwind)
1527 return eSectionTypeCompactUnwind;
1528 if (section_name == g_sect_name_cfstring)
1529 return eSectionTypeDataObjCCFStrings;
1530 if (section_name == g_sect_name_go_symtab)
1531 return eSectionTypeGoSymtab;
1532 if (section_name == g_sect_name_objc_data ||
1533 section_name == g_sect_name_objc_classrefs ||
1534 section_name == g_sect_name_objc_superrefs ||
1535 section_name == g_sect_name_objc_const ||
1536 section_name == g_sect_name_objc_classlist) {
1537 return eSectionTypeDataPointers;
1538 }
1539
1540 switch (mach_sect_type) {
1541 // TODO: categorize sections by other flags for regular sections
1542 case S_REGULAR:
1543 if (section_name == g_sect_name_text)
1544 return eSectionTypeCode;
1545 if (section_name == g_sect_name_data)
1546 return eSectionTypeData;
1547 return eSectionTypeOther;
1548 case S_ZEROFILL:
1549 return eSectionTypeZeroFill;
1550 case S_CSTRING_LITERALS: // section with only literal C strings
1551 return eSectionTypeDataCString;
1552 case S_4BYTE_LITERALS: // section with only 4 byte literals
1553 return eSectionTypeData4;
1554 case S_8BYTE_LITERALS: // section with only 8 byte literals
1555 return eSectionTypeData8;
1556 case S_LITERAL_POINTERS: // section with only pointers to literals
1557 return eSectionTypeDataPointers;
1558 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1559 return eSectionTypeDataPointers;
1560 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1561 return eSectionTypeDataPointers;
1562 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1563 // the reserved2 field
1564 return eSectionTypeCode;
1565 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1566 // initialization
1567 return eSectionTypeDataPointers;
1568 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1569 // termination
1570 return eSectionTypeDataPointers;
1571 case S_COALESCED:
1572 return eSectionTypeOther;
1573 case S_GB_ZEROFILL:
1574 return eSectionTypeZeroFill;
1575 case S_INTERPOSING: // section with only pairs of function pointers for
1576 // interposing
1577 return eSectionTypeCode;
1578 case S_16BYTE_LITERALS: // section with only 16 byte literals
1579 return eSectionTypeData16;
1580 case S_DTRACE_DOF:
1581 return eSectionTypeDebug;
1582 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1583 return eSectionTypeDataPointers;
1584 default:
1585 return eSectionTypeOther;
1586 }
1587}
1588
1589struct ObjectFileMachO::SegmentParsingContext {
1590 const EncryptedFileRanges EncryptedRanges;
1591 lldb_private::SectionList &UnifiedList;
1592 uint32_t NextSegmentIdx = 0;
1593 uint32_t NextSectionIdx = 0;
1594 bool FileAddressesChanged = false;
1595
1596 SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
1597 lldb_private::SectionList &UnifiedList)
1598 : EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
1599};
1600
1601void ObjectFileMachO::ProcessSegmentCommand(const load_command &load_cmd_,
1602 lldb::offset_t offset,
1603 uint32_t cmd_idx,
1604 SegmentParsingContext &context) {
1605 segment_command_64 load_cmd;
1606 memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1607
1608 if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1609 return;
1610
1611 ModuleSP module_sp = GetModule();
1612 const bool is_core = GetType() == eTypeCoreFile;
1613 const bool is_dsym = (m_header.filetype == MH_DSYM);
1614 bool add_section = true;
1615 bool add_to_unified = true;
1616 ConstString const_segname(
1617 load_cmd.segname,
1618 std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname)));
1619
1620 SectionSP unified_section_sp(
1621 context.UnifiedList.FindSectionByName(const_segname));
1622 if (is_dsym && unified_section_sp) {
1623 if (const_segname == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001624 // We need to keep the __LINKEDIT segment private to this object file
1625 // only
Pavel Labathb417eea2018-03-06 13:53:26 +00001626 add_to_unified = false;
1627 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001628 // This is the dSYM file and this section has already been created by the
1629 // object file, no need to create it.
Pavel Labathb417eea2018-03-06 13:53:26 +00001630 add_section = false;
1631 }
1632 }
1633 load_cmd.vmaddr = m_data.GetAddress(&offset);
1634 load_cmd.vmsize = m_data.GetAddress(&offset);
1635 load_cmd.fileoff = m_data.GetAddress(&offset);
1636 load_cmd.filesize = m_data.GetAddress(&offset);
1637 if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1638 return;
1639
1640 SanitizeSegmentCommand(load_cmd, cmd_idx);
1641
1642 const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1643 const bool segment_is_encrypted =
1644 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1645
Adrian Prantl05097242018-04-30 16:49:04 +00001646 // Keep a list of mach segments around in case we need to get at data that
1647 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001648 m_mach_segments.push_back(load_cmd);
1649
Adrian Prantl05097242018-04-30 16:49:04 +00001650 // Use a segment ID of the segment index shifted left by 8 so they never
1651 // conflict with any of the sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001652 SectionSP segment_sp;
1653 if (add_section && (const_segname || is_core)) {
1654 segment_sp.reset(new Section(
1655 module_sp, // Module to which this section belongs
1656 this, // Object file to which this sections belongs
1657 ++context.NextSegmentIdx
1658 << 8, // Section ID is the 1 based segment index
Adrian Prantl05097242018-04-30 16:49:04 +00001659 // shifted right by 8 bits as not to collide with any of the 256
1660 // section IDs that are possible
Pavel Labathb417eea2018-03-06 13:53:26 +00001661 const_segname, // Name of this section
1662 eSectionTypeContainer, // This section is a container of other
1663 // sections.
1664 load_cmd.vmaddr, // File VM address == addresses as they are
1665 // found in the object file
1666 load_cmd.vmsize, // VM size in bytes of this section
1667 load_cmd.fileoff, // Offset to the data for this section in
1668 // the file
1669 load_cmd.filesize, // Size in bytes of this section as found
1670 // in the file
1671 0, // Segments have no alignment information
1672 load_cmd.flags)); // Flags for this section
1673
1674 segment_sp->SetIsEncrypted(segment_is_encrypted);
1675 m_sections_ap->AddSection(segment_sp);
1676 segment_sp->SetPermissions(segment_permissions);
1677 if (add_to_unified)
1678 context.UnifiedList.AddSection(segment_sp);
1679 } else if (unified_section_sp) {
1680 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1681 // Check to see if the module was read from memory?
Pavel Labathd1e3fe22018-12-11 15:21:15 +00001682 if (module_sp->GetObjectFile()->GetBaseAddress().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001683 // We have a module that is in memory and needs to have its file
1684 // address adjusted. We need to do this because when we load a file
1685 // from memory, its addresses will be slid already, yet the addresses
1686 // in the new symbol file will still be unslid. Since everything is
1687 // stored as section offset, this shouldn't cause any problems.
Pavel Labathb417eea2018-03-06 13:53:26 +00001688
Adrian Prantl05097242018-04-30 16:49:04 +00001689 // Make sure we've parsed the symbol table from the ObjectFile before
1690 // we go around changing its Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001691 module_sp->GetObjectFile()->GetSymtab();
Adrian Prantl05097242018-04-30 16:49:04 +00001692 // eh_frame would present the same problems but we parse that on a per-
1693 // function basis as-needed so it's more difficult to remove its use of
1694 // the Sections. Realistically, the environments where this code path
1695 // will be taken will not have eh_frame sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001696
1697 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1698
Adrian Prantl05097242018-04-30 16:49:04 +00001699 // Notify the module that the section addresses have been changed once
1700 // we're done so any file-address caches can be updated.
Pavel Labathb417eea2018-03-06 13:53:26 +00001701 context.FileAddressesChanged = true;
1702 }
1703 }
1704 m_sections_ap->AddSection(unified_section_sp);
1705 }
1706
1707 struct section_64 sect64;
1708 ::memset(&sect64, 0, sizeof(sect64));
Adrian Prantl05097242018-04-30 16:49:04 +00001709 // Push a section into our mach sections for the section at index zero
1710 // (NO_SECT) if we don't have any mach sections yet...
Pavel Labathb417eea2018-03-06 13:53:26 +00001711 if (m_mach_sections.empty())
1712 m_mach_sections.push_back(sect64);
1713 uint32_t segment_sect_idx;
1714 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1715
1716 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1717 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1718 ++segment_sect_idx) {
1719 if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1720 sizeof(sect64.sectname)) == NULL)
1721 break;
1722 if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1723 sizeof(sect64.segname)) == NULL)
1724 break;
1725 sect64.addr = m_data.GetAddress(&offset);
1726 sect64.size = m_data.GetAddress(&offset);
1727
1728 if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
1729 break;
1730
Adrian Prantl05097242018-04-30 16:49:04 +00001731 // Keep a list of mach sections around in case we need to get at data that
1732 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001733 m_mach_sections.push_back(sect64);
1734
1735 if (add_section) {
1736 ConstString section_name(
1737 sect64.sectname,
1738 std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname)));
1739 if (!const_segname) {
Adrian Prantl05097242018-04-30 16:49:04 +00001740 // We have a segment with no name so we need to conjure up segments
1741 // that correspond to the section's segname if there isn't already such
1742 // a section. If there is such a section, we resize the section so that
1743 // it spans all sections. We also mark these sections as fake so
1744 // address matches don't hit if they land in the gaps between the child
1745 // sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001746 const_segname.SetTrimmedCStringWithLength(sect64.segname,
1747 sizeof(sect64.segname));
1748 segment_sp = context.UnifiedList.FindSectionByName(const_segname);
1749 if (segment_sp.get()) {
1750 Section *segment = segment_sp.get();
1751 // Grow the section size as needed.
1752 const lldb::addr_t sect64_min_addr = sect64.addr;
1753 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1754 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1755 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1756 const lldb::addr_t curr_seg_max_addr =
1757 curr_seg_min_addr + curr_seg_byte_size;
1758 if (sect64_min_addr >= curr_seg_min_addr) {
1759 const lldb::addr_t new_seg_byte_size =
1760 sect64_max_addr - curr_seg_min_addr;
1761 // Only grow the section size if needed
1762 if (new_seg_byte_size > curr_seg_byte_size)
1763 segment->SetByteSize(new_seg_byte_size);
1764 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001765 // We need to change the base address of the segment and adjust the
1766 // child section offsets for all existing children.
Pavel Labathb417eea2018-03-06 13:53:26 +00001767 const lldb::addr_t slide_amount =
1768 sect64_min_addr - curr_seg_min_addr;
1769 segment->Slide(slide_amount, false);
1770 segment->GetChildren().Slide(-slide_amount, false);
1771 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1772 }
1773
1774 // Grow the section size as needed.
1775 if (sect64.offset) {
1776 const lldb::addr_t segment_min_file_offset =
1777 segment->GetFileOffset();
1778 const lldb::addr_t segment_max_file_offset =
1779 segment_min_file_offset + segment->GetFileSize();
1780
1781 const lldb::addr_t section_min_file_offset = sect64.offset;
1782 const lldb::addr_t section_max_file_offset =
1783 section_min_file_offset + sect64.size;
1784 const lldb::addr_t new_file_offset =
1785 std::min(section_min_file_offset, segment_min_file_offset);
1786 const lldb::addr_t new_file_size =
1787 std::max(section_max_file_offset, segment_max_file_offset) -
1788 new_file_offset;
1789 segment->SetFileOffset(new_file_offset);
1790 segment->SetFileSize(new_file_size);
1791 }
1792 } else {
1793 // Create a fake section for the section's named segment
1794 segment_sp.reset(new Section(
1795 segment_sp, // Parent section
1796 module_sp, // Module to which this section belongs
1797 this, // Object file to which this section belongs
1798 ++context.NextSegmentIdx
1799 << 8, // Section ID is the 1 based segment index
1800 // shifted right by 8 bits as not to
1801 // collide with any of the 256 section IDs
1802 // that are possible
1803 const_segname, // Name of this section
1804 eSectionTypeContainer, // This section is a container of
1805 // other sections.
1806 sect64.addr, // File VM address == addresses as they are
1807 // found in the object file
1808 sect64.size, // VM size in bytes of this section
1809 sect64.offset, // Offset to the data for this section in
1810 // the file
1811 sect64.offset ? sect64.size : 0, // Size in bytes of
1812 // this section as
1813 // found in the file
1814 sect64.align,
1815 load_cmd.flags)); // Flags for this section
1816 segment_sp->SetIsFake(true);
1817 segment_sp->SetPermissions(segment_permissions);
1818 m_sections_ap->AddSection(segment_sp);
1819 if (add_to_unified)
1820 context.UnifiedList.AddSection(segment_sp);
1821 segment_sp->SetIsEncrypted(segment_is_encrypted);
1822 }
1823 }
1824 assert(segment_sp.get());
1825
1826 lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1827
1828 SectionSP section_sp(new Section(
1829 segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1830 sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1831 sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1832 sect64.flags));
1833 // Set the section to be encrypted to match the segment
1834
1835 bool section_is_encrypted = false;
1836 if (!segment_is_encrypted && load_cmd.filesize != 0)
1837 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1838 sect64.offset) != NULL;
1839
1840 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1841 section_sp->SetPermissions(segment_permissions);
1842 segment_sp->GetChildren().AddSection(section_sp);
1843
1844 if (segment_sp->IsFake()) {
1845 segment_sp.reset();
1846 const_segname.Clear();
1847 }
1848 }
1849 }
1850 if (segment_sp && is_dsym) {
1851 if (first_segment_sectID <= context.NextSectionIdx) {
1852 lldb::user_id_t sect_uid;
1853 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1854 ++sect_uid) {
1855 SectionSP curr_section_sp(
1856 segment_sp->GetChildren().FindSectionByID(sect_uid));
1857 SectionSP next_section_sp;
1858 if (sect_uid + 1 <= context.NextSectionIdx)
1859 next_section_sp =
1860 segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1861
1862 if (curr_section_sp.get()) {
1863 if (curr_section_sp->GetByteSize() == 0) {
1864 if (next_section_sp.get() != NULL)
1865 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1866 curr_section_sp->GetFileAddress());
1867 else
1868 curr_section_sp->SetByteSize(load_cmd.vmsize);
1869 }
1870 }
1871 }
1872 }
1873 }
1874}
1875
1876void ObjectFileMachO::ProcessDysymtabCommand(const load_command &load_cmd,
1877 lldb::offset_t offset) {
1878 m_dysymtab.cmd = load_cmd.cmd;
1879 m_dysymtab.cmdsize = load_cmd.cmdsize;
1880 m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1881 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1882}
1883
1884void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1885 if (m_sections_ap)
1886 return;
1887
1888 m_sections_ap.reset(new SectionList());
1889
1890 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1891 // bool dump_sections = false;
1892 ModuleSP module_sp(GetModule());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001893
Pavel Labathf90054d2018-03-03 22:07:47 +00001894 offset = MachHeaderSizeFromMagic(m_header.magic);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001895
Pavel Labathb417eea2018-03-06 13:53:26 +00001896 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1897 struct load_command load_cmd;
1898 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001899 const lldb::offset_t load_cmd_offset = offset;
1900 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
1901 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001902
Pavel Labathb417eea2018-03-06 13:53:26 +00001903 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1904 ProcessSegmentCommand(load_cmd, offset, i, context);
1905 else if (load_cmd.cmd == LC_DYSYMTAB)
1906 ProcessDysymtabCommand(load_cmd, offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907
Pavel Labathf90054d2018-03-03 22:07:47 +00001908 offset = load_cmd_offset + load_cmd.cmdsize;
1909 }
1910
Pavel Labathb417eea2018-03-06 13:53:26 +00001911 if (context.FileAddressesChanged && module_sp)
Pavel Labathf90054d2018-03-03 22:07:47 +00001912 module_sp->SectionFileAddressesChanged();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913}
1914
1915class MachSymtabSectionInfo {
1916public:
1917 MachSymtabSectionInfo(SectionList *section_list)
1918 : m_section_list(section_list), m_section_infos() {
Adrian Prantl05097242018-04-30 16:49:04 +00001919 // Get the number of sections down to a depth of 1 to include all segments
1920 // and their sections, but no other sections that may be added for debug
1921 // map or
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922 m_section_infos.resize(section_list->GetNumSections(1));
1923 }
1924
1925 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1926 if (n_sect == 0)
1927 return SectionSP();
1928 if (n_sect < m_section_infos.size()) {
1929 if (!m_section_infos[n_sect].section_sp) {
1930 SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1931 m_section_infos[n_sect].section_sp = section_sp;
1932 if (section_sp) {
1933 m_section_infos[n_sect].vm_range.SetBaseAddress(
1934 section_sp->GetFileAddress());
1935 m_section_infos[n_sect].vm_range.SetByteSize(
1936 section_sp->GetByteSize());
1937 } else {
1938 Host::SystemLog(Host::eSystemLogError,
1939 "error: unable to find section for section %u\n",
1940 n_sect);
1941 }
1942 }
1943 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1944 // Symbol is in section.
1945 return m_section_infos[n_sect].section_sp;
1946 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1947 m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1948 file_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001949 // Symbol is in section with zero size, but has the same start address
1950 // as the section. This can happen with linker symbols (symbols that
1951 // start with the letter 'l' or 'L'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952 return m_section_infos[n_sect].section_sp;
1953 }
1954 }
1955 return m_section_list->FindSectionContainingFileAddress(file_addr);
1956 }
1957
1958protected:
1959 struct SectionInfo {
1960 SectionInfo() : vm_range(), section_sp() {}
1961
1962 VMRange vm_range;
1963 SectionSP section_sp;
1964 };
1965 SectionList *m_section_list;
1966 std::vector<SectionInfo> m_section_infos;
1967};
1968
1969struct TrieEntry {
1970 TrieEntry()
1971 : name(), address(LLDB_INVALID_ADDRESS), flags(0), other(0),
1972 import_name() {}
1973
1974 void Clear() {
1975 name.Clear();
1976 address = LLDB_INVALID_ADDRESS;
1977 flags = 0;
1978 other = 0;
1979 import_name.Clear();
1980 }
1981
1982 void Dump() const {
1983 printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
1984 static_cast<unsigned long long>(address),
1985 static_cast<unsigned long long>(flags),
1986 static_cast<unsigned long long>(other), name.GetCString());
1987 if (import_name)
1988 printf(" -> \"%s\"\n", import_name.GetCString());
1989 else
1990 printf("\n");
1991 }
1992 ConstString name;
1993 uint64_t address;
1994 uint64_t flags;
1995 uint64_t other;
1996 ConstString import_name;
1997};
1998
1999struct TrieEntryWithOffset {
2000 lldb::offset_t nodeOffset;
2001 TrieEntry entry;
2002
2003 TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
2004
2005 void Dump(uint32_t idx) const {
2006 printf("[%3u] 0x%16.16llx: ", idx,
2007 static_cast<unsigned long long>(nodeOffset));
2008 entry.Dump();
2009 }
2010
2011 bool operator<(const TrieEntryWithOffset &other) const {
2012 return (nodeOffset < other.nodeOffset);
2013 }
2014};
2015
2016static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
2017 const bool is_arm,
2018 std::vector<llvm::StringRef> &nameSlices,
2019 std::set<lldb::addr_t> &resolver_addresses,
2020 std::vector<TrieEntryWithOffset> &output) {
2021 if (!data.ValidOffset(offset))
Greg Clayton8f265f72015-10-28 20:49:34 +00002022 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002023
2024 const uint64_t terminalSize = data.GetULEB128(&offset);
2025 lldb::offset_t children_offset = offset + terminalSize;
2026 if (terminalSize != 0) {
2027 TrieEntryWithOffset e(offset);
2028 e.entry.flags = data.GetULEB128(&offset);
2029 const char *import_name = NULL;
2030 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2031 e.entry.address = 0;
2032 e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2033 import_name = data.GetCStr(&offset);
2034 } else {
2035 e.entry.address = data.GetULEB128(&offset);
2036 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2037 e.entry.other = data.GetULEB128(&offset);
2038 uint64_t resolver_addr = e.entry.other;
2039 if (is_arm)
2040 resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2041 resolver_addresses.insert(resolver_addr);
2042 } else
2043 e.entry.other = 0;
2044 }
2045 // Only add symbols that are reexport symbols with a valid import name
2046 if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name &&
2047 import_name[0]) {
2048 std::string name;
2049 if (!nameSlices.empty()) {
2050 for (auto name_slice : nameSlices)
2051 name.append(name_slice.data(), name_slice.size());
2052 }
2053 if (name.size() > 1) {
2054 // Skip the leading '_'
2055 e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2056 }
2057 if (import_name) {
2058 // Skip the leading '_'
2059 e.entry.import_name.SetCString(import_name + 1);
2060 }
2061 output.push_back(e);
2062 }
2063 }
2064
2065 const uint8_t childrenCount = data.GetU8(&children_offset);
2066 for (uint8_t i = 0; i < childrenCount; ++i) {
2067 const char *cstr = data.GetCStr(&children_offset);
2068 if (cstr)
2069 nameSlices.push_back(llvm::StringRef(cstr));
2070 else
2071 return false; // Corrupt data
2072 lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2073 if (childNodeOffset) {
2074 if (!ParseTrieEntries(data, childNodeOffset, is_arm, nameSlices,
2075 resolver_addresses, output)) {
2076 return false;
2077 }
2078 }
2079 nameSlices.pop_back();
2080 }
2081 return true;
Greg Clayton9191db42013-10-21 18:40:51 +00002082}
2083
Jason Molenda649a6072015-11-10 05:21:54 +00002084// Read the UUID out of a dyld_shared_cache file on-disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002085UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
2086 const ByteOrder byte_order,
2087 const uint32_t addr_byte_size) {
2088 UUID dsc_uuid;
Pavel Labath50251fc2017-12-21 10:54:30 +00002089 DataBufferSP DscData = MapFileData(
2090 dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002091 if (!DscData)
2092 return dsc_uuid;
2093 DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
Jason Molenda649a6072015-11-10 05:21:54 +00002094
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002095 char version_str[7];
2096 lldb::offset_t offset = 0;
2097 memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
2098 version_str[6] = '\0';
2099 if (strcmp(version_str, "dyld_v") == 0) {
2100 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
Pavel Labath2f93fd12018-06-26 15:12:20 +00002101 dsc_uuid = UUID::fromOptionalData(
2102 dsc_header_data.GetData(&offset, sizeof(uuid_t)), sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103 }
Jason Molendafd443e92018-02-07 01:28:29 +00002104 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2105 if (log && dsc_uuid.IsValid()) {
2106 log->Printf("Shared cache %s has UUID %s", dyld_shared_cache.GetPath().c_str(),
2107 dsc_uuid.GetAsString().c_str());
2108 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 return dsc_uuid;
Jason Molenda649a6072015-11-10 05:21:54 +00002110}
2111
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112size_t ObjectFileMachO::ParseSymtab() {
Pavel Labathf9d16472017-05-15 13:02:37 +00002113 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2114 Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002115 m_file.GetFilename().AsCString(""));
2116 ModuleSP module_sp(GetModule());
2117 if (!module_sp)
2118 return 0;
2119
2120 struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2121 struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2122 struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2123 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2124 FunctionStarts function_starts;
2125 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2126 uint32_t i;
2127 FileSpecList dylib_files;
2128 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2129 static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2130 static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2131 static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2132
2133 for (i = 0; i < m_header.ncmds; ++i) {
2134 const lldb::offset_t cmd_offset = offset;
2135 // Read in the load command and load command size
2136 struct load_command lc;
2137 if (m_data.GetU32(&offset, &lc, 2) == NULL)
2138 break;
2139 // Watch for the symbol table load command
2140 switch (lc.cmd) {
2141 case LC_SYMTAB:
2142 symtab_load_command.cmd = lc.cmd;
2143 symtab_load_command.cmdsize = lc.cmdsize;
2144 // Read in the rest of the symtab load command
2145 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2146 0) // fill in symoff, nsyms, stroff, strsize fields
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002147 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002148 if (symtab_load_command.symoff == 0) {
2149 if (log)
2150 module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2151 return 0;
2152 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002153
Kate Stoneb9c1b512016-09-06 20:57:50 +00002154 if (symtab_load_command.stroff == 0) {
2155 if (log)
2156 module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2157 return 0;
2158 }
Greg Clayton77ccca72011-12-30 00:32:24 +00002159
Kate Stoneb9c1b512016-09-06 20:57:50 +00002160 if (symtab_load_command.nsyms == 0) {
2161 if (log)
2162 module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
2163 return 0;
2164 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002165
Kate Stoneb9c1b512016-09-06 20:57:50 +00002166 if (symtab_load_command.strsize == 0) {
2167 if (log)
2168 module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2169 return 0;
2170 }
2171 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002172
Kate Stoneb9c1b512016-09-06 20:57:50 +00002173 case LC_DYLD_INFO:
2174 case LC_DYLD_INFO_ONLY:
2175 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2176 dyld_info.cmd = lc.cmd;
2177 dyld_info.cmdsize = lc.cmdsize;
2178 } else {
2179 memset(&dyld_info, 0, sizeof(dyld_info));
2180 }
2181 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002182
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 case LC_LOAD_DYLIB:
2184 case LC_LOAD_WEAK_DYLIB:
2185 case LC_REEXPORT_DYLIB:
2186 case LC_LOADFVMLIB:
2187 case LC_LOAD_UPWARD_DYLIB: {
2188 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2189 const char *path = m_data.PeekCStr(name_offset);
2190 if (path) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002191 FileSpec file_spec(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192 // Strip the path if there is @rpath, @executable, etc so we just use
2193 // the basename
2194 if (path[0] == '@')
2195 file_spec.GetDirectory().Clear();
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002196
Kate Stoneb9c1b512016-09-06 20:57:50 +00002197 if (lc.cmd == LC_REEXPORT_DYLIB) {
2198 m_reexported_dylibs.AppendIfUnique(file_spec);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002199 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200
2201 dylib_files.Append(file_spec);
2202 }
2203 } break;
2204
2205 case LC_FUNCTION_STARTS:
2206 function_starts_load_command.cmd = lc.cmd;
2207 function_starts_load_command.cmdsize = lc.cmdsize;
2208 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2209 NULL) // fill in symoff, nsyms, stroff, strsize fields
2210 memset(&function_starts_load_command, 0,
2211 sizeof(function_starts_load_command));
2212 break;
2213
2214 default:
2215 break;
2216 }
2217 offset = cmd_offset + lc.cmdsize;
2218 }
2219
2220 if (symtab_load_command.cmd) {
2221 Symtab *symtab = m_symtab_ap.get();
2222 SectionList *section_list = GetSectionList();
2223 if (section_list == NULL)
2224 return 0;
2225
2226 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2227 const ByteOrder byte_order = m_data.GetByteOrder();
2228 bool bit_width_32 = addr_byte_size == 4;
2229 const size_t nlist_byte_size =
2230 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2231
2232 DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size);
2233 DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size);
2234 DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size);
2235 DataExtractor indirect_symbol_index_data(NULL, 0, byte_order,
2236 addr_byte_size);
2237 DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size);
2238
2239 const addr_t nlist_data_byte_size =
2240 symtab_load_command.nsyms * nlist_byte_size;
2241 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2242 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2243
2244 ProcessSP process_sp(m_process_wp.lock());
2245 Process *process = process_sp.get();
2246
2247 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2248
2249 if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2250 Target &target = process->GetTarget();
2251
2252 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2253
2254 SectionSP linkedit_section_sp(
2255 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2256 // Reading mach file from memory in a process or core file...
2257
2258 if (linkedit_section_sp) {
2259 addr_t linkedit_load_addr =
2260 linkedit_section_sp->GetLoadBaseAddress(&target);
2261 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2262 // We might be trying to access the symbol table before the
Adrian Prantl05097242018-04-30 16:49:04 +00002263 // __LINKEDIT's load address has been set in the target. We can't
2264 // fail to read the symbol table, so calculate the right address
2265 // manually
Kate Stoneb9c1b512016-09-06 20:57:50 +00002266 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2267 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2268 }
2269
2270 const addr_t linkedit_file_offset =
2271 linkedit_section_sp->GetFileOffset();
2272 const addr_t symoff_addr = linkedit_load_addr +
2273 symtab_load_command.symoff -
2274 linkedit_file_offset;
2275 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2276 linkedit_file_offset;
2277
2278 bool data_was_read = false;
2279
2280#if defined(__APPLE__) && \
2281 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2282 if (m_header.flags & 0x80000000u &&
2283 process->GetAddressByteSize() == sizeof(void *)) {
2284 // This mach-o memory file is in the dyld shared cache. If this
2285 // program is not remote and this is iOS, then this process will
Adrian Prantl05097242018-04-30 16:49:04 +00002286 // share the same shared cache as the process we are debugging and we
2287 // can read the entire __LINKEDIT from the address space in this
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 // process. This is a needed optimization that is used for local iOS
2289 // debugging only since all shared libraries in the shared cache do
2290 // not have corresponding files that exist in the file system of the
2291 // device. They have been combined into a single file. This means we
2292 // always have to load these files from memory. All of the symbol and
2293 // string tables from all of the __LINKEDIT sections from the shared
2294 // libraries in the shared cache have been merged into a single large
2295 // symbol and string table. Reading all of this symbol and string
Adrian Prantl05097242018-04-30 16:49:04 +00002296 // table data across can slow down debug launch times, so we optimize
2297 // this by reading the memory for the __LINKEDIT section from this
2298 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299
Jason Molenda07580ff2018-05-04 00:59:37 +00002300 UUID lldb_shared_cache;
2301 addr_t lldb_shared_cache_addr;
2302 GetLLDBSharedCacheUUID (lldb_shared_cache_addr, lldb_shared_cache);
2303 UUID process_shared_cache;
2304 addr_t process_shared_cache_addr;
2305 GetProcessSharedCacheUUID(process, process_shared_cache_addr, process_shared_cache);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306 bool use_lldb_cache = true;
2307 if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
Jason Molenda07580ff2018-05-04 00:59:37 +00002308 (lldb_shared_cache != process_shared_cache
2309 || process_shared_cache_addr != lldb_shared_cache_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310 use_lldb_cache = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002311 }
2312
2313 PlatformSP platform_sp(target.GetPlatform());
2314 if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2315 data_was_read = true;
2316 nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2317 eByteOrderLittle);
2318 strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2319 eByteOrderLittle);
2320 if (function_starts_load_command.cmd) {
2321 const addr_t func_start_addr =
2322 linkedit_load_addr + function_starts_load_command.dataoff -
2323 linkedit_file_offset;
2324 function_starts_data.SetData(
2325 (void *)func_start_addr,
2326 function_starts_load_command.datasize, eByteOrderLittle);
2327 }
2328 }
2329 }
2330#endif
2331
2332 if (!data_was_read) {
2333 // Always load dyld - the dynamic linker - from memory if we didn't
Adrian Prantl05097242018-04-30 16:49:04 +00002334 // find a binary anywhere else. lldb will not register
2335 // dylib/framework/bundle loads/unloads if we don't have the dyld
2336 // symbols, we force dyld to load from memory despite the user's
Kate Stoneb9c1b512016-09-06 20:57:50 +00002337 // target.memory-module-load-level setting.
2338 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2339 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2340 DataBufferSP nlist_data_sp(
2341 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2342 if (nlist_data_sp)
2343 nlist_data.SetData(nlist_data_sp, 0,
2344 nlist_data_sp->GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345 if (m_dysymtab.nindirectsyms != 0) {
2346 const addr_t indirect_syms_addr = linkedit_load_addr +
2347 m_dysymtab.indirectsymoff -
2348 linkedit_file_offset;
2349 DataBufferSP indirect_syms_data_sp(
2350 ReadMemory(process_sp, indirect_syms_addr,
2351 m_dysymtab.nindirectsyms * 4));
2352 if (indirect_syms_data_sp)
2353 indirect_symbol_index_data.SetData(
2354 indirect_syms_data_sp, 0,
2355 indirect_syms_data_sp->GetByteSize());
Jason Molendab0d33e92018-09-06 00:55:27 +00002356 // If this binary is outside the shared cache,
2357 // cache the string table.
2358 // Binaries in the shared cache all share a giant string table, and
2359 // we can't share the string tables across multiple ObjectFileMachO's,
2360 // so we'd end up re-reading this mega-strtab for every binary
2361 // in the shared cache - it would be a big perf problem.
2362 // For binaries outside the shared cache, it's faster to read the
2363 // entire strtab at once instead of piece-by-piece as we process
2364 // the nlist records.
2365 if ((m_header.flags & 0x80000000u) == 0) {
2366 DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr,
2367 strtab_data_byte_size));
2368 if (strtab_data_sp) {
2369 strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
2370 }
2371 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372 }
Jim Ingham8a5d7a22018-08-15 23:10:32 +00002373 }
2374 if (memory_module_load_level >=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002375 eMemoryModuleLoadLevelPartial) {
2376 if (function_starts_load_command.cmd) {
2377 const addr_t func_start_addr =
2378 linkedit_load_addr + function_starts_load_command.dataoff -
2379 linkedit_file_offset;
2380 DataBufferSP func_start_data_sp(
2381 ReadMemory(process_sp, func_start_addr,
2382 function_starts_load_command.datasize));
2383 if (func_start_data_sp)
2384 function_starts_data.SetData(func_start_data_sp, 0,
2385 func_start_data_sp->GetByteSize());
2386 }
2387 }
2388 }
2389 }
2390 } else {
2391 nlist_data.SetData(m_data, symtab_load_command.symoff,
2392 nlist_data_byte_size);
2393 strtab_data.SetData(m_data, symtab_load_command.stroff,
2394 strtab_data_byte_size);
2395
2396 if (dyld_info.export_size > 0) {
2397 dyld_trie_data.SetData(m_data, dyld_info.export_off,
2398 dyld_info.export_size);
2399 }
2400
2401 if (m_dysymtab.nindirectsyms != 0) {
2402 indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2403 m_dysymtab.nindirectsyms * 4);
2404 }
2405 if (function_starts_load_command.cmd) {
2406 function_starts_data.SetData(m_data,
2407 function_starts_load_command.dataoff,
2408 function_starts_load_command.datasize);
2409 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002410 }
2411
Kate Stoneb9c1b512016-09-06 20:57:50 +00002412 if (nlist_data.GetByteSize() == 0 &&
2413 memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2414 if (log)
2415 module_sp->LogMessage(log, "failed to read nlist data");
2416 return 0;
2417 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002418
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2420 if (!have_strtab_data) {
2421 if (process) {
2422 if (strtab_addr == LLDB_INVALID_ADDRESS) {
2423 if (log)
2424 module_sp->LogMessage(log, "failed to locate the strtab in memory");
2425 return 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002426 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002427 } else {
2428 if (log)
2429 module_sp->LogMessage(log, "failed to read strtab data");
2430 return 0;
2431 }
2432 }
Greg Clayton9191db42013-10-21 18:40:51 +00002433
Kate Stoneb9c1b512016-09-06 20:57:50 +00002434 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2435 const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2436 const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2437 const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2438 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2439 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2440 SectionSP text_section_sp(
2441 section_list->FindSectionByName(g_segment_name_TEXT));
2442 SectionSP data_section_sp(
2443 section_list->FindSectionByName(g_segment_name_DATA));
2444 SectionSP data_dirty_section_sp(
2445 section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2446 SectionSP data_const_section_sp(
2447 section_list->FindSectionByName(g_segment_name_DATA_CONST));
2448 SectionSP objc_section_sp(
2449 section_list->FindSectionByName(g_segment_name_OBJC));
2450 SectionSP eh_frame_section_sp;
2451 if (text_section_sp.get())
2452 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2453 g_section_name_eh_frame);
2454 else
2455 eh_frame_section_sp =
2456 section_list->FindSectionByName(g_section_name_eh_frame);
Greg Clayton77ccca72011-12-30 00:32:24 +00002457
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
Greg Clayton86eac942013-08-13 21:32:34 +00002459
Kate Stoneb9c1b512016-09-06 20:57:50 +00002460 // lldb works best if it knows the start address of all functions in a
Adrian Prantl05097242018-04-30 16:49:04 +00002461 // module. Linker symbols or debug info are normally the best source of
2462 // information for start addr / size but they may be stripped in a released
2463 // binary. Two additional sources of information exist in Mach-O binaries:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002464 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2465 // function's start address in the
2466 // binary, relative to the text section.
2467 // eh_frame - the eh_frame FDEs have the start addr & size of
2468 // each function
2469 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2470 // all modern binaries.
2471 // Binaries built to run on older releases may need to use eh_frame
2472 // information.
Greg Clayton4c82d422012-05-18 23:20:01 +00002473
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474 if (text_section_sp && function_starts_data.GetByteSize()) {
2475 FunctionStarts::Entry function_start_entry;
2476 function_start_entry.data = false;
2477 lldb::offset_t function_start_offset = 0;
2478 function_start_entry.addr = text_section_sp->GetFileAddress();
2479 uint64_t delta;
2480 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2481 0) {
2482 // Now append the current entry
2483 function_start_entry.addr += delta;
2484 function_starts.Append(function_start_entry);
2485 }
2486 } else {
2487 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
Adrian Prantl05097242018-04-30 16:49:04 +00002488 // load command claiming an eh_frame but it doesn't actually have the
2489 // eh_frame content. And if we have a dSYM, we don't need to do any of
2490 // this fill-in-the-missing-symbols works anyway - the debug info should
2491 // give us all the functions in the module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002492 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2493 m_type != eTypeDebugInfo) {
2494 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
Pavel Labath3f2a0812017-06-28 09:09:19 +00002495 DWARFCallFrameInfo::EH);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002496 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2497 eh_frame.GetFunctionAddressAndSizeVector(functions);
2498 addr_t text_base_addr = text_section_sp->GetFileAddress();
2499 size_t count = functions.GetSize();
2500 for (size_t i = 0; i < count; ++i) {
2501 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2502 functions.GetEntryAtIndex(i);
2503 if (func) {
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002504 FunctionStarts::Entry function_start_entry;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505 function_start_entry.addr = func->base - text_base_addr;
2506 function_starts.Append(function_start_entry);
2507 }
Jason Molendad63d3c72013-04-16 00:18:44 +00002508 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002509 }
2510 }
2511
2512 const size_t function_starts_count = function_starts.GetSize();
2513
2514 // For user process binaries (executables, dylibs, frameworks, bundles), if
Adrian Prantl05097242018-04-30 16:49:04 +00002515 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2516 // going to assume the binary has been stripped. Don't allow assembly
2517 // language instruction emulation because we don't know proper function
2518 // start boundaries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519 //
2520 // For all other types of binaries (kernels, stand-alone bare board
Adrian Prantl05097242018-04-30 16:49:04 +00002521 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2522 // sections - we should not make any assumptions about them based on that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002523 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2524 m_allow_assembly_emulation_unwind_plans = false;
2525 Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2526 LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2527
2528 if (unwind_or_symbol_log)
2529 module_sp->LogMessage(
2530 unwind_or_symbol_log,
2531 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2532 }
2533
2534 const user_id_t TEXT_eh_frame_sectID =
2535 eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2536 : static_cast<user_id_t>(NO_SECT);
2537
2538 lldb::offset_t nlist_data_offset = 0;
2539
2540 uint32_t N_SO_index = UINT32_MAX;
2541
2542 MachSymtabSectionInfo section_info(section_list);
2543 std::vector<uint32_t> N_FUN_indexes;
2544 std::vector<uint32_t> N_NSYM_indexes;
2545 std::vector<uint32_t> N_INCL_indexes;
2546 std::vector<uint32_t> N_BRAC_indexes;
2547 std::vector<uint32_t> N_COMM_indexes;
2548 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2549 typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2550 typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2551 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2552 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2553 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00002554 // Any symbols that get merged into another will get an entry in this map
2555 // so we know
Kate Stoneb9c1b512016-09-06 20:57:50 +00002556 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2557 uint32_t nlist_idx = 0;
2558 Symbol *symbol_ptr = NULL;
2559
2560 uint32_t sym_idx = 0;
2561 Symbol *sym = NULL;
2562 size_t num_syms = 0;
2563 std::string memory_symbol_name;
2564 uint32_t unmapped_local_symbols_found = 0;
2565
2566 std::vector<TrieEntryWithOffset> trie_entries;
2567 std::set<lldb::addr_t> resolver_addresses;
2568
2569 if (dyld_trie_data.GetByteSize() > 0) {
2570 std::vector<llvm::StringRef> nameSlices;
2571 ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2572 resolver_addresses, trie_entries);
2573
2574 ConstString text_segment_name("__TEXT");
2575 SectionSP text_segment_sp =
2576 GetSectionList()->FindSectionByName(text_segment_name);
2577 if (text_segment_sp) {
2578 const lldb::addr_t text_segment_file_addr =
2579 text_segment_sp->GetFileAddress();
2580 if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2581 for (auto &e : trie_entries)
2582 e.entry.address += text_segment_file_addr;
2583 }
2584 }
2585 }
2586
2587 typedef std::set<ConstString> IndirectSymbols;
2588 IndirectSymbols indirect_symbol_names;
2589
2590#if defined(__APPLE__) && \
2591 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2592
2593 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
Adrian Prantl05097242018-04-30 16:49:04 +00002594 // optimized by moving LOCAL symbols out of the memory mapped portion of
2595 // the DSC. The symbol information has all been retained, but it isn't
2596 // available in the normal nlist data. However, there *are* duplicate
2597 // entries of *some*
Kate Stoneb9c1b512016-09-06 20:57:50 +00002598 // LOCAL symbols in the normal nlist data. To handle this situation
2599 // correctly, we must first attempt
2600 // to parse any DSC unmapped symbol information. If we find any, we set a
Adrian Prantl05097242018-04-30 16:49:04 +00002601 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002602
2603 if (m_header.flags & 0x80000000u) {
Adrian Prantl05097242018-04-30 16:49:04 +00002604 // Before we can start mapping the DSC, we need to make certain the
2605 // target process is actually using the cache we can find.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002606
2607 // Next we need to determine the correct path for the dyld shared cache.
2608
2609 ArchSpec header_arch;
2610 GetArchitecture(header_arch);
2611 char dsc_path[PATH_MAX];
2612 char dsc_path_development[PATH_MAX];
2613
2614 snprintf(
2615 dsc_path, sizeof(dsc_path), "%s%s%s",
2616 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2617 */
2618 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2619 header_arch.GetArchitectureName());
2620
2621 snprintf(
2622 dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2623 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2624 */
2625 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
Ilia K4f730dc2016-09-12 05:25:33 +00002626 header_arch.GetArchitectureName(), ".development");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002627
2628 FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2629 FileSpec dsc_development_filespec(dsc_path_development, false);
2630 FileSpec dsc_filespec;
2631
2632 UUID dsc_uuid;
2633 UUID process_shared_cache_uuid;
Jason Molenda07580ff2018-05-04 00:59:37 +00002634 addr_t process_shared_cache_base_addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002635
2636 if (process) {
Jason Molenda07580ff2018-05-04 00:59:37 +00002637 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, process_shared_cache_uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002638 }
2639
Adrian Prantl05097242018-04-30 16:49:04 +00002640 // First see if we can find an exact match for the inferior process
2641 // shared cache UUID in the development or non-development shared caches
2642 // on disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002643 if (process_shared_cache_uuid.IsValid()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002644 if (FileSystem::Instance().Exists(dsc_development_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002645 UUID dsc_development_uuid = GetSharedCacheUUID(
2646 dsc_development_filespec, byte_order, addr_byte_size);
2647 if (dsc_development_uuid.IsValid() &&
2648 dsc_development_uuid == process_shared_cache_uuid) {
2649 dsc_filespec = dsc_development_filespec;
2650 dsc_uuid = dsc_development_uuid;
2651 }
2652 }
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002653 if (!dsc_uuid.IsValid() &&
2654 FileSystem::Instance().Exists(dsc_nondevelopment_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002655 UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2656 dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2657 if (dsc_nondevelopment_uuid.IsValid() &&
2658 dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2659 dsc_filespec = dsc_nondevelopment_filespec;
2660 dsc_uuid = dsc_nondevelopment_uuid;
2661 }
2662 }
2663 }
2664
2665 // Failing a UUID match, prefer the development dyld_shared cache if both
2666 // are present.
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002667 if (!FileSystem::Instance().Exists(dsc_filespec)) {
2668 if (FileSystem::Instance().Exists(dsc_development_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002669 dsc_filespec = dsc_development_filespec;
2670 } else {
2671 dsc_filespec = dsc_nondevelopment_filespec;
2672 }
2673 }
2674
2675 /* The dyld_cache_header has a pointer to the
2676 dyld_cache_local_symbols_info structure (localSymbolsOffset).
2677 The dyld_cache_local_symbols_info structure gives us three things:
2678 1. The start and count of the nlist records in the dyld_shared_cache
2679 file
2680 2. The start and size of the strings for these nlist records
2681 3. The start and count of dyld_cache_local_symbols_entry entries
2682
2683 There is one dyld_cache_local_symbols_entry per dylib/framework in the
2684 dyld shared cache.
2685 The "dylibOffset" field is the Mach-O header of this dylib/framework in
2686 the dyld shared cache.
2687 The dyld_cache_local_symbols_entry also lists the start of this
2688 dylib/framework's nlist records
2689 and the count of how many nlist records there are for this
2690 dylib/framework.
2691 */
2692
2693 // Process the dyld shared cache header to find the unmapped symbols
2694
Pavel Labath50251fc2017-12-21 10:54:30 +00002695 DataBufferSP dsc_data_sp = MapFileData(
2696 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697 if (!dsc_uuid.IsValid()) {
2698 dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2699 }
2700 if (dsc_data_sp) {
2701 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2702
2703 bool uuid_match = true;
2704 if (dsc_uuid.IsValid() && process) {
2705 if (process_shared_cache_uuid.IsValid() &&
2706 dsc_uuid != process_shared_cache_uuid) {
2707 // The on-disk dyld_shared_cache file is not the same as the one in
Adrian Prantl05097242018-04-30 16:49:04 +00002708 // this process' memory, don't use it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709 uuid_match = false;
2710 ModuleSP module_sp(GetModule());
2711 if (module_sp)
2712 module_sp->ReportWarning("process shared cache does not match "
2713 "on-disk dyld_shared_cache file, some "
2714 "symbol names will be missing.");
2715 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002716 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00002717
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002719
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
Jason Molenda955dcf22016-05-04 03:09:40 +00002721
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722 // If the mappingOffset points to a location inside the header, we've
2723 // opened an old dyld shared cache, and should not proceed further.
2724 if (uuid_match &&
2725 mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
Jason Molenda955dcf22016-05-04 03:09:40 +00002726
Pavel Labath50251fc2017-12-21 10:54:30 +00002727 DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2728 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2729 mappingOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002730
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2732 byte_order, addr_byte_size);
2733 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002734
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735 // The File addresses (from the in-memory Mach-O load commands) for
Adrian Prantl05097242018-04-30 16:49:04 +00002736 // the shared libraries in the shared library cache need to be
2737 // adjusted by an offset to match up with the dylibOffset identifying
2738 // field in the dyld_cache_local_symbol_entry's. This offset is
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739 // recorded in mapping_offset_value.
2740 const uint64_t mapping_offset_value =
2741 dsc_mapping_info_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002742
Kate Stoneb9c1b512016-09-06 20:57:50 +00002743 offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2744 localSymbolsOffset);
2745 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2746 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002747
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 if (localSymbolsOffset && localSymbolsSize) {
2749 // Map the local symbols
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002750 DataBufferSP dsc_local_symbols_data_sp =
Pavel Labath50251fc2017-12-21 10:54:30 +00002751 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002752
2753 if (dsc_local_symbols_data_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2755 byte_order, addr_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002756
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002758
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2760 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2761 UndefinedNameToDescMap undefined_name_to_desc;
2762 SymbolIndexToName reexport_shlib_needs_fixup;
Jim Inghamea3ac272014-01-10 22:55:37 +00002763
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 // Read the local_symbols_infos struct in one shot
2765 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2766 dsc_local_symbols_data.GetU32(&offset,
2767 &local_symbols_info.nlistOffset, 6);
Jim Inghamea3ac272014-01-10 22:55:37 +00002768
Kate Stoneb9c1b512016-09-06 20:57:50 +00002769 SectionSP text_section_sp(
2770 section_list->FindSectionByName(GetSegmentNameTEXT()));
Greg Claytonb65c6292015-02-20 22:20:05 +00002771
Kate Stoneb9c1b512016-09-06 20:57:50 +00002772 uint32_t header_file_offset =
2773 (text_section_sp->GetFileAddress() - mapping_offset_value);
Jason Molendaa5609c82012-06-21 01:51:02 +00002774
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775 offset = local_symbols_info.entriesOffset;
2776 for (uint32_t entry_index = 0;
2777 entry_index < local_symbols_info.entriesCount;
2778 entry_index++) {
2779 struct lldb_copy_dyld_cache_local_symbols_entry
2780 local_symbols_entry;
2781 local_symbols_entry.dylibOffset =
2782 dsc_local_symbols_data.GetU32(&offset);
2783 local_symbols_entry.nlistStartIndex =
2784 dsc_local_symbols_data.GetU32(&offset);
2785 local_symbols_entry.nlistCount =
2786 dsc_local_symbols_data.GetU32(&offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002787
Kate Stoneb9c1b512016-09-06 20:57:50 +00002788 if (header_file_offset == local_symbols_entry.dylibOffset) {
2789 unmapped_local_symbols_found = local_symbols_entry.nlistCount;
Jason Molendaa5609c82012-06-21 01:51:02 +00002790
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 // The normal nlist code cannot correctly size the Symbols
2792 // array, we need to allocate it here.
2793 sym = symtab->Resize(
2794 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2795 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2796 num_syms = symtab->GetNumSymbols();
Jason Molendaa5609c82012-06-21 01:51:02 +00002797
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 nlist_data_offset =
2799 local_symbols_info.nlistOffset +
2800 (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2801 uint32_t string_table_offset =
2802 local_symbols_info.stringsOffset;
Jason Molendaa5609c82012-06-21 01:51:02 +00002803
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 for (uint32_t nlist_index = 0;
2805 nlist_index < local_symbols_entry.nlistCount;
2806 nlist_index++) {
2807 /////////////////////////////
Jason Molenda649a6072015-11-10 05:21:54 +00002808 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 struct nlist_64 nlist;
2810 if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(
2811 nlist_data_offset, nlist_byte_size))
2812 break;
Eugene Zelenko8157a882015-10-23 16:56:07 +00002813
Kate Stoneb9c1b512016-09-06 20:57:50 +00002814 nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(
2815 &nlist_data_offset);
2816 nlist.n_type = dsc_local_symbols_data.GetU8_unchecked(
2817 &nlist_data_offset);
2818 nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked(
2819 &nlist_data_offset);
2820 nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked(
2821 &nlist_data_offset);
2822 nlist.n_value =
2823 dsc_local_symbols_data.GetAddress_unchecked(
2824 &nlist_data_offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002825
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 SymbolType type = eSymbolTypeInvalid;
2827 const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2828 string_table_offset + nlist.n_strx);
Jason Molendaf8130862012-06-22 03:28:35 +00002829
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002831 // No symbol should be NULL, even the symbols with no
Adrian Prantl05097242018-04-30 16:49:04 +00002832 // string values should have an offset zero which
2833 // points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00002834 Host::SystemLog(
2835 Host::eSystemLogError,
2836 "error: DSC unmapped local symbol[%u] has invalid "
2837 "string table offset 0x%x in %s, ignoring symbol\n",
2838 entry_index, nlist.n_strx,
2839 module_sp->GetFileSpec().GetPath().c_str());
Greg Claytonfd814c52013-08-13 01:42:25 +00002840 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 }
2842 if (symbol_name[0] == '\0')
Greg Claytonfd814c52013-08-13 01:42:25 +00002843 symbol_name = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002844
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 const char *symbol_name_non_abi_mangled = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002846
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847 SectionSP symbol_section;
2848 uint32_t symbol_byte_size = 0;
2849 bool add_nlist = true;
2850 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2851 bool demangled_is_synthesized = false;
2852 bool is_gsym = false;
2853 bool set_value = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00002854
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 assert(sym_idx < num_syms);
Jason Molenda4e7511e2013-03-06 23:19:17 +00002856
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 sym[sym_idx].SetDebug(is_debug);
Greg Clayton29e08cb2012-03-14 01:53:24 +00002858
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859 if (is_debug) {
2860 switch (nlist.n_type) {
2861 case N_GSYM:
2862 // global symbol: name,,NO_SECT,type,0
2863 // Sometimes the N_GSYM value contains the address.
2864
2865 // FIXME: In the .o files, we have a GSYM and a debug
2866 // symbol for all the ObjC data. They
2867 // have the same address, but we want to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +00002868 // we always find only the real symbol, 'cause we
2869 // don't currently correctly attribute the
Kate Stoneb9c1b512016-09-06 20:57:50 +00002870 // GSYM one to the ObjCClass/Ivar/MetaClass
Adrian Prantl05097242018-04-30 16:49:04 +00002871 // symbol type. This is a temporary hack to make
2872 // sure the ObjectiveC symbols get treated correctly.
2873 // To do this right, we should coalesce all the GSYM
2874 // & global symbols that have the same address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875
2876 is_gsym = true;
2877 sym[sym_idx].SetExternal(true);
2878
2879 if (symbol_name && symbol_name[0] == '_' &&
2880 symbol_name[1] == 'O') {
Greg Clayton1e28adf2015-02-25 17:25:02 +00002881 llvm::StringRef symbol_name_ref(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002882 if (symbol_name_ref.startswith(
2883 g_objc_v2_prefix_class)) {
2884 symbol_name_non_abi_mangled = symbol_name + 1;
2885 symbol_name =
2886 symbol_name + g_objc_v2_prefix_class.size();
2887 type = eSymbolTypeObjCClass;
2888 demangled_is_synthesized = true;
2889
2890 } else if (symbol_name_ref.startswith(
2891 g_objc_v2_prefix_metaclass)) {
2892 symbol_name_non_abi_mangled = symbol_name + 1;
2893 symbol_name = symbol_name +
2894 g_objc_v2_prefix_metaclass.size();
2895 type = eSymbolTypeObjCMetaClass;
2896 demangled_is_synthesized = true;
2897 } else if (symbol_name_ref.startswith(
2898 g_objc_v2_prefix_ivar)) {
2899 symbol_name_non_abi_mangled = symbol_name + 1;
2900 symbol_name =
2901 symbol_name + g_objc_v2_prefix_ivar.size();
2902 type = eSymbolTypeObjCIVar;
2903 demangled_is_synthesized = true;
Greg Clayton1e28adf2015-02-25 17:25:02 +00002904 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002906 if (nlist.n_value != 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907 symbol_section = section_info.GetSection(
2908 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002909 type = eSymbolTypeData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 }
2911 break;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002912
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 case N_FNAME:
2914 // procedure name (f77 kludge): name,,NO_SECT,0,0
2915 type = eSymbolTypeCompiler;
2916 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002917
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 case N_FUN:
2919 // procedure: name,,n_sect,linenumber,address
2920 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002921 type = eSymbolTypeCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002922 symbol_section = section_info.GetSection(
2923 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002924
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 N_FUN_addr_to_sym_idx.insert(
2926 std::make_pair(nlist.n_value, sym_idx));
2927 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00002928 // symbol table in lieu of using nlist_idx in case
2929 // we ever start trimming entries out
Greg Claytonfd814c52013-08-13 01:42:25 +00002930 N_FUN_indexes.push_back(sym_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002931 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002932 type = eSymbolTypeCompiler;
2933
Kate Stoneb9c1b512016-09-06 20:57:50 +00002934 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00002935 // Copy the size of the function into the
2936 // original
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 // STAB entry so we don't have
2938 // to hunt for it later
2939 symtab->SymbolAtIndex(N_FUN_indexes.back())
2940 ->SetByteSize(nlist.n_value);
2941 N_FUN_indexes.pop_back();
2942 // We don't really need the end function STAB as
Adrian Prantl05097242018-04-30 16:49:04 +00002943 // it contains the size which we already placed
2944 // with the original symbol, so don't add it if
2945 // we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00002946 add_nlist = false;
Greg Claytondacc4a92013-05-14 22:19:37 +00002947 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 }
2949 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002950
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 case N_STSYM:
2952 // static symbol: name,,n_sect,type,address
2953 N_STSYM_addr_to_sym_idx.insert(
2954 std::make_pair(nlist.n_value, sym_idx));
2955 symbol_section = section_info.GetSection(
2956 nlist.n_sect, nlist.n_value);
2957 if (symbol_name && symbol_name[0]) {
2958 type = ObjectFile::GetSymbolTypeFromName(
2959 symbol_name + 1, eSymbolTypeData);
2960 }
2961 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002962
Kate Stoneb9c1b512016-09-06 20:57:50 +00002963 case N_LCSYM:
2964 // .lcomm symbol: name,,n_sect,type,address
2965 symbol_section = section_info.GetSection(
2966 nlist.n_sect, nlist.n_value);
2967 type = eSymbolTypeCommonBlock;
2968 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002969
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 case N_BNSYM:
2971 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00002972 // table in lieu of using nlist_idx in case we ever
2973 // start trimming entries out Skip these if we want
2974 // minimal symbol tables
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 add_nlist = false;
2976 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002977
Kate Stoneb9c1b512016-09-06 20:57:50 +00002978 case N_ENSYM:
2979 // Set the size of the N_BNSYM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002980 // index of this N_ENSYM so that we can always skip
2981 // the entire symbol if we need to navigate more
2982 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983 // Skip these if we want minimal symbol tables
2984 add_nlist = false;
2985 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002986
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 case N_OPT:
2988 // emitted with gcc2_compiled and in gcc source
2989 type = eSymbolTypeCompiler;
2990 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002991
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 case N_RSYM:
2993 // register sym: name,,NO_SECT,type,register
2994 type = eSymbolTypeVariable;
2995 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002996
Kate Stoneb9c1b512016-09-06 20:57:50 +00002997 case N_SLINE:
2998 // src line: 0,,n_sect,linenumber,address
2999 symbol_section = section_info.GetSection(
3000 nlist.n_sect, nlist.n_value);
3001 type = eSymbolTypeLineEntry;
3002 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003003
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004 case N_SSYM:
3005 // structure elt: name,,NO_SECT,type,struct_offset
3006 type = eSymbolTypeVariableType;
3007 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003008
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 case N_SO:
3010 // source file name
3011 type = eSymbolTypeSourceFile;
3012 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003013 add_nlist = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003014 if (N_SO_index != UINT32_MAX) {
3015 // Set the size of the N_SO to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003016 // index of this N_SO so that we can always skip
3017 // the entire N_SO if we need to navigate more
3018 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003019 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3020 symbol_ptr->SetByteSize(sym_idx);
3021 symbol_ptr->SetSizeIsSibling(true);
Greg Claytonfd814c52013-08-13 01:42:25 +00003022 }
3023 N_NSYM_indexes.clear();
3024 N_INCL_indexes.clear();
3025 N_BRAC_indexes.clear();
3026 N_COMM_indexes.clear();
3027 N_FUN_indexes.clear();
3028 N_SO_index = UINT32_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 } else {
3030 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00003031 // symbol table in lieu of using nlist_idx in case
3032 // we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033 const bool N_SO_has_full_path =
3034 symbol_name[0] == '/';
3035 if (N_SO_has_full_path) {
3036 if ((N_SO_index == sym_idx - 1) &&
3037 ((sym_idx - 1) < num_syms)) {
3038 // We have two consecutive N_SO entries where
Adrian Prantl05097242018-04-30 16:49:04 +00003039 // the first contains a directory and the
3040 // second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003041 sym[sym_idx - 1].GetMangled().SetValue(
3042 ConstString(symbol_name), false);
3043 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3044 add_nlist = false;
3045 } else {
3046 // This is the first entry in a N_SO that
3047 // contains a directory or
3048 // a full path to the source file
Greg Claytonfd814c52013-08-13 01:42:25 +00003049 N_SO_index = sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050 }
3051 } else if ((N_SO_index == sym_idx - 1) &&
3052 ((sym_idx - 1) < num_syms)) {
3053 // This is usually the second N_SO entry that
Adrian Prantl05097242018-04-30 16:49:04 +00003054 // contains just the filename, so here we combine
3055 // it with the first one if we are minimizing the
3056 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003057 const char *so_path =
3058 sym[sym_idx - 1]
3059 .GetMangled()
3060 .GetDemangledName(
3061 lldb::eLanguageTypeUnknown)
3062 .AsCString();
3063 if (so_path && so_path[0]) {
3064 std::string full_so_path(so_path);
3065 const size_t double_slash_pos =
3066 full_so_path.find("//");
3067 if (double_slash_pos != std::string::npos) {
3068 // The linker has been generating bad N_SO
3069 // entries with doubled up paths
Adrian Prantl05097242018-04-30 16:49:04 +00003070 // in the format "%s%s" where the first
3071 // string in the DW_AT_comp_dir, and the
3072 // second is the directory for the source
3073 // file so you end up with a path that looks
3074 // like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00003075 FileSpec so_dir(so_path, false);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00003076 if (!FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003077 so_dir.SetFile(
3078 &full_so_path[double_slash_pos + 1],
3079 false);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00003080 if (FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003081 // Trim off the incorrect path
3082 full_so_path.erase(0,
3083 double_slash_pos + 1);
3084 }
3085 }
3086 }
3087 if (*full_so_path.rbegin() != '/')
3088 full_so_path += '/';
3089 full_so_path += symbol_name;
3090 sym[sym_idx - 1].GetMangled().SetValue(
3091 ConstString(full_so_path.c_str()), false);
3092 add_nlist = false;
3093 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3094 }
3095 } else {
3096 // This could be a relative path to a N_SO
3097 N_SO_index = sym_idx;
Greg Claytonfd814c52013-08-13 01:42:25 +00003098 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 }
3100 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003101
Kate Stoneb9c1b512016-09-06 20:57:50 +00003102 case N_OSO:
3103 // object file name: name,,0,0,st_mtime
3104 type = eSymbolTypeObjectFile;
3105 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003106
Kate Stoneb9c1b512016-09-06 20:57:50 +00003107 case N_LSYM:
3108 // local sym: name,,NO_SECT,type,offset
3109 type = eSymbolTypeLocal;
3110 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003111
Kate Stoneb9c1b512016-09-06 20:57:50 +00003112 //----------------------------------------------------------------------
3113 // INCL scopes
3114 //----------------------------------------------------------------------
3115 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00003116 // include file beginning: name,,NO_SECT,0,sum We use
3117 // the current number of symbols in the symbol table
3118 // in lieu of using nlist_idx in case we ever start
3119 // trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 N_INCL_indexes.push_back(sym_idx);
3121 type = eSymbolTypeScopeBegin;
3122 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003123
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 case N_EINCL:
3125 // include file end: name,,NO_SECT,0,0
3126 // Set the size of the N_BINCL to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003127 // index of this N_EINCL so that we can always skip
3128 // the entire symbol if we need to navigate more
3129 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 if (!N_INCL_indexes.empty()) {
3131 symbol_ptr =
3132 symtab->SymbolAtIndex(N_INCL_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003133 symbol_ptr->SetByteSize(sym_idx + 1);
3134 symbol_ptr->SetSizeIsSibling(true);
3135 N_INCL_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136 }
3137 type = eSymbolTypeScopeEnd;
3138 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003139
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 case N_SOL:
3141 // #included file name: name,,n_sect,0,address
3142 type = eSymbolTypeHeaderFile;
Greg Claytonfd814c52013-08-13 01:42:25 +00003143
Kate Stoneb9c1b512016-09-06 20:57:50 +00003144 // We currently don't use the header files on darwin
3145 add_nlist = false;
3146 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003147
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 case N_PARAMS:
3149 // compiler parameters: name,,NO_SECT,0,0
3150 type = eSymbolTypeCompiler;
3151 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003152
Kate Stoneb9c1b512016-09-06 20:57:50 +00003153 case N_VERSION:
3154 // compiler version: name,,NO_SECT,0,0
3155 type = eSymbolTypeCompiler;
3156 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003157
Kate Stoneb9c1b512016-09-06 20:57:50 +00003158 case N_OLEVEL:
3159 // compiler -O level: name,,NO_SECT,0,0
3160 type = eSymbolTypeCompiler;
3161 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003162
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163 case N_PSYM:
3164 // parameter: name,,NO_SECT,type,offset
3165 type = eSymbolTypeVariable;
3166 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003167
Kate Stoneb9c1b512016-09-06 20:57:50 +00003168 case N_ENTRY:
3169 // alternate entry: name,,n_sect,linenumber,address
3170 symbol_section = section_info.GetSection(
3171 nlist.n_sect, nlist.n_value);
3172 type = eSymbolTypeLineEntry;
3173 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003174
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175 //----------------------------------------------------------------------
3176 // Left and Right Braces
3177 //----------------------------------------------------------------------
3178 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00003179 // left bracket: 0,,NO_SECT,nesting level,address We
3180 // use the current number of symbols in the symbol
3181 // table in lieu of using nlist_idx in case we ever
3182 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003183 symbol_section = section_info.GetSection(
3184 nlist.n_sect, nlist.n_value);
3185 N_BRAC_indexes.push_back(sym_idx);
3186 type = eSymbolTypeScopeBegin;
3187 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003188
Kate Stoneb9c1b512016-09-06 20:57:50 +00003189 case N_RBRAC:
3190 // right bracket: 0,,NO_SECT,nesting level,address
3191 // Set the size of the N_LBRAC to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003192 // index of this N_RBRAC so that we can always skip
3193 // the entire symbol if we need to navigate more
3194 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003195 symbol_section = section_info.GetSection(
3196 nlist.n_sect, nlist.n_value);
3197 if (!N_BRAC_indexes.empty()) {
3198 symbol_ptr =
3199 symtab->SymbolAtIndex(N_BRAC_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003200 symbol_ptr->SetByteSize(sym_idx + 1);
3201 symbol_ptr->SetSizeIsSibling(true);
3202 N_BRAC_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 }
3204 type = eSymbolTypeScopeEnd;
3205 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003206
Kate Stoneb9c1b512016-09-06 20:57:50 +00003207 case N_EXCL:
3208 // deleted include file: name,,NO_SECT,0,sum
3209 type = eSymbolTypeHeaderFile;
3210 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003211
Kate Stoneb9c1b512016-09-06 20:57:50 +00003212 //----------------------------------------------------------------------
3213 // COMM scopes
3214 //----------------------------------------------------------------------
3215 case N_BCOMM:
3216 // begin common: name,,NO_SECT,0,0
3217 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00003218 // table in lieu of using nlist_idx in case we ever
3219 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003220 type = eSymbolTypeScopeBegin;
3221 N_COMM_indexes.push_back(sym_idx);
3222 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003223
Kate Stoneb9c1b512016-09-06 20:57:50 +00003224 case N_ECOML:
3225 // end common (local name): 0,,n_sect,0,address
3226 symbol_section = section_info.GetSection(
3227 nlist.n_sect, nlist.n_value);
3228 // Fall through
Greg Claytonfd814c52013-08-13 01:42:25 +00003229
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230 case N_ECOMM:
3231 // end common: name,,n_sect,0,0
3232 // Set the size of the N_BCOMM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003233 // index of this N_ECOMM/N_ECOML so that we can
3234 // always skip the entire symbol if we need to
3235 // navigate more quickly at the source level when
3236 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003237 if (!N_COMM_indexes.empty()) {
3238 symbol_ptr =
3239 symtab->SymbolAtIndex(N_COMM_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003240 symbol_ptr->SetByteSize(sym_idx + 1);
3241 symbol_ptr->SetSizeIsSibling(true);
3242 N_COMM_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 }
3244 type = eSymbolTypeScopeEnd;
3245 break;
3246
3247 case N_LENG:
3248 // second stab entry with length information
3249 type = eSymbolTypeAdditional;
3250 break;
3251
3252 default:
3253 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003254 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003255 } else {
3256 // uint8_t n_pext = N_PEXT & nlist.n_type;
3257 uint8_t n_type = N_TYPE & nlist.n_type;
3258 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
Greg Claytonfd814c52013-08-13 01:42:25 +00003259
Kate Stoneb9c1b512016-09-06 20:57:50 +00003260 switch (n_type) {
3261 case N_INDR: {
3262 const char *reexport_name_cstr =
3263 strtab_data.PeekCStr(nlist.n_value);
3264 if (reexport_name_cstr && reexport_name_cstr[0]) {
3265 type = eSymbolTypeReExported;
3266 ConstString reexport_name(
3267 reexport_name_cstr +
3268 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3269 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3270 set_value = false;
3271 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3272 indirect_symbol_names.insert(
3273 ConstString(symbol_name +
3274 ((symbol_name[0] == '_') ? 1 : 0)));
3275 } else
3276 type = eSymbolTypeUndefined;
3277 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003278
Kate Stoneb9c1b512016-09-06 20:57:50 +00003279 case N_UNDF:
3280 if (symbol_name && symbol_name[0]) {
3281 ConstString undefined_name(
3282 symbol_name +
3283 ((symbol_name[0] == '_') ? 1 : 0));
3284 undefined_name_to_desc[undefined_name] =
3285 nlist.n_desc;
3286 }
3287 // Fall through
3288 case N_PBUD:
3289 type = eSymbolTypeUndefined;
3290 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003291
Kate Stoneb9c1b512016-09-06 20:57:50 +00003292 case N_ABS:
3293 type = eSymbolTypeAbsolute;
3294 break;
Greg Clayton60038be2015-02-14 00:51:13 +00003295
Kate Stoneb9c1b512016-09-06 20:57:50 +00003296 case N_SECT: {
3297 symbol_section = section_info.GetSection(
3298 nlist.n_sect, nlist.n_value);
Jason Molenda62e06812016-02-16 04:14:33 +00003299
Kate Stoneb9c1b512016-09-06 20:57:50 +00003300 if (symbol_section == NULL) {
3301 // TODO: warn about this?
3302 add_nlist = false;
3303 break;
3304 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003305
Kate Stoneb9c1b512016-09-06 20:57:50 +00003306 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3307 type = eSymbolTypeException;
3308 } else {
3309 uint32_t section_type =
3310 symbol_section->Get() & SECTION_TYPE;
Greg Claytonfd814c52013-08-13 01:42:25 +00003311
Kate Stoneb9c1b512016-09-06 20:57:50 +00003312 switch (section_type) {
3313 case S_CSTRING_LITERALS:
3314 type = eSymbolTypeData;
3315 break; // section with only literal C strings
3316 case S_4BYTE_LITERALS:
3317 type = eSymbolTypeData;
3318 break; // section with only 4 byte literals
3319 case S_8BYTE_LITERALS:
3320 type = eSymbolTypeData;
3321 break; // section with only 8 byte literals
3322 case S_LITERAL_POINTERS:
3323 type = eSymbolTypeTrampoline;
3324 break; // section with only pointers to literals
3325 case S_NON_LAZY_SYMBOL_POINTERS:
3326 type = eSymbolTypeTrampoline;
3327 break; // section with only non-lazy symbol
3328 // pointers
3329 case S_LAZY_SYMBOL_POINTERS:
3330 type = eSymbolTypeTrampoline;
3331 break; // section with only lazy symbol pointers
3332 case S_SYMBOL_STUBS:
3333 type = eSymbolTypeTrampoline;
3334 break; // section with only symbol stubs, byte
3335 // size of stub in the reserved2 field
3336 case S_MOD_INIT_FUNC_POINTERS:
3337 type = eSymbolTypeCode;
3338 break; // section with only function pointers for
3339 // initialization
3340 case S_MOD_TERM_FUNC_POINTERS:
3341 type = eSymbolTypeCode;
3342 break; // section with only function pointers for
3343 // termination
3344 case S_INTERPOSING:
3345 type = eSymbolTypeTrampoline;
3346 break; // section with only pairs of function
3347 // pointers for interposing
3348 case S_16BYTE_LITERALS:
3349 type = eSymbolTypeData;
3350 break; // section with only 16 byte literals
3351 case S_DTRACE_DOF:
3352 type = eSymbolTypeInstrumentation;
3353 break;
3354 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3355 type = eSymbolTypeTrampoline;
3356 break;
3357 default:
3358 switch (symbol_section->GetType()) {
3359 case lldb::eSectionTypeCode:
3360 type = eSymbolTypeCode;
Greg Claytonfd814c52013-08-13 01:42:25 +00003361 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003362 case eSectionTypeData:
3363 case eSectionTypeDataCString: // Inlined C string
3364 // data
3365 case eSectionTypeDataCStringPointers: // Pointers
3366 // to C
3367 // string
3368 // data
3369 case eSectionTypeDataSymbolAddress: // Address of
3370 // a symbol in
3371 // the symbol
3372 // table
3373 case eSectionTypeData4:
3374 case eSectionTypeData8:
3375 case eSectionTypeData16:
3376 type = eSymbolTypeData;
3377 break;
3378 default:
3379 break;
3380 }
3381 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003382 }
3383
Kate Stoneb9c1b512016-09-06 20:57:50 +00003384 if (type == eSymbolTypeInvalid) {
3385 const char *symbol_sect_name =
3386 symbol_section->GetName().AsCString();
3387 if (symbol_section->IsDescendant(
3388 text_section_sp.get())) {
3389 if (symbol_section->IsClear(
3390 S_ATTR_PURE_INSTRUCTIONS |
3391 S_ATTR_SELF_MODIFYING_CODE |
3392 S_ATTR_SOME_INSTRUCTIONS))
3393 type = eSymbolTypeData;
3394 else
3395 type = eSymbolTypeCode;
3396 } else if (symbol_section->IsDescendant(
3397 data_section_sp.get()) ||
3398 symbol_section->IsDescendant(
3399 data_dirty_section_sp.get()) ||
3400 symbol_section->IsDescendant(
3401 data_const_section_sp.get())) {
3402 if (symbol_sect_name &&
3403 ::strstr(symbol_sect_name, "__objc") ==
3404 symbol_sect_name) {
3405 type = eSymbolTypeRuntime;
Greg Claytonfd814c52013-08-13 01:42:25 +00003406
Kate Stoneb9c1b512016-09-06 20:57:50 +00003407 if (symbol_name) {
3408 llvm::StringRef symbol_name_ref(
3409 symbol_name);
3410 if (symbol_name_ref.startswith("_OBJC_")) {
3411 static const llvm::StringRef
3412 g_objc_v2_prefix_class(
3413 "_OBJC_CLASS_$_");
3414 static const llvm::StringRef
3415 g_objc_v2_prefix_metaclass(
3416 "_OBJC_METACLASS_$_");
3417 static const llvm::StringRef
3418 g_objc_v2_prefix_ivar(
3419 "_OBJC_IVAR_$_");
3420 if (symbol_name_ref.startswith(
3421 g_objc_v2_prefix_class)) {
3422 symbol_name_non_abi_mangled =
3423 symbol_name + 1;
3424 symbol_name =
3425 symbol_name +
3426 g_objc_v2_prefix_class.size();
3427 type = eSymbolTypeObjCClass;
3428 demangled_is_synthesized = true;
3429 } else if (
3430 symbol_name_ref.startswith(
3431 g_objc_v2_prefix_metaclass)) {
3432 symbol_name_non_abi_mangled =
3433 symbol_name + 1;
3434 symbol_name =
3435 symbol_name +
3436 g_objc_v2_prefix_metaclass.size();
3437 type = eSymbolTypeObjCMetaClass;
3438 demangled_is_synthesized = true;
3439 } else if (symbol_name_ref.startswith(
3440 g_objc_v2_prefix_ivar)) {
3441 symbol_name_non_abi_mangled =
3442 symbol_name + 1;
3443 symbol_name =
3444 symbol_name +
3445 g_objc_v2_prefix_ivar.size();
3446 type = eSymbolTypeObjCIVar;
3447 demangled_is_synthesized = true;
3448 }
Greg Clayton38f9cc42014-06-16 22:53:16 +00003449 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003450 }
3451 } else if (symbol_sect_name &&
3452 ::strstr(symbol_sect_name,
3453 "__gcc_except_tab") ==
3454 symbol_sect_name) {
3455 type = eSymbolTypeException;
3456 } else {
3457 type = eSymbolTypeData;
Greg Claytonfd814c52013-08-13 01:42:25 +00003458 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003459 } else if (symbol_sect_name &&
3460 ::strstr(symbol_sect_name,
3461 "__IMPORT") ==
3462 symbol_sect_name) {
3463 type = eSymbolTypeTrampoline;
3464 } else if (symbol_section->IsDescendant(
3465 objc_section_sp.get())) {
3466 type = eSymbolTypeRuntime;
3467 if (symbol_name && symbol_name[0] == '.') {
3468 llvm::StringRef symbol_name_ref(symbol_name);
3469 static const llvm::StringRef
3470 g_objc_v1_prefix_class(
3471 ".objc_class_name_");
3472 if (symbol_name_ref.startswith(
3473 g_objc_v1_prefix_class)) {
3474 symbol_name_non_abi_mangled = symbol_name;
3475 symbol_name = symbol_name +
3476 g_objc_v1_prefix_class.size();
3477 type = eSymbolTypeObjCClass;
3478 demangled_is_synthesized = true;
3479 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003480 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003481 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003482 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003483 }
3484 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003485 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003486 }
Greg Claytondacc4a92013-05-14 22:19:37 +00003487
Kate Stoneb9c1b512016-09-06 20:57:50 +00003488 if (add_nlist) {
3489 uint64_t symbol_value = nlist.n_value;
3490 if (symbol_name_non_abi_mangled) {
3491 sym[sym_idx].GetMangled().SetMangledName(
3492 ConstString(symbol_name_non_abi_mangled));
3493 sym[sym_idx].GetMangled().SetDemangledName(
3494 ConstString(symbol_name));
3495 } else {
3496 bool symbol_name_is_mangled = false;
Greg Claytonfd814c52013-08-13 01:42:25 +00003497
Kate Stoneb9c1b512016-09-06 20:57:50 +00003498 if (symbol_name && symbol_name[0] == '_') {
Greg Claytonfd814c52013-08-13 01:42:25 +00003499 symbol_name_is_mangled = symbol_name[1] == '_';
Kate Stoneb9c1b512016-09-06 20:57:50 +00003500 symbol_name++; // Skip the leading underscore
3501 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003502
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003504 ConstString const_symbol_name(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003505 sym[sym_idx].GetMangled().SetValue(
3506 const_symbol_name, symbol_name_is_mangled);
3507 if (is_gsym && is_debug) {
3508 const char *gsym_name =
3509 sym[sym_idx]
3510 .GetMangled()
3511 .GetName(lldb::eLanguageTypeUnknown,
3512 Mangled::ePreferMangled)
3513 .GetCString();
3514 if (gsym_name)
3515 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3516 }
3517 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003518 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003519 if (symbol_section) {
3520 const addr_t section_file_addr =
3521 symbol_section->GetFileAddress();
3522 if (symbol_byte_size == 0 &&
3523 function_starts_count > 0) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003524 addr_t symbol_lookup_file_addr = nlist.n_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003525 // Do an exact address match for non-ARM addresses,
Adrian Prantl05097242018-04-30 16:49:04 +00003526 // else get the closest since the symbol might be a
3527 // thumb symbol which has an address with bit zero
3528 // set
Kate Stoneb9c1b512016-09-06 20:57:50 +00003529 FunctionStarts::Entry *func_start_entry =
3530 function_starts.FindEntry(
3531 symbol_lookup_file_addr, !is_arm);
3532 if (is_arm && func_start_entry) {
3533 // Verify that the function start address is the
Adrian Prantl05097242018-04-30 16:49:04 +00003534 // symbol address (ARM) or the symbol address + 1
3535 // (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003536 if (func_start_entry->addr !=
3537 symbol_lookup_file_addr &&
3538 func_start_entry->addr !=
3539 (symbol_lookup_file_addr + 1)) {
3540 // Not the right entry, NULL it out...
3541 func_start_entry = NULL;
3542 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003543 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003544 if (func_start_entry) {
3545 func_start_entry->data = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00003546
Kate Stoneb9c1b512016-09-06 20:57:50 +00003547 addr_t symbol_file_addr = func_start_entry->addr;
3548 uint32_t symbol_flags = 0;
3549 if (is_arm) {
3550 if (symbol_file_addr & 1)
3551 symbol_flags =
3552 MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3553 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3554 }
3555
3556 const FunctionStarts::Entry
3557 *next_func_start_entry =
3558 function_starts.FindNextEntry(
3559 func_start_entry);
3560 const addr_t section_end_file_addr =
3561 section_file_addr +
3562 symbol_section->GetByteSize();
3563 if (next_func_start_entry) {
3564 addr_t next_symbol_file_addr =
3565 next_func_start_entry->addr;
3566 // Be sure the clear the Thumb address bit when
Adrian Prantl05097242018-04-30 16:49:04 +00003567 // we calculate the size from the current and
3568 // next address
Greg Claytonfd814c52013-08-13 01:42:25 +00003569 if (is_arm)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003570 next_symbol_file_addr &=
3571 THUMB_ADDRESS_BIT_MASK;
3572 symbol_byte_size = std::min<lldb::addr_t>(
3573 next_symbol_file_addr - symbol_file_addr,
3574 section_end_file_addr - symbol_file_addr);
3575 } else {
3576 symbol_byte_size =
3577 section_end_file_addr - symbol_file_addr;
3578 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003579 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003580 }
3581 symbol_value -= section_file_addr;
Greg Claytonfd814c52013-08-13 01:42:25 +00003582 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003583
Kate Stoneb9c1b512016-09-06 20:57:50 +00003584 if (is_debug == false) {
3585 if (type == eSymbolTypeCode) {
3586 // See if we can find a N_FUN entry for any code
Adrian Prantl05097242018-04-30 16:49:04 +00003587 // symbols. If we do find a match, and the name
3588 // matches, then we can merge the two into just the
3589 // function symbol to avoid duplicate entries in
3590 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003591 std::pair<ValueToSymbolIndexMap::const_iterator,
3592 ValueToSymbolIndexMap::const_iterator>
3593 range;
3594 range = N_FUN_addr_to_sym_idx.equal_range(
3595 nlist.n_value);
3596 if (range.first != range.second) {
3597 bool found_it = false;
3598 for (ValueToSymbolIndexMap::const_iterator pos =
3599 range.first;
3600 pos != range.second; ++pos) {
3601 if (sym[sym_idx].GetMangled().GetName(
3602 lldb::eLanguageTypeUnknown,
3603 Mangled::ePreferMangled) ==
3604 sym[pos->second].GetMangled().GetName(
3605 lldb::eLanguageTypeUnknown,
3606 Mangled::ePreferMangled)) {
3607 m_nlist_idx_to_sym_idx[nlist_idx] =
3608 pos->second;
3609 // We just need the flags from the linker
3610 // symbol, so put these flags
3611 // into the N_FUN flags to avoid duplicate
3612 // symbols in the symbol table
3613 sym[pos->second].SetExternal(
3614 sym[sym_idx].IsExternal());
3615 sym[pos->second].SetFlags(nlist.n_type << 16 |
3616 nlist.n_desc);
3617 if (resolver_addresses.find(nlist.n_value) !=
3618 resolver_addresses.end())
3619 sym[pos->second].SetType(
3620 eSymbolTypeResolver);
3621 sym[sym_idx].Clear();
3622 found_it = true;
3623 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003624 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003625 }
3626 if (found_it)
3627 continue;
3628 } else {
3629 if (resolver_addresses.find(nlist.n_value) !=
3630 resolver_addresses.end())
3631 type = eSymbolTypeResolver;
Greg Claytonfd814c52013-08-13 01:42:25 +00003632 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003633 } else if (type == eSymbolTypeData ||
3634 type == eSymbolTypeObjCClass ||
3635 type == eSymbolTypeObjCMetaClass ||
3636 type == eSymbolTypeObjCIVar) {
3637 // See if we can find a N_STSYM entry for any data
Adrian Prantl05097242018-04-30 16:49:04 +00003638 // symbols. If we do find a match, and the name
3639 // matches, then we can merge the two into just the
3640 // Static symbol to avoid duplicate entries in the
3641 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003642 std::pair<ValueToSymbolIndexMap::const_iterator,
3643 ValueToSymbolIndexMap::const_iterator>
3644 range;
3645 range = N_STSYM_addr_to_sym_idx.equal_range(
3646 nlist.n_value);
3647 if (range.first != range.second) {
3648 bool found_it = false;
3649 for (ValueToSymbolIndexMap::const_iterator pos =
3650 range.first;
3651 pos != range.second; ++pos) {
3652 if (sym[sym_idx].GetMangled().GetName(
3653 lldb::eLanguageTypeUnknown,
3654 Mangled::ePreferMangled) ==
3655 sym[pos->second].GetMangled().GetName(
3656 lldb::eLanguageTypeUnknown,
3657 Mangled::ePreferMangled)) {
3658 m_nlist_idx_to_sym_idx[nlist_idx] =
3659 pos->second;
3660 // We just need the flags from the linker
3661 // symbol, so put these flags
3662 // into the N_STSYM flags to avoid duplicate
3663 // symbols in the symbol table
3664 sym[pos->second].SetExternal(
3665 sym[sym_idx].IsExternal());
3666 sym[pos->second].SetFlags(nlist.n_type << 16 |
3667 nlist.n_desc);
3668 sym[sym_idx].Clear();
3669 found_it = true;
3670 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003671 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003672 }
3673 if (found_it)
3674 continue;
3675 } else {
3676 const char *gsym_name =
3677 sym[sym_idx]
3678 .GetMangled()
3679 .GetName(lldb::eLanguageTypeUnknown,
3680 Mangled::ePreferMangled)
3681 .GetCString();
3682 if (gsym_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00003683 // Combine N_GSYM stab entries with the non
3684 // stab symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00003685 ConstNameToSymbolIndexMap::const_iterator pos =
3686 N_GSYM_name_to_sym_idx.find(gsym_name);
3687 if (pos != N_GSYM_name_to_sym_idx.end()) {
3688 const uint32_t GSYM_sym_idx = pos->second;
3689 m_nlist_idx_to_sym_idx[nlist_idx] =
3690 GSYM_sym_idx;
3691 // Copy the address, because often the N_GSYM
3692 // address has an invalid address of zero
3693 // when the global is a common symbol
3694 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3695 symbol_section);
3696 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3697 symbol_value);
3698 // We just need the flags from the linker
3699 // symbol, so put these flags
3700 // into the N_GSYM flags to avoid duplicate
3701 // symbols in the symbol table
3702 sym[GSYM_sym_idx].SetFlags(
3703 nlist.n_type << 16 | nlist.n_desc);
3704 sym[sym_idx].Clear();
3705 continue;
3706 }
3707 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003708 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003709 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003710 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003711
Kate Stoneb9c1b512016-09-06 20:57:50 +00003712 sym[sym_idx].SetID(nlist_idx);
3713 sym[sym_idx].SetType(type);
3714 if (set_value) {
3715 sym[sym_idx].GetAddressRef().SetSection(
3716 symbol_section);
3717 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
Greg Clayton29e08cb2012-03-14 01:53:24 +00003718 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003719 sym[sym_idx].SetFlags(nlist.n_type << 16 |
3720 nlist.n_desc);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003721
Kate Stoneb9c1b512016-09-06 20:57:50 +00003722 if (symbol_byte_size > 0)
3723 sym[sym_idx].SetByteSize(symbol_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003724
Kate Stoneb9c1b512016-09-06 20:57:50 +00003725 if (demangled_is_synthesized)
3726 sym[sym_idx].SetDemangledNameIsSynthesized(true);
Greg Clayton60038be2015-02-14 00:51:13 +00003727 ++sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003728 } else {
3729 sym[sym_idx].Clear();
3730 }
Greg Clayton9191db42013-10-21 18:40:51 +00003731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003732 /////////////////////////////
3733 }
3734 break; // No more entries to consider
Greg Clayton9191db42013-10-21 18:40:51 +00003735 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003736 }
3737
3738 for (const auto &pos : reexport_shlib_needs_fixup) {
3739 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3740 if (undef_pos != undefined_name_to_desc.end()) {
3741 const uint8_t dylib_ordinal =
3742 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3743 if (dylib_ordinal > 0 &&
3744 dylib_ordinal < dylib_files.GetSize())
3745 sym[pos.first].SetReExportedSymbolSharedLibrary(
3746 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3747 }
3748 }
Greg Clayton9191db42013-10-21 18:40:51 +00003749 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003750 }
Greg Clayton9191db42013-10-21 18:40:51 +00003751 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003752 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003753 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003754
3755 // Must reset this in case it was mutated above!
3756 nlist_data_offset = 0;
3757#endif
3758
3759 if (nlist_data.GetByteSize() > 0) {
3760
3761 // If the sym array was not created while parsing the DSC unmapped
3762 // symbols, create it now.
3763 if (sym == NULL) {
3764 sym = symtab->Resize(symtab_load_command.nsyms +
3765 m_dysymtab.nindirectsyms);
3766 num_syms = symtab->GetNumSymbols();
3767 }
3768
3769 if (unmapped_local_symbols_found) {
3770 assert(m_dysymtab.ilocalsym == 0);
3771 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3772 nlist_idx = m_dysymtab.nlocalsym;
3773 } else {
3774 nlist_idx = 0;
3775 }
3776
3777 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3778 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3779 UndefinedNameToDescMap undefined_name_to_desc;
3780 SymbolIndexToName reexport_shlib_needs_fixup;
3781 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
3782 struct nlist_64 nlist;
3783 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset,
3784 nlist_byte_size))
3785 break;
3786
3787 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
3788 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
3789 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
3790 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
3791 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
3792
3793 SymbolType type = eSymbolTypeInvalid;
3794 const char *symbol_name = NULL;
3795
3796 if (have_strtab_data) {
3797 symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3798
3799 if (symbol_name == NULL) {
Adrian Prantl05097242018-04-30 16:49:04 +00003800 // No symbol should be NULL, even the symbols with no string values
3801 // should have an offset zero which points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802 Host::SystemLog(Host::eSystemLogError,
3803 "error: symbol[%u] has invalid string table offset "
3804 "0x%x in %s, ignoring symbol\n",
3805 nlist_idx, nlist.n_strx,
3806 module_sp->GetFileSpec().GetPath().c_str());
3807 continue;
3808 }
3809 if (symbol_name[0] == '\0')
3810 symbol_name = NULL;
3811 } else {
3812 const addr_t str_addr = strtab_addr + nlist.n_strx;
Zachary Turner97206d52017-05-12 04:51:55 +00003813 Status str_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003814 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3815 str_error))
3816 symbol_name = memory_symbol_name.c_str();
3817 }
3818 const char *symbol_name_non_abi_mangled = NULL;
3819
3820 SectionSP symbol_section;
3821 lldb::addr_t symbol_byte_size = 0;
3822 bool add_nlist = true;
3823 bool is_gsym = false;
3824 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3825 bool demangled_is_synthesized = false;
3826 bool set_value = true;
3827 assert(sym_idx < num_syms);
3828
3829 sym[sym_idx].SetDebug(is_debug);
3830
3831 if (is_debug) {
3832 switch (nlist.n_type) {
3833 case N_GSYM:
3834 // global symbol: name,,NO_SECT,type,0
3835 // Sometimes the N_GSYM value contains the address.
3836
3837 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3838 // the ObjC data. They
3839 // have the same address, but we want to ensure that we always find
Adrian Prantl05097242018-04-30 16:49:04 +00003840 // only the real symbol, 'cause we don't currently correctly
3841 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3842 // type. This is a temporary hack to make sure the ObjectiveC
3843 // symbols get treated correctly. To do this right, we should
3844 // coalesce all the GSYM & global symbols that have the same
3845 // address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003846 is_gsym = true;
3847 sym[sym_idx].SetExternal(true);
3848
3849 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3850 llvm::StringRef symbol_name_ref(symbol_name);
3851 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3852 symbol_name_non_abi_mangled = symbol_name + 1;
3853 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3854 type = eSymbolTypeObjCClass;
3855 demangled_is_synthesized = true;
3856
3857 } else if (symbol_name_ref.startswith(
3858 g_objc_v2_prefix_metaclass)) {
3859 symbol_name_non_abi_mangled = symbol_name + 1;
3860 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3861 type = eSymbolTypeObjCMetaClass;
3862 demangled_is_synthesized = true;
3863 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3864 symbol_name_non_abi_mangled = symbol_name + 1;
3865 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3866 type = eSymbolTypeObjCIVar;
3867 demangled_is_synthesized = true;
3868 }
3869 } else {
3870 if (nlist.n_value != 0)
3871 symbol_section =
3872 section_info.GetSection(nlist.n_sect, nlist.n_value);
3873 type = eSymbolTypeData;
3874 }
3875 break;
3876
3877 case N_FNAME:
3878 // procedure name (f77 kludge): name,,NO_SECT,0,0
3879 type = eSymbolTypeCompiler;
3880 break;
3881
3882 case N_FUN:
3883 // procedure: name,,n_sect,linenumber,address
3884 if (symbol_name) {
3885 type = eSymbolTypeCode;
3886 symbol_section =
3887 section_info.GetSection(nlist.n_sect, nlist.n_value);
3888
3889 N_FUN_addr_to_sym_idx.insert(
3890 std::make_pair(nlist.n_value, sym_idx));
3891 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003892 // lieu of using nlist_idx in case we ever start trimming entries
3893 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003894 N_FUN_indexes.push_back(sym_idx);
3895 } else {
3896 type = eSymbolTypeCompiler;
3897
3898 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003899 // Copy the size of the function into the original STAB entry
3900 // so we don't have to hunt for it later
Kate Stoneb9c1b512016-09-06 20:57:50 +00003901 symtab->SymbolAtIndex(N_FUN_indexes.back())
3902 ->SetByteSize(nlist.n_value);
3903 N_FUN_indexes.pop_back();
Adrian Prantl05097242018-04-30 16:49:04 +00003904 // We don't really need the end function STAB as it contains
3905 // the size which we already placed with the original symbol,
3906 // so don't add it if we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003907 add_nlist = false;
3908 }
3909 }
3910 break;
3911
3912 case N_STSYM:
3913 // static symbol: name,,n_sect,type,address
3914 N_STSYM_addr_to_sym_idx.insert(
3915 std::make_pair(nlist.n_value, sym_idx));
3916 symbol_section =
3917 section_info.GetSection(nlist.n_sect, nlist.n_value);
3918 if (symbol_name && symbol_name[0]) {
3919 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3920 eSymbolTypeData);
3921 }
3922 break;
3923
3924 case N_LCSYM:
3925 // .lcomm symbol: name,,n_sect,type,address
3926 symbol_section =
3927 section_info.GetSection(nlist.n_sect, nlist.n_value);
3928 type = eSymbolTypeCommonBlock;
3929 break;
3930
3931 case N_BNSYM:
3932 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00003933 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003934 // Skip these if we want minimal symbol tables
3935 add_nlist = false;
3936 break;
3937
3938 case N_ENSYM:
3939 // Set the size of the N_BNSYM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003940 // N_ENSYM so that we can always skip the entire symbol if we need
3941 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003942 // Skip these if we want minimal symbol tables
3943 add_nlist = false;
3944 break;
3945
3946 case N_OPT:
3947 // emitted with gcc2_compiled and in gcc source
3948 type = eSymbolTypeCompiler;
3949 break;
3950
3951 case N_RSYM:
3952 // register sym: name,,NO_SECT,type,register
3953 type = eSymbolTypeVariable;
3954 break;
3955
3956 case N_SLINE:
3957 // src line: 0,,n_sect,linenumber,address
3958 symbol_section =
3959 section_info.GetSection(nlist.n_sect, nlist.n_value);
3960 type = eSymbolTypeLineEntry;
3961 break;
3962
3963 case N_SSYM:
3964 // structure elt: name,,NO_SECT,type,struct_offset
3965 type = eSymbolTypeVariableType;
3966 break;
3967
3968 case N_SO:
3969 // source file name
3970 type = eSymbolTypeSourceFile;
3971 if (symbol_name == NULL) {
3972 add_nlist = false;
3973 if (N_SO_index != UINT32_MAX) {
3974 // Set the size of the N_SO to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003975 // N_SO so that we can always skip the entire N_SO if we need
3976 // to navigate more quickly at the source level when parsing
3977 // STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003978 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3979 symbol_ptr->SetByteSize(sym_idx);
3980 symbol_ptr->SetSizeIsSibling(true);
3981 }
3982 N_NSYM_indexes.clear();
3983 N_INCL_indexes.clear();
3984 N_BRAC_indexes.clear();
3985 N_COMM_indexes.clear();
3986 N_FUN_indexes.clear();
3987 N_SO_index = UINT32_MAX;
3988 } else {
3989 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003990 // lieu of using nlist_idx in case we ever start trimming entries
3991 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992 const bool N_SO_has_full_path = symbol_name[0] == '/';
3993 if (N_SO_has_full_path) {
3994 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3995 // We have two consecutive N_SO entries where the first
Adrian Prantl05097242018-04-30 16:49:04 +00003996 // contains a directory and the second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003997 sym[sym_idx - 1].GetMangled().SetValue(
3998 ConstString(symbol_name), false);
3999 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4000 add_nlist = false;
4001 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004002 // This is the first entry in a N_SO that contains a
4003 // directory or a full path to the source file
Kate Stoneb9c1b512016-09-06 20:57:50 +00004004 N_SO_index = sym_idx;
4005 }
4006 } else if ((N_SO_index == sym_idx - 1) &&
4007 ((sym_idx - 1) < num_syms)) {
4008 // This is usually the second N_SO entry that contains just the
Adrian Prantl05097242018-04-30 16:49:04 +00004009 // filename, so here we combine it with the first one if we are
4010 // minimizing the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004011 const char *so_path =
4012 sym[sym_idx - 1]
4013 .GetMangled()
4014 .GetDemangledName(lldb::eLanguageTypeUnknown)
4015 .AsCString();
4016 if (so_path && so_path[0]) {
4017 std::string full_so_path(so_path);
4018 const size_t double_slash_pos = full_so_path.find("//");
4019 if (double_slash_pos != std::string::npos) {
4020 // The linker has been generating bad N_SO entries with
Adrian Prantl05097242018-04-30 16:49:04 +00004021 // doubled up paths in the format "%s%s" where the first
4022 // string in the DW_AT_comp_dir, and the second is the
4023 // directory for the source file so you end up with a path
4024 // that looks like "/tmp/src//tmp/src/"
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004025 FileSpec so_dir(so_path);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00004026 if (!FileSystem::Instance().Exists(so_dir)) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004027 so_dir.SetFile(&full_so_path[double_slash_pos + 1],
Jonas Devlieghere937348c2018-06-13 22:08:14 +00004028 FileSpec::Style::native);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00004029 if (FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004030 // Trim off the incorrect path
4031 full_so_path.erase(0, double_slash_pos + 1);
4032 }
4033 }
4034 }
4035 if (*full_so_path.rbegin() != '/')
4036 full_so_path += '/';
4037 full_so_path += symbol_name;
4038 sym[sym_idx - 1].GetMangled().SetValue(
4039 ConstString(full_so_path.c_str()), false);
4040 add_nlist = false;
4041 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4042 }
4043 } else {
4044 // This could be a relative path to a N_SO
4045 N_SO_index = sym_idx;
4046 }
4047 }
4048 break;
4049
4050 case N_OSO:
4051 // object file name: name,,0,0,st_mtime
4052 type = eSymbolTypeObjectFile;
4053 break;
4054
4055 case N_LSYM:
4056 // local sym: name,,NO_SECT,type,offset
4057 type = eSymbolTypeLocal;
4058 break;
4059
4060 //----------------------------------------------------------------------
4061 // INCL scopes
4062 //----------------------------------------------------------------------
4063 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00004064 // include file beginning: name,,NO_SECT,0,sum We use the current
4065 // number of symbols in the symbol table in lieu of using nlist_idx
4066 // in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004067 N_INCL_indexes.push_back(sym_idx);
4068 type = eSymbolTypeScopeBegin;
4069 break;
4070
4071 case N_EINCL:
4072 // include file end: name,,NO_SECT,0,0
4073 // Set the size of the N_BINCL to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004074 // N_EINCL so that we can always skip the entire symbol if we need
4075 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004076 if (!N_INCL_indexes.empty()) {
4077 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
4078 symbol_ptr->SetByteSize(sym_idx + 1);
4079 symbol_ptr->SetSizeIsSibling(true);
4080 N_INCL_indexes.pop_back();
4081 }
4082 type = eSymbolTypeScopeEnd;
4083 break;
4084
4085 case N_SOL:
4086 // #included file name: name,,n_sect,0,address
4087 type = eSymbolTypeHeaderFile;
4088
4089 // We currently don't use the header files on darwin
4090 add_nlist = false;
4091 break;
4092
4093 case N_PARAMS:
4094 // compiler parameters: name,,NO_SECT,0,0
4095 type = eSymbolTypeCompiler;
4096 break;
4097
4098 case N_VERSION:
4099 // compiler version: name,,NO_SECT,0,0
4100 type = eSymbolTypeCompiler;
4101 break;
4102
4103 case N_OLEVEL:
4104 // compiler -O level: name,,NO_SECT,0,0
4105 type = eSymbolTypeCompiler;
4106 break;
4107
4108 case N_PSYM:
4109 // parameter: name,,NO_SECT,type,offset
4110 type = eSymbolTypeVariable;
4111 break;
4112
4113 case N_ENTRY:
4114 // alternate entry: name,,n_sect,linenumber,address
4115 symbol_section =
4116 section_info.GetSection(nlist.n_sect, nlist.n_value);
4117 type = eSymbolTypeLineEntry;
4118 break;
4119
4120 //----------------------------------------------------------------------
4121 // Left and Right Braces
4122 //----------------------------------------------------------------------
4123 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004124 // left bracket: 0,,NO_SECT,nesting level,address We use the
4125 // current number of symbols in the symbol table in lieu of using
4126 // nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004127 symbol_section =
4128 section_info.GetSection(nlist.n_sect, nlist.n_value);
4129 N_BRAC_indexes.push_back(sym_idx);
4130 type = eSymbolTypeScopeBegin;
4131 break;
4132
4133 case N_RBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004134 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4135 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4136 // can always skip the entire symbol if we need to navigate more
4137 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004138 symbol_section =
4139 section_info.GetSection(nlist.n_sect, nlist.n_value);
4140 if (!N_BRAC_indexes.empty()) {
4141 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4142 symbol_ptr->SetByteSize(sym_idx + 1);
4143 symbol_ptr->SetSizeIsSibling(true);
4144 N_BRAC_indexes.pop_back();
4145 }
4146 type = eSymbolTypeScopeEnd;
4147 break;
4148
4149 case N_EXCL:
4150 // deleted include file: name,,NO_SECT,0,sum
4151 type = eSymbolTypeHeaderFile;
4152 break;
4153
4154 //----------------------------------------------------------------------
4155 // COMM scopes
4156 //----------------------------------------------------------------------
4157 case N_BCOMM:
4158 // begin common: name,,NO_SECT,0,0
4159 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00004160 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004161 type = eSymbolTypeScopeBegin;
4162 N_COMM_indexes.push_back(sym_idx);
4163 break;
4164
4165 case N_ECOML:
4166 // end common (local name): 0,,n_sect,0,address
4167 symbol_section =
4168 section_info.GetSection(nlist.n_sect, nlist.n_value);
4169 LLVM_FALLTHROUGH;
4170
4171 case N_ECOMM:
4172 // end common: name,,n_sect,0,0
4173 // Set the size of the N_BCOMM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004174 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4175 // we need to navigate more quickly at the source level when
4176 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004177 if (!N_COMM_indexes.empty()) {
4178 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4179 symbol_ptr->SetByteSize(sym_idx + 1);
4180 symbol_ptr->SetSizeIsSibling(true);
4181 N_COMM_indexes.pop_back();
4182 }
4183 type = eSymbolTypeScopeEnd;
4184 break;
4185
4186 case N_LENG:
4187 // second stab entry with length information
4188 type = eSymbolTypeAdditional;
4189 break;
4190
4191 default:
4192 break;
4193 }
4194 } else {
4195 // uint8_t n_pext = N_PEXT & nlist.n_type;
4196 uint8_t n_type = N_TYPE & nlist.n_type;
4197 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4198
4199 switch (n_type) {
4200 case N_INDR: {
4201 const char *reexport_name_cstr =
4202 strtab_data.PeekCStr(nlist.n_value);
4203 if (reexport_name_cstr && reexport_name_cstr[0]) {
4204 type = eSymbolTypeReExported;
4205 ConstString reexport_name(
4206 reexport_name_cstr +
4207 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4208 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4209 set_value = false;
4210 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4211 indirect_symbol_names.insert(
4212 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4213 } else
4214 type = eSymbolTypeUndefined;
4215 } break;
4216
4217 case N_UNDF:
4218 if (symbol_name && symbol_name[0]) {
4219 ConstString undefined_name(symbol_name +
4220 ((symbol_name[0] == '_') ? 1 : 0));
4221 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4222 }
4223 LLVM_FALLTHROUGH;
4224
4225 case N_PBUD:
4226 type = eSymbolTypeUndefined;
4227 break;
4228
4229 case N_ABS:
4230 type = eSymbolTypeAbsolute;
4231 break;
4232
4233 case N_SECT: {
4234 symbol_section =
4235 section_info.GetSection(nlist.n_sect, nlist.n_value);
4236
4237 if (!symbol_section) {
4238 // TODO: warn about this?
4239 add_nlist = false;
4240 break;
4241 }
4242
4243 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4244 type = eSymbolTypeException;
4245 } else {
4246 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4247
4248 switch (section_type) {
4249 case S_CSTRING_LITERALS:
4250 type = eSymbolTypeData;
4251 break; // section with only literal C strings
4252 case S_4BYTE_LITERALS:
4253 type = eSymbolTypeData;
4254 break; // section with only 4 byte literals
4255 case S_8BYTE_LITERALS:
4256 type = eSymbolTypeData;
4257 break; // section with only 8 byte literals
4258 case S_LITERAL_POINTERS:
4259 type = eSymbolTypeTrampoline;
4260 break; // section with only pointers to literals
4261 case S_NON_LAZY_SYMBOL_POINTERS:
4262 type = eSymbolTypeTrampoline;
4263 break; // section with only non-lazy symbol pointers
4264 case S_LAZY_SYMBOL_POINTERS:
4265 type = eSymbolTypeTrampoline;
4266 break; // section with only lazy symbol pointers
4267 case S_SYMBOL_STUBS:
4268 type = eSymbolTypeTrampoline;
4269 break; // section with only symbol stubs, byte size of stub in
4270 // the reserved2 field
4271 case S_MOD_INIT_FUNC_POINTERS:
4272 type = eSymbolTypeCode;
4273 break; // section with only function pointers for initialization
4274 case S_MOD_TERM_FUNC_POINTERS:
4275 type = eSymbolTypeCode;
4276 break; // section with only function pointers for termination
4277 case S_INTERPOSING:
4278 type = eSymbolTypeTrampoline;
4279 break; // section with only pairs of function pointers for
4280 // interposing
4281 case S_16BYTE_LITERALS:
4282 type = eSymbolTypeData;
4283 break; // section with only 16 byte literals
4284 case S_DTRACE_DOF:
4285 type = eSymbolTypeInstrumentation;
4286 break;
4287 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4288 type = eSymbolTypeTrampoline;
4289 break;
4290 default:
4291 switch (symbol_section->GetType()) {
4292 case lldb::eSectionTypeCode:
4293 type = eSymbolTypeCode;
4294 break;
4295 case eSectionTypeData:
4296 case eSectionTypeDataCString: // Inlined C string data
4297 case eSectionTypeDataCStringPointers: // Pointers to C string
4298 // data
4299 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4300 // the symbol table
4301 case eSectionTypeData4:
4302 case eSectionTypeData8:
4303 case eSectionTypeData16:
4304 type = eSymbolTypeData;
4305 break;
4306 default:
4307 break;
4308 }
4309 break;
4310 }
4311
4312 if (type == eSymbolTypeInvalid) {
4313 const char *symbol_sect_name =
4314 symbol_section->GetName().AsCString();
4315 if (symbol_section->IsDescendant(text_section_sp.get())) {
4316 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4317 S_ATTR_SELF_MODIFYING_CODE |
4318 S_ATTR_SOME_INSTRUCTIONS))
4319 type = eSymbolTypeData;
4320 else
4321 type = eSymbolTypeCode;
4322 } else if (symbol_section->IsDescendant(
4323 data_section_sp.get()) ||
4324 symbol_section->IsDescendant(
4325 data_dirty_section_sp.get()) ||
4326 symbol_section->IsDescendant(
4327 data_const_section_sp.get())) {
4328 if (symbol_sect_name &&
4329 ::strstr(symbol_sect_name, "__objc") ==
4330 symbol_sect_name) {
4331 type = eSymbolTypeRuntime;
4332
4333 if (symbol_name) {
4334 llvm::StringRef symbol_name_ref(symbol_name);
4335 if (symbol_name_ref.startswith("_OBJC_")) {
4336 static const llvm::StringRef g_objc_v2_prefix_class(
4337 "_OBJC_CLASS_$_");
4338 static const llvm::StringRef g_objc_v2_prefix_metaclass(
4339 "_OBJC_METACLASS_$_");
4340 static const llvm::StringRef g_objc_v2_prefix_ivar(
4341 "_OBJC_IVAR_$_");
4342 if (symbol_name_ref.startswith(
4343 g_objc_v2_prefix_class)) {
4344 symbol_name_non_abi_mangled = symbol_name + 1;
4345 symbol_name =
4346 symbol_name + g_objc_v2_prefix_class.size();
4347 type = eSymbolTypeObjCClass;
4348 demangled_is_synthesized = true;
4349 } else if (symbol_name_ref.startswith(
4350 g_objc_v2_prefix_metaclass)) {
4351 symbol_name_non_abi_mangled = symbol_name + 1;
4352 symbol_name =
4353 symbol_name + g_objc_v2_prefix_metaclass.size();
4354 type = eSymbolTypeObjCMetaClass;
4355 demangled_is_synthesized = true;
4356 } else if (symbol_name_ref.startswith(
4357 g_objc_v2_prefix_ivar)) {
4358 symbol_name_non_abi_mangled = symbol_name + 1;
4359 symbol_name =
4360 symbol_name + g_objc_v2_prefix_ivar.size();
4361 type = eSymbolTypeObjCIVar;
4362 demangled_is_synthesized = true;
4363 }
4364 }
4365 }
4366 } else if (symbol_sect_name &&
4367 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4368 symbol_sect_name) {
4369 type = eSymbolTypeException;
4370 } else {
4371 type = eSymbolTypeData;
4372 }
4373 } else if (symbol_sect_name &&
4374 ::strstr(symbol_sect_name, "__IMPORT") ==
4375 symbol_sect_name) {
4376 type = eSymbolTypeTrampoline;
4377 } else if (symbol_section->IsDescendant(
4378 objc_section_sp.get())) {
4379 type = eSymbolTypeRuntime;
4380 if (symbol_name && symbol_name[0] == '.') {
4381 llvm::StringRef symbol_name_ref(symbol_name);
4382 static const llvm::StringRef g_objc_v1_prefix_class(
4383 ".objc_class_name_");
4384 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4385 symbol_name_non_abi_mangled = symbol_name;
4386 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4387 type = eSymbolTypeObjCClass;
4388 demangled_is_synthesized = true;
4389 }
4390 }
4391 }
4392 }
4393 }
4394 } break;
4395 }
4396 }
4397
4398 if (add_nlist) {
4399 uint64_t symbol_value = nlist.n_value;
4400
4401 if (symbol_name_non_abi_mangled) {
4402 sym[sym_idx].GetMangled().SetMangledName(
4403 ConstString(symbol_name_non_abi_mangled));
4404 sym[sym_idx].GetMangled().SetDemangledName(
4405 ConstString(symbol_name));
4406 } else {
4407 bool symbol_name_is_mangled = false;
4408
4409 if (symbol_name && symbol_name[0] == '_') {
4410 symbol_name_is_mangled = symbol_name[1] == '_';
4411 symbol_name++; // Skip the leading underscore
4412 }
4413
4414 if (symbol_name) {
4415 ConstString const_symbol_name(symbol_name);
4416 sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4417 symbol_name_is_mangled);
4418 }
4419 }
4420
4421 if (is_gsym) {
4422 const char *gsym_name = sym[sym_idx]
4423 .GetMangled()
4424 .GetName(lldb::eLanguageTypeUnknown,
4425 Mangled::ePreferMangled)
4426 .GetCString();
4427 if (gsym_name)
4428 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4429 }
4430
4431 if (symbol_section) {
4432 const addr_t section_file_addr = symbol_section->GetFileAddress();
4433 if (symbol_byte_size == 0 && function_starts_count > 0) {
4434 addr_t symbol_lookup_file_addr = nlist.n_value;
4435 // Do an exact address match for non-ARM addresses, else get the
Adrian Prantl05097242018-04-30 16:49:04 +00004436 // closest since the symbol might be a thumb symbol which has an
4437 // address with bit zero set
Kate Stoneb9c1b512016-09-06 20:57:50 +00004438 FunctionStarts::Entry *func_start_entry =
4439 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4440 if (is_arm && func_start_entry) {
4441 // Verify that the function start address is the symbol address
Adrian Prantl05097242018-04-30 16:49:04 +00004442 // (ARM) or the symbol address + 1 (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004443 if (func_start_entry->addr != symbol_lookup_file_addr &&
4444 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4445 // Not the right entry, NULL it out...
4446 func_start_entry = NULL;
4447 }
4448 }
4449 if (func_start_entry) {
4450 func_start_entry->data = true;
4451
4452 addr_t symbol_file_addr = func_start_entry->addr;
4453 if (is_arm)
4454 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4455
4456 const FunctionStarts::Entry *next_func_start_entry =
4457 function_starts.FindNextEntry(func_start_entry);
4458 const addr_t section_end_file_addr =
4459 section_file_addr + symbol_section->GetByteSize();
4460 if (next_func_start_entry) {
4461 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4462 // Be sure the clear the Thumb address bit when we calculate
Adrian Prantl05097242018-04-30 16:49:04 +00004463 // the size from the current and next address
Kate Stoneb9c1b512016-09-06 20:57:50 +00004464 if (is_arm)
4465 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4466 symbol_byte_size = std::min<lldb::addr_t>(
4467 next_symbol_file_addr - symbol_file_addr,
4468 section_end_file_addr - symbol_file_addr);
4469 } else {
4470 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4471 }
4472 }
4473 }
4474 symbol_value -= section_file_addr;
4475 }
4476
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004477 if (!is_debug) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004478 if (type == eSymbolTypeCode) {
Adrian Prantl05097242018-04-30 16:49:04 +00004479 // See if we can find a N_FUN entry for any code symbols. If we
4480 // do find a match, and the name matches, then we can merge the
4481 // two into just the function symbol to avoid duplicate entries
4482 // in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004483 std::pair<ValueToSymbolIndexMap::const_iterator,
4484 ValueToSymbolIndexMap::const_iterator>
4485 range;
4486 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4487 if (range.first != range.second) {
4488 bool found_it = false;
4489 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4490 pos != range.second; ++pos) {
4491 if (sym[sym_idx].GetMangled().GetName(
4492 lldb::eLanguageTypeUnknown,
4493 Mangled::ePreferMangled) ==
4494 sym[pos->second].GetMangled().GetName(
4495 lldb::eLanguageTypeUnknown,
4496 Mangled::ePreferMangled)) {
4497 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4498 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004499 // these flags into the N_FUN flags to avoid duplicate
4500 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004501 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4502 sym[pos->second].SetFlags(nlist.n_type << 16 |
4503 nlist.n_desc);
4504 if (resolver_addresses.find(nlist.n_value) !=
4505 resolver_addresses.end())
4506 sym[pos->second].SetType(eSymbolTypeResolver);
4507 sym[sym_idx].Clear();
4508 found_it = true;
4509 break;
4510 }
4511 }
4512 if (found_it)
4513 continue;
4514 } else {
4515 if (resolver_addresses.find(nlist.n_value) !=
4516 resolver_addresses.end())
4517 type = eSymbolTypeResolver;
4518 }
4519 } else if (type == eSymbolTypeData ||
4520 type == eSymbolTypeObjCClass ||
4521 type == eSymbolTypeObjCMetaClass ||
4522 type == eSymbolTypeObjCIVar) {
Adrian Prantl05097242018-04-30 16:49:04 +00004523 // See if we can find a N_STSYM entry for any data symbols. If we
4524 // do find a match, and the name matches, then we can merge the
4525 // two into just the Static symbol to avoid duplicate entries in
4526 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004527 std::pair<ValueToSymbolIndexMap::const_iterator,
4528 ValueToSymbolIndexMap::const_iterator>
4529 range;
4530 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4531 if (range.first != range.second) {
4532 bool found_it = false;
4533 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4534 pos != range.second; ++pos) {
4535 if (sym[sym_idx].GetMangled().GetName(
4536 lldb::eLanguageTypeUnknown,
4537 Mangled::ePreferMangled) ==
4538 sym[pos->second].GetMangled().GetName(
4539 lldb::eLanguageTypeUnknown,
4540 Mangled::ePreferMangled)) {
4541 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4542 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004543 // these flags into the N_STSYM flags to avoid duplicate
4544 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004545 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4546 sym[pos->second].SetFlags(nlist.n_type << 16 |
4547 nlist.n_desc);
4548 sym[sym_idx].Clear();
4549 found_it = true;
4550 break;
4551 }
4552 }
4553 if (found_it)
4554 continue;
4555 } else {
4556 // Combine N_GSYM stab entries with the non stab symbol
4557 const char *gsym_name = sym[sym_idx]
4558 .GetMangled()
4559 .GetName(lldb::eLanguageTypeUnknown,
4560 Mangled::ePreferMangled)
4561 .GetCString();
4562 if (gsym_name) {
4563 ConstNameToSymbolIndexMap::const_iterator pos =
4564 N_GSYM_name_to_sym_idx.find(gsym_name);
4565 if (pos != N_GSYM_name_to_sym_idx.end()) {
4566 const uint32_t GSYM_sym_idx = pos->second;
4567 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00004568 // Copy the address, because often the N_GSYM address has
4569 // an invalid address of zero when the global is a common
4570 // symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00004571 sym[GSYM_sym_idx].GetAddressRef().SetSection(
4572 symbol_section);
4573 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4574 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004575 // these flags into the N_GSYM flags to avoid duplicate
4576 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004577 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
4578 nlist.n_desc);
4579 sym[sym_idx].Clear();
4580 continue;
4581 }
4582 }
4583 }
4584 }
4585 }
4586
4587 sym[sym_idx].SetID(nlist_idx);
4588 sym[sym_idx].SetType(type);
4589 if (set_value) {
4590 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4591 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4592 }
4593 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4594
4595 if (symbol_byte_size > 0)
4596 sym[sym_idx].SetByteSize(symbol_byte_size);
4597
4598 if (demangled_is_synthesized)
4599 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4600
4601 ++sym_idx;
4602 } else {
4603 sym[sym_idx].Clear();
4604 }
4605 }
4606
4607 for (const auto &pos : reexport_shlib_needs_fixup) {
4608 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4609 if (undef_pos != undefined_name_to_desc.end()) {
4610 const uint8_t dylib_ordinal =
4611 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4612 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4613 sym[pos.first].SetReExportedSymbolSharedLibrary(
4614 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4615 }
4616 }
4617 }
4618
4619 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4620
4621 if (function_starts_count > 0) {
4622 uint32_t num_synthetic_function_symbols = 0;
4623 for (i = 0; i < function_starts_count; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004624 if (!function_starts.GetEntryRef(i).data)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004625 ++num_synthetic_function_symbols;
4626 }
4627
4628 if (num_synthetic_function_symbols > 0) {
4629 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4630 num_syms = sym_idx + num_synthetic_function_symbols;
4631 sym = symtab->Resize(num_syms);
4632 }
4633 for (i = 0; i < function_starts_count; ++i) {
4634 const FunctionStarts::Entry *func_start_entry =
4635 function_starts.GetEntryAtIndex(i);
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004636 if (!func_start_entry->data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004637 addr_t symbol_file_addr = func_start_entry->addr;
4638 uint32_t symbol_flags = 0;
4639 if (is_arm) {
4640 if (symbol_file_addr & 1)
4641 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4642 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4643 }
4644 Address symbol_addr;
4645 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4646 SectionSP symbol_section(symbol_addr.GetSection());
4647 uint32_t symbol_byte_size = 0;
4648 if (symbol_section) {
4649 const addr_t section_file_addr =
4650 symbol_section->GetFileAddress();
4651 const FunctionStarts::Entry *next_func_start_entry =
4652 function_starts.FindNextEntry(func_start_entry);
4653 const addr_t section_end_file_addr =
4654 section_file_addr + symbol_section->GetByteSize();
4655 if (next_func_start_entry) {
4656 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4657 if (is_arm)
4658 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4659 symbol_byte_size = std::min<lldb::addr_t>(
4660 next_symbol_file_addr - symbol_file_addr,
4661 section_end_file_addr - symbol_file_addr);
4662 } else {
4663 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4664 }
4665 sym[sym_idx].SetID(synthetic_sym_id++);
4666 sym[sym_idx].GetMangled().SetDemangledName(
4667 GetNextSyntheticSymbolName());
4668 sym[sym_idx].SetType(eSymbolTypeCode);
4669 sym[sym_idx].SetIsSynthetic(true);
4670 sym[sym_idx].GetAddressRef() = symbol_addr;
4671 if (symbol_flags)
4672 sym[sym_idx].SetFlags(symbol_flags);
4673 if (symbol_byte_size)
4674 sym[sym_idx].SetByteSize(symbol_byte_size);
4675 ++sym_idx;
4676 }
4677 }
4678 }
4679 }
4680 }
4681 }
4682
Adrian Prantl05097242018-04-30 16:49:04 +00004683 // Trim our symbols down to just what we ended up with after removing any
4684 // symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004685 if (sym_idx < num_syms) {
4686 num_syms = sym_idx;
4687 sym = symtab->Resize(num_syms);
4688 }
4689
4690 // Now synthesize indirect symbols
4691 if (m_dysymtab.nindirectsyms != 0) {
4692 if (indirect_symbol_index_data.GetByteSize()) {
4693 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4694 m_nlist_idx_to_sym_idx.end();
4695
4696 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4697 ++sect_idx) {
4698 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4699 S_SYMBOL_STUBS) {
4700 uint32_t symbol_stub_byte_size =
4701 m_mach_sections[sect_idx].reserved2;
4702 if (symbol_stub_byte_size == 0)
4703 continue;
4704
4705 const uint32_t num_symbol_stubs =
4706 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4707
4708 if (num_symbol_stubs == 0)
4709 continue;
4710
4711 const uint32_t symbol_stub_index_offset =
4712 m_mach_sections[sect_idx].reserved1;
4713 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs;
4714 ++stub_idx) {
4715 const uint32_t symbol_stub_index =
4716 symbol_stub_index_offset + stub_idx;
4717 const lldb::addr_t symbol_stub_addr =
4718 m_mach_sections[sect_idx].addr +
4719 (stub_idx * symbol_stub_byte_size);
4720 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4721 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4722 symbol_stub_offset, 4)) {
4723 const uint32_t stub_sym_id =
4724 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4725 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4726 continue;
4727
4728 NListIndexToSymbolIndexMap::const_iterator index_pos =
4729 m_nlist_idx_to_sym_idx.find(stub_sym_id);
4730 Symbol *stub_symbol = NULL;
4731 if (index_pos != end_index_pos) {
Adrian Prantl05097242018-04-30 16:49:04 +00004732 // We have a remapping from the original nlist index to a
4733 // current symbol index, so just look this up by index
Kate Stoneb9c1b512016-09-06 20:57:50 +00004734 stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4735 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004736 // We need to lookup a symbol using the original nlist symbol
4737 // index since this index is coming from the S_SYMBOL_STUBS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004738 stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4739 }
4740
4741 if (stub_symbol) {
4742 Address so_addr(symbol_stub_addr, section_list);
4743
4744 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4745 // Change the external symbol into a trampoline that makes
Adrian Prantl05097242018-04-30 16:49:04 +00004746 // sense These symbols were N_UNDF N_EXT, and are useless
4747 // to us, so we can re-use them so we don't have to make up
4748 // a synthetic symbol for no good reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004749 if (resolver_addresses.find(symbol_stub_addr) ==
4750 resolver_addresses.end())
4751 stub_symbol->SetType(eSymbolTypeTrampoline);
4752 else
4753 stub_symbol->SetType(eSymbolTypeResolver);
4754 stub_symbol->SetExternal(false);
4755 stub_symbol->GetAddressRef() = so_addr;
4756 stub_symbol->SetByteSize(symbol_stub_byte_size);
4757 } else {
4758 // Make a synthetic symbol to describe the trampoline stub
4759 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4760 if (sym_idx >= num_syms) {
4761 sym = symtab->Resize(++num_syms);
4762 stub_symbol = NULL; // this pointer no longer valid
4763 }
4764 sym[sym_idx].SetID(synthetic_sym_id++);
4765 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4766 if (resolver_addresses.find(symbol_stub_addr) ==
4767 resolver_addresses.end())
4768 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4769 else
4770 sym[sym_idx].SetType(eSymbolTypeResolver);
4771 sym[sym_idx].SetIsSynthetic(true);
4772 sym[sym_idx].GetAddressRef() = so_addr;
4773 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4774 ++sym_idx;
4775 }
4776 } else {
4777 if (log)
4778 log->Warning("symbol stub referencing symbol table symbol "
4779 "%u that isn't in our minimal symbol table, "
4780 "fix this!!!",
4781 stub_sym_id);
4782 }
4783 }
4784 }
4785 }
4786 }
4787 }
4788 }
4789
4790 if (!trie_entries.empty()) {
4791 for (const auto &e : trie_entries) {
4792 if (e.entry.import_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00004793 // Only add indirect symbols from the Trie entries if we didn't have
4794 // a N_INDR nlist entry for this already
Kate Stoneb9c1b512016-09-06 20:57:50 +00004795 if (indirect_symbol_names.find(e.entry.name) ==
4796 indirect_symbol_names.end()) {
4797 // Make a synthetic symbol to describe re-exported symbol.
4798 if (sym_idx >= num_syms)
4799 sym = symtab->Resize(++num_syms);
4800 sym[sym_idx].SetID(synthetic_sym_id++);
4801 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4802 sym[sym_idx].SetType(eSymbolTypeReExported);
4803 sym[sym_idx].SetIsSynthetic(true);
4804 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4805 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4806 sym[sym_idx].SetReExportedSymbolSharedLibrary(
4807 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4808 }
4809 ++sym_idx;
4810 }
4811 }
4812 }
4813 }
4814
Davide Italiano407c6912018-11-02 21:59:14 +00004815 // StreamFile s(stdout, false);
4816 // s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4817 // symtab->Dump(&s, NULL, eSortOrderNone);
4818 // Set symbol byte sizes correctly since mach-o nlist entries don't have
4819 // sizes
4820 symtab->CalculateSymbolSizes();
4821
4822 // s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4823 // symtab->Dump(&s, NULL, eSortOrderNone);
4824
Kate Stoneb9c1b512016-09-06 20:57:50 +00004825 return symtab->GetNumSymbols();
4826 }
4827 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004828}
4829
Kate Stoneb9c1b512016-09-06 20:57:50 +00004830void ObjectFileMachO::Dump(Stream *s) {
4831 ModuleSP module_sp(GetModule());
4832 if (module_sp) {
4833 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4834 s->Printf("%p: ", static_cast<void *>(this));
4835 s->Indent();
4836 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4837 s->PutCString("ObjectFileMachO64");
4838 else
4839 s->PutCString("ObjectFileMachO32");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004840
Kate Stoneb9c1b512016-09-06 20:57:50 +00004841 ArchSpec header_arch;
4842 GetArchitecture(header_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004843
Kate Stoneb9c1b512016-09-06 20:57:50 +00004844 *s << ", file = '" << m_file
Adrian Prantl9702c962018-05-11 00:41:20 +00004845 << "', triple = " << header_arch.GetTriple().getTriple() << "\n";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004846
Kate Stoneb9c1b512016-09-06 20:57:50 +00004847 SectionList *sections = GetSectionList();
4848 if (sections)
4849 sections->Dump(s, NULL, true, UINT32_MAX);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004850
Kate Stoneb9c1b512016-09-06 20:57:50 +00004851 if (m_symtab_ap.get())
4852 m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4853 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004854}
4855
Kate Stoneb9c1b512016-09-06 20:57:50 +00004856bool ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4857 const lldb_private::DataExtractor &data,
4858 lldb::offset_t lc_offset,
4859 lldb_private::UUID &uuid) {
4860 uint32_t i;
4861 struct uuid_command load_cmd;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004862
Kate Stoneb9c1b512016-09-06 20:57:50 +00004863 lldb::offset_t offset = lc_offset;
4864 for (i = 0; i < header.ncmds; ++i) {
4865 const lldb::offset_t cmd_offset = offset;
4866 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4867 break;
4868
4869 if (load_cmd.cmd == LC_UUID) {
4870 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4871
4872 if (uuid_bytes) {
4873 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4874 // We pretend these object files have no UUID to prevent crashing.
4875
4876 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4877 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4878 0xbb, 0x14, 0xf0, 0x0d};
4879
4880 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4881 return false;
4882
Pavel Labath2f93fd12018-06-26 15:12:20 +00004883 uuid = UUID::fromOptionalData(uuid_bytes, 16);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004884 return true;
4885 }
4886 return false;
4887 }
4888 offset = cmd_offset + load_cmd.cmdsize;
4889 }
4890 return false;
4891}
4892
Jason Molenda32762fd2018-10-11 00:28:35 +00004893static llvm::StringRef GetOSName(uint32_t cmd) {
Adrian Prantl9702c962018-05-11 00:41:20 +00004894 switch (cmd) {
4895 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004896 return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004897 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Jason Molenda32762fd2018-10-11 00:28:35 +00004898 return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
Adrian Prantl9702c962018-05-11 00:41:20 +00004899 case llvm::MachO::LC_VERSION_MIN_TVOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004900 return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004901 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004902 return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004903 default:
4904 llvm_unreachable("unexpected LC_VERSION load command");
4905 }
4906}
4907
Jason Molenda32762fd2018-10-11 00:28:35 +00004908namespace {
4909 struct OSEnv {
4910 llvm::StringRef os_type;
4911 llvm::StringRef environment;
4912 OSEnv(uint32_t cmd) {
4913 switch (cmd) {
4914 case PLATFORM_MACOS:
4915 os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4916 return;
4917 case PLATFORM_IOS:
4918 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4919 return;
4920 case PLATFORM_TVOS:
4921 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4922 return;
4923 case PLATFORM_WATCHOS:
4924 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4925 return;
4926// NEED_BRIDGEOS_TRIPLE case PLATFORM_BRIDGEOS:
4927// NEED_BRIDGEOS_TRIPLE os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4928// NEED_BRIDGEOS_TRIPLE return;
4929#if defined (PLATFORM_IOSSIMULATOR) && defined (PLATFORM_TVOSSIMULATOR) && defined (PLATFORM_WATCHOSSIMULATOR)
4930 case PLATFORM_IOSSIMULATOR:
4931 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4932 environment =
4933 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4934 return;
4935 case PLATFORM_TVOSSIMULATOR:
4936 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4937 environment =
4938 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4939 return;
4940 case PLATFORM_WATCHOSSIMULATOR:
4941 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4942 environment =
4943 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4944 return;
4945#endif
4946 default: {
4947 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
4948 LIBLLDB_LOG_PROCESS));
4949 if (log)
4950 log->Printf("unsupported platform in LC_BUILD_VERSION");
4951 }
4952 }
4953 }
4954 };
4955
4956 struct MinOS {
Eric Liu7d2f7832018-10-11 14:44:12 +00004957 uint32_t major_version, minor_version, patch_version;
Jason Molenda32762fd2018-10-11 00:28:35 +00004958 MinOS(uint32_t version)
Eric Liu7d2f7832018-10-11 14:44:12 +00004959 : major_version(version >> 16),
4960 minor_version((version >> 8) & 0xffu),
4961 patch_version(version & 0xffu) {}
Jason Molenda32762fd2018-10-11 00:28:35 +00004962 };
4963} // namespace
4964
Kate Stoneb9c1b512016-09-06 20:57:50 +00004965bool ObjectFileMachO::GetArchitecture(const llvm::MachO::mach_header &header,
4966 const lldb_private::DataExtractor &data,
4967 lldb::offset_t lc_offset,
4968 ArchSpec &arch) {
4969 arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4970
4971 if (arch.IsValid()) {
4972 llvm::Triple &triple = arch.GetTriple();
4973
4974 // Set OS to an unspecified unknown or a "*" so it can match any OS
4975 triple.setOS(llvm::Triple::UnknownOS);
4976 triple.setOSName(llvm::StringRef());
4977
4978 if (header.filetype == MH_PRELOAD) {
4979 if (header.cputype == CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00004980 // If this is a 32-bit arm binary, and it's a standalone binary, force
4981 // the Vendor to Apple so we don't accidentally pick up the generic
4982 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4983 // frame pointer register; most other armv7 ABIs use a combination of
4984 // r7 and r11.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004985 triple.setVendor(llvm::Triple::Apple);
4986 } else {
4987 // Set vendor to an unspecified unknown or a "*" so it can match any
Adrian Prantl05097242018-04-30 16:49:04 +00004988 // vendor This is required for correct behavior of EFI debugging on
4989 // x86_64
Kate Stoneb9c1b512016-09-06 20:57:50 +00004990 triple.setVendor(llvm::Triple::UnknownVendor);
4991 triple.setVendorName(llvm::StringRef());
4992 }
4993 return true;
4994 } else {
4995 struct load_command load_cmd;
Jason Molenda32762fd2018-10-11 00:28:35 +00004996 llvm::SmallString<16> os_name;
4997 llvm::raw_svector_ostream os(os_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004998
Jason Molenda32762fd2018-10-11 00:28:35 +00004999 // See if there is an LC_VERSION_MIN_* load command that can give
5000 // us the OS type.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005001 lldb::offset_t offset = lc_offset;
5002 for (uint32_t i = 0; i < header.ncmds; ++i) {
Greg Claytonf4d6de62013-04-24 22:29:28 +00005003 const lldb::offset_t cmd_offset = offset;
5004 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005005 break;
5006
Adrian Prantl9702c962018-05-11 00:41:20 +00005007 struct version_min_command version_min;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005008 switch (load_cmd.cmd) {
5009 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005010 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005011 case llvm::MachO::LC_VERSION_MIN_TVOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00005012 case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
Adrian Prantl9702c962018-05-11 00:41:20 +00005013 if (load_cmd.cmdsize != sizeof(version_min))
5014 break;
Jason Molenda32762fd2018-10-11 00:28:35 +00005015 if (data.ExtractBytes(cmd_offset, sizeof(version_min),
5016 data.GetByteOrder(), &version_min) == 0)
5017 break;
5018 MinOS min_os(version_min.version);
Eric Liu7d2f7832018-10-11 14:44:12 +00005019 os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
5020 << min_os.minor_version << '.' << min_os.patch_version;
Adrian Prantl9702c962018-05-11 00:41:20 +00005021 triple.setOSName(os.str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005022 return true;
Jason Molenda32762fd2018-10-11 00:28:35 +00005023 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005024 default:
5025 break;
Greg Claytonf4d6de62013-04-24 22:29:28 +00005026 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005027
Greg Claytonf4d6de62013-04-24 22:29:28 +00005028 offset = cmd_offset + load_cmd.cmdsize;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005029 }
5030
Jason Molenda32762fd2018-10-11 00:28:35 +00005031 // See if there is an LC_BUILD_VERSION load command that can give
5032 // us the OS type.
5033
5034 offset = lc_offset;
5035 for (uint32_t i = 0; i < header.ncmds; ++i) {
5036 const lldb::offset_t cmd_offset = offset;
5037 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
5038 break;
Adrian Prantl874e32d2018-11-13 23:14:37 +00005039 do {
5040 if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
5041 struct build_version_command build_version;
5042 if (load_cmd.cmdsize < sizeof(build_version)) {
5043 // Malformed load command.
5044 break;
5045 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005046 if (data.ExtractBytes(cmd_offset, sizeof(build_version),
5047 data.GetByteOrder(), &build_version) == 0)
Adrian Prantl874e32d2018-11-13 23:14:37 +00005048 break;
5049 MinOS min_os(build_version.minos);
5050 OSEnv os_env(build_version.platform);
5051 if (os_env.os_type.empty())
5052 break;
5053 os << os_env.os_type << min_os.major_version << '.'
5054 << min_os.minor_version << '.' << min_os.patch_version;
5055 triple.setOSName(os.str());
5056 if (!os_env.environment.empty())
5057 triple.setEnvironmentName(os_env.environment);
5058 return true;
5059 }
5060 } while (0);
Jason Molenda32762fd2018-10-11 00:28:35 +00005061 offset = cmd_offset + load_cmd.cmdsize;
5062 }
5063
Kate Stoneb9c1b512016-09-06 20:57:50 +00005064 if (header.filetype != MH_KEXT_BUNDLE) {
5065 // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
5066 // so lets not say our Vendor is Apple, leave it as an unspecified
5067 // unknown
5068 triple.setVendor(llvm::Triple::UnknownVendor);
5069 triple.setVendorName(llvm::StringRef());
5070 }
Greg Claytonf4d6de62013-04-24 22:29:28 +00005071 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005072 }
5073 return arch.IsValid();
Greg Claytonf4d6de62013-04-24 22:29:28 +00005074}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005075
Kate Stoneb9c1b512016-09-06 20:57:50 +00005076bool ObjectFileMachO::GetUUID(lldb_private::UUID *uuid) {
5077 ModuleSP module_sp(GetModule());
5078 if (module_sp) {
5079 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5080 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5081 return GetUUID(m_header, m_data, offset, *uuid);
5082 }
5083 return false;
Greg Clayton7ab7f892014-05-29 21:33:45 +00005084}
5085
Kate Stoneb9c1b512016-09-06 20:57:50 +00005086uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
5087 uint32_t count = 0;
5088 ModuleSP module_sp(GetModule());
5089 if (module_sp) {
5090 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5091 struct load_command load_cmd;
5092 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5093 std::vector<std::string> rpath_paths;
5094 std::vector<std::string> rpath_relative_paths;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005095 std::vector<std::string> at_exec_relative_paths;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005096 uint32_t i;
5097 for (i = 0; i < m_header.ncmds; ++i) {
5098 const uint32_t cmd_offset = offset;
5099 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5100 break;
5101
5102 switch (load_cmd.cmd) {
5103 case LC_RPATH:
5104 case LC_LOAD_DYLIB:
5105 case LC_LOAD_WEAK_DYLIB:
5106 case LC_REEXPORT_DYLIB:
5107 case LC_LOAD_DYLINKER:
5108 case LC_LOADFVMLIB:
5109 case LC_LOAD_UPWARD_DYLIB: {
5110 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5111 const char *path = m_data.PeekCStr(name_offset);
5112 if (path) {
5113 if (load_cmd.cmd == LC_RPATH)
5114 rpath_paths.push_back(path);
5115 else {
5116 if (path[0] == '@') {
5117 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5118 rpath_relative_paths.push_back(path + strlen("@rpath"));
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005119 else if (strncmp(path, "@executable_path",
5120 strlen("@executable_path")) == 0)
5121 at_exec_relative_paths.push_back(path
5122 + strlen("@executable_path"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005123 } else {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005124 FileSpec file_spec(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005125 if (files.AppendIfUnique(file_spec))
5126 count++;
5127 }
5128 }
5129 }
5130 } break;
5131
5132 default:
5133 break;
5134 }
5135 offset = cmd_offset + load_cmd.cmdsize;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005136 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005137
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005138 FileSpec this_file_spec(m_file);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005139 FileSystem::Instance().Resolve(this_file_spec);
5140
Kate Stoneb9c1b512016-09-06 20:57:50 +00005141 if (!rpath_paths.empty()) {
5142 // Fixup all LC_RPATH values to be absolute paths
Kate Stoneb9c1b512016-09-06 20:57:50 +00005143 std::string loader_path("@loader_path");
5144 std::string executable_path("@executable_path");
5145 for (auto &rpath : rpath_paths) {
5146 if (rpath.find(loader_path) == 0) {
5147 rpath.erase(0, loader_path.size());
5148 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5149 } else if (rpath.find(executable_path) == 0) {
5150 rpath.erase(0, executable_path.size());
5151 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5152 }
5153 }
5154
5155 for (const auto &rpath_relative_path : rpath_relative_paths) {
5156 for (const auto &rpath : rpath_paths) {
5157 std::string path = rpath;
5158 path += rpath_relative_path;
Adrian Prantl05097242018-04-30 16:49:04 +00005159 // It is OK to resolve this path because we must find a file on disk
5160 // for us to accept it anyway if it is rpath relative.
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005161 FileSpec file_spec(path);
5162 FileSystem::Instance().Resolve(file_spec);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00005163 if (FileSystem::Instance().Exists(file_spec) &&
5164 files.AppendIfUnique(file_spec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005165 count++;
5166 break;
5167 }
5168 }
5169 }
5170 }
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005171
5172 // We may have @executable_paths but no RPATHS. Figure those out here.
5173 // Only do this if this object file is the executable. We have no way to
5174 // get back to the actual executable otherwise, so we won't get the right
5175 // path.
5176 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5177 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5178 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5179 FileSpec file_spec =
5180 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00005181 if (FileSystem::Instance().Exists(file_spec) &&
5182 files.AppendIfUnique(file_spec))
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005183 count++;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005184 }
5185 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005186 }
5187 return count;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005188}
5189
Kate Stoneb9c1b512016-09-06 20:57:50 +00005190lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5191 // If the object file is not an executable it can't hold the entry point.
Adrian Prantl05097242018-04-30 16:49:04 +00005192 // m_entry_point_address is initialized to an invalid address, so we can just
5193 // return that. If m_entry_point_address is valid it means we've found it
5194 // already, so return the cached value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005195
Kate Stoneb9c1b512016-09-06 20:57:50 +00005196 if (!IsExecutable() || m_entry_point_address.IsValid())
Jim Ingham672e6f52011-03-07 23:44:08 +00005197 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00005198
Kate Stoneb9c1b512016-09-06 20:57:50 +00005199 // Otherwise, look for the UnixThread or Thread command. The data for the
Adrian Prantl05097242018-04-30 16:49:04 +00005200 // Thread command is given in /usr/include/mach-o.h, but it is basically:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005201 //
5202 // uint32_t flavor - this is the flavor argument you would pass to
5203 // thread_get_state
5204 // uint32_t count - this is the count of longs in the thread state data
5205 // struct XXX_thread_state state - this is the structure from
5206 // <machine/thread_status.h> corresponding to the flavor.
5207 // <repeat this trio>
5208 //
5209 // So we just keep reading the various register flavors till we find the GPR
5210 // one, then read the PC out of there.
5211 // FIXME: We will need to have a "RegisterContext data provider" class at some
5212 // point that can get all the registers
5213 // out of data in this form & attach them to a given thread. That should
Adrian Prantl05097242018-04-30 16:49:04 +00005214 // underlie the MacOS X User process plugin, and we'll also need it for the
5215 // MacOS X Core File process plugin. When we have that we can also use it
5216 // here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005217 //
5218 // For now we hard-code the offsets and flavors we need:
5219 //
5220 //
Greg Claytonc9660542012-02-05 02:38:54 +00005221
Kate Stoneb9c1b512016-09-06 20:57:50 +00005222 ModuleSP module_sp(GetModule());
5223 if (module_sp) {
5224 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5225 struct load_command load_cmd;
5226 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5227 uint32_t i;
5228 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5229 bool done = false;
5230
5231 for (i = 0; i < m_header.ncmds; ++i) {
5232 const lldb::offset_t cmd_offset = offset;
5233 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5234 break;
5235
5236 switch (load_cmd.cmd) {
5237 case LC_UNIXTHREAD:
5238 case LC_THREAD: {
5239 while (offset < cmd_offset + load_cmd.cmdsize) {
5240 uint32_t flavor = m_data.GetU32(&offset);
5241 uint32_t count = m_data.GetU32(&offset);
5242 if (count == 0) {
5243 // We've gotten off somehow, log and exit;
5244 return m_entry_point_address;
5245 }
5246
5247 switch (m_header.cputype) {
5248 case llvm::MachO::CPU_TYPE_ARM:
5249 if (flavor == 1 ||
5250 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 from
5251 // mach/arm/thread_status.h
Greg Claytonc3776bf2012-02-09 06:16:32 +00005252 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005253 offset += 60; // This is the offset of pc in the GPR thread state
5254 // data structure.
5255 start_address = m_data.GetU32(&offset);
5256 done = true;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005257 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005258 break;
5259 case llvm::MachO::CPU_TYPE_ARM64:
5260 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5261 {
5262 offset += 256; // This is the offset of pc in the GPR thread state
5263 // data structure.
5264 start_address = m_data.GetU64(&offset);
5265 done = true;
5266 }
5267 break;
5268 case llvm::MachO::CPU_TYPE_I386:
5269 if (flavor ==
5270 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5271 {
5272 offset += 40; // This is the offset of eip in the GPR thread state
5273 // data structure.
5274 start_address = m_data.GetU32(&offset);
5275 done = true;
5276 }
5277 break;
5278 case llvm::MachO::CPU_TYPE_X86_64:
5279 if (flavor ==
5280 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5281 {
5282 offset += 16 * 8; // This is the offset of rip in the GPR thread
5283 // state data structure.
5284 start_address = m_data.GetU64(&offset);
5285 done = true;
5286 }
5287 break;
5288 default:
5289 return m_entry_point_address;
5290 }
5291 // Haven't found the GPR flavor yet, skip over the data for this
5292 // flavor:
5293 if (done)
5294 break;
5295 offset += count * 4;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005296 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005297 } break;
5298 case LC_MAIN: {
5299 ConstString text_segment_name("__TEXT");
5300 uint64_t entryoffset = m_data.GetU64(&offset);
5301 SectionSP text_segment_sp =
5302 GetSectionList()->FindSectionByName(text_segment_name);
5303 if (text_segment_sp) {
5304 done = true;
5305 start_address = text_segment_sp->GetFileAddress() + entryoffset;
5306 }
5307 } break;
5308
5309 default:
5310 break;
5311 }
5312 if (done)
5313 break;
5314
5315 // Go to the next load command:
5316 offset = cmd_offset + load_cmd.cmdsize;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005317 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005318
5319 if (start_address != LLDB_INVALID_ADDRESS) {
5320 // We got the start address from the load commands, so now resolve that
Adrian Prantl05097242018-04-30 16:49:04 +00005321 // address in the sections of this ObjectFile:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005322 if (!m_entry_point_address.ResolveAddressUsingFileSections(
5323 start_address, GetSectionList())) {
5324 m_entry_point_address.Clear();
5325 }
5326 } else {
5327 // We couldn't read the UnixThread load command - maybe it wasn't there.
Adrian Prantl05097242018-04-30 16:49:04 +00005328 // As a fallback look for the "start" symbol in the main executable.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005329
5330 ModuleSP module_sp(GetModule());
5331
5332 if (module_sp) {
5333 SymbolContextList contexts;
5334 SymbolContext context;
5335 if (module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5336 eSymbolTypeCode, contexts)) {
5337 if (contexts.GetContextAtIndex(0, context))
5338 m_entry_point_address = context.symbol->GetAddress();
5339 }
5340 }
5341 }
5342 }
5343
5344 return m_entry_point_address;
5345}
5346
Pavel Labathd1e3fe22018-12-11 15:21:15 +00005347lldb_private::Address ObjectFileMachO::GetBaseAddress() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005348 lldb_private::Address header_addr;
5349 SectionList *section_list = GetSectionList();
5350 if (section_list) {
5351 SectionSP text_segment_sp(
5352 section_list->FindSectionByName(GetSegmentNameTEXT()));
5353 if (text_segment_sp) {
5354 header_addr.SetSection(text_segment_sp);
5355 header_addr.SetOffset(0);
5356 }
5357 }
5358 return header_addr;
5359}
5360
5361uint32_t ObjectFileMachO::GetNumThreadContexts() {
5362 ModuleSP module_sp(GetModule());
5363 if (module_sp) {
5364 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5365 if (!m_thread_context_offsets_valid) {
5366 m_thread_context_offsets_valid = true;
5367 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5368 FileRangeArray::Entry file_range;
5369 thread_command thread_cmd;
5370 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5371 const uint32_t cmd_offset = offset;
5372 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5373 break;
5374
5375 if (thread_cmd.cmd == LC_THREAD) {
5376 file_range.SetRangeBase(offset);
5377 file_range.SetByteSize(thread_cmd.cmdsize - 8);
5378 m_thread_context_offsets.Append(file_range);
5379 }
5380 offset = cmd_offset + thread_cmd.cmdsize;
5381 }
5382 }
5383 }
5384 return m_thread_context_offsets.GetSize();
Greg Claytonc3776bf2012-02-09 06:16:32 +00005385}
5386
Jason Molenda3533cec2017-04-06 01:50:11 +00005387std::string ObjectFileMachO::GetIdentifierString() {
5388 std::string result;
5389 ModuleSP module_sp(GetModule());
5390 if (module_sp) {
5391 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005392
Adrian Prantl05097242018-04-30 16:49:04 +00005393 // First, look over the load commands for an LC_NOTE load command with
5394 // data_owner string "kern ver str" & use that if found.
Jason Molenda3533cec2017-04-06 01:50:11 +00005395 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5396 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5397 const uint32_t cmd_offset = offset;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005398 load_command lc;
5399 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5400 break;
5401 if (lc.cmd == LC_NOTE)
5402 {
5403 char data_owner[17];
5404 m_data.CopyData (offset, 16, data_owner);
5405 data_owner[16] = '\0';
5406 offset += 16;
5407 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5408 uint64_t size = m_data.GetU64_unchecked (&offset);
5409
Adrian Prantl05097242018-04-30 16:49:04 +00005410 // "kern ver str" has a uint32_t version and then a nul terminated
5411 // c-string.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005412 if (strcmp ("kern ver str", data_owner) == 0)
5413 {
5414 offset = fileoff;
5415 uint32_t version;
5416 if (m_data.GetU32 (&offset, &version, 1) != nullptr)
5417 {
5418 if (version == 1)
5419 {
5420 uint32_t strsize = size - sizeof (uint32_t);
5421 char *buf = (char*) malloc (strsize);
5422 if (buf)
5423 {
5424 m_data.CopyData (offset, strsize, buf);
5425 buf[strsize - 1] = '\0';
5426 result = buf;
5427 if (buf)
5428 free (buf);
5429 return result;
5430 }
5431 }
5432 }
5433 }
5434 }
5435 offset = cmd_offset + lc.cmdsize;
5436 }
5437
Adrian Prantl05097242018-04-30 16:49:04 +00005438 // Second, make a pass over the load commands looking for an obsolete
5439 // LC_IDENT load command.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005440 offset = MachHeaderSizeFromMagic(m_header.magic);
5441 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5442 const uint32_t cmd_offset = offset;
Jason Molenda3533cec2017-04-06 01:50:11 +00005443 struct ident_command ident_command;
5444 if (m_data.GetU32(&offset, &ident_command, 2) == NULL)
5445 break;
5446 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005447 char *buf = (char *) malloc (ident_command.cmdsize);
Jason Molenda3533cec2017-04-06 01:50:11 +00005448 if (buf != nullptr
5449 && m_data.CopyData (offset, ident_command.cmdsize, buf) == ident_command.cmdsize) {
5450 buf[ident_command.cmdsize - 1] = '\0';
5451 result = buf;
5452 }
5453 if (buf)
5454 free (buf);
5455 }
5456 offset = cmd_offset + ident_command.cmdsize;
5457 }
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005458
Jason Molenda3533cec2017-04-06 01:50:11 +00005459 }
5460 return result;
5461}
5462
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005463bool ObjectFileMachO::GetCorefileMainBinaryInfo (addr_t &address, UUID &uuid) {
5464 address = LLDB_INVALID_ADDRESS;
5465 uuid.Clear();
5466 ModuleSP module_sp(GetModule());
5467 if (module_sp) {
5468 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5469 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5470 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5471 const uint32_t cmd_offset = offset;
5472 load_command lc;
5473 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5474 break;
5475 if (lc.cmd == LC_NOTE)
5476 {
5477 char data_owner[17];
5478 memset (data_owner, 0, sizeof (data_owner));
5479 m_data.CopyData (offset, 16, data_owner);
5480 offset += 16;
5481 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5482 uint64_t size = m_data.GetU64_unchecked (&offset);
5483
Adrian Prantl05097242018-04-30 16:49:04 +00005484 // "main bin spec" (main binary specification) data payload is
5485 // formatted:
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005486 // uint32_t version [currently 1]
5487 // uint32_t type [0 == unspecified, 1 == kernel, 2 == user process]
5488 // uint64_t address [ UINT64_MAX if address not specified ]
5489 // uuid_t uuid [ all zero's if uuid not specified ]
5490 // uint32_t log2_pagesize [ process page size in log base 2, e.g. 4k pages are 12. 0 for unspecified ]
5491
5492 if (strcmp ("main bin spec", data_owner) == 0 && size >= 32)
5493 {
5494 offset = fileoff;
5495 uint32_t version;
5496 if (m_data.GetU32 (&offset, &version, 1) != nullptr && version == 1)
5497 {
5498 uint32_t type = 0;
5499 uuid_t raw_uuid;
Jason Molenda3f608292017-04-13 02:12:32 +00005500 memset (raw_uuid, 0, sizeof (uuid_t));
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005501
Pavel Labath2f93fd12018-06-26 15:12:20 +00005502 if (m_data.GetU32(&offset, &type, 1) &&
5503 m_data.GetU64(&offset, &address, 1) &&
5504 m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
5505 uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t));
5506 return true;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005507 }
5508 }
5509 }
5510 }
5511 offset = cmd_offset + lc.cmdsize;
5512 }
5513 }
5514 return false;
5515}
5516
Greg Claytonc3776bf2012-02-09 06:16:32 +00005517lldb::RegisterContextSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005518ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5519 lldb_private::Thread &thread) {
5520 lldb::RegisterContextSP reg_ctx_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00005521
Kate Stoneb9c1b512016-09-06 20:57:50 +00005522 ModuleSP module_sp(GetModule());
5523 if (module_sp) {
5524 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5525 if (!m_thread_context_offsets_valid)
5526 GetNumThreadContexts();
Greg Claytona1743492012-03-13 23:14:29 +00005527
Kate Stoneb9c1b512016-09-06 20:57:50 +00005528 const FileRangeArray::Entry *thread_context_file_range =
5529 m_thread_context_offsets.GetEntryAtIndex(idx);
5530 if (thread_context_file_range) {
Jason Molenda4e7511e2013-03-06 23:19:17 +00005531
Kate Stoneb9c1b512016-09-06 20:57:50 +00005532 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5533 thread_context_file_range->GetByteSize());
Jim Ingham28eb5712012-10-12 17:34:26 +00005534
Kate Stoneb9c1b512016-09-06 20:57:50 +00005535 switch (m_header.cputype) {
5536 case llvm::MachO::CPU_TYPE_ARM64:
5537 reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data));
5538 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005539
Kate Stoneb9c1b512016-09-06 20:57:50 +00005540 case llvm::MachO::CPU_TYPE_ARM:
5541 reg_ctx_sp.reset(new RegisterContextDarwin_arm_Mach(thread, data));
5542 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005543
Kate Stoneb9c1b512016-09-06 20:57:50 +00005544 case llvm::MachO::CPU_TYPE_I386:
5545 reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data));
5546 break;
5547
5548 case llvm::MachO::CPU_TYPE_X86_64:
5549 reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data));
5550 break;
5551 }
Greg Claytonc3776bf2012-02-09 06:16:32 +00005552 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005553 }
5554 return reg_ctx_sp;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005555}
5556
Kate Stoneb9c1b512016-09-06 20:57:50 +00005557ObjectFile::Type ObjectFileMachO::CalculateType() {
5558 switch (m_header.filetype) {
5559 case MH_OBJECT: // 0x1u
5560 if (GetAddressByteSize() == 4) {
5561 // 32 bit kexts are just object files, but they do have a valid
5562 // UUID load command.
5563 UUID uuid;
5564 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005565 // this checking for the UUID load command is not enough we could
5566 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5567 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005568 if (m_strata == eStrataInvalid)
5569 m_strata = eStrataKernel;
5570 return eTypeSharedLibrary;
5571 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005572 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005573 return eTypeObjectFile;
5574
5575 case MH_EXECUTE:
5576 return eTypeExecutable; // 0x2u
5577 case MH_FVMLIB:
5578 return eTypeSharedLibrary; // 0x3u
5579 case MH_CORE:
5580 return eTypeCoreFile; // 0x4u
5581 case MH_PRELOAD:
5582 return eTypeSharedLibrary; // 0x5u
5583 case MH_DYLIB:
5584 return eTypeSharedLibrary; // 0x6u
5585 case MH_DYLINKER:
5586 return eTypeDynamicLinker; // 0x7u
5587 case MH_BUNDLE:
5588 return eTypeSharedLibrary; // 0x8u
5589 case MH_DYLIB_STUB:
5590 return eTypeStubLibrary; // 0x9u
5591 case MH_DSYM:
5592 return eTypeDebugInfo; // 0xAu
5593 case MH_KEXT_BUNDLE:
5594 return eTypeSharedLibrary; // 0xBu
5595 default:
5596 break;
5597 }
5598 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005599}
5600
Kate Stoneb9c1b512016-09-06 20:57:50 +00005601ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5602 switch (m_header.filetype) {
5603 case MH_OBJECT: // 0x1u
5604 {
5605 // 32 bit kexts are just object files, but they do have a valid
5606 // UUID load command.
5607 UUID uuid;
5608 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005609 // this checking for the UUID load command is not enough we could
5610 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5611 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005612 if (m_type == eTypeInvalid)
5613 m_type = eTypeSharedLibrary;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005614
Kate Stoneb9c1b512016-09-06 20:57:50 +00005615 return eStrataKernel;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005616 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005617 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005618 return eStrataUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005619
5620 case MH_EXECUTE: // 0x2u
5621 // Check for the MH_DYLDLINK bit in the flags
5622 if (m_header.flags & MH_DYLDLINK) {
5623 return eStrataUser;
5624 } else {
5625 SectionList *section_list = GetSectionList();
5626 if (section_list) {
5627 static ConstString g_kld_section_name("__KLD");
5628 if (section_list->FindSectionByName(g_kld_section_name))
5629 return eStrataKernel;
5630 }
5631 }
5632 return eStrataRawImage;
5633
5634 case MH_FVMLIB:
5635 return eStrataUser; // 0x3u
5636 case MH_CORE:
5637 return eStrataUnknown; // 0x4u
5638 case MH_PRELOAD:
5639 return eStrataRawImage; // 0x5u
5640 case MH_DYLIB:
5641 return eStrataUser; // 0x6u
5642 case MH_DYLINKER:
5643 return eStrataUser; // 0x7u
5644 case MH_BUNDLE:
5645 return eStrataUser; // 0x8u
5646 case MH_DYLIB_STUB:
5647 return eStrataUser; // 0x9u
5648 case MH_DSYM:
5649 return eStrataUnknown; // 0xAu
5650 case MH_KEXT_BUNDLE:
5651 return eStrataKernel; // 0xBu
5652 default:
5653 break;
5654 }
5655 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005656}
5657
Pavel Labath2272c482018-06-18 15:02:23 +00005658llvm::VersionTuple ObjectFileMachO::GetVersion() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005659 ModuleSP module_sp(GetModule());
5660 if (module_sp) {
5661 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5662 struct dylib_command load_cmd;
5663 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5664 uint32_t version_cmd = 0;
5665 uint64_t version = 0;
5666 uint32_t i;
5667 for (i = 0; i < m_header.ncmds; ++i) {
5668 const lldb::offset_t cmd_offset = offset;
5669 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5670 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005671
Kate Stoneb9c1b512016-09-06 20:57:50 +00005672 if (load_cmd.cmd == LC_ID_DYLIB) {
5673 if (version_cmd == 0) {
5674 version_cmd = load_cmd.cmd;
5675 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5676 break;
5677 version = load_cmd.dylib.current_version;
Greg Claytonc2ff9312012-02-22 19:41:02 +00005678 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005679 break; // Break for now unless there is another more complete version
5680 // number load command in the future.
5681 }
5682 offset = cmd_offset + load_cmd.cmdsize;
5683 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00005684
Kate Stoneb9c1b512016-09-06 20:57:50 +00005685 if (version_cmd == LC_ID_DYLIB) {
Pavel Labath2272c482018-06-18 15:02:23 +00005686 unsigned major = (version & 0xFFFF0000ull) >> 16;
5687 unsigned minor = (version & 0x0000FF00ull) >> 8;
5688 unsigned subminor = (version & 0x000000FFull);
5689 return llvm::VersionTuple(major, minor, subminor);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005690 }
5691 }
Pavel Labath2272c482018-06-18 15:02:23 +00005692 return llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005693}
5694
5695bool ObjectFileMachO::GetArchitecture(ArchSpec &arch) {
5696 ModuleSP module_sp(GetModule());
5697 if (module_sp) {
5698 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5699 return GetArchitecture(m_header, m_data,
5700 MachHeaderSizeFromMagic(m_header.magic), arch);
5701 }
5702 return false;
5703}
5704
Jason Molenda07580ff2018-05-04 00:59:37 +00005705void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process, addr_t &base_addr, UUID &uuid) {
5706 uuid.Clear();
5707 base_addr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005708 if (process && process->GetDynamicLoader()) {
5709 DynamicLoader *dl = process->GetDynamicLoader();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005710 LazyBool using_shared_cache;
5711 LazyBool private_shared_cache;
Jason Molenda07580ff2018-05-04 00:59:37 +00005712 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005713 private_shared_cache);
5714 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005715 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005716 if (log)
Jason Molenda07580ff2018-05-04 00:59:37 +00005717 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 +00005718}
5719
Jason Molenda07580ff2018-05-04 00:59:37 +00005720// From dyld SPI header dyld_process_info.h
5721typedef void *dyld_process_info;
5722struct lldb_copy__dyld_process_cache_info {
5723 uuid_t cacheUUID; // UUID of cache used by process
5724 uint64_t cacheBaseAddress; // load address of dyld shared cache
5725 bool noCache; // process is running without a dyld cache
5726 bool privateCache; // process is using a private copy of its dyld cache
5727};
5728
5729// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with llvm
5730// enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile errors.
5731// So we need to use the actual underlying types of task_t and kern_return_t
5732// below.
5733extern "C" unsigned int /*task_t*/ mach_task_self();
5734
5735void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5736 uuid.Clear();
5737 base_addr = LLDB_INVALID_ADDRESS;
5738
Kate Stoneb9c1b512016-09-06 20:57:50 +00005739#if defined(__APPLE__) && \
5740 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5741 uint8_t *(*dyld_get_all_image_infos)(void);
5742 dyld_get_all_image_infos =
5743 (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5744 if (dyld_get_all_image_infos) {
5745 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5746 if (dyld_all_image_infos_address) {
5747 uint32_t *version = (uint32_t *)
5748 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5749 if (*version >= 13) {
5750 uuid_t *sharedCacheUUID_address = 0;
5751 int wordsize = sizeof(uint8_t *);
5752 if (wordsize == 8) {
5753 sharedCacheUUID_address =
5754 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5755 160); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005756 if (*version >= 15)
5757 base_addr = *(uint64_t *) ((uint8_t *) dyld_all_image_infos_address
5758 + 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +00005759 } else {
5760 sharedCacheUUID_address =
5761 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5762 84); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005763 if (*version >= 15) {
5764 base_addr = 0;
5765 base_addr = *(uint32_t *) ((uint8_t *) dyld_all_image_infos_address
5766 + 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5767 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005768 }
Pavel Labath2f93fd12018-06-26 15:12:20 +00005769 uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005770 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005771 }
Jason Molendafd443e92018-02-07 01:28:29 +00005772 } else {
5773 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
Jason Molenda07580ff2018-05-04 00:59:37 +00005774 dyld_process_info (*dyld_process_info_create)(unsigned int /* task_t */ task, uint64_t timestamp, unsigned int /*kern_return_t*/ *kernelError);
5775 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5776 void (*dyld_process_info_release)(dyld_process_info info);
5777
5778 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, unsigned int /*kern_return_t*/ *))
5779 dlsym (RTLD_DEFAULT, "_dyld_process_info_create");
5780 dyld_process_info_get_cache = (void (*)(void *, void *))
5781 dlsym (RTLD_DEFAULT, "_dyld_process_info_get_cache");
5782 dyld_process_info_release = (void (*)(void *))
5783 dlsym (RTLD_DEFAULT, "_dyld_process_info_release");
5784
5785 if (dyld_process_info_create && dyld_process_info_get_cache) {
5786 unsigned int /*kern_return_t */ kern_ret;
5787 dyld_process_info process_info = dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5788 if (process_info) {
5789 struct lldb_copy__dyld_process_cache_info sc_info;
5790 memset (&sc_info, 0, sizeof (struct lldb_copy__dyld_process_cache_info));
5791 dyld_process_info_get_cache (process_info, &sc_info);
5792 if (sc_info.cacheBaseAddress != 0) {
5793 base_addr = sc_info.cacheBaseAddress;
Pavel Labath2f93fd12018-06-26 15:12:20 +00005794 uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
Jason Molenda07580ff2018-05-04 00:59:37 +00005795 }
5796 dyld_process_info_release (process_info);
5797 }
Jason Molendafd443e92018-02-07 01:28:29 +00005798 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005799 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005800 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005801 if (log && uuid.IsValid())
Jason Molenda07580ff2018-05-04 00:59:37 +00005802 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 +00005803#endif
Jason Molenda0e0954c2013-04-16 06:24:42 +00005804}
5805
Pavel Labath2272c482018-06-18 15:02:23 +00005806llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5807 if (!m_min_os_version) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005808 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labath2272c482018-06-18 15:02:23 +00005809 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005810 const lldb::offset_t load_cmd_offset = offset;
5811
5812 version_min_command lc;
5813 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5814 break;
5815 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5816 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5817 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5818 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5819 if (m_data.GetU32(&offset, &lc.version,
5820 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5821 const uint32_t xxxx = lc.version >> 16;
5822 const uint32_t yy = (lc.version >> 8) & 0xffu;
5823 const uint32_t zz = lc.version & 0xffu;
5824 if (xxxx) {
Pavel Labath2272c482018-06-18 15:02:23 +00005825 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5826 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005827 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005828 }
5829 } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5830 // struct build_version_command {
5831 // uint32_t cmd; /* LC_BUILD_VERSION */
5832 // uint32_t cmdsize; /* sizeof(struct build_version_command) plus */
5833 // /* ntools * sizeof(struct build_tool_version) */
5834 // uint32_t platform; /* platform */
5835 // uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5836 // uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5837 // uint32_t ntools; /* number of tool entries following this */
5838 // };
5839
5840 offset += 4; // skip platform
5841 uint32_t minos = m_data.GetU32(&offset);
5842
5843 const uint32_t xxxx = minos >> 16;
5844 const uint32_t yy = (minos >> 8) & 0xffu;
5845 const uint32_t zz = minos & 0xffu;
5846 if (xxxx) {
5847 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5848 break;
Greg Clayton9b234982013-10-24 22:54:08 +00005849 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005850 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005851
Kate Stoneb9c1b512016-09-06 20:57:50 +00005852 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005853 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005854
Pavel Labath2272c482018-06-18 15:02:23 +00005855 if (!m_min_os_version) {
5856 // Set version to an empty value so we don't keep trying to
5857 m_min_os_version = llvm::VersionTuple();
Greg Clayton9b234982013-10-24 22:54:08 +00005858 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005859 }
5860
Pavel Labath2272c482018-06-18 15:02:23 +00005861 return *m_min_os_version;
Greg Clayton9b234982013-10-24 22:54:08 +00005862}
5863
Kate Stoneb9c1b512016-09-06 20:57:50 +00005864uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions,
5865 uint32_t num_versions) {
5866 if (m_sdk_versions.empty()) {
5867 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5868 bool success = false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005869 for (uint32_t i = 0; !success && i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005870 const lldb::offset_t load_cmd_offset = offset;
5871
5872 version_min_command lc;
5873 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5874 break;
5875 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5876 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5877 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5878 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5879 if (m_data.GetU32(&offset, &lc.version,
5880 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5881 const uint32_t xxxx = lc.sdk >> 16;
5882 const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5883 const uint32_t zz = lc.sdk & 0xffu;
5884 if (xxxx) {
5885 m_sdk_versions.push_back(xxxx);
5886 m_sdk_versions.push_back(yy);
5887 m_sdk_versions.push_back(zz);
Jason Molenda32a91422018-06-25 23:45:39 +00005888 success = true;
5889 } else {
5890 GetModule()->ReportWarning(
5891 "minimum OS version load command with invalid (0) version found.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005892 }
Greg Clayton9b234982013-10-24 22:54:08 +00005893 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005894 }
5895 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005896 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005897
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005898 if (!success) {
5899 offset = MachHeaderSizeFromMagic(m_header.magic);
5900 for (uint32_t i = 0; !success && i < m_header.ncmds; ++i) {
5901 const lldb::offset_t load_cmd_offset = offset;
Jason Molenda32762fd2018-10-11 00:28:35 +00005902
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005903 version_min_command lc;
5904 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5905 break;
5906 if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5907 // struct build_version_command {
5908 // uint32_t cmd; /* LC_BUILD_VERSION */
5909 // uint32_t cmdsize; /* sizeof(struct
5910 // build_version_command) plus */
5911 // /* ntools * sizeof(struct
5912 // build_tool_version) */
5913 // uint32_t platform; /* platform */
5914 // uint32_t minos; /* X.Y.Z is encoded in nibbles
5915 // xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded
5916 // in nibbles xxxx.yy.zz */ uint32_t ntools; /* number
5917 // of tool entries following this */
5918 // };
Jason Molenda32762fd2018-10-11 00:28:35 +00005919
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005920 offset += 4; // skip platform
5921 uint32_t minos = m_data.GetU32(&offset);
Jason Molenda32762fd2018-10-11 00:28:35 +00005922
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005923 const uint32_t xxxx = minos >> 16;
5924 const uint32_t yy = (minos >> 8) & 0xffu;
5925 const uint32_t zz = minos & 0xffu;
5926 if (xxxx) {
5927 m_sdk_versions.push_back(xxxx);
5928 m_sdk_versions.push_back(yy);
5929 m_sdk_versions.push_back(zz);
5930 success = true;
5931 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005932 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005933 offset = load_cmd_offset + lc.cmdsize;
5934 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005935 }
5936
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005937 if (!success) {
Jason Molenda32a91422018-06-25 23:45:39 +00005938 // Push an invalid value so we don't try to find
5939 // the version # again on the next call to this
5940 // method.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005941 m_sdk_versions.push_back(UINT32_MAX);
Greg Clayton9b234982013-10-24 22:54:08 +00005942 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005943 }
5944
Jason Molenda32a91422018-06-25 23:45:39 +00005945 // Legitimate version numbers will have 3 entries pushed
5946 // on to m_sdk_versions. If we only have one value, it's
5947 // the sentinel value indicating that this object file
5948 // does not have a valid minimum os version #.
5949 if (m_sdk_versions.size() > 1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005950 if (versions != NULL && num_versions > 0) {
5951 for (size_t i = 0; i < num_versions; ++i) {
5952 if (i < m_sdk_versions.size())
5953 versions[i] = m_sdk_versions[i];
5954 else
5955 versions[i] = 0;
5956 }
5957 }
5958 return m_sdk_versions.size();
5959 }
5960 // Call the superclasses version that will empty out the data
5961 return ObjectFile::GetSDKVersion(versions, num_versions);
Greg Clayton9b234982013-10-24 22:54:08 +00005962}
5963
Kate Stoneb9c1b512016-09-06 20:57:50 +00005964bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5965 return m_header.filetype == llvm::MachO::MH_DYLINKER;
Greg Clayton08928f32015-02-05 02:01:34 +00005966}
5967
Kate Stoneb9c1b512016-09-06 20:57:50 +00005968bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5969 return m_allow_assembly_emulation_unwind_plans;
Jason Molenda955dcf22016-05-04 03:09:40 +00005970}
5971
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005972//------------------------------------------------------------------
5973// PluginInterface protocol
5974//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00005975lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5976 return GetPluginNameStatic();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005977}
5978
Kate Stoneb9c1b512016-09-06 20:57:50 +00005979uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005980
Kate Stoneb9c1b512016-09-06 20:57:50 +00005981Section *ObjectFileMachO::GetMachHeaderSection() {
Adrian Prantl05097242018-04-30 16:49:04 +00005982 // Find the first address of the mach header which is the first non-zero file
5983 // sized section whose file offset is zero. This is the base file address of
5984 // the mach-o file which can be subtracted from the vmaddr of the other
Kate Stoneb9c1b512016-09-06 20:57:50 +00005985 // segments found in memory and added to the load address
5986 ModuleSP module_sp = GetModule();
Greg Clayton57577c02018-12-21 17:04:18 +00005987 if (!module_sp)
5988 return nullptr;
5989 SectionList *section_list = GetSectionList();
5990 if (!section_list)
5991 return nullptr;
5992 const size_t num_sections = section_list->GetSize();
5993 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5994 Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5995 if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
5996 return section;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005997 }
5998 return nullptr;
Greg Clayton07347372015-06-08 21:53:11 +00005999}
6000
Greg Clayton57577c02018-12-21 17:04:18 +00006001bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
6002 if (!section)
6003 return false;
6004 const bool is_dsym = (m_header.filetype == MH_DSYM);
6005 if (section->GetFileSize() == 0 && !is_dsym)
6006 return false;
6007 if (section->IsThreadSpecific())
6008 return false;
6009 if (GetModule().get() != section->GetModule().get())
6010 return false;
6011 // Be careful with __LINKEDIT and __DWARF segments
6012 if (section->GetName() == GetSegmentNameLINKEDIT() ||
6013 section->GetName() == GetSegmentNameDWARF()) {
6014 // Only map __LINKEDIT and __DWARF if we have an in memory image and
6015 // this isn't a kernel binary like a kext or mach_kernel.
6016 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 false;
6020 }
6021 return true;
6022}
6023
Kate Stoneb9c1b512016-09-06 20:57:50 +00006024lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
Greg Clayton57577c02018-12-21 17:04:18 +00006025 lldb::addr_t header_load_address, const Section *header_section,
Kate Stoneb9c1b512016-09-06 20:57:50 +00006026 const Section *section) {
6027 ModuleSP module_sp = GetModule();
Greg Clayton57577c02018-12-21 17:04:18 +00006028 if (module_sp && header_section && section &&
6029 header_load_address != LLDB_INVALID_ADDRESS) {
6030 lldb::addr_t file_addr = header_section->GetFileAddress();
6031 if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
6032 return section->GetFileAddress() - file_addr + header_load_address;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006033 }
6034 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00006035}
6036
Kate Stoneb9c1b512016-09-06 20:57:50 +00006037bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
6038 bool value_is_offset) {
6039 ModuleSP module_sp = GetModule();
6040 if (module_sp) {
6041 size_t num_loaded_sections = 0;
6042 SectionList *section_list = GetSectionList();
6043 if (section_list) {
6044 const size_t num_sections = section_list->GetSize();
Greg Clayton7524e092014-02-06 20:10:16 +00006045
Kate Stoneb9c1b512016-09-06 20:57:50 +00006046 if (value_is_offset) {
6047 // "value" is an offset to apply to each top level segment
6048 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +00006049 // Iterate through the object file sections to find all of the
6050 // sections that size on disk (to avoid __PAGEZERO) and load them
Kate Stoneb9c1b512016-09-06 20:57:50 +00006051 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
Greg Clayton57577c02018-12-21 17:04:18 +00006052 if (SectionIsLoadable(section_sp.get()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00006053 if (target.GetSectionLoadList().SetSectionLoadAddress(
6054 section_sp, section_sp->GetFileAddress() + value))
6055 ++num_loaded_sections;
Greg Clayton7524e092014-02-06 20:10:16 +00006056 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006057 } else {
6058 // "value" is the new base address of the mach_header, adjust each
6059 // section accordingly
6060
6061 Section *mach_header_section = GetMachHeaderSection();
6062 if (mach_header_section) {
6063 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6064 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6065
6066 lldb::addr_t section_load_addr =
6067 CalculateSectionLoadAddressForMemoryImage(
6068 value, mach_header_section, section_sp.get());
6069 if (section_load_addr != LLDB_INVALID_ADDRESS) {
6070 if (target.GetSectionLoadList().SetSectionLoadAddress(
6071 section_sp, section_load_addr))
6072 ++num_loaded_sections;
6073 }
6074 }
6075 }
6076 }
Greg Clayton7524e092014-02-06 20:10:16 +00006077 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006078 return num_loaded_sections > 0;
6079 }
6080 return false;
Greg Clayton7524e092014-02-06 20:10:16 +00006081}
6082
Kate Stoneb9c1b512016-09-06 20:57:50 +00006083bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00006084 const FileSpec &outfile, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00006085 if (process_sp) {
6086 Target &target = process_sp->GetTarget();
6087 const ArchSpec target_arch = target.GetArchitecture();
6088 const llvm::Triple &target_triple = target_arch.GetTriple();
6089 if (target_triple.getVendor() == llvm::Triple::Apple &&
6090 (target_triple.getOS() == llvm::Triple::MacOSX ||
6091 target_triple.getOS() == llvm::Triple::IOS ||
6092 target_triple.getOS() == llvm::Triple::WatchOS ||
6093 target_triple.getOS() == llvm::Triple::TvOS)) {
Jason Molenda32762fd2018-10-11 00:28:35 +00006094 // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00006095 bool make_core = false;
6096 switch (target_arch.GetMachine()) {
6097 case llvm::Triple::aarch64:
6098 case llvm::Triple::arm:
6099 case llvm::Triple::thumb:
6100 case llvm::Triple::x86:
6101 case llvm::Triple::x86_64:
6102 make_core = true;
6103 break;
6104 default:
6105 error.SetErrorStringWithFormat("unsupported core architecture: %s",
6106 target_triple.str().c_str());
6107 break;
6108 }
6109
6110 if (make_core) {
6111 std::vector<segment_command_64> segment_load_commands;
6112 // uint32_t range_info_idx = 0;
6113 MemoryRegionInfo range_info;
Zachary Turner97206d52017-05-12 04:51:55 +00006114 Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006115 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6116 const ByteOrder byte_order = target_arch.GetByteOrder();
6117 if (range_error.Success()) {
6118 while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
6119 const addr_t addr = range_info.GetRange().GetRangeBase();
6120 const addr_t size = range_info.GetRange().GetByteSize();
6121
6122 if (size == 0)
6123 break;
6124
6125 // Calculate correct protections
6126 uint32_t prot = 0;
6127 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
6128 prot |= VM_PROT_READ;
6129 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
6130 prot |= VM_PROT_WRITE;
6131 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
6132 prot |= VM_PROT_EXECUTE;
6133
6134 // printf ("[%3u] [0x%16.16" PRIx64 " -
6135 // 0x%16.16" PRIx64 ") %c%c%c\n",
6136 // range_info_idx,
6137 // addr,
6138 // size,
6139 // (prot & VM_PROT_READ ) ? 'r' :
6140 // '-',
6141 // (prot & VM_PROT_WRITE ) ? 'w' :
6142 // '-',
6143 // (prot & VM_PROT_EXECUTE) ? 'x' :
6144 // '-');
6145
6146 if (prot != 0) {
6147 uint32_t cmd_type = LC_SEGMENT_64;
6148 uint32_t segment_size = sizeof(segment_command_64);
6149 if (addr_byte_size == 4) {
6150 cmd_type = LC_SEGMENT;
6151 segment_size = sizeof(segment_command);
6152 }
6153 segment_command_64 segment = {
6154 cmd_type, // uint32_t cmd;
6155 segment_size, // uint32_t cmdsize;
6156 {0}, // char segname[16];
6157 addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
6158 size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
6159 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
6160 size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
6161 prot, // uint32_t maxprot;
6162 prot, // uint32_t initprot;
6163 0, // uint32_t nsects;
6164 0}; // uint32_t flags;
6165 segment_load_commands.push_back(segment);
6166 } else {
6167 // No protections and a size of 1 used to be returned from old
6168 // debugservers when we asked about a region that was past the
6169 // last memory region and it indicates the end...
6170 if (size == 1)
6171 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006172 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006173
Kate Stoneb9c1b512016-09-06 20:57:50 +00006174 range_error = process_sp->GetMemoryRegionInfo(
6175 range_info.GetRange().GetRangeEnd(), range_info);
6176 if (range_error.Fail())
6177 break;
6178 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006179
Kate Stoneb9c1b512016-09-06 20:57:50 +00006180 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
Greg Claytona2715cf2014-06-13 00:54:12 +00006181
Kate Stoneb9c1b512016-09-06 20:57:50 +00006182 mach_header_64 mach_header;
6183 if (addr_byte_size == 8) {
6184 mach_header.magic = MH_MAGIC_64;
6185 } else {
6186 mach_header.magic = MH_MAGIC;
6187 }
6188 mach_header.cputype = target_arch.GetMachOCPUType();
6189 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6190 mach_header.filetype = MH_CORE;
6191 mach_header.ncmds = segment_load_commands.size();
6192 mach_header.flags = 0;
6193 mach_header.reserved = 0;
6194 ThreadList &thread_list = process_sp->GetThreadList();
6195 const uint32_t num_threads = thread_list.GetSize();
Greg Claytona2715cf2014-06-13 00:54:12 +00006196
Adrian Prantl05097242018-04-30 16:49:04 +00006197 // Make an array of LC_THREAD data items. Each one contains the
6198 // contents of the LC_THREAD load command. The data doesn't contain
6199 // the load command + load command size, we will add the load command
6200 // and load command size as we emit the data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006201 std::vector<StreamString> LC_THREAD_datas(num_threads);
6202 for (auto &LC_THREAD_data : LC_THREAD_datas) {
6203 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6204 LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6205 LC_THREAD_data.SetByteOrder(byte_order);
6206 }
6207 for (uint32_t thread_idx = 0; thread_idx < num_threads;
6208 ++thread_idx) {
6209 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6210 if (thread_sp) {
6211 switch (mach_header.cputype) {
6212 case llvm::MachO::CPU_TYPE_ARM64:
6213 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6214 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6215 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006216
Kate Stoneb9c1b512016-09-06 20:57:50 +00006217 case llvm::MachO::CPU_TYPE_ARM:
6218 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6219 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6220 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006221
Kate Stoneb9c1b512016-09-06 20:57:50 +00006222 case llvm::MachO::CPU_TYPE_I386:
6223 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6224 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6225 break;
Jason Molenda22952582014-11-12 01:11:36 +00006226
Kate Stoneb9c1b512016-09-06 20:57:50 +00006227 case llvm::MachO::CPU_TYPE_X86_64:
6228 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6229 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6230 break;
6231 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006232 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006233 }
6234
6235 // The size of the load command is the size of the segments...
6236 if (addr_byte_size == 8) {
6237 mach_header.sizeofcmds = segment_load_commands.size() *
6238 sizeof(struct segment_command_64);
6239 } else {
6240 mach_header.sizeofcmds =
6241 segment_load_commands.size() * sizeof(struct segment_command);
6242 }
6243
6244 // and the size of all LC_THREAD load command
6245 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6246 ++mach_header.ncmds;
6247 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6248 }
6249
6250 printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x "
6251 "0x%8.8x 0x%8.8x\n",
6252 mach_header.magic, mach_header.cputype, mach_header.cpusubtype,
6253 mach_header.filetype, mach_header.ncmds,
6254 mach_header.sizeofcmds, mach_header.flags,
6255 mach_header.reserved);
6256
6257 // Write the mach header
6258 buffer.PutHex32(mach_header.magic);
6259 buffer.PutHex32(mach_header.cputype);
6260 buffer.PutHex32(mach_header.cpusubtype);
6261 buffer.PutHex32(mach_header.filetype);
6262 buffer.PutHex32(mach_header.ncmds);
6263 buffer.PutHex32(mach_header.sizeofcmds);
6264 buffer.PutHex32(mach_header.flags);
6265 if (addr_byte_size == 8) {
6266 buffer.PutHex32(mach_header.reserved);
6267 }
6268
6269 // Skip the mach header and all load commands and align to the next
6270 // 0x1000 byte boundary
6271 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6272 if (file_offset & 0x00000fff) {
6273 file_offset += 0x00001000ull;
6274 file_offset &= (~0x00001000ull + 1);
6275 }
6276
6277 for (auto &segment : segment_load_commands) {
6278 segment.fileoff = file_offset;
6279 file_offset += segment.filesize;
6280 }
6281
6282 // Write out all of the LC_THREAD load commands
6283 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6284 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6285 buffer.PutHex32(LC_THREAD);
6286 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
Zachary Turnerc1564272016-11-16 21:15:24 +00006287 buffer.Write(LC_THREAD_data.GetString().data(),
6288 LC_THREAD_data_size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006289 }
6290
6291 // Write out all of the segment load commands
6292 for (const auto &segment : segment_load_commands) {
6293 printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6294 ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6295 ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6296 segment.cmd, segment.cmdsize, segment.vmaddr,
6297 segment.vmaddr + segment.vmsize, segment.fileoff,
6298 segment.filesize, segment.maxprot, segment.initprot,
6299 segment.nsects, segment.flags);
6300
6301 buffer.PutHex32(segment.cmd);
6302 buffer.PutHex32(segment.cmdsize);
6303 buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6304 if (addr_byte_size == 8) {
6305 buffer.PutHex64(segment.vmaddr);
6306 buffer.PutHex64(segment.vmsize);
6307 buffer.PutHex64(segment.fileoff);
6308 buffer.PutHex64(segment.filesize);
6309 } else {
6310 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6311 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6312 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6313 buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6314 }
6315 buffer.PutHex32(segment.maxprot);
6316 buffer.PutHex32(segment.initprot);
6317 buffer.PutHex32(segment.nsects);
6318 buffer.PutHex32(segment.flags);
6319 }
6320
6321 File core_file;
6322 std::string core_file_path(outfile.GetPath());
Jonas Devlieghere50bc1ed2018-11-02 22:34:51 +00006323 error = FileSystem::Instance().Open(core_file, outfile,
6324 File::eOpenOptionWrite |
6325 File::eOpenOptionTruncate |
6326 File::eOpenOptionCanCreate);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006327 if (error.Success()) {
6328 // Read 1 page at a time
6329 uint8_t bytes[0x1000];
6330 // Write the mach header and load commands out to the core file
6331 size_t bytes_written = buffer.GetString().size();
6332 error = core_file.Write(buffer.GetString().data(), bytes_written);
6333 if (error.Success()) {
6334 // Now write the file data for all memory segments in the process
6335 for (const auto &segment : segment_load_commands) {
6336 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6337 error.SetErrorStringWithFormat(
6338 "unable to seek to offset 0x%" PRIx64 " in '%s'",
6339 segment.fileoff, core_file_path.c_str());
6340 break;
6341 }
6342
6343 printf("Saving %" PRId64
6344 " bytes of data for memory region at 0x%" PRIx64 "\n",
6345 segment.vmsize, segment.vmaddr);
6346 addr_t bytes_left = segment.vmsize;
6347 addr_t addr = segment.vmaddr;
Zachary Turner97206d52017-05-12 04:51:55 +00006348 Status memory_read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006349 while (bytes_left > 0 && error.Success()) {
6350 const size_t bytes_to_read =
6351 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6352 const size_t bytes_read = process_sp->ReadMemory(
6353 addr, bytes, bytes_to_read, memory_read_error);
6354 if (bytes_read == bytes_to_read) {
6355 size_t bytes_written = bytes_read;
6356 error = core_file.Write(bytes, bytes_written);
6357 bytes_left -= bytes_read;
6358 addr += bytes_read;
6359 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00006360 // Some pages within regions are not readable, those should
6361 // be zero filled
Kate Stoneb9c1b512016-09-06 20:57:50 +00006362 memset(bytes, 0, bytes_to_read);
6363 size_t bytes_written = bytes_to_read;
6364 error = core_file.Write(bytes, bytes_written);
6365 bytes_left -= bytes_to_read;
6366 addr += bytes_to_read;
6367 }
6368 }
6369 }
6370 }
6371 }
6372 } else {
6373 error.SetErrorString(
6374 "process doesn't support getting memory region info");
Greg Claytona2715cf2014-06-13 00:54:12 +00006375 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006376 }
6377 return true; // This is the right plug to handle saving core files for
6378 // this process
Greg Claytona2715cf2014-06-13 00:54:12 +00006379 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006380 }
6381 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00006382}