blob: 06908fecf984163208b80793292fda81ed992d65 [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
Pavel Labathf760f5a2019-01-03 10:37:19 +0000918 spec.GetArchitecture() = GetArchitecture(header, data, data_offset);
919 if (spec.GetArchitecture().IsValid()) {
920 GetUUID(header, data, data_offset, spec.GetUUID());
921 specs.Append(spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922 }
923 }
924 }
925 }
926 return specs.GetSize() - initial_count;
927}
928
929const ConstString &ObjectFileMachO::GetSegmentNameTEXT() {
930 static ConstString g_segment_name_TEXT("__TEXT");
931 return g_segment_name_TEXT;
932}
933
934const ConstString &ObjectFileMachO::GetSegmentNameDATA() {
935 static ConstString g_segment_name_DATA("__DATA");
936 return g_segment_name_DATA;
937}
938
939const ConstString &ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
940 static ConstString g_segment_name("__DATA_DIRTY");
941 return g_segment_name;
942}
943
944const ConstString &ObjectFileMachO::GetSegmentNameDATA_CONST() {
945 static ConstString g_segment_name("__DATA_CONST");
946 return g_segment_name;
947}
948
949const ConstString &ObjectFileMachO::GetSegmentNameOBJC() {
950 static ConstString g_segment_name_OBJC("__OBJC");
951 return g_segment_name_OBJC;
952}
953
954const ConstString &ObjectFileMachO::GetSegmentNameLINKEDIT() {
955 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
956 return g_section_name_LINKEDIT;
957}
958
Greg Clayton57577c02018-12-21 17:04:18 +0000959const ConstString &ObjectFileMachO::GetSegmentNameDWARF() {
960 static ConstString g_section_name("__DWARF");
961 return g_section_name;
962}
963
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964const ConstString &ObjectFileMachO::GetSectionNameEHFrame() {
965 static ConstString g_section_name_eh_frame("__eh_frame");
966 return g_section_name_eh_frame;
967}
968
969bool ObjectFileMachO::MagicBytesMatch(DataBufferSP &data_sp,
970 lldb::addr_t data_offset,
971 lldb::addr_t data_length) {
972 DataExtractor data;
973 data.SetData(data_sp, data_offset, data_length);
974 lldb::offset_t offset = 0;
975 uint32_t magic = data.GetU32(&offset);
976 return MachHeaderSizeFromMagic(magic) != 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977}
978
Greg Clayton5ce9c562013-02-06 17:22:03 +0000979ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 DataBufferSP &data_sp,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000981 lldb::offset_t data_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 const FileSpec *file,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000983 lldb::offset_t file_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 lldb::offset_t length)
985 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
986 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
987 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
988 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
989 ::memset(&m_header, 0, sizeof(m_header));
990 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991}
992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
994 lldb::DataBufferSP &header_data_sp,
995 const lldb::ProcessSP &process_sp,
996 lldb::addr_t header_addr)
997 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
998 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
999 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
1000 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
1001 ::memset(&m_header, 0, sizeof(m_header));
1002 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Greg Claytonc9660542012-02-05 02:38:54 +00001003}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005bool ObjectFileMachO::ParseHeader(DataExtractor &data,
1006 lldb::offset_t *data_offset_ptr,
1007 llvm::MachO::mach_header &header) {
1008 data.SetByteOrder(endian::InlHostByteOrder());
1009 // Leave magic in the original byte order
1010 header.magic = data.GetU32(data_offset_ptr);
1011 bool can_parse = false;
1012 bool is_64_bit = false;
1013 switch (header.magic) {
1014 case MH_MAGIC:
1015 data.SetByteOrder(endian::InlHostByteOrder());
1016 data.SetAddressByteSize(4);
1017 can_parse = true;
1018 break;
1019
1020 case MH_MAGIC_64:
1021 data.SetByteOrder(endian::InlHostByteOrder());
1022 data.SetAddressByteSize(8);
1023 can_parse = true;
1024 is_64_bit = true;
1025 break;
1026
1027 case MH_CIGAM:
1028 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1029 ? eByteOrderLittle
1030 : eByteOrderBig);
1031 data.SetAddressByteSize(4);
1032 can_parse = true;
1033 break;
1034
1035 case MH_CIGAM_64:
1036 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1037 ? eByteOrderLittle
1038 : eByteOrderBig);
1039 data.SetAddressByteSize(8);
1040 is_64_bit = true;
1041 can_parse = true;
1042 break;
1043
1044 default:
1045 break;
1046 }
1047
1048 if (can_parse) {
1049 data.GetU32(data_offset_ptr, &header.cputype, 6);
1050 if (is_64_bit)
1051 *data_offset_ptr += 4;
1052 return true;
1053 } else {
1054 memset(&header, 0, sizeof(header));
1055 }
1056 return false;
1057}
1058
1059bool ObjectFileMachO::ParseHeader() {
1060 ModuleSP module_sp(GetModule());
1061 if (module_sp) {
1062 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Greg Claytonf4d6de62013-04-24 22:29:28 +00001063 bool can_parse = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064 lldb::offset_t offset = 0;
1065 m_data.SetByteOrder(endian::InlHostByteOrder());
1066 // Leave magic in the original byte order
1067 m_header.magic = m_data.GetU32(&offset);
1068 switch (m_header.magic) {
1069 case MH_MAGIC:
1070 m_data.SetByteOrder(endian::InlHostByteOrder());
1071 m_data.SetAddressByteSize(4);
1072 can_parse = true;
1073 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 case MH_MAGIC_64:
1076 m_data.SetByteOrder(endian::InlHostByteOrder());
1077 m_data.SetAddressByteSize(8);
1078 can_parse = true;
1079 break;
Greg Claytona1743492012-03-13 23:14:29 +00001080
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 case MH_CIGAM:
1082 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1083 ? eByteOrderLittle
1084 : eByteOrderBig);
1085 m_data.SetAddressByteSize(4);
1086 can_parse = true;
1087 break;
Greg Claytona1743492012-03-13 23:14:29 +00001088
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089 case MH_CIGAM_64:
1090 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1091 ? eByteOrderLittle
1092 : eByteOrderBig);
1093 m_data.SetAddressByteSize(8);
1094 can_parse = true;
1095 break;
Greg Claytona1743492012-03-13 23:14:29 +00001096
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 default:
1098 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099 }
1100
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 if (can_parse) {
1102 m_data.GetU32(&offset, &m_header.cputype, 6);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103
Pavel Labathf760f5a2019-01-03 10:37:19 +00001104 if (ArchSpec mach_arch = GetArchitecture()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105 // Check if the module has a required architecture
1106 const ArchSpec &module_arch = module_sp->GetArchitecture();
1107 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1108 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 if (SetModulesArchitecture(mach_arch)) {
1111 const size_t header_and_lc_size =
1112 m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1113 if (m_data.GetByteSize() < header_and_lc_size) {
1114 DataBufferSP data_sp;
1115 ProcessSP process_sp(m_process_wp.lock());
1116 if (process_sp) {
1117 data_sp =
1118 ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1119 } else {
1120 // Read in all only the load command data from the file on disk
Pavel Labath50251fc2017-12-21 10:54:30 +00001121 data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 if (data_sp->GetByteSize() != header_and_lc_size)
Greg Clayton8f265f72015-10-28 20:49:34 +00001123 return false;
1124 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 if (data_sp)
1126 m_data.SetData(data_sp);
1127 }
Greg Clayton9191db42013-10-21 18:40:51 +00001128 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129 return true;
1130 }
1131 } else {
1132 memset(&m_header, 0, sizeof(struct mach_header));
1133 }
1134 }
1135 return false;
1136}
1137
1138ByteOrder ObjectFileMachO::GetByteOrder() const {
1139 return m_data.GetByteOrder();
1140}
1141
1142bool ObjectFileMachO::IsExecutable() const {
1143 return m_header.filetype == MH_EXECUTE;
1144}
1145
1146uint32_t ObjectFileMachO::GetAddressByteSize() const {
1147 return m_data.GetAddressByteSize();
1148}
1149
1150AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
1151 Symtab *symtab = GetSymtab();
1152 if (symtab) {
1153 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1154 if (symbol) {
1155 if (symbol->ValueIsAddress()) {
1156 SectionSP section_sp(symbol->GetAddressRef().GetSection());
1157 if (section_sp) {
1158 const lldb::SectionType section_type = section_sp->GetType();
1159 switch (section_type) {
1160 case eSectionTypeInvalid:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001161 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001162
1163 case eSectionTypeCode:
1164 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001165 // For ARM we have a bit in the n_desc field of the symbol that
1166 // tells us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001168 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001170 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171
1172 case eSectionTypeContainer:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001173 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174
1175 case eSectionTypeData:
1176 case eSectionTypeDataCString:
1177 case eSectionTypeDataCStringPointers:
1178 case eSectionTypeDataSymbolAddress:
1179 case eSectionTypeData4:
1180 case eSectionTypeData8:
1181 case eSectionTypeData16:
1182 case eSectionTypeDataPointers:
1183 case eSectionTypeZeroFill:
1184 case eSectionTypeDataObjCMessageRefs:
1185 case eSectionTypeDataObjCCFStrings:
1186 case eSectionTypeGoSymtab:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001187 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001188
1189 case eSectionTypeDebug:
1190 case eSectionTypeDWARFDebugAbbrev:
George Rimar004bcb72018-11-14 13:01:15 +00001191 case eSectionTypeDWARFDebugAbbrevDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 case eSectionTypeDWARFDebugAddr:
1193 case eSectionTypeDWARFDebugAranges:
Tamas Berghammer963ce482017-08-25 13:56:14 +00001194 case eSectionTypeDWARFDebugCuIndex:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 case eSectionTypeDWARFDebugFrame:
1196 case eSectionTypeDWARFDebugInfo:
George Rimar004bcb72018-11-14 13:01:15 +00001197 case eSectionTypeDWARFDebugInfoDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 case eSectionTypeDWARFDebugLine:
George Rimarc6c7bfc2018-09-13 17:06:47 +00001199 case eSectionTypeDWARFDebugLineStr:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 case eSectionTypeDWARFDebugLoc:
George Rimare4dee262018-10-23 09:46:15 +00001201 case eSectionTypeDWARFDebugLocLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 case eSectionTypeDWARFDebugMacInfo:
1203 case eSectionTypeDWARFDebugMacro:
Pavel Labatha041d842018-06-01 12:06:45 +00001204 case eSectionTypeDWARFDebugNames:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 case eSectionTypeDWARFDebugPubNames:
1206 case eSectionTypeDWARFDebugPubTypes:
1207 case eSectionTypeDWARFDebugRanges:
George Rimar6e357122018-10-10 08:11:15 +00001208 case eSectionTypeDWARFDebugRngLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 case eSectionTypeDWARFDebugStr:
George Rimar004bcb72018-11-14 13:01:15 +00001210 case eSectionTypeDWARFDebugStrDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 case eSectionTypeDWARFDebugStrOffsets:
George Rimar004bcb72018-11-14 13:01:15 +00001212 case eSectionTypeDWARFDebugStrOffsetsDwo:
Greg Clayton2550ca12018-05-08 17:19:24 +00001213 case eSectionTypeDWARFDebugTypes:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 case eSectionTypeDWARFAppleNames:
1215 case eSectionTypeDWARFAppleTypes:
1216 case eSectionTypeDWARFAppleNamespaces:
1217 case eSectionTypeDWARFAppleObjC:
Jan Kratochvile4777a92018-04-29 19:47:48 +00001218 case eSectionTypeDWARFGNUDebugAltLink:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001219 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220
1221 case eSectionTypeEHFrame:
1222 case eSectionTypeARMexidx:
1223 case eSectionTypeARMextab:
1224 case eSectionTypeCompactUnwind:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001225 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226
1227 case eSectionTypeAbsoluteAddress:
1228 case eSectionTypeELFSymbolTable:
1229 case eSectionTypeELFDynamicSymbols:
1230 case eSectionTypeELFRelocationEntries:
1231 case eSectionTypeELFDynamicLinkInfo:
1232 case eSectionTypeOther:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001233 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234 }
1235 }
1236 }
1237
1238 const SymbolType symbol_type = symbol->GetType();
1239 switch (symbol_type) {
1240 case eSymbolTypeAny:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001241 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 case eSymbolTypeAbsolute:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001243 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244
1245 case eSymbolTypeCode:
1246 case eSymbolTypeTrampoline:
1247 case eSymbolTypeResolver:
1248 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001249 // For ARM we have a bit in the n_desc field of the symbol that tells
1250 // us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001252 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001254 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255
1256 case eSymbolTypeData:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001257 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 case eSymbolTypeRuntime:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001259 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260 case eSymbolTypeException:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001261 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 case eSymbolTypeSourceFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001263 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264 case eSymbolTypeHeaderFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001265 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 case eSymbolTypeObjectFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001267 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 case eSymbolTypeCommonBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001269 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 case eSymbolTypeBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001271 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 case eSymbolTypeLocal:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001273 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 case eSymbolTypeParam:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001275 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276 case eSymbolTypeVariable:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001277 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 case eSymbolTypeVariableType:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001279 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280 case eSymbolTypeLineEntry:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001281 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 case eSymbolTypeLineHeader:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001283 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 case eSymbolTypeScopeBegin:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001285 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 case eSymbolTypeScopeEnd:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001287 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 case eSymbolTypeAdditional:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001289 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 case eSymbolTypeCompiler:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001291 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292 case eSymbolTypeInstrumentation:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001293 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 case eSymbolTypeUndefined:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001295 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 case eSymbolTypeObjCClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001297 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 case eSymbolTypeObjCMetaClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001299 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 case eSymbolTypeObjCIVar:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001301 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302 case eSymbolTypeReExported:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001303 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 }
1305 }
1306 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001307 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001308}
1309
1310Symtab *ObjectFileMachO::GetSymtab() {
1311 ModuleSP module_sp(GetModule());
1312 if (module_sp) {
1313 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1314 if (m_symtab_ap.get() == NULL) {
1315 m_symtab_ap.reset(new Symtab(this));
1316 std::lock_guard<std::recursive_mutex> symtab_guard(
1317 m_symtab_ap->GetMutex());
1318 ParseSymtab();
Davide Italiano407c6912018-11-02 21:59:14 +00001319 m_symtab_ap->Finalize();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 }
1321 }
1322 return m_symtab_ap.get();
1323}
1324
1325bool ObjectFileMachO::IsStripped() {
1326 if (m_dysymtab.cmd == 0) {
1327 ModuleSP module_sp(GetModule());
1328 if (module_sp) {
1329 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1330 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1331 const lldb::offset_t load_cmd_offset = offset;
1332
1333 load_command lc;
1334 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
1335 break;
1336 if (lc.cmd == LC_DYSYMTAB) {
1337 m_dysymtab.cmd = lc.cmd;
1338 m_dysymtab.cmdsize = lc.cmdsize;
1339 if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1340 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1341 NULL) {
1342 // Clear m_dysymtab if we were unable to read all items from the
1343 // load command
1344 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1345 }
1346 }
1347 offset = load_cmd_offset + lc.cmdsize;
1348 }
1349 }
1350 }
1351 if (m_dysymtab.cmd)
1352 return m_dysymtab.nlocalsym <= 1;
1353 return false;
1354}
1355
Pavel Labathb417eea2018-03-06 13:53:26 +00001356ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
1357 EncryptedFileRanges result;
Pavel Labathf90054d2018-03-03 22:07:47 +00001358 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labathb417eea2018-03-06 13:53:26 +00001359
Pavel Labathf90054d2018-03-03 22:07:47 +00001360 encryption_info_command encryption_cmd;
Pavel Labathb417eea2018-03-06 13:53:26 +00001361 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001362 const lldb::offset_t load_cmd_offset = offset;
1363 if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL)
1364 break;
1365
Adrian Prantl05097242018-04-30 16:49:04 +00001366 // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1367 // 3 fields we care about, so treat them the same.
Pavel Labathf90054d2018-03-03 22:07:47 +00001368 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1369 encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1370 if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1371 if (encryption_cmd.cryptid != 0) {
1372 EncryptedFileRanges::Entry entry;
1373 entry.SetRangeBase(encryption_cmd.cryptoff);
1374 entry.SetByteSize(encryption_cmd.cryptsize);
Pavel Labathb417eea2018-03-06 13:53:26 +00001375 result.Append(entry);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376 }
1377 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 }
Pavel Labathf90054d2018-03-03 22:07:47 +00001379 offset = load_cmd_offset + encryption_cmd.cmdsize;
1380 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381
Pavel Labathb417eea2018-03-06 13:53:26 +00001382 return result;
1383}
1384
1385void ObjectFileMachO::SanitizeSegmentCommand(segment_command_64 &seg_cmd,
1386 uint32_t cmd_idx) {
1387 if (m_length == 0 || seg_cmd.filesize == 0)
1388 return;
1389
1390 if (seg_cmd.fileoff > m_length) {
1391 // We have a load command that says it extends past the end of the file.
1392 // This is likely a corrupt file. We don't have any way to return an error
1393 // condition here (this method was likely invoked from something like
1394 // ObjectFile::GetSectionList()), so we just null out the section contents,
1395 // and dump a message to stdout. The most common case here is core file
1396 // debugging with a truncated file.
1397 const char *lc_segment_name =
1398 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1399 GetModule()->ReportWarning(
1400 "load command %u %s has a fileoff (0x%" PRIx64
1401 ") that extends beyond the end of the file (0x%" PRIx64
1402 "), ignoring this section",
1403 cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
1404
1405 seg_cmd.fileoff = 0;
1406 seg_cmd.filesize = 0;
1407 }
1408
1409 if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1410 // We have a load command that says it extends past the end of the file.
1411 // This is likely a corrupt file. We don't have any way to return an error
1412 // condition here (this method was likely invoked from something like
1413 // ObjectFile::GetSectionList()), so we just null out the section contents,
1414 // and dump a message to stdout. The most common case here is core file
1415 // debugging with a truncated file.
1416 const char *lc_segment_name =
1417 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1418 GetModule()->ReportWarning(
1419 "load command %u %s has a fileoff + filesize (0x%" PRIx64
1420 ") that extends beyond the end of the file (0x%" PRIx64
1421 "), the segment will be truncated to match",
1422 cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
1423
1424 // Truncate the length
1425 seg_cmd.filesize = m_length - seg_cmd.fileoff;
1426 }
1427}
1428
1429static uint32_t GetSegmentPermissions(const segment_command_64 &seg_cmd) {
1430 uint32_t result = 0;
1431 if (seg_cmd.initprot & VM_PROT_READ)
1432 result |= ePermissionsReadable;
1433 if (seg_cmd.initprot & VM_PROT_WRITE)
1434 result |= ePermissionsWritable;
1435 if (seg_cmd.initprot & VM_PROT_EXECUTE)
1436 result |= ePermissionsExecutable;
1437 return result;
1438}
1439
1440static lldb::SectionType GetSectionType(uint32_t flags,
1441 ConstString section_name) {
1442
1443 if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1444 return eSectionTypeCode;
1445
1446 uint32_t mach_sect_type = flags & SECTION_TYPE;
1447 static ConstString g_sect_name_objc_data("__objc_data");
1448 static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1449 static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1450 static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
1451 static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
1452 static ConstString g_sect_name_objc_const("__objc_const");
1453 static ConstString g_sect_name_objc_classlist("__objc_classlist");
1454 static ConstString g_sect_name_cfstring("__cfstring");
1455
1456 static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
1457 static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1458 static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1459 static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1460 static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1461 static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
George Rimare4dee262018-10-23 09:46:15 +00001462 static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
Pavel Labathb417eea2018-03-06 13:53:26 +00001463 static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
Pavel Labatha041d842018-06-01 12:06:45 +00001464 static ConstString g_sect_name_dwarf_debug_names("__debug_names");
Pavel Labathb417eea2018-03-06 13:53:26 +00001465 static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1466 static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1467 static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1468 static ConstString g_sect_name_dwarf_debug_str("__debug_str");
Greg Clayton2550ca12018-05-08 17:19:24 +00001469 static ConstString g_sect_name_dwarf_debug_types("__debug_types");
Pavel Labathb417eea2018-03-06 13:53:26 +00001470 static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1471 static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1472 static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1473 static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1474 static ConstString g_sect_name_eh_frame("__eh_frame");
1475 static ConstString g_sect_name_compact_unwind("__unwind_info");
1476 static ConstString g_sect_name_text("__text");
1477 static ConstString g_sect_name_data("__data");
1478 static ConstString g_sect_name_go_symtab("__gosymtab");
1479
1480 if (section_name == g_sect_name_dwarf_debug_abbrev)
1481 return eSectionTypeDWARFDebugAbbrev;
1482 if (section_name == g_sect_name_dwarf_debug_aranges)
1483 return eSectionTypeDWARFDebugAranges;
1484 if (section_name == g_sect_name_dwarf_debug_frame)
1485 return eSectionTypeDWARFDebugFrame;
1486 if (section_name == g_sect_name_dwarf_debug_info)
1487 return eSectionTypeDWARFDebugInfo;
1488 if (section_name == g_sect_name_dwarf_debug_line)
1489 return eSectionTypeDWARFDebugLine;
1490 if (section_name == g_sect_name_dwarf_debug_loc)
1491 return eSectionTypeDWARFDebugLoc;
George Rimare4dee262018-10-23 09:46:15 +00001492 if (section_name == g_sect_name_dwarf_debug_loclists)
1493 return eSectionTypeDWARFDebugLocLists;
Pavel Labathb417eea2018-03-06 13:53:26 +00001494 if (section_name == g_sect_name_dwarf_debug_macinfo)
1495 return eSectionTypeDWARFDebugMacInfo;
Pavel Labatha041d842018-06-01 12:06:45 +00001496 if (section_name == g_sect_name_dwarf_debug_names)
1497 return eSectionTypeDWARFDebugNames;
Pavel Labathb417eea2018-03-06 13:53:26 +00001498 if (section_name == g_sect_name_dwarf_debug_pubnames)
1499 return eSectionTypeDWARFDebugPubNames;
1500 if (section_name == g_sect_name_dwarf_debug_pubtypes)
1501 return eSectionTypeDWARFDebugPubTypes;
1502 if (section_name == g_sect_name_dwarf_debug_ranges)
George Rimar6e357122018-10-10 08:11:15 +00001503 return eSectionTypeDWARFDebugRanges;
Pavel Labathb417eea2018-03-06 13:53:26 +00001504 if (section_name == g_sect_name_dwarf_debug_str)
1505 return eSectionTypeDWARFDebugStr;
Greg Clayton2550ca12018-05-08 17:19:24 +00001506 if (section_name == g_sect_name_dwarf_debug_types)
1507 return eSectionTypeDWARFDebugTypes;
Pavel Labathb417eea2018-03-06 13:53:26 +00001508 if (section_name == g_sect_name_dwarf_apple_names)
1509 return eSectionTypeDWARFAppleNames;
1510 if (section_name == g_sect_name_dwarf_apple_types)
1511 return eSectionTypeDWARFAppleTypes;
1512 if (section_name == g_sect_name_dwarf_apple_namespaces)
1513 return eSectionTypeDWARFAppleNamespaces;
1514 if (section_name == g_sect_name_dwarf_apple_objc)
1515 return eSectionTypeDWARFAppleObjC;
1516 if (section_name == g_sect_name_objc_selrefs)
1517 return eSectionTypeDataCStringPointers;
1518 if (section_name == g_sect_name_objc_msgrefs)
1519 return eSectionTypeDataObjCMessageRefs;
1520 if (section_name == g_sect_name_eh_frame)
1521 return eSectionTypeEHFrame;
1522 if (section_name == g_sect_name_compact_unwind)
1523 return eSectionTypeCompactUnwind;
1524 if (section_name == g_sect_name_cfstring)
1525 return eSectionTypeDataObjCCFStrings;
1526 if (section_name == g_sect_name_go_symtab)
1527 return eSectionTypeGoSymtab;
1528 if (section_name == g_sect_name_objc_data ||
1529 section_name == g_sect_name_objc_classrefs ||
1530 section_name == g_sect_name_objc_superrefs ||
1531 section_name == g_sect_name_objc_const ||
1532 section_name == g_sect_name_objc_classlist) {
1533 return eSectionTypeDataPointers;
1534 }
1535
1536 switch (mach_sect_type) {
1537 // TODO: categorize sections by other flags for regular sections
1538 case S_REGULAR:
1539 if (section_name == g_sect_name_text)
1540 return eSectionTypeCode;
1541 if (section_name == g_sect_name_data)
1542 return eSectionTypeData;
1543 return eSectionTypeOther;
1544 case S_ZEROFILL:
1545 return eSectionTypeZeroFill;
1546 case S_CSTRING_LITERALS: // section with only literal C strings
1547 return eSectionTypeDataCString;
1548 case S_4BYTE_LITERALS: // section with only 4 byte literals
1549 return eSectionTypeData4;
1550 case S_8BYTE_LITERALS: // section with only 8 byte literals
1551 return eSectionTypeData8;
1552 case S_LITERAL_POINTERS: // section with only pointers to literals
1553 return eSectionTypeDataPointers;
1554 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1555 return eSectionTypeDataPointers;
1556 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1557 return eSectionTypeDataPointers;
1558 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1559 // the reserved2 field
1560 return eSectionTypeCode;
1561 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1562 // initialization
1563 return eSectionTypeDataPointers;
1564 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1565 // termination
1566 return eSectionTypeDataPointers;
1567 case S_COALESCED:
1568 return eSectionTypeOther;
1569 case S_GB_ZEROFILL:
1570 return eSectionTypeZeroFill;
1571 case S_INTERPOSING: // section with only pairs of function pointers for
1572 // interposing
1573 return eSectionTypeCode;
1574 case S_16BYTE_LITERALS: // section with only 16 byte literals
1575 return eSectionTypeData16;
1576 case S_DTRACE_DOF:
1577 return eSectionTypeDebug;
1578 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1579 return eSectionTypeDataPointers;
1580 default:
1581 return eSectionTypeOther;
1582 }
1583}
1584
1585struct ObjectFileMachO::SegmentParsingContext {
1586 const EncryptedFileRanges EncryptedRanges;
1587 lldb_private::SectionList &UnifiedList;
1588 uint32_t NextSegmentIdx = 0;
1589 uint32_t NextSectionIdx = 0;
1590 bool FileAddressesChanged = false;
1591
1592 SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
1593 lldb_private::SectionList &UnifiedList)
1594 : EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
1595};
1596
1597void ObjectFileMachO::ProcessSegmentCommand(const load_command &load_cmd_,
1598 lldb::offset_t offset,
1599 uint32_t cmd_idx,
1600 SegmentParsingContext &context) {
1601 segment_command_64 load_cmd;
1602 memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1603
1604 if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1605 return;
1606
1607 ModuleSP module_sp = GetModule();
1608 const bool is_core = GetType() == eTypeCoreFile;
1609 const bool is_dsym = (m_header.filetype == MH_DSYM);
1610 bool add_section = true;
1611 bool add_to_unified = true;
1612 ConstString const_segname(
1613 load_cmd.segname,
1614 std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname)));
1615
1616 SectionSP unified_section_sp(
1617 context.UnifiedList.FindSectionByName(const_segname));
1618 if (is_dsym && unified_section_sp) {
1619 if (const_segname == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001620 // We need to keep the __LINKEDIT segment private to this object file
1621 // only
Pavel Labathb417eea2018-03-06 13:53:26 +00001622 add_to_unified = false;
1623 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001624 // This is the dSYM file and this section has already been created by the
1625 // object file, no need to create it.
Pavel Labathb417eea2018-03-06 13:53:26 +00001626 add_section = false;
1627 }
1628 }
1629 load_cmd.vmaddr = m_data.GetAddress(&offset);
1630 load_cmd.vmsize = m_data.GetAddress(&offset);
1631 load_cmd.fileoff = m_data.GetAddress(&offset);
1632 load_cmd.filesize = m_data.GetAddress(&offset);
1633 if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1634 return;
1635
1636 SanitizeSegmentCommand(load_cmd, cmd_idx);
1637
1638 const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1639 const bool segment_is_encrypted =
1640 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1641
Adrian Prantl05097242018-04-30 16:49:04 +00001642 // Keep a list of mach segments around in case we need to get at data that
1643 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001644 m_mach_segments.push_back(load_cmd);
1645
Adrian Prantl05097242018-04-30 16:49:04 +00001646 // Use a segment ID of the segment index shifted left by 8 so they never
1647 // conflict with any of the sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001648 SectionSP segment_sp;
1649 if (add_section && (const_segname || is_core)) {
1650 segment_sp.reset(new Section(
1651 module_sp, // Module to which this section belongs
1652 this, // Object file to which this sections belongs
1653 ++context.NextSegmentIdx
1654 << 8, // Section ID is the 1 based segment index
Adrian Prantl05097242018-04-30 16:49:04 +00001655 // shifted right by 8 bits as not to collide with any of the 256
1656 // section IDs that are possible
Pavel Labathb417eea2018-03-06 13:53:26 +00001657 const_segname, // Name of this section
1658 eSectionTypeContainer, // This section is a container of other
1659 // sections.
1660 load_cmd.vmaddr, // File VM address == addresses as they are
1661 // found in the object file
1662 load_cmd.vmsize, // VM size in bytes of this section
1663 load_cmd.fileoff, // Offset to the data for this section in
1664 // the file
1665 load_cmd.filesize, // Size in bytes of this section as found
1666 // in the file
1667 0, // Segments have no alignment information
1668 load_cmd.flags)); // Flags for this section
1669
1670 segment_sp->SetIsEncrypted(segment_is_encrypted);
1671 m_sections_ap->AddSection(segment_sp);
1672 segment_sp->SetPermissions(segment_permissions);
1673 if (add_to_unified)
1674 context.UnifiedList.AddSection(segment_sp);
1675 } else if (unified_section_sp) {
1676 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1677 // Check to see if the module was read from memory?
Pavel Labathd1e3fe22018-12-11 15:21:15 +00001678 if (module_sp->GetObjectFile()->GetBaseAddress().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001679 // We have a module that is in memory and needs to have its file
1680 // address adjusted. We need to do this because when we load a file
1681 // from memory, its addresses will be slid already, yet the addresses
1682 // in the new symbol file will still be unslid. Since everything is
1683 // stored as section offset, this shouldn't cause any problems.
Pavel Labathb417eea2018-03-06 13:53:26 +00001684
Adrian Prantl05097242018-04-30 16:49:04 +00001685 // Make sure we've parsed the symbol table from the ObjectFile before
1686 // we go around changing its Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001687 module_sp->GetObjectFile()->GetSymtab();
Adrian Prantl05097242018-04-30 16:49:04 +00001688 // eh_frame would present the same problems but we parse that on a per-
1689 // function basis as-needed so it's more difficult to remove its use of
1690 // the Sections. Realistically, the environments where this code path
1691 // will be taken will not have eh_frame sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001692
1693 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1694
Adrian Prantl05097242018-04-30 16:49:04 +00001695 // Notify the module that the section addresses have been changed once
1696 // we're done so any file-address caches can be updated.
Pavel Labathb417eea2018-03-06 13:53:26 +00001697 context.FileAddressesChanged = true;
1698 }
1699 }
1700 m_sections_ap->AddSection(unified_section_sp);
1701 }
1702
1703 struct section_64 sect64;
1704 ::memset(&sect64, 0, sizeof(sect64));
Adrian Prantl05097242018-04-30 16:49:04 +00001705 // Push a section into our mach sections for the section at index zero
1706 // (NO_SECT) if we don't have any mach sections yet...
Pavel Labathb417eea2018-03-06 13:53:26 +00001707 if (m_mach_sections.empty())
1708 m_mach_sections.push_back(sect64);
1709 uint32_t segment_sect_idx;
1710 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1711
1712 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1713 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1714 ++segment_sect_idx) {
1715 if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1716 sizeof(sect64.sectname)) == NULL)
1717 break;
1718 if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1719 sizeof(sect64.segname)) == NULL)
1720 break;
1721 sect64.addr = m_data.GetAddress(&offset);
1722 sect64.size = m_data.GetAddress(&offset);
1723
1724 if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
1725 break;
1726
Adrian Prantl05097242018-04-30 16:49:04 +00001727 // Keep a list of mach sections around in case we need to get at data that
1728 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001729 m_mach_sections.push_back(sect64);
1730
1731 if (add_section) {
1732 ConstString section_name(
1733 sect64.sectname,
1734 std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname)));
1735 if (!const_segname) {
Adrian Prantl05097242018-04-30 16:49:04 +00001736 // We have a segment with no name so we need to conjure up segments
1737 // that correspond to the section's segname if there isn't already such
1738 // a section. If there is such a section, we resize the section so that
1739 // it spans all sections. We also mark these sections as fake so
1740 // address matches don't hit if they land in the gaps between the child
1741 // sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001742 const_segname.SetTrimmedCStringWithLength(sect64.segname,
1743 sizeof(sect64.segname));
1744 segment_sp = context.UnifiedList.FindSectionByName(const_segname);
1745 if (segment_sp.get()) {
1746 Section *segment = segment_sp.get();
1747 // Grow the section size as needed.
1748 const lldb::addr_t sect64_min_addr = sect64.addr;
1749 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1750 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1751 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1752 const lldb::addr_t curr_seg_max_addr =
1753 curr_seg_min_addr + curr_seg_byte_size;
1754 if (sect64_min_addr >= curr_seg_min_addr) {
1755 const lldb::addr_t new_seg_byte_size =
1756 sect64_max_addr - curr_seg_min_addr;
1757 // Only grow the section size if needed
1758 if (new_seg_byte_size > curr_seg_byte_size)
1759 segment->SetByteSize(new_seg_byte_size);
1760 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001761 // We need to change the base address of the segment and adjust the
1762 // child section offsets for all existing children.
Pavel Labathb417eea2018-03-06 13:53:26 +00001763 const lldb::addr_t slide_amount =
1764 sect64_min_addr - curr_seg_min_addr;
1765 segment->Slide(slide_amount, false);
1766 segment->GetChildren().Slide(-slide_amount, false);
1767 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1768 }
1769
1770 // Grow the section size as needed.
1771 if (sect64.offset) {
1772 const lldb::addr_t segment_min_file_offset =
1773 segment->GetFileOffset();
1774 const lldb::addr_t segment_max_file_offset =
1775 segment_min_file_offset + segment->GetFileSize();
1776
1777 const lldb::addr_t section_min_file_offset = sect64.offset;
1778 const lldb::addr_t section_max_file_offset =
1779 section_min_file_offset + sect64.size;
1780 const lldb::addr_t new_file_offset =
1781 std::min(section_min_file_offset, segment_min_file_offset);
1782 const lldb::addr_t new_file_size =
1783 std::max(section_max_file_offset, segment_max_file_offset) -
1784 new_file_offset;
1785 segment->SetFileOffset(new_file_offset);
1786 segment->SetFileSize(new_file_size);
1787 }
1788 } else {
1789 // Create a fake section for the section's named segment
1790 segment_sp.reset(new Section(
1791 segment_sp, // Parent section
1792 module_sp, // Module to which this section belongs
1793 this, // Object file to which this section belongs
1794 ++context.NextSegmentIdx
1795 << 8, // Section ID is the 1 based segment index
1796 // shifted right by 8 bits as not to
1797 // collide with any of the 256 section IDs
1798 // that are possible
1799 const_segname, // Name of this section
1800 eSectionTypeContainer, // This section is a container of
1801 // other sections.
1802 sect64.addr, // File VM address == addresses as they are
1803 // found in the object file
1804 sect64.size, // VM size in bytes of this section
1805 sect64.offset, // Offset to the data for this section in
1806 // the file
1807 sect64.offset ? sect64.size : 0, // Size in bytes of
1808 // this section as
1809 // found in the file
1810 sect64.align,
1811 load_cmd.flags)); // Flags for this section
1812 segment_sp->SetIsFake(true);
1813 segment_sp->SetPermissions(segment_permissions);
1814 m_sections_ap->AddSection(segment_sp);
1815 if (add_to_unified)
1816 context.UnifiedList.AddSection(segment_sp);
1817 segment_sp->SetIsEncrypted(segment_is_encrypted);
1818 }
1819 }
1820 assert(segment_sp.get());
1821
1822 lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1823
1824 SectionSP section_sp(new Section(
1825 segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1826 sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1827 sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1828 sect64.flags));
1829 // Set the section to be encrypted to match the segment
1830
1831 bool section_is_encrypted = false;
1832 if (!segment_is_encrypted && load_cmd.filesize != 0)
1833 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1834 sect64.offset) != NULL;
1835
1836 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1837 section_sp->SetPermissions(segment_permissions);
1838 segment_sp->GetChildren().AddSection(section_sp);
1839
1840 if (segment_sp->IsFake()) {
1841 segment_sp.reset();
1842 const_segname.Clear();
1843 }
1844 }
1845 }
1846 if (segment_sp && is_dsym) {
1847 if (first_segment_sectID <= context.NextSectionIdx) {
1848 lldb::user_id_t sect_uid;
1849 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1850 ++sect_uid) {
1851 SectionSP curr_section_sp(
1852 segment_sp->GetChildren().FindSectionByID(sect_uid));
1853 SectionSP next_section_sp;
1854 if (sect_uid + 1 <= context.NextSectionIdx)
1855 next_section_sp =
1856 segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1857
1858 if (curr_section_sp.get()) {
1859 if (curr_section_sp->GetByteSize() == 0) {
1860 if (next_section_sp.get() != NULL)
1861 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1862 curr_section_sp->GetFileAddress());
1863 else
1864 curr_section_sp->SetByteSize(load_cmd.vmsize);
1865 }
1866 }
1867 }
1868 }
1869 }
1870}
1871
1872void ObjectFileMachO::ProcessDysymtabCommand(const load_command &load_cmd,
1873 lldb::offset_t offset) {
1874 m_dysymtab.cmd = load_cmd.cmd;
1875 m_dysymtab.cmdsize = load_cmd.cmdsize;
1876 m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1877 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1878}
1879
1880void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1881 if (m_sections_ap)
1882 return;
1883
1884 m_sections_ap.reset(new SectionList());
1885
1886 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1887 // bool dump_sections = false;
1888 ModuleSP module_sp(GetModule());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001889
Pavel Labathf90054d2018-03-03 22:07:47 +00001890 offset = MachHeaderSizeFromMagic(m_header.magic);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001891
Pavel Labathb417eea2018-03-06 13:53:26 +00001892 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1893 struct load_command load_cmd;
1894 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001895 const lldb::offset_t load_cmd_offset = offset;
1896 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
1897 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001898
Pavel Labathb417eea2018-03-06 13:53:26 +00001899 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1900 ProcessSegmentCommand(load_cmd, offset, i, context);
1901 else if (load_cmd.cmd == LC_DYSYMTAB)
1902 ProcessDysymtabCommand(load_cmd, offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903
Pavel Labathf90054d2018-03-03 22:07:47 +00001904 offset = load_cmd_offset + load_cmd.cmdsize;
1905 }
1906
Pavel Labathb417eea2018-03-06 13:53:26 +00001907 if (context.FileAddressesChanged && module_sp)
Pavel Labathf90054d2018-03-03 22:07:47 +00001908 module_sp->SectionFileAddressesChanged();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001909}
1910
1911class MachSymtabSectionInfo {
1912public:
1913 MachSymtabSectionInfo(SectionList *section_list)
1914 : m_section_list(section_list), m_section_infos() {
Adrian Prantl05097242018-04-30 16:49:04 +00001915 // Get the number of sections down to a depth of 1 to include all segments
1916 // and their sections, but no other sections that may be added for debug
1917 // map or
Kate Stoneb9c1b512016-09-06 20:57:50 +00001918 m_section_infos.resize(section_list->GetNumSections(1));
1919 }
1920
1921 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1922 if (n_sect == 0)
1923 return SectionSP();
1924 if (n_sect < m_section_infos.size()) {
1925 if (!m_section_infos[n_sect].section_sp) {
1926 SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1927 m_section_infos[n_sect].section_sp = section_sp;
1928 if (section_sp) {
1929 m_section_infos[n_sect].vm_range.SetBaseAddress(
1930 section_sp->GetFileAddress());
1931 m_section_infos[n_sect].vm_range.SetByteSize(
1932 section_sp->GetByteSize());
1933 } else {
1934 Host::SystemLog(Host::eSystemLogError,
1935 "error: unable to find section for section %u\n",
1936 n_sect);
1937 }
1938 }
1939 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1940 // Symbol is in section.
1941 return m_section_infos[n_sect].section_sp;
1942 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1943 m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1944 file_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001945 // Symbol is in section with zero size, but has the same start address
1946 // as the section. This can happen with linker symbols (symbols that
1947 // start with the letter 'l' or 'L'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948 return m_section_infos[n_sect].section_sp;
1949 }
1950 }
1951 return m_section_list->FindSectionContainingFileAddress(file_addr);
1952 }
1953
1954protected:
1955 struct SectionInfo {
1956 SectionInfo() : vm_range(), section_sp() {}
1957
1958 VMRange vm_range;
1959 SectionSP section_sp;
1960 };
1961 SectionList *m_section_list;
1962 std::vector<SectionInfo> m_section_infos;
1963};
1964
1965struct TrieEntry {
1966 TrieEntry()
1967 : name(), address(LLDB_INVALID_ADDRESS), flags(0), other(0),
1968 import_name() {}
1969
1970 void Clear() {
1971 name.Clear();
1972 address = LLDB_INVALID_ADDRESS;
1973 flags = 0;
1974 other = 0;
1975 import_name.Clear();
1976 }
1977
1978 void Dump() const {
1979 printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
1980 static_cast<unsigned long long>(address),
1981 static_cast<unsigned long long>(flags),
1982 static_cast<unsigned long long>(other), name.GetCString());
1983 if (import_name)
1984 printf(" -> \"%s\"\n", import_name.GetCString());
1985 else
1986 printf("\n");
1987 }
1988 ConstString name;
1989 uint64_t address;
1990 uint64_t flags;
1991 uint64_t other;
1992 ConstString import_name;
1993};
1994
1995struct TrieEntryWithOffset {
1996 lldb::offset_t nodeOffset;
1997 TrieEntry entry;
1998
1999 TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
2000
2001 void Dump(uint32_t idx) const {
2002 printf("[%3u] 0x%16.16llx: ", idx,
2003 static_cast<unsigned long long>(nodeOffset));
2004 entry.Dump();
2005 }
2006
2007 bool operator<(const TrieEntryWithOffset &other) const {
2008 return (nodeOffset < other.nodeOffset);
2009 }
2010};
2011
2012static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
2013 const bool is_arm,
2014 std::vector<llvm::StringRef> &nameSlices,
2015 std::set<lldb::addr_t> &resolver_addresses,
2016 std::vector<TrieEntryWithOffset> &output) {
2017 if (!data.ValidOffset(offset))
Greg Clayton8f265f72015-10-28 20:49:34 +00002018 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019
2020 const uint64_t terminalSize = data.GetULEB128(&offset);
2021 lldb::offset_t children_offset = offset + terminalSize;
2022 if (terminalSize != 0) {
2023 TrieEntryWithOffset e(offset);
2024 e.entry.flags = data.GetULEB128(&offset);
2025 const char *import_name = NULL;
2026 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2027 e.entry.address = 0;
2028 e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2029 import_name = data.GetCStr(&offset);
2030 } else {
2031 e.entry.address = data.GetULEB128(&offset);
2032 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2033 e.entry.other = data.GetULEB128(&offset);
2034 uint64_t resolver_addr = e.entry.other;
2035 if (is_arm)
2036 resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2037 resolver_addresses.insert(resolver_addr);
2038 } else
2039 e.entry.other = 0;
2040 }
2041 // Only add symbols that are reexport symbols with a valid import name
2042 if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name &&
2043 import_name[0]) {
2044 std::string name;
2045 if (!nameSlices.empty()) {
2046 for (auto name_slice : nameSlices)
2047 name.append(name_slice.data(), name_slice.size());
2048 }
2049 if (name.size() > 1) {
2050 // Skip the leading '_'
2051 e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2052 }
2053 if (import_name) {
2054 // Skip the leading '_'
2055 e.entry.import_name.SetCString(import_name + 1);
2056 }
2057 output.push_back(e);
2058 }
2059 }
2060
2061 const uint8_t childrenCount = data.GetU8(&children_offset);
2062 for (uint8_t i = 0; i < childrenCount; ++i) {
2063 const char *cstr = data.GetCStr(&children_offset);
2064 if (cstr)
2065 nameSlices.push_back(llvm::StringRef(cstr));
2066 else
2067 return false; // Corrupt data
2068 lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2069 if (childNodeOffset) {
2070 if (!ParseTrieEntries(data, childNodeOffset, is_arm, nameSlices,
2071 resolver_addresses, output)) {
2072 return false;
2073 }
2074 }
2075 nameSlices.pop_back();
2076 }
2077 return true;
Greg Clayton9191db42013-10-21 18:40:51 +00002078}
2079
Jason Molenda649a6072015-11-10 05:21:54 +00002080// Read the UUID out of a dyld_shared_cache file on-disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
2082 const ByteOrder byte_order,
2083 const uint32_t addr_byte_size) {
2084 UUID dsc_uuid;
Pavel Labath50251fc2017-12-21 10:54:30 +00002085 DataBufferSP DscData = MapFileData(
2086 dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002087 if (!DscData)
2088 return dsc_uuid;
2089 DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
Jason Molenda649a6072015-11-10 05:21:54 +00002090
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002091 char version_str[7];
2092 lldb::offset_t offset = 0;
2093 memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
2094 version_str[6] = '\0';
2095 if (strcmp(version_str, "dyld_v") == 0) {
2096 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
Pavel Labath2f93fd12018-06-26 15:12:20 +00002097 dsc_uuid = UUID::fromOptionalData(
2098 dsc_header_data.GetData(&offset, sizeof(uuid_t)), sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099 }
Jason Molendafd443e92018-02-07 01:28:29 +00002100 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2101 if (log && dsc_uuid.IsValid()) {
2102 log->Printf("Shared cache %s has UUID %s", dyld_shared_cache.GetPath().c_str(),
2103 dsc_uuid.GetAsString().c_str());
2104 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105 return dsc_uuid;
Jason Molenda649a6072015-11-10 05:21:54 +00002106}
2107
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108size_t ObjectFileMachO::ParseSymtab() {
Pavel Labathf9d16472017-05-15 13:02:37 +00002109 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2110 Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002111 m_file.GetFilename().AsCString(""));
2112 ModuleSP module_sp(GetModule());
2113 if (!module_sp)
2114 return 0;
2115
2116 struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2117 struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2118 struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2119 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2120 FunctionStarts function_starts;
2121 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2122 uint32_t i;
2123 FileSpecList dylib_files;
2124 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2125 static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2126 static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2127 static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2128
2129 for (i = 0; i < m_header.ncmds; ++i) {
2130 const lldb::offset_t cmd_offset = offset;
2131 // Read in the load command and load command size
2132 struct load_command lc;
2133 if (m_data.GetU32(&offset, &lc, 2) == NULL)
2134 break;
2135 // Watch for the symbol table load command
2136 switch (lc.cmd) {
2137 case LC_SYMTAB:
2138 symtab_load_command.cmd = lc.cmd;
2139 symtab_load_command.cmdsize = lc.cmdsize;
2140 // Read in the rest of the symtab load command
2141 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2142 0) // fill in symoff, nsyms, stroff, strsize fields
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002143 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144 if (symtab_load_command.symoff == 0) {
2145 if (log)
2146 module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2147 return 0;
2148 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002149
Kate Stoneb9c1b512016-09-06 20:57:50 +00002150 if (symtab_load_command.stroff == 0) {
2151 if (log)
2152 module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2153 return 0;
2154 }
Greg Clayton77ccca72011-12-30 00:32:24 +00002155
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156 if (symtab_load_command.nsyms == 0) {
2157 if (log)
2158 module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
2159 return 0;
2160 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002161
Kate Stoneb9c1b512016-09-06 20:57:50 +00002162 if (symtab_load_command.strsize == 0) {
2163 if (log)
2164 module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2165 return 0;
2166 }
2167 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002168
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 case LC_DYLD_INFO:
2170 case LC_DYLD_INFO_ONLY:
2171 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2172 dyld_info.cmd = lc.cmd;
2173 dyld_info.cmdsize = lc.cmdsize;
2174 } else {
2175 memset(&dyld_info, 0, sizeof(dyld_info));
2176 }
2177 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002178
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179 case LC_LOAD_DYLIB:
2180 case LC_LOAD_WEAK_DYLIB:
2181 case LC_REEXPORT_DYLIB:
2182 case LC_LOADFVMLIB:
2183 case LC_LOAD_UPWARD_DYLIB: {
2184 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2185 const char *path = m_data.PeekCStr(name_offset);
2186 if (path) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002187 FileSpec file_spec(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188 // Strip the path if there is @rpath, @executable, etc so we just use
2189 // the basename
2190 if (path[0] == '@')
2191 file_spec.GetDirectory().Clear();
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002192
Kate Stoneb9c1b512016-09-06 20:57:50 +00002193 if (lc.cmd == LC_REEXPORT_DYLIB) {
2194 m_reexported_dylibs.AppendIfUnique(file_spec);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002195 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196
2197 dylib_files.Append(file_spec);
2198 }
2199 } break;
2200
2201 case LC_FUNCTION_STARTS:
2202 function_starts_load_command.cmd = lc.cmd;
2203 function_starts_load_command.cmdsize = lc.cmdsize;
2204 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2205 NULL) // fill in symoff, nsyms, stroff, strsize fields
2206 memset(&function_starts_load_command, 0,
2207 sizeof(function_starts_load_command));
2208 break;
2209
2210 default:
2211 break;
2212 }
2213 offset = cmd_offset + lc.cmdsize;
2214 }
2215
2216 if (symtab_load_command.cmd) {
2217 Symtab *symtab = m_symtab_ap.get();
2218 SectionList *section_list = GetSectionList();
2219 if (section_list == NULL)
2220 return 0;
2221
2222 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2223 const ByteOrder byte_order = m_data.GetByteOrder();
2224 bool bit_width_32 = addr_byte_size == 4;
2225 const size_t nlist_byte_size =
2226 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2227
2228 DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size);
2229 DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size);
2230 DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size);
2231 DataExtractor indirect_symbol_index_data(NULL, 0, byte_order,
2232 addr_byte_size);
2233 DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size);
2234
2235 const addr_t nlist_data_byte_size =
2236 symtab_load_command.nsyms * nlist_byte_size;
2237 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2238 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2239
2240 ProcessSP process_sp(m_process_wp.lock());
2241 Process *process = process_sp.get();
2242
2243 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2244
2245 if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2246 Target &target = process->GetTarget();
2247
2248 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2249
2250 SectionSP linkedit_section_sp(
2251 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2252 // Reading mach file from memory in a process or core file...
2253
2254 if (linkedit_section_sp) {
2255 addr_t linkedit_load_addr =
2256 linkedit_section_sp->GetLoadBaseAddress(&target);
2257 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2258 // We might be trying to access the symbol table before the
Adrian Prantl05097242018-04-30 16:49:04 +00002259 // __LINKEDIT's load address has been set in the target. We can't
2260 // fail to read the symbol table, so calculate the right address
2261 // manually
Kate Stoneb9c1b512016-09-06 20:57:50 +00002262 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2263 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2264 }
2265
2266 const addr_t linkedit_file_offset =
2267 linkedit_section_sp->GetFileOffset();
2268 const addr_t symoff_addr = linkedit_load_addr +
2269 symtab_load_command.symoff -
2270 linkedit_file_offset;
2271 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2272 linkedit_file_offset;
2273
2274 bool data_was_read = false;
2275
2276#if defined(__APPLE__) && \
2277 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2278 if (m_header.flags & 0x80000000u &&
2279 process->GetAddressByteSize() == sizeof(void *)) {
2280 // This mach-o memory file is in the dyld shared cache. If this
2281 // program is not remote and this is iOS, then this process will
Adrian Prantl05097242018-04-30 16:49:04 +00002282 // share the same shared cache as the process we are debugging and we
2283 // can read the entire __LINKEDIT from the address space in this
Kate Stoneb9c1b512016-09-06 20:57:50 +00002284 // process. This is a needed optimization that is used for local iOS
2285 // debugging only since all shared libraries in the shared cache do
2286 // not have corresponding files that exist in the file system of the
2287 // device. They have been combined into a single file. This means we
2288 // always have to load these files from memory. All of the symbol and
2289 // string tables from all of the __LINKEDIT sections from the shared
2290 // libraries in the shared cache have been merged into a single large
2291 // symbol and string table. Reading all of this symbol and string
Adrian Prantl05097242018-04-30 16:49:04 +00002292 // table data across can slow down debug launch times, so we optimize
2293 // this by reading the memory for the __LINKEDIT section from this
2294 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295
Jason Molenda07580ff2018-05-04 00:59:37 +00002296 UUID lldb_shared_cache;
2297 addr_t lldb_shared_cache_addr;
2298 GetLLDBSharedCacheUUID (lldb_shared_cache_addr, lldb_shared_cache);
2299 UUID process_shared_cache;
2300 addr_t process_shared_cache_addr;
2301 GetProcessSharedCacheUUID(process, process_shared_cache_addr, process_shared_cache);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302 bool use_lldb_cache = true;
2303 if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
Jason Molenda07580ff2018-05-04 00:59:37 +00002304 (lldb_shared_cache != process_shared_cache
2305 || process_shared_cache_addr != lldb_shared_cache_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306 use_lldb_cache = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002307 }
2308
2309 PlatformSP platform_sp(target.GetPlatform());
2310 if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2311 data_was_read = true;
2312 nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2313 eByteOrderLittle);
2314 strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2315 eByteOrderLittle);
2316 if (function_starts_load_command.cmd) {
2317 const addr_t func_start_addr =
2318 linkedit_load_addr + function_starts_load_command.dataoff -
2319 linkedit_file_offset;
2320 function_starts_data.SetData(
2321 (void *)func_start_addr,
2322 function_starts_load_command.datasize, eByteOrderLittle);
2323 }
2324 }
2325 }
2326#endif
2327
2328 if (!data_was_read) {
2329 // Always load dyld - the dynamic linker - from memory if we didn't
Adrian Prantl05097242018-04-30 16:49:04 +00002330 // find a binary anywhere else. lldb will not register
2331 // dylib/framework/bundle loads/unloads if we don't have the dyld
2332 // symbols, we force dyld to load from memory despite the user's
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333 // target.memory-module-load-level setting.
2334 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2335 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2336 DataBufferSP nlist_data_sp(
2337 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2338 if (nlist_data_sp)
2339 nlist_data.SetData(nlist_data_sp, 0,
2340 nlist_data_sp->GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 if (m_dysymtab.nindirectsyms != 0) {
2342 const addr_t indirect_syms_addr = linkedit_load_addr +
2343 m_dysymtab.indirectsymoff -
2344 linkedit_file_offset;
2345 DataBufferSP indirect_syms_data_sp(
2346 ReadMemory(process_sp, indirect_syms_addr,
2347 m_dysymtab.nindirectsyms * 4));
2348 if (indirect_syms_data_sp)
2349 indirect_symbol_index_data.SetData(
2350 indirect_syms_data_sp, 0,
2351 indirect_syms_data_sp->GetByteSize());
Jason Molendab0d33e92018-09-06 00:55:27 +00002352 // If this binary is outside the shared cache,
2353 // cache the string table.
2354 // Binaries in the shared cache all share a giant string table, and
2355 // we can't share the string tables across multiple ObjectFileMachO's,
2356 // so we'd end up re-reading this mega-strtab for every binary
2357 // in the shared cache - it would be a big perf problem.
2358 // For binaries outside the shared cache, it's faster to read the
2359 // entire strtab at once instead of piece-by-piece as we process
2360 // the nlist records.
2361 if ((m_header.flags & 0x80000000u) == 0) {
2362 DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr,
2363 strtab_data_byte_size));
2364 if (strtab_data_sp) {
2365 strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
2366 }
2367 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002368 }
Jim Ingham8a5d7a22018-08-15 23:10:32 +00002369 }
2370 if (memory_module_load_level >=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371 eMemoryModuleLoadLevelPartial) {
2372 if (function_starts_load_command.cmd) {
2373 const addr_t func_start_addr =
2374 linkedit_load_addr + function_starts_load_command.dataoff -
2375 linkedit_file_offset;
2376 DataBufferSP func_start_data_sp(
2377 ReadMemory(process_sp, func_start_addr,
2378 function_starts_load_command.datasize));
2379 if (func_start_data_sp)
2380 function_starts_data.SetData(func_start_data_sp, 0,
2381 func_start_data_sp->GetByteSize());
2382 }
2383 }
2384 }
2385 }
2386 } else {
2387 nlist_data.SetData(m_data, symtab_load_command.symoff,
2388 nlist_data_byte_size);
2389 strtab_data.SetData(m_data, symtab_load_command.stroff,
2390 strtab_data_byte_size);
2391
2392 if (dyld_info.export_size > 0) {
2393 dyld_trie_data.SetData(m_data, dyld_info.export_off,
2394 dyld_info.export_size);
2395 }
2396
2397 if (m_dysymtab.nindirectsyms != 0) {
2398 indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2399 m_dysymtab.nindirectsyms * 4);
2400 }
2401 if (function_starts_load_command.cmd) {
2402 function_starts_data.SetData(m_data,
2403 function_starts_load_command.dataoff,
2404 function_starts_load_command.datasize);
2405 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002406 }
2407
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408 if (nlist_data.GetByteSize() == 0 &&
2409 memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2410 if (log)
2411 module_sp->LogMessage(log, "failed to read nlist data");
2412 return 0;
2413 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002414
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2416 if (!have_strtab_data) {
2417 if (process) {
2418 if (strtab_addr == LLDB_INVALID_ADDRESS) {
2419 if (log)
2420 module_sp->LogMessage(log, "failed to locate the strtab in memory");
2421 return 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002422 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002423 } else {
2424 if (log)
2425 module_sp->LogMessage(log, "failed to read strtab data");
2426 return 0;
2427 }
2428 }
Greg Clayton9191db42013-10-21 18:40:51 +00002429
Kate Stoneb9c1b512016-09-06 20:57:50 +00002430 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2431 const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2432 const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2433 const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2434 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2435 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2436 SectionSP text_section_sp(
2437 section_list->FindSectionByName(g_segment_name_TEXT));
2438 SectionSP data_section_sp(
2439 section_list->FindSectionByName(g_segment_name_DATA));
2440 SectionSP data_dirty_section_sp(
2441 section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2442 SectionSP data_const_section_sp(
2443 section_list->FindSectionByName(g_segment_name_DATA_CONST));
2444 SectionSP objc_section_sp(
2445 section_list->FindSectionByName(g_segment_name_OBJC));
2446 SectionSP eh_frame_section_sp;
2447 if (text_section_sp.get())
2448 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2449 g_section_name_eh_frame);
2450 else
2451 eh_frame_section_sp =
2452 section_list->FindSectionByName(g_section_name_eh_frame);
Greg Clayton77ccca72011-12-30 00:32:24 +00002453
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
Greg Clayton86eac942013-08-13 21:32:34 +00002455
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 // lldb works best if it knows the start address of all functions in a
Adrian Prantl05097242018-04-30 16:49:04 +00002457 // module. Linker symbols or debug info are normally the best source of
2458 // information for start addr / size but they may be stripped in a released
2459 // binary. Two additional sources of information exist in Mach-O binaries:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002460 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2461 // function's start address in the
2462 // binary, relative to the text section.
2463 // eh_frame - the eh_frame FDEs have the start addr & size of
2464 // each function
2465 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2466 // all modern binaries.
2467 // Binaries built to run on older releases may need to use eh_frame
2468 // information.
Greg Clayton4c82d422012-05-18 23:20:01 +00002469
Kate Stoneb9c1b512016-09-06 20:57:50 +00002470 if (text_section_sp && function_starts_data.GetByteSize()) {
2471 FunctionStarts::Entry function_start_entry;
2472 function_start_entry.data = false;
2473 lldb::offset_t function_start_offset = 0;
2474 function_start_entry.addr = text_section_sp->GetFileAddress();
2475 uint64_t delta;
2476 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2477 0) {
2478 // Now append the current entry
2479 function_start_entry.addr += delta;
2480 function_starts.Append(function_start_entry);
2481 }
2482 } else {
2483 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
Adrian Prantl05097242018-04-30 16:49:04 +00002484 // load command claiming an eh_frame but it doesn't actually have the
2485 // eh_frame content. And if we have a dSYM, we don't need to do any of
2486 // this fill-in-the-missing-symbols works anyway - the debug info should
2487 // give us all the functions in the module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002488 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2489 m_type != eTypeDebugInfo) {
2490 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
Pavel Labath3f2a0812017-06-28 09:09:19 +00002491 DWARFCallFrameInfo::EH);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002492 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2493 eh_frame.GetFunctionAddressAndSizeVector(functions);
2494 addr_t text_base_addr = text_section_sp->GetFileAddress();
2495 size_t count = functions.GetSize();
2496 for (size_t i = 0; i < count; ++i) {
2497 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2498 functions.GetEntryAtIndex(i);
2499 if (func) {
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002500 FunctionStarts::Entry function_start_entry;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002501 function_start_entry.addr = func->base - text_base_addr;
2502 function_starts.Append(function_start_entry);
2503 }
Jason Molendad63d3c72013-04-16 00:18:44 +00002504 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505 }
2506 }
2507
2508 const size_t function_starts_count = function_starts.GetSize();
2509
2510 // For user process binaries (executables, dylibs, frameworks, bundles), if
Adrian Prantl05097242018-04-30 16:49:04 +00002511 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2512 // going to assume the binary has been stripped. Don't allow assembly
2513 // language instruction emulation because we don't know proper function
2514 // start boundaries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002515 //
2516 // For all other types of binaries (kernels, stand-alone bare board
Adrian Prantl05097242018-04-30 16:49:04 +00002517 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2518 // sections - we should not make any assumptions about them based on that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2520 m_allow_assembly_emulation_unwind_plans = false;
2521 Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2522 LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2523
2524 if (unwind_or_symbol_log)
2525 module_sp->LogMessage(
2526 unwind_or_symbol_log,
2527 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2528 }
2529
2530 const user_id_t TEXT_eh_frame_sectID =
2531 eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2532 : static_cast<user_id_t>(NO_SECT);
2533
2534 lldb::offset_t nlist_data_offset = 0;
2535
2536 uint32_t N_SO_index = UINT32_MAX;
2537
2538 MachSymtabSectionInfo section_info(section_list);
2539 std::vector<uint32_t> N_FUN_indexes;
2540 std::vector<uint32_t> N_NSYM_indexes;
2541 std::vector<uint32_t> N_INCL_indexes;
2542 std::vector<uint32_t> N_BRAC_indexes;
2543 std::vector<uint32_t> N_COMM_indexes;
2544 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2545 typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2546 typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2547 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2548 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2549 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00002550 // Any symbols that get merged into another will get an entry in this map
2551 // so we know
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2553 uint32_t nlist_idx = 0;
2554 Symbol *symbol_ptr = NULL;
2555
2556 uint32_t sym_idx = 0;
2557 Symbol *sym = NULL;
2558 size_t num_syms = 0;
2559 std::string memory_symbol_name;
2560 uint32_t unmapped_local_symbols_found = 0;
2561
2562 std::vector<TrieEntryWithOffset> trie_entries;
2563 std::set<lldb::addr_t> resolver_addresses;
2564
2565 if (dyld_trie_data.GetByteSize() > 0) {
2566 std::vector<llvm::StringRef> nameSlices;
2567 ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2568 resolver_addresses, trie_entries);
2569
2570 ConstString text_segment_name("__TEXT");
2571 SectionSP text_segment_sp =
2572 GetSectionList()->FindSectionByName(text_segment_name);
2573 if (text_segment_sp) {
2574 const lldb::addr_t text_segment_file_addr =
2575 text_segment_sp->GetFileAddress();
2576 if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2577 for (auto &e : trie_entries)
2578 e.entry.address += text_segment_file_addr;
2579 }
2580 }
2581 }
2582
2583 typedef std::set<ConstString> IndirectSymbols;
2584 IndirectSymbols indirect_symbol_names;
2585
2586#if defined(__APPLE__) && \
2587 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2588
2589 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
Adrian Prantl05097242018-04-30 16:49:04 +00002590 // optimized by moving LOCAL symbols out of the memory mapped portion of
2591 // the DSC. The symbol information has all been retained, but it isn't
2592 // available in the normal nlist data. However, there *are* duplicate
2593 // entries of *some*
Kate Stoneb9c1b512016-09-06 20:57:50 +00002594 // LOCAL symbols in the normal nlist data. To handle this situation
2595 // correctly, we must first attempt
2596 // to parse any DSC unmapped symbol information. If we find any, we set a
Adrian Prantl05097242018-04-30 16:49:04 +00002597 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002598
2599 if (m_header.flags & 0x80000000u) {
Adrian Prantl05097242018-04-30 16:49:04 +00002600 // Before we can start mapping the DSC, we need to make certain the
2601 // target process is actually using the cache we can find.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002602
2603 // Next we need to determine the correct path for the dyld shared cache.
2604
2605 ArchSpec header_arch;
2606 GetArchitecture(header_arch);
2607 char dsc_path[PATH_MAX];
2608 char dsc_path_development[PATH_MAX];
2609
2610 snprintf(
2611 dsc_path, sizeof(dsc_path), "%s%s%s",
2612 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2613 */
2614 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2615 header_arch.GetArchitectureName());
2616
2617 snprintf(
2618 dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2619 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2620 */
2621 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
Ilia K4f730dc2016-09-12 05:25:33 +00002622 header_arch.GetArchitectureName(), ".development");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623
2624 FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2625 FileSpec dsc_development_filespec(dsc_path_development, false);
2626 FileSpec dsc_filespec;
2627
2628 UUID dsc_uuid;
2629 UUID process_shared_cache_uuid;
Jason Molenda07580ff2018-05-04 00:59:37 +00002630 addr_t process_shared_cache_base_addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002631
2632 if (process) {
Jason Molenda07580ff2018-05-04 00:59:37 +00002633 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, process_shared_cache_uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634 }
2635
Adrian Prantl05097242018-04-30 16:49:04 +00002636 // First see if we can find an exact match for the inferior process
2637 // shared cache UUID in the development or non-development shared caches
2638 // on disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002639 if (process_shared_cache_uuid.IsValid()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002640 if (FileSystem::Instance().Exists(dsc_development_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002641 UUID dsc_development_uuid = GetSharedCacheUUID(
2642 dsc_development_filespec, byte_order, addr_byte_size);
2643 if (dsc_development_uuid.IsValid() &&
2644 dsc_development_uuid == process_shared_cache_uuid) {
2645 dsc_filespec = dsc_development_filespec;
2646 dsc_uuid = dsc_development_uuid;
2647 }
2648 }
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002649 if (!dsc_uuid.IsValid() &&
2650 FileSystem::Instance().Exists(dsc_nondevelopment_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002651 UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2652 dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2653 if (dsc_nondevelopment_uuid.IsValid() &&
2654 dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2655 dsc_filespec = dsc_nondevelopment_filespec;
2656 dsc_uuid = dsc_nondevelopment_uuid;
2657 }
2658 }
2659 }
2660
2661 // Failing a UUID match, prefer the development dyld_shared cache if both
2662 // are present.
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002663 if (!FileSystem::Instance().Exists(dsc_filespec)) {
2664 if (FileSystem::Instance().Exists(dsc_development_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002665 dsc_filespec = dsc_development_filespec;
2666 } else {
2667 dsc_filespec = dsc_nondevelopment_filespec;
2668 }
2669 }
2670
2671 /* The dyld_cache_header has a pointer to the
2672 dyld_cache_local_symbols_info structure (localSymbolsOffset).
2673 The dyld_cache_local_symbols_info structure gives us three things:
2674 1. The start and count of the nlist records in the dyld_shared_cache
2675 file
2676 2. The start and size of the strings for these nlist records
2677 3. The start and count of dyld_cache_local_symbols_entry entries
2678
2679 There is one dyld_cache_local_symbols_entry per dylib/framework in the
2680 dyld shared cache.
2681 The "dylibOffset" field is the Mach-O header of this dylib/framework in
2682 the dyld shared cache.
2683 The dyld_cache_local_symbols_entry also lists the start of this
2684 dylib/framework's nlist records
2685 and the count of how many nlist records there are for this
2686 dylib/framework.
2687 */
2688
2689 // Process the dyld shared cache header to find the unmapped symbols
2690
Pavel Labath50251fc2017-12-21 10:54:30 +00002691 DataBufferSP dsc_data_sp = MapFileData(
2692 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002693 if (!dsc_uuid.IsValid()) {
2694 dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2695 }
2696 if (dsc_data_sp) {
2697 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2698
2699 bool uuid_match = true;
2700 if (dsc_uuid.IsValid() && process) {
2701 if (process_shared_cache_uuid.IsValid() &&
2702 dsc_uuid != process_shared_cache_uuid) {
2703 // The on-disk dyld_shared_cache file is not the same as the one in
Adrian Prantl05097242018-04-30 16:49:04 +00002704 // this process' memory, don't use it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705 uuid_match = false;
2706 ModuleSP module_sp(GetModule());
2707 if (module_sp)
2708 module_sp->ReportWarning("process shared cache does not match "
2709 "on-disk dyld_shared_cache file, some "
2710 "symbol names will be missing.");
2711 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002712 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00002713
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002715
Kate Stoneb9c1b512016-09-06 20:57:50 +00002716 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
Jason Molenda955dcf22016-05-04 03:09:40 +00002717
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 // If the mappingOffset points to a location inside the header, we've
2719 // opened an old dyld shared cache, and should not proceed further.
2720 if (uuid_match &&
2721 mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
Jason Molenda955dcf22016-05-04 03:09:40 +00002722
Pavel Labath50251fc2017-12-21 10:54:30 +00002723 DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2724 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2725 mappingOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002726
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2728 byte_order, addr_byte_size);
2729 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002730
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731 // The File addresses (from the in-memory Mach-O load commands) for
Adrian Prantl05097242018-04-30 16:49:04 +00002732 // the shared libraries in the shared library cache need to be
2733 // adjusted by an offset to match up with the dylibOffset identifying
2734 // field in the dyld_cache_local_symbol_entry's. This offset is
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735 // recorded in mapping_offset_value.
2736 const uint64_t mapping_offset_value =
2737 dsc_mapping_info_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002738
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739 offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2740 localSymbolsOffset);
2741 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2742 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002743
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744 if (localSymbolsOffset && localSymbolsSize) {
2745 // Map the local symbols
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002746 DataBufferSP dsc_local_symbols_data_sp =
Pavel Labath50251fc2017-12-21 10:54:30 +00002747 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002748
2749 if (dsc_local_symbols_data_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002750 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2751 byte_order, addr_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002752
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002754
Kate Stoneb9c1b512016-09-06 20:57:50 +00002755 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2756 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2757 UndefinedNameToDescMap undefined_name_to_desc;
2758 SymbolIndexToName reexport_shlib_needs_fixup;
Jim Inghamea3ac272014-01-10 22:55:37 +00002759
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 // Read the local_symbols_infos struct in one shot
2761 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2762 dsc_local_symbols_data.GetU32(&offset,
2763 &local_symbols_info.nlistOffset, 6);
Jim Inghamea3ac272014-01-10 22:55:37 +00002764
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765 SectionSP text_section_sp(
2766 section_list->FindSectionByName(GetSegmentNameTEXT()));
Greg Claytonb65c6292015-02-20 22:20:05 +00002767
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 uint32_t header_file_offset =
2769 (text_section_sp->GetFileAddress() - mapping_offset_value);
Jason Molendaa5609c82012-06-21 01:51:02 +00002770
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771 offset = local_symbols_info.entriesOffset;
2772 for (uint32_t entry_index = 0;
2773 entry_index < local_symbols_info.entriesCount;
2774 entry_index++) {
2775 struct lldb_copy_dyld_cache_local_symbols_entry
2776 local_symbols_entry;
2777 local_symbols_entry.dylibOffset =
2778 dsc_local_symbols_data.GetU32(&offset);
2779 local_symbols_entry.nlistStartIndex =
2780 dsc_local_symbols_data.GetU32(&offset);
2781 local_symbols_entry.nlistCount =
2782 dsc_local_symbols_data.GetU32(&offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002783
Kate Stoneb9c1b512016-09-06 20:57:50 +00002784 if (header_file_offset == local_symbols_entry.dylibOffset) {
2785 unmapped_local_symbols_found = local_symbols_entry.nlistCount;
Jason Molendaa5609c82012-06-21 01:51:02 +00002786
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787 // The normal nlist code cannot correctly size the Symbols
2788 // array, we need to allocate it here.
2789 sym = symtab->Resize(
2790 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2791 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2792 num_syms = symtab->GetNumSymbols();
Jason Molendaa5609c82012-06-21 01:51:02 +00002793
Kate Stoneb9c1b512016-09-06 20:57:50 +00002794 nlist_data_offset =
2795 local_symbols_info.nlistOffset +
2796 (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2797 uint32_t string_table_offset =
2798 local_symbols_info.stringsOffset;
Jason Molendaa5609c82012-06-21 01:51:02 +00002799
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 for (uint32_t nlist_index = 0;
2801 nlist_index < local_symbols_entry.nlistCount;
2802 nlist_index++) {
2803 /////////////////////////////
Jason Molenda649a6072015-11-10 05:21:54 +00002804 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 struct nlist_64 nlist;
2806 if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(
2807 nlist_data_offset, nlist_byte_size))
2808 break;
Eugene Zelenko8157a882015-10-23 16:56:07 +00002809
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(
2811 &nlist_data_offset);
2812 nlist.n_type = dsc_local_symbols_data.GetU8_unchecked(
2813 &nlist_data_offset);
2814 nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked(
2815 &nlist_data_offset);
2816 nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked(
2817 &nlist_data_offset);
2818 nlist.n_value =
2819 dsc_local_symbols_data.GetAddress_unchecked(
2820 &nlist_data_offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002821
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 SymbolType type = eSymbolTypeInvalid;
2823 const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2824 string_table_offset + nlist.n_strx);
Jason Molendaf8130862012-06-22 03:28:35 +00002825
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002827 // No symbol should be NULL, even the symbols with no
Adrian Prantl05097242018-04-30 16:49:04 +00002828 // string values should have an offset zero which
2829 // points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 Host::SystemLog(
2831 Host::eSystemLogError,
2832 "error: DSC unmapped local symbol[%u] has invalid "
2833 "string table offset 0x%x in %s, ignoring symbol\n",
2834 entry_index, nlist.n_strx,
2835 module_sp->GetFileSpec().GetPath().c_str());
Greg Claytonfd814c52013-08-13 01:42:25 +00002836 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002837 }
2838 if (symbol_name[0] == '\0')
Greg Claytonfd814c52013-08-13 01:42:25 +00002839 symbol_name = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002840
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 const char *symbol_name_non_abi_mangled = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002842
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 SectionSP symbol_section;
2844 uint32_t symbol_byte_size = 0;
2845 bool add_nlist = true;
2846 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2847 bool demangled_is_synthesized = false;
2848 bool is_gsym = false;
2849 bool set_value = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00002850
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851 assert(sym_idx < num_syms);
Jason Molenda4e7511e2013-03-06 23:19:17 +00002852
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853 sym[sym_idx].SetDebug(is_debug);
Greg Clayton29e08cb2012-03-14 01:53:24 +00002854
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 if (is_debug) {
2856 switch (nlist.n_type) {
2857 case N_GSYM:
2858 // global symbol: name,,NO_SECT,type,0
2859 // Sometimes the N_GSYM value contains the address.
2860
2861 // FIXME: In the .o files, we have a GSYM and a debug
2862 // symbol for all the ObjC data. They
2863 // have the same address, but we want to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +00002864 // we always find only the real symbol, 'cause we
2865 // don't currently correctly attribute the
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 // GSYM one to the ObjCClass/Ivar/MetaClass
Adrian Prantl05097242018-04-30 16:49:04 +00002867 // symbol type. This is a temporary hack to make
2868 // sure the ObjectiveC symbols get treated correctly.
2869 // To do this right, we should coalesce all the GSYM
2870 // & global symbols that have the same address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871
2872 is_gsym = true;
2873 sym[sym_idx].SetExternal(true);
2874
2875 if (symbol_name && symbol_name[0] == '_' &&
2876 symbol_name[1] == 'O') {
Greg Clayton1e28adf2015-02-25 17:25:02 +00002877 llvm::StringRef symbol_name_ref(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 if (symbol_name_ref.startswith(
2879 g_objc_v2_prefix_class)) {
2880 symbol_name_non_abi_mangled = symbol_name + 1;
2881 symbol_name =
2882 symbol_name + g_objc_v2_prefix_class.size();
2883 type = eSymbolTypeObjCClass;
2884 demangled_is_synthesized = true;
2885
2886 } else if (symbol_name_ref.startswith(
2887 g_objc_v2_prefix_metaclass)) {
2888 symbol_name_non_abi_mangled = symbol_name + 1;
2889 symbol_name = symbol_name +
2890 g_objc_v2_prefix_metaclass.size();
2891 type = eSymbolTypeObjCMetaClass;
2892 demangled_is_synthesized = true;
2893 } else if (symbol_name_ref.startswith(
2894 g_objc_v2_prefix_ivar)) {
2895 symbol_name_non_abi_mangled = symbol_name + 1;
2896 symbol_name =
2897 symbol_name + g_objc_v2_prefix_ivar.size();
2898 type = eSymbolTypeObjCIVar;
2899 demangled_is_synthesized = true;
Greg Clayton1e28adf2015-02-25 17:25:02 +00002900 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002902 if (nlist.n_value != 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 symbol_section = section_info.GetSection(
2904 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002905 type = eSymbolTypeData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906 }
2907 break;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002908
Kate Stoneb9c1b512016-09-06 20:57:50 +00002909 case N_FNAME:
2910 // procedure name (f77 kludge): name,,NO_SECT,0,0
2911 type = eSymbolTypeCompiler;
2912 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002913
Kate Stoneb9c1b512016-09-06 20:57:50 +00002914 case N_FUN:
2915 // procedure: name,,n_sect,linenumber,address
2916 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002917 type = eSymbolTypeCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 symbol_section = section_info.GetSection(
2919 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002920
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 N_FUN_addr_to_sym_idx.insert(
2922 std::make_pair(nlist.n_value, sym_idx));
2923 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00002924 // symbol table in lieu of using nlist_idx in case
2925 // we ever start trimming entries out
Greg Claytonfd814c52013-08-13 01:42:25 +00002926 N_FUN_indexes.push_back(sym_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002927 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002928 type = eSymbolTypeCompiler;
2929
Kate Stoneb9c1b512016-09-06 20:57:50 +00002930 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00002931 // Copy the size of the function into the
2932 // original
Kate Stoneb9c1b512016-09-06 20:57:50 +00002933 // STAB entry so we don't have
2934 // to hunt for it later
2935 symtab->SymbolAtIndex(N_FUN_indexes.back())
2936 ->SetByteSize(nlist.n_value);
2937 N_FUN_indexes.pop_back();
2938 // We don't really need the end function STAB as
Adrian Prantl05097242018-04-30 16:49:04 +00002939 // it contains the size which we already placed
2940 // with the original symbol, so don't add it if
2941 // we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00002942 add_nlist = false;
Greg Claytondacc4a92013-05-14 22:19:37 +00002943 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 }
2945 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002946
Kate Stoneb9c1b512016-09-06 20:57:50 +00002947 case N_STSYM:
2948 // static symbol: name,,n_sect,type,address
2949 N_STSYM_addr_to_sym_idx.insert(
2950 std::make_pair(nlist.n_value, sym_idx));
2951 symbol_section = section_info.GetSection(
2952 nlist.n_sect, nlist.n_value);
2953 if (symbol_name && symbol_name[0]) {
2954 type = ObjectFile::GetSymbolTypeFromName(
2955 symbol_name + 1, eSymbolTypeData);
2956 }
2957 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002958
Kate Stoneb9c1b512016-09-06 20:57:50 +00002959 case N_LCSYM:
2960 // .lcomm symbol: name,,n_sect,type,address
2961 symbol_section = section_info.GetSection(
2962 nlist.n_sect, nlist.n_value);
2963 type = eSymbolTypeCommonBlock;
2964 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002965
Kate Stoneb9c1b512016-09-06 20:57:50 +00002966 case N_BNSYM:
2967 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00002968 // table in lieu of using nlist_idx in case we ever
2969 // start trimming entries out Skip these if we want
2970 // minimal symbol tables
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 add_nlist = false;
2972 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002973
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974 case N_ENSYM:
2975 // Set the size of the N_BNSYM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002976 // index of this N_ENSYM so that we can always skip
2977 // the entire symbol if we need to navigate more
2978 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00002979 // Skip these if we want minimal symbol tables
2980 add_nlist = false;
2981 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002982
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983 case N_OPT:
2984 // emitted with gcc2_compiled and in gcc source
2985 type = eSymbolTypeCompiler;
2986 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002987
Kate Stoneb9c1b512016-09-06 20:57:50 +00002988 case N_RSYM:
2989 // register sym: name,,NO_SECT,type,register
2990 type = eSymbolTypeVariable;
2991 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002992
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993 case N_SLINE:
2994 // src line: 0,,n_sect,linenumber,address
2995 symbol_section = section_info.GetSection(
2996 nlist.n_sect, nlist.n_value);
2997 type = eSymbolTypeLineEntry;
2998 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002999
Kate Stoneb9c1b512016-09-06 20:57:50 +00003000 case N_SSYM:
3001 // structure elt: name,,NO_SECT,type,struct_offset
3002 type = eSymbolTypeVariableType;
3003 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003004
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005 case N_SO:
3006 // source file name
3007 type = eSymbolTypeSourceFile;
3008 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003009 add_nlist = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 if (N_SO_index != UINT32_MAX) {
3011 // Set the size of the N_SO to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003012 // index of this N_SO so that we can always skip
3013 // the entire N_SO if we need to navigate more
3014 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3016 symbol_ptr->SetByteSize(sym_idx);
3017 symbol_ptr->SetSizeIsSibling(true);
Greg Claytonfd814c52013-08-13 01:42:25 +00003018 }
3019 N_NSYM_indexes.clear();
3020 N_INCL_indexes.clear();
3021 N_BRAC_indexes.clear();
3022 N_COMM_indexes.clear();
3023 N_FUN_indexes.clear();
3024 N_SO_index = UINT32_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003025 } else {
3026 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00003027 // symbol table in lieu of using nlist_idx in case
3028 // we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 const bool N_SO_has_full_path =
3030 symbol_name[0] == '/';
3031 if (N_SO_has_full_path) {
3032 if ((N_SO_index == sym_idx - 1) &&
3033 ((sym_idx - 1) < num_syms)) {
3034 // We have two consecutive N_SO entries where
Adrian Prantl05097242018-04-30 16:49:04 +00003035 // the first contains a directory and the
3036 // second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 sym[sym_idx - 1].GetMangled().SetValue(
3038 ConstString(symbol_name), false);
3039 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3040 add_nlist = false;
3041 } else {
3042 // This is the first entry in a N_SO that
3043 // contains a directory or
3044 // a full path to the source file
Greg Claytonfd814c52013-08-13 01:42:25 +00003045 N_SO_index = sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 }
3047 } else if ((N_SO_index == sym_idx - 1) &&
3048 ((sym_idx - 1) < num_syms)) {
3049 // This is usually the second N_SO entry that
Adrian Prantl05097242018-04-30 16:49:04 +00003050 // contains just the filename, so here we combine
3051 // it with the first one if we are minimizing the
3052 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003053 const char *so_path =
3054 sym[sym_idx - 1]
3055 .GetMangled()
3056 .GetDemangledName(
3057 lldb::eLanguageTypeUnknown)
3058 .AsCString();
3059 if (so_path && so_path[0]) {
3060 std::string full_so_path(so_path);
3061 const size_t double_slash_pos =
3062 full_so_path.find("//");
3063 if (double_slash_pos != std::string::npos) {
3064 // The linker has been generating bad N_SO
3065 // entries with doubled up paths
Adrian Prantl05097242018-04-30 16:49:04 +00003066 // in the format "%s%s" where the first
3067 // string in the DW_AT_comp_dir, and the
3068 // second is the directory for the source
3069 // file so you end up with a path that looks
3070 // like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00003071 FileSpec so_dir(so_path, false);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00003072 if (!FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003073 so_dir.SetFile(
3074 &full_so_path[double_slash_pos + 1],
3075 false);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00003076 if (FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003077 // Trim off the incorrect path
3078 full_so_path.erase(0,
3079 double_slash_pos + 1);
3080 }
3081 }
3082 }
3083 if (*full_so_path.rbegin() != '/')
3084 full_so_path += '/';
3085 full_so_path += symbol_name;
3086 sym[sym_idx - 1].GetMangled().SetValue(
3087 ConstString(full_so_path.c_str()), false);
3088 add_nlist = false;
3089 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3090 }
3091 } else {
3092 // This could be a relative path to a N_SO
3093 N_SO_index = sym_idx;
Greg Claytonfd814c52013-08-13 01:42:25 +00003094 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003095 }
3096 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003097
Kate Stoneb9c1b512016-09-06 20:57:50 +00003098 case N_OSO:
3099 // object file name: name,,0,0,st_mtime
3100 type = eSymbolTypeObjectFile;
3101 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003102
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103 case N_LSYM:
3104 // local sym: name,,NO_SECT,type,offset
3105 type = eSymbolTypeLocal;
3106 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003107
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108 //----------------------------------------------------------------------
3109 // INCL scopes
3110 //----------------------------------------------------------------------
3111 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00003112 // include file beginning: name,,NO_SECT,0,sum We use
3113 // the current number of symbols in the symbol table
3114 // in lieu of using nlist_idx in case we ever start
3115 // trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003116 N_INCL_indexes.push_back(sym_idx);
3117 type = eSymbolTypeScopeBegin;
3118 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003119
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 case N_EINCL:
3121 // include file end: name,,NO_SECT,0,0
3122 // Set the size of the N_BINCL to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003123 // index of this N_EINCL so that we can always skip
3124 // the entire symbol if we need to navigate more
3125 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126 if (!N_INCL_indexes.empty()) {
3127 symbol_ptr =
3128 symtab->SymbolAtIndex(N_INCL_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003129 symbol_ptr->SetByteSize(sym_idx + 1);
3130 symbol_ptr->SetSizeIsSibling(true);
3131 N_INCL_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003132 }
3133 type = eSymbolTypeScopeEnd;
3134 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003135
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136 case N_SOL:
3137 // #included file name: name,,n_sect,0,address
3138 type = eSymbolTypeHeaderFile;
Greg Claytonfd814c52013-08-13 01:42:25 +00003139
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 // We currently don't use the header files on darwin
3141 add_nlist = false;
3142 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003143
Kate Stoneb9c1b512016-09-06 20:57:50 +00003144 case N_PARAMS:
3145 // compiler parameters: name,,NO_SECT,0,0
3146 type = eSymbolTypeCompiler;
3147 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003148
Kate Stoneb9c1b512016-09-06 20:57:50 +00003149 case N_VERSION:
3150 // compiler version: name,,NO_SECT,0,0
3151 type = eSymbolTypeCompiler;
3152 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003153
Kate Stoneb9c1b512016-09-06 20:57:50 +00003154 case N_OLEVEL:
3155 // compiler -O level: name,,NO_SECT,0,0
3156 type = eSymbolTypeCompiler;
3157 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003158
Kate Stoneb9c1b512016-09-06 20:57:50 +00003159 case N_PSYM:
3160 // parameter: name,,NO_SECT,type,offset
3161 type = eSymbolTypeVariable;
3162 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003163
Kate Stoneb9c1b512016-09-06 20:57:50 +00003164 case N_ENTRY:
3165 // alternate entry: name,,n_sect,linenumber,address
3166 symbol_section = section_info.GetSection(
3167 nlist.n_sect, nlist.n_value);
3168 type = eSymbolTypeLineEntry;
3169 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003170
Kate Stoneb9c1b512016-09-06 20:57:50 +00003171 //----------------------------------------------------------------------
3172 // Left and Right Braces
3173 //----------------------------------------------------------------------
3174 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00003175 // left bracket: 0,,NO_SECT,nesting level,address We
3176 // use the current number of symbols in the symbol
3177 // table in lieu of using nlist_idx in case we ever
3178 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003179 symbol_section = section_info.GetSection(
3180 nlist.n_sect, nlist.n_value);
3181 N_BRAC_indexes.push_back(sym_idx);
3182 type = eSymbolTypeScopeBegin;
3183 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003184
Kate Stoneb9c1b512016-09-06 20:57:50 +00003185 case N_RBRAC:
3186 // right bracket: 0,,NO_SECT,nesting level,address
3187 // Set the size of the N_LBRAC to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003188 // index of this N_RBRAC so that we can always skip
3189 // the entire symbol if we need to navigate more
3190 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191 symbol_section = section_info.GetSection(
3192 nlist.n_sect, nlist.n_value);
3193 if (!N_BRAC_indexes.empty()) {
3194 symbol_ptr =
3195 symtab->SymbolAtIndex(N_BRAC_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003196 symbol_ptr->SetByteSize(sym_idx + 1);
3197 symbol_ptr->SetSizeIsSibling(true);
3198 N_BRAC_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003199 }
3200 type = eSymbolTypeScopeEnd;
3201 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003202
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 case N_EXCL:
3204 // deleted include file: name,,NO_SECT,0,sum
3205 type = eSymbolTypeHeaderFile;
3206 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003207
Kate Stoneb9c1b512016-09-06 20:57:50 +00003208 //----------------------------------------------------------------------
3209 // COMM scopes
3210 //----------------------------------------------------------------------
3211 case N_BCOMM:
3212 // begin common: name,,NO_SECT,0,0
3213 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00003214 // table in lieu of using nlist_idx in case we ever
3215 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003216 type = eSymbolTypeScopeBegin;
3217 N_COMM_indexes.push_back(sym_idx);
3218 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003219
Kate Stoneb9c1b512016-09-06 20:57:50 +00003220 case N_ECOML:
3221 // end common (local name): 0,,n_sect,0,address
3222 symbol_section = section_info.GetSection(
3223 nlist.n_sect, nlist.n_value);
3224 // Fall through
Greg Claytonfd814c52013-08-13 01:42:25 +00003225
Kate Stoneb9c1b512016-09-06 20:57:50 +00003226 case N_ECOMM:
3227 // end common: name,,n_sect,0,0
3228 // Set the size of the N_BCOMM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003229 // index of this N_ECOMM/N_ECOML so that we can
3230 // always skip the entire symbol if we need to
3231 // navigate more quickly at the source level when
3232 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003233 if (!N_COMM_indexes.empty()) {
3234 symbol_ptr =
3235 symtab->SymbolAtIndex(N_COMM_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003236 symbol_ptr->SetByteSize(sym_idx + 1);
3237 symbol_ptr->SetSizeIsSibling(true);
3238 N_COMM_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003239 }
3240 type = eSymbolTypeScopeEnd;
3241 break;
3242
3243 case N_LENG:
3244 // second stab entry with length information
3245 type = eSymbolTypeAdditional;
3246 break;
3247
3248 default:
3249 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003250 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003251 } else {
3252 // uint8_t n_pext = N_PEXT & nlist.n_type;
3253 uint8_t n_type = N_TYPE & nlist.n_type;
3254 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
Greg Claytonfd814c52013-08-13 01:42:25 +00003255
Kate Stoneb9c1b512016-09-06 20:57:50 +00003256 switch (n_type) {
3257 case N_INDR: {
3258 const char *reexport_name_cstr =
3259 strtab_data.PeekCStr(nlist.n_value);
3260 if (reexport_name_cstr && reexport_name_cstr[0]) {
3261 type = eSymbolTypeReExported;
3262 ConstString reexport_name(
3263 reexport_name_cstr +
3264 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3265 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3266 set_value = false;
3267 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3268 indirect_symbol_names.insert(
3269 ConstString(symbol_name +
3270 ((symbol_name[0] == '_') ? 1 : 0)));
3271 } else
3272 type = eSymbolTypeUndefined;
3273 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003274
Kate Stoneb9c1b512016-09-06 20:57:50 +00003275 case N_UNDF:
3276 if (symbol_name && symbol_name[0]) {
3277 ConstString undefined_name(
3278 symbol_name +
3279 ((symbol_name[0] == '_') ? 1 : 0));
3280 undefined_name_to_desc[undefined_name] =
3281 nlist.n_desc;
3282 }
3283 // Fall through
3284 case N_PBUD:
3285 type = eSymbolTypeUndefined;
3286 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003287
Kate Stoneb9c1b512016-09-06 20:57:50 +00003288 case N_ABS:
3289 type = eSymbolTypeAbsolute;
3290 break;
Greg Clayton60038be2015-02-14 00:51:13 +00003291
Kate Stoneb9c1b512016-09-06 20:57:50 +00003292 case N_SECT: {
3293 symbol_section = section_info.GetSection(
3294 nlist.n_sect, nlist.n_value);
Jason Molenda62e06812016-02-16 04:14:33 +00003295
Kate Stoneb9c1b512016-09-06 20:57:50 +00003296 if (symbol_section == NULL) {
3297 // TODO: warn about this?
3298 add_nlist = false;
3299 break;
3300 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003301
Kate Stoneb9c1b512016-09-06 20:57:50 +00003302 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3303 type = eSymbolTypeException;
3304 } else {
3305 uint32_t section_type =
3306 symbol_section->Get() & SECTION_TYPE;
Greg Claytonfd814c52013-08-13 01:42:25 +00003307
Kate Stoneb9c1b512016-09-06 20:57:50 +00003308 switch (section_type) {
3309 case S_CSTRING_LITERALS:
3310 type = eSymbolTypeData;
3311 break; // section with only literal C strings
3312 case S_4BYTE_LITERALS:
3313 type = eSymbolTypeData;
3314 break; // section with only 4 byte literals
3315 case S_8BYTE_LITERALS:
3316 type = eSymbolTypeData;
3317 break; // section with only 8 byte literals
3318 case S_LITERAL_POINTERS:
3319 type = eSymbolTypeTrampoline;
3320 break; // section with only pointers to literals
3321 case S_NON_LAZY_SYMBOL_POINTERS:
3322 type = eSymbolTypeTrampoline;
3323 break; // section with only non-lazy symbol
3324 // pointers
3325 case S_LAZY_SYMBOL_POINTERS:
3326 type = eSymbolTypeTrampoline;
3327 break; // section with only lazy symbol pointers
3328 case S_SYMBOL_STUBS:
3329 type = eSymbolTypeTrampoline;
3330 break; // section with only symbol stubs, byte
3331 // size of stub in the reserved2 field
3332 case S_MOD_INIT_FUNC_POINTERS:
3333 type = eSymbolTypeCode;
3334 break; // section with only function pointers for
3335 // initialization
3336 case S_MOD_TERM_FUNC_POINTERS:
3337 type = eSymbolTypeCode;
3338 break; // section with only function pointers for
3339 // termination
3340 case S_INTERPOSING:
3341 type = eSymbolTypeTrampoline;
3342 break; // section with only pairs of function
3343 // pointers for interposing
3344 case S_16BYTE_LITERALS:
3345 type = eSymbolTypeData;
3346 break; // section with only 16 byte literals
3347 case S_DTRACE_DOF:
3348 type = eSymbolTypeInstrumentation;
3349 break;
3350 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3351 type = eSymbolTypeTrampoline;
3352 break;
3353 default:
3354 switch (symbol_section->GetType()) {
3355 case lldb::eSectionTypeCode:
3356 type = eSymbolTypeCode;
Greg Claytonfd814c52013-08-13 01:42:25 +00003357 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003358 case eSectionTypeData:
3359 case eSectionTypeDataCString: // Inlined C string
3360 // data
3361 case eSectionTypeDataCStringPointers: // Pointers
3362 // to C
3363 // string
3364 // data
3365 case eSectionTypeDataSymbolAddress: // Address of
3366 // a symbol in
3367 // the symbol
3368 // table
3369 case eSectionTypeData4:
3370 case eSectionTypeData8:
3371 case eSectionTypeData16:
3372 type = eSymbolTypeData;
3373 break;
3374 default:
3375 break;
3376 }
3377 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003378 }
3379
Kate Stoneb9c1b512016-09-06 20:57:50 +00003380 if (type == eSymbolTypeInvalid) {
3381 const char *symbol_sect_name =
3382 symbol_section->GetName().AsCString();
3383 if (symbol_section->IsDescendant(
3384 text_section_sp.get())) {
3385 if (symbol_section->IsClear(
3386 S_ATTR_PURE_INSTRUCTIONS |
3387 S_ATTR_SELF_MODIFYING_CODE |
3388 S_ATTR_SOME_INSTRUCTIONS))
3389 type = eSymbolTypeData;
3390 else
3391 type = eSymbolTypeCode;
3392 } else if (symbol_section->IsDescendant(
3393 data_section_sp.get()) ||
3394 symbol_section->IsDescendant(
3395 data_dirty_section_sp.get()) ||
3396 symbol_section->IsDescendant(
3397 data_const_section_sp.get())) {
3398 if (symbol_sect_name &&
3399 ::strstr(symbol_sect_name, "__objc") ==
3400 symbol_sect_name) {
3401 type = eSymbolTypeRuntime;
Greg Claytonfd814c52013-08-13 01:42:25 +00003402
Kate Stoneb9c1b512016-09-06 20:57:50 +00003403 if (symbol_name) {
3404 llvm::StringRef symbol_name_ref(
3405 symbol_name);
3406 if (symbol_name_ref.startswith("_OBJC_")) {
3407 static const llvm::StringRef
3408 g_objc_v2_prefix_class(
3409 "_OBJC_CLASS_$_");
3410 static const llvm::StringRef
3411 g_objc_v2_prefix_metaclass(
3412 "_OBJC_METACLASS_$_");
3413 static const llvm::StringRef
3414 g_objc_v2_prefix_ivar(
3415 "_OBJC_IVAR_$_");
3416 if (symbol_name_ref.startswith(
3417 g_objc_v2_prefix_class)) {
3418 symbol_name_non_abi_mangled =
3419 symbol_name + 1;
3420 symbol_name =
3421 symbol_name +
3422 g_objc_v2_prefix_class.size();
3423 type = eSymbolTypeObjCClass;
3424 demangled_is_synthesized = true;
3425 } else if (
3426 symbol_name_ref.startswith(
3427 g_objc_v2_prefix_metaclass)) {
3428 symbol_name_non_abi_mangled =
3429 symbol_name + 1;
3430 symbol_name =
3431 symbol_name +
3432 g_objc_v2_prefix_metaclass.size();
3433 type = eSymbolTypeObjCMetaClass;
3434 demangled_is_synthesized = true;
3435 } else if (symbol_name_ref.startswith(
3436 g_objc_v2_prefix_ivar)) {
3437 symbol_name_non_abi_mangled =
3438 symbol_name + 1;
3439 symbol_name =
3440 symbol_name +
3441 g_objc_v2_prefix_ivar.size();
3442 type = eSymbolTypeObjCIVar;
3443 demangled_is_synthesized = true;
3444 }
Greg Clayton38f9cc42014-06-16 22:53:16 +00003445 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003446 }
3447 } else if (symbol_sect_name &&
3448 ::strstr(symbol_sect_name,
3449 "__gcc_except_tab") ==
3450 symbol_sect_name) {
3451 type = eSymbolTypeException;
3452 } else {
3453 type = eSymbolTypeData;
Greg Claytonfd814c52013-08-13 01:42:25 +00003454 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003455 } else if (symbol_sect_name &&
3456 ::strstr(symbol_sect_name,
3457 "__IMPORT") ==
3458 symbol_sect_name) {
3459 type = eSymbolTypeTrampoline;
3460 } else if (symbol_section->IsDescendant(
3461 objc_section_sp.get())) {
3462 type = eSymbolTypeRuntime;
3463 if (symbol_name && symbol_name[0] == '.') {
3464 llvm::StringRef symbol_name_ref(symbol_name);
3465 static const llvm::StringRef
3466 g_objc_v1_prefix_class(
3467 ".objc_class_name_");
3468 if (symbol_name_ref.startswith(
3469 g_objc_v1_prefix_class)) {
3470 symbol_name_non_abi_mangled = symbol_name;
3471 symbol_name = symbol_name +
3472 g_objc_v1_prefix_class.size();
3473 type = eSymbolTypeObjCClass;
3474 demangled_is_synthesized = true;
3475 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003476 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003477 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003478 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003479 }
3480 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003481 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003482 }
Greg Claytondacc4a92013-05-14 22:19:37 +00003483
Kate Stoneb9c1b512016-09-06 20:57:50 +00003484 if (add_nlist) {
3485 uint64_t symbol_value = nlist.n_value;
3486 if (symbol_name_non_abi_mangled) {
3487 sym[sym_idx].GetMangled().SetMangledName(
3488 ConstString(symbol_name_non_abi_mangled));
3489 sym[sym_idx].GetMangled().SetDemangledName(
3490 ConstString(symbol_name));
3491 } else {
3492 bool symbol_name_is_mangled = false;
Greg Claytonfd814c52013-08-13 01:42:25 +00003493
Kate Stoneb9c1b512016-09-06 20:57:50 +00003494 if (symbol_name && symbol_name[0] == '_') {
Greg Claytonfd814c52013-08-13 01:42:25 +00003495 symbol_name_is_mangled = symbol_name[1] == '_';
Kate Stoneb9c1b512016-09-06 20:57:50 +00003496 symbol_name++; // Skip the leading underscore
3497 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003498
Kate Stoneb9c1b512016-09-06 20:57:50 +00003499 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003500 ConstString const_symbol_name(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003501 sym[sym_idx].GetMangled().SetValue(
3502 const_symbol_name, symbol_name_is_mangled);
3503 if (is_gsym && is_debug) {
3504 const char *gsym_name =
3505 sym[sym_idx]
3506 .GetMangled()
3507 .GetName(lldb::eLanguageTypeUnknown,
3508 Mangled::ePreferMangled)
3509 .GetCString();
3510 if (gsym_name)
3511 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3512 }
3513 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003514 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003515 if (symbol_section) {
3516 const addr_t section_file_addr =
3517 symbol_section->GetFileAddress();
3518 if (symbol_byte_size == 0 &&
3519 function_starts_count > 0) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003520 addr_t symbol_lookup_file_addr = nlist.n_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003521 // Do an exact address match for non-ARM addresses,
Adrian Prantl05097242018-04-30 16:49:04 +00003522 // else get the closest since the symbol might be a
3523 // thumb symbol which has an address with bit zero
3524 // set
Kate Stoneb9c1b512016-09-06 20:57:50 +00003525 FunctionStarts::Entry *func_start_entry =
3526 function_starts.FindEntry(
3527 symbol_lookup_file_addr, !is_arm);
3528 if (is_arm && func_start_entry) {
3529 // Verify that the function start address is the
Adrian Prantl05097242018-04-30 16:49:04 +00003530 // symbol address (ARM) or the symbol address + 1
3531 // (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003532 if (func_start_entry->addr !=
3533 symbol_lookup_file_addr &&
3534 func_start_entry->addr !=
3535 (symbol_lookup_file_addr + 1)) {
3536 // Not the right entry, NULL it out...
3537 func_start_entry = NULL;
3538 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003539 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003540 if (func_start_entry) {
3541 func_start_entry->data = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00003542
Kate Stoneb9c1b512016-09-06 20:57:50 +00003543 addr_t symbol_file_addr = func_start_entry->addr;
3544 uint32_t symbol_flags = 0;
3545 if (is_arm) {
3546 if (symbol_file_addr & 1)
3547 symbol_flags =
3548 MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3549 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3550 }
3551
3552 const FunctionStarts::Entry
3553 *next_func_start_entry =
3554 function_starts.FindNextEntry(
3555 func_start_entry);
3556 const addr_t section_end_file_addr =
3557 section_file_addr +
3558 symbol_section->GetByteSize();
3559 if (next_func_start_entry) {
3560 addr_t next_symbol_file_addr =
3561 next_func_start_entry->addr;
3562 // Be sure the clear the Thumb address bit when
Adrian Prantl05097242018-04-30 16:49:04 +00003563 // we calculate the size from the current and
3564 // next address
Greg Claytonfd814c52013-08-13 01:42:25 +00003565 if (is_arm)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003566 next_symbol_file_addr &=
3567 THUMB_ADDRESS_BIT_MASK;
3568 symbol_byte_size = std::min<lldb::addr_t>(
3569 next_symbol_file_addr - symbol_file_addr,
3570 section_end_file_addr - symbol_file_addr);
3571 } else {
3572 symbol_byte_size =
3573 section_end_file_addr - symbol_file_addr;
3574 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003575 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003576 }
3577 symbol_value -= section_file_addr;
Greg Claytonfd814c52013-08-13 01:42:25 +00003578 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003579
Kate Stoneb9c1b512016-09-06 20:57:50 +00003580 if (is_debug == false) {
3581 if (type == eSymbolTypeCode) {
3582 // See if we can find a N_FUN entry for any code
Adrian Prantl05097242018-04-30 16:49:04 +00003583 // symbols. If we do find a match, and the name
3584 // matches, then we can merge the two into just the
3585 // function symbol to avoid duplicate entries in
3586 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003587 std::pair<ValueToSymbolIndexMap::const_iterator,
3588 ValueToSymbolIndexMap::const_iterator>
3589 range;
3590 range = N_FUN_addr_to_sym_idx.equal_range(
3591 nlist.n_value);
3592 if (range.first != range.second) {
3593 bool found_it = false;
3594 for (ValueToSymbolIndexMap::const_iterator pos =
3595 range.first;
3596 pos != range.second; ++pos) {
3597 if (sym[sym_idx].GetMangled().GetName(
3598 lldb::eLanguageTypeUnknown,
3599 Mangled::ePreferMangled) ==
3600 sym[pos->second].GetMangled().GetName(
3601 lldb::eLanguageTypeUnknown,
3602 Mangled::ePreferMangled)) {
3603 m_nlist_idx_to_sym_idx[nlist_idx] =
3604 pos->second;
3605 // We just need the flags from the linker
3606 // symbol, so put these flags
3607 // into the N_FUN flags to avoid duplicate
3608 // symbols in the symbol table
3609 sym[pos->second].SetExternal(
3610 sym[sym_idx].IsExternal());
3611 sym[pos->second].SetFlags(nlist.n_type << 16 |
3612 nlist.n_desc);
3613 if (resolver_addresses.find(nlist.n_value) !=
3614 resolver_addresses.end())
3615 sym[pos->second].SetType(
3616 eSymbolTypeResolver);
3617 sym[sym_idx].Clear();
3618 found_it = true;
3619 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003620 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003621 }
3622 if (found_it)
3623 continue;
3624 } else {
3625 if (resolver_addresses.find(nlist.n_value) !=
3626 resolver_addresses.end())
3627 type = eSymbolTypeResolver;
Greg Claytonfd814c52013-08-13 01:42:25 +00003628 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003629 } else if (type == eSymbolTypeData ||
3630 type == eSymbolTypeObjCClass ||
3631 type == eSymbolTypeObjCMetaClass ||
3632 type == eSymbolTypeObjCIVar) {
3633 // See if we can find a N_STSYM entry for any data
Adrian Prantl05097242018-04-30 16:49:04 +00003634 // symbols. If we do find a match, and the name
3635 // matches, then we can merge the two into just the
3636 // Static symbol to avoid duplicate entries in the
3637 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003638 std::pair<ValueToSymbolIndexMap::const_iterator,
3639 ValueToSymbolIndexMap::const_iterator>
3640 range;
3641 range = N_STSYM_addr_to_sym_idx.equal_range(
3642 nlist.n_value);
3643 if (range.first != range.second) {
3644 bool found_it = false;
3645 for (ValueToSymbolIndexMap::const_iterator pos =
3646 range.first;
3647 pos != range.second; ++pos) {
3648 if (sym[sym_idx].GetMangled().GetName(
3649 lldb::eLanguageTypeUnknown,
3650 Mangled::ePreferMangled) ==
3651 sym[pos->second].GetMangled().GetName(
3652 lldb::eLanguageTypeUnknown,
3653 Mangled::ePreferMangled)) {
3654 m_nlist_idx_to_sym_idx[nlist_idx] =
3655 pos->second;
3656 // We just need the flags from the linker
3657 // symbol, so put these flags
3658 // into the N_STSYM flags to avoid duplicate
3659 // symbols in the symbol table
3660 sym[pos->second].SetExternal(
3661 sym[sym_idx].IsExternal());
3662 sym[pos->second].SetFlags(nlist.n_type << 16 |
3663 nlist.n_desc);
3664 sym[sym_idx].Clear();
3665 found_it = true;
3666 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003667 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003668 }
3669 if (found_it)
3670 continue;
3671 } else {
3672 const char *gsym_name =
3673 sym[sym_idx]
3674 .GetMangled()
3675 .GetName(lldb::eLanguageTypeUnknown,
3676 Mangled::ePreferMangled)
3677 .GetCString();
3678 if (gsym_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00003679 // Combine N_GSYM stab entries with the non
3680 // stab symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00003681 ConstNameToSymbolIndexMap::const_iterator pos =
3682 N_GSYM_name_to_sym_idx.find(gsym_name);
3683 if (pos != N_GSYM_name_to_sym_idx.end()) {
3684 const uint32_t GSYM_sym_idx = pos->second;
3685 m_nlist_idx_to_sym_idx[nlist_idx] =
3686 GSYM_sym_idx;
3687 // Copy the address, because often the N_GSYM
3688 // address has an invalid address of zero
3689 // when the global is a common symbol
3690 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3691 symbol_section);
3692 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3693 symbol_value);
3694 // We just need the flags from the linker
3695 // symbol, so put these flags
3696 // into the N_GSYM flags to avoid duplicate
3697 // symbols in the symbol table
3698 sym[GSYM_sym_idx].SetFlags(
3699 nlist.n_type << 16 | nlist.n_desc);
3700 sym[sym_idx].Clear();
3701 continue;
3702 }
3703 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003704 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003705 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003706 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003707
Kate Stoneb9c1b512016-09-06 20:57:50 +00003708 sym[sym_idx].SetID(nlist_idx);
3709 sym[sym_idx].SetType(type);
3710 if (set_value) {
3711 sym[sym_idx].GetAddressRef().SetSection(
3712 symbol_section);
3713 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
Greg Clayton29e08cb2012-03-14 01:53:24 +00003714 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003715 sym[sym_idx].SetFlags(nlist.n_type << 16 |
3716 nlist.n_desc);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003717
Kate Stoneb9c1b512016-09-06 20:57:50 +00003718 if (symbol_byte_size > 0)
3719 sym[sym_idx].SetByteSize(symbol_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003720
Kate Stoneb9c1b512016-09-06 20:57:50 +00003721 if (demangled_is_synthesized)
3722 sym[sym_idx].SetDemangledNameIsSynthesized(true);
Greg Clayton60038be2015-02-14 00:51:13 +00003723 ++sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003724 } else {
3725 sym[sym_idx].Clear();
3726 }
Greg Clayton9191db42013-10-21 18:40:51 +00003727 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003728 /////////////////////////////
3729 }
3730 break; // No more entries to consider
Greg Clayton9191db42013-10-21 18:40:51 +00003731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003732 }
3733
3734 for (const auto &pos : reexport_shlib_needs_fixup) {
3735 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3736 if (undef_pos != undefined_name_to_desc.end()) {
3737 const uint8_t dylib_ordinal =
3738 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3739 if (dylib_ordinal > 0 &&
3740 dylib_ordinal < dylib_files.GetSize())
3741 sym[pos.first].SetReExportedSymbolSharedLibrary(
3742 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3743 }
3744 }
Greg Clayton9191db42013-10-21 18:40:51 +00003745 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003746 }
Greg Clayton9191db42013-10-21 18:40:51 +00003747 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003748 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003749 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003750
3751 // Must reset this in case it was mutated above!
3752 nlist_data_offset = 0;
3753#endif
3754
3755 if (nlist_data.GetByteSize() > 0) {
3756
3757 // If the sym array was not created while parsing the DSC unmapped
3758 // symbols, create it now.
3759 if (sym == NULL) {
3760 sym = symtab->Resize(symtab_load_command.nsyms +
3761 m_dysymtab.nindirectsyms);
3762 num_syms = symtab->GetNumSymbols();
3763 }
3764
3765 if (unmapped_local_symbols_found) {
3766 assert(m_dysymtab.ilocalsym == 0);
3767 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3768 nlist_idx = m_dysymtab.nlocalsym;
3769 } else {
3770 nlist_idx = 0;
3771 }
3772
3773 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3774 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3775 UndefinedNameToDescMap undefined_name_to_desc;
3776 SymbolIndexToName reexport_shlib_needs_fixup;
3777 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
3778 struct nlist_64 nlist;
3779 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset,
3780 nlist_byte_size))
3781 break;
3782
3783 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
3784 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
3785 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
3786 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
3787 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
3788
3789 SymbolType type = eSymbolTypeInvalid;
3790 const char *symbol_name = NULL;
3791
3792 if (have_strtab_data) {
3793 symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3794
3795 if (symbol_name == NULL) {
Adrian Prantl05097242018-04-30 16:49:04 +00003796 // No symbol should be NULL, even the symbols with no string values
3797 // should have an offset zero which points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00003798 Host::SystemLog(Host::eSystemLogError,
3799 "error: symbol[%u] has invalid string table offset "
3800 "0x%x in %s, ignoring symbol\n",
3801 nlist_idx, nlist.n_strx,
3802 module_sp->GetFileSpec().GetPath().c_str());
3803 continue;
3804 }
3805 if (symbol_name[0] == '\0')
3806 symbol_name = NULL;
3807 } else {
3808 const addr_t str_addr = strtab_addr + nlist.n_strx;
Zachary Turner97206d52017-05-12 04:51:55 +00003809 Status str_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003810 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3811 str_error))
3812 symbol_name = memory_symbol_name.c_str();
3813 }
3814 const char *symbol_name_non_abi_mangled = NULL;
3815
3816 SectionSP symbol_section;
3817 lldb::addr_t symbol_byte_size = 0;
3818 bool add_nlist = true;
3819 bool is_gsym = false;
3820 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3821 bool demangled_is_synthesized = false;
3822 bool set_value = true;
3823 assert(sym_idx < num_syms);
3824
3825 sym[sym_idx].SetDebug(is_debug);
3826
3827 if (is_debug) {
3828 switch (nlist.n_type) {
3829 case N_GSYM:
3830 // global symbol: name,,NO_SECT,type,0
3831 // Sometimes the N_GSYM value contains the address.
3832
3833 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3834 // the ObjC data. They
3835 // have the same address, but we want to ensure that we always find
Adrian Prantl05097242018-04-30 16:49:04 +00003836 // only the real symbol, 'cause we don't currently correctly
3837 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3838 // type. This is a temporary hack to make sure the ObjectiveC
3839 // symbols get treated correctly. To do this right, we should
3840 // coalesce all the GSYM & global symbols that have the same
3841 // address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003842 is_gsym = true;
3843 sym[sym_idx].SetExternal(true);
3844
3845 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3846 llvm::StringRef symbol_name_ref(symbol_name);
3847 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3848 symbol_name_non_abi_mangled = symbol_name + 1;
3849 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3850 type = eSymbolTypeObjCClass;
3851 demangled_is_synthesized = true;
3852
3853 } else if (symbol_name_ref.startswith(
3854 g_objc_v2_prefix_metaclass)) {
3855 symbol_name_non_abi_mangled = symbol_name + 1;
3856 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3857 type = eSymbolTypeObjCMetaClass;
3858 demangled_is_synthesized = true;
3859 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3860 symbol_name_non_abi_mangled = symbol_name + 1;
3861 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3862 type = eSymbolTypeObjCIVar;
3863 demangled_is_synthesized = true;
3864 }
3865 } else {
3866 if (nlist.n_value != 0)
3867 symbol_section =
3868 section_info.GetSection(nlist.n_sect, nlist.n_value);
3869 type = eSymbolTypeData;
3870 }
3871 break;
3872
3873 case N_FNAME:
3874 // procedure name (f77 kludge): name,,NO_SECT,0,0
3875 type = eSymbolTypeCompiler;
3876 break;
3877
3878 case N_FUN:
3879 // procedure: name,,n_sect,linenumber,address
3880 if (symbol_name) {
3881 type = eSymbolTypeCode;
3882 symbol_section =
3883 section_info.GetSection(nlist.n_sect, nlist.n_value);
3884
3885 N_FUN_addr_to_sym_idx.insert(
3886 std::make_pair(nlist.n_value, sym_idx));
3887 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003888 // lieu of using nlist_idx in case we ever start trimming entries
3889 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003890 N_FUN_indexes.push_back(sym_idx);
3891 } else {
3892 type = eSymbolTypeCompiler;
3893
3894 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003895 // Copy the size of the function into the original STAB entry
3896 // so we don't have to hunt for it later
Kate Stoneb9c1b512016-09-06 20:57:50 +00003897 symtab->SymbolAtIndex(N_FUN_indexes.back())
3898 ->SetByteSize(nlist.n_value);
3899 N_FUN_indexes.pop_back();
Adrian Prantl05097242018-04-30 16:49:04 +00003900 // We don't really need the end function STAB as it contains
3901 // the size which we already placed with the original symbol,
3902 // so don't add it if we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003903 add_nlist = false;
3904 }
3905 }
3906 break;
3907
3908 case N_STSYM:
3909 // static symbol: name,,n_sect,type,address
3910 N_STSYM_addr_to_sym_idx.insert(
3911 std::make_pair(nlist.n_value, sym_idx));
3912 symbol_section =
3913 section_info.GetSection(nlist.n_sect, nlist.n_value);
3914 if (symbol_name && symbol_name[0]) {
3915 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3916 eSymbolTypeData);
3917 }
3918 break;
3919
3920 case N_LCSYM:
3921 // .lcomm symbol: name,,n_sect,type,address
3922 symbol_section =
3923 section_info.GetSection(nlist.n_sect, nlist.n_value);
3924 type = eSymbolTypeCommonBlock;
3925 break;
3926
3927 case N_BNSYM:
3928 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00003929 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003930 // Skip these if we want minimal symbol tables
3931 add_nlist = false;
3932 break;
3933
3934 case N_ENSYM:
3935 // Set the size of the N_BNSYM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003936 // N_ENSYM so that we can always skip the entire symbol if we need
3937 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003938 // Skip these if we want minimal symbol tables
3939 add_nlist = false;
3940 break;
3941
3942 case N_OPT:
3943 // emitted with gcc2_compiled and in gcc source
3944 type = eSymbolTypeCompiler;
3945 break;
3946
3947 case N_RSYM:
3948 // register sym: name,,NO_SECT,type,register
3949 type = eSymbolTypeVariable;
3950 break;
3951
3952 case N_SLINE:
3953 // src line: 0,,n_sect,linenumber,address
3954 symbol_section =
3955 section_info.GetSection(nlist.n_sect, nlist.n_value);
3956 type = eSymbolTypeLineEntry;
3957 break;
3958
3959 case N_SSYM:
3960 // structure elt: name,,NO_SECT,type,struct_offset
3961 type = eSymbolTypeVariableType;
3962 break;
3963
3964 case N_SO:
3965 // source file name
3966 type = eSymbolTypeSourceFile;
3967 if (symbol_name == NULL) {
3968 add_nlist = false;
3969 if (N_SO_index != UINT32_MAX) {
3970 // Set the size of the N_SO to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003971 // N_SO so that we can always skip the entire N_SO if we need
3972 // to navigate more quickly at the source level when parsing
3973 // STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003974 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3975 symbol_ptr->SetByteSize(sym_idx);
3976 symbol_ptr->SetSizeIsSibling(true);
3977 }
3978 N_NSYM_indexes.clear();
3979 N_INCL_indexes.clear();
3980 N_BRAC_indexes.clear();
3981 N_COMM_indexes.clear();
3982 N_FUN_indexes.clear();
3983 N_SO_index = UINT32_MAX;
3984 } else {
3985 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003986 // lieu of using nlist_idx in case we ever start trimming entries
3987 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003988 const bool N_SO_has_full_path = symbol_name[0] == '/';
3989 if (N_SO_has_full_path) {
3990 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3991 // We have two consecutive N_SO entries where the first
Adrian Prantl05097242018-04-30 16:49:04 +00003992 // contains a directory and the second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003993 sym[sym_idx - 1].GetMangled().SetValue(
3994 ConstString(symbol_name), false);
3995 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3996 add_nlist = false;
3997 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003998 // This is the first entry in a N_SO that contains a
3999 // directory or a full path to the source file
Kate Stoneb9c1b512016-09-06 20:57:50 +00004000 N_SO_index = sym_idx;
4001 }
4002 } else if ((N_SO_index == sym_idx - 1) &&
4003 ((sym_idx - 1) < num_syms)) {
4004 // This is usually the second N_SO entry that contains just the
Adrian Prantl05097242018-04-30 16:49:04 +00004005 // filename, so here we combine it with the first one if we are
4006 // minimizing the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004007 const char *so_path =
4008 sym[sym_idx - 1]
4009 .GetMangled()
4010 .GetDemangledName(lldb::eLanguageTypeUnknown)
4011 .AsCString();
4012 if (so_path && so_path[0]) {
4013 std::string full_so_path(so_path);
4014 const size_t double_slash_pos = full_so_path.find("//");
4015 if (double_slash_pos != std::string::npos) {
4016 // The linker has been generating bad N_SO entries with
Adrian Prantl05097242018-04-30 16:49:04 +00004017 // doubled up paths in the format "%s%s" where the first
4018 // string in the DW_AT_comp_dir, and the second is the
4019 // directory for the source file so you end up with a path
4020 // that looks like "/tmp/src//tmp/src/"
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004021 FileSpec so_dir(so_path);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00004022 if (!FileSystem::Instance().Exists(so_dir)) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004023 so_dir.SetFile(&full_so_path[double_slash_pos + 1],
Jonas Devlieghere937348c2018-06-13 22:08:14 +00004024 FileSpec::Style::native);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00004025 if (FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004026 // Trim off the incorrect path
4027 full_so_path.erase(0, double_slash_pos + 1);
4028 }
4029 }
4030 }
4031 if (*full_so_path.rbegin() != '/')
4032 full_so_path += '/';
4033 full_so_path += symbol_name;
4034 sym[sym_idx - 1].GetMangled().SetValue(
4035 ConstString(full_so_path.c_str()), false);
4036 add_nlist = false;
4037 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4038 }
4039 } else {
4040 // This could be a relative path to a N_SO
4041 N_SO_index = sym_idx;
4042 }
4043 }
4044 break;
4045
4046 case N_OSO:
4047 // object file name: name,,0,0,st_mtime
4048 type = eSymbolTypeObjectFile;
4049 break;
4050
4051 case N_LSYM:
4052 // local sym: name,,NO_SECT,type,offset
4053 type = eSymbolTypeLocal;
4054 break;
4055
4056 //----------------------------------------------------------------------
4057 // INCL scopes
4058 //----------------------------------------------------------------------
4059 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00004060 // include file beginning: name,,NO_SECT,0,sum We use the current
4061 // number of symbols in the symbol table in lieu of using nlist_idx
4062 // in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004063 N_INCL_indexes.push_back(sym_idx);
4064 type = eSymbolTypeScopeBegin;
4065 break;
4066
4067 case N_EINCL:
4068 // include file end: name,,NO_SECT,0,0
4069 // Set the size of the N_BINCL to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004070 // N_EINCL so that we can always skip the entire symbol if we need
4071 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004072 if (!N_INCL_indexes.empty()) {
4073 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
4074 symbol_ptr->SetByteSize(sym_idx + 1);
4075 symbol_ptr->SetSizeIsSibling(true);
4076 N_INCL_indexes.pop_back();
4077 }
4078 type = eSymbolTypeScopeEnd;
4079 break;
4080
4081 case N_SOL:
4082 // #included file name: name,,n_sect,0,address
4083 type = eSymbolTypeHeaderFile;
4084
4085 // We currently don't use the header files on darwin
4086 add_nlist = false;
4087 break;
4088
4089 case N_PARAMS:
4090 // compiler parameters: name,,NO_SECT,0,0
4091 type = eSymbolTypeCompiler;
4092 break;
4093
4094 case N_VERSION:
4095 // compiler version: name,,NO_SECT,0,0
4096 type = eSymbolTypeCompiler;
4097 break;
4098
4099 case N_OLEVEL:
4100 // compiler -O level: name,,NO_SECT,0,0
4101 type = eSymbolTypeCompiler;
4102 break;
4103
4104 case N_PSYM:
4105 // parameter: name,,NO_SECT,type,offset
4106 type = eSymbolTypeVariable;
4107 break;
4108
4109 case N_ENTRY:
4110 // alternate entry: name,,n_sect,linenumber,address
4111 symbol_section =
4112 section_info.GetSection(nlist.n_sect, nlist.n_value);
4113 type = eSymbolTypeLineEntry;
4114 break;
4115
4116 //----------------------------------------------------------------------
4117 // Left and Right Braces
4118 //----------------------------------------------------------------------
4119 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004120 // left bracket: 0,,NO_SECT,nesting level,address We use the
4121 // current number of symbols in the symbol table in lieu of using
4122 // nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004123 symbol_section =
4124 section_info.GetSection(nlist.n_sect, nlist.n_value);
4125 N_BRAC_indexes.push_back(sym_idx);
4126 type = eSymbolTypeScopeBegin;
4127 break;
4128
4129 case N_RBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004130 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4131 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4132 // can always skip the entire symbol if we need to navigate more
4133 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004134 symbol_section =
4135 section_info.GetSection(nlist.n_sect, nlist.n_value);
4136 if (!N_BRAC_indexes.empty()) {
4137 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4138 symbol_ptr->SetByteSize(sym_idx + 1);
4139 symbol_ptr->SetSizeIsSibling(true);
4140 N_BRAC_indexes.pop_back();
4141 }
4142 type = eSymbolTypeScopeEnd;
4143 break;
4144
4145 case N_EXCL:
4146 // deleted include file: name,,NO_SECT,0,sum
4147 type = eSymbolTypeHeaderFile;
4148 break;
4149
4150 //----------------------------------------------------------------------
4151 // COMM scopes
4152 //----------------------------------------------------------------------
4153 case N_BCOMM:
4154 // begin common: name,,NO_SECT,0,0
4155 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00004156 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004157 type = eSymbolTypeScopeBegin;
4158 N_COMM_indexes.push_back(sym_idx);
4159 break;
4160
4161 case N_ECOML:
4162 // end common (local name): 0,,n_sect,0,address
4163 symbol_section =
4164 section_info.GetSection(nlist.n_sect, nlist.n_value);
4165 LLVM_FALLTHROUGH;
4166
4167 case N_ECOMM:
4168 // end common: name,,n_sect,0,0
4169 // Set the size of the N_BCOMM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004170 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4171 // we need to navigate more quickly at the source level when
4172 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004173 if (!N_COMM_indexes.empty()) {
4174 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4175 symbol_ptr->SetByteSize(sym_idx + 1);
4176 symbol_ptr->SetSizeIsSibling(true);
4177 N_COMM_indexes.pop_back();
4178 }
4179 type = eSymbolTypeScopeEnd;
4180 break;
4181
4182 case N_LENG:
4183 // second stab entry with length information
4184 type = eSymbolTypeAdditional;
4185 break;
4186
4187 default:
4188 break;
4189 }
4190 } else {
4191 // uint8_t n_pext = N_PEXT & nlist.n_type;
4192 uint8_t n_type = N_TYPE & nlist.n_type;
4193 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4194
4195 switch (n_type) {
4196 case N_INDR: {
4197 const char *reexport_name_cstr =
4198 strtab_data.PeekCStr(nlist.n_value);
4199 if (reexport_name_cstr && reexport_name_cstr[0]) {
4200 type = eSymbolTypeReExported;
4201 ConstString reexport_name(
4202 reexport_name_cstr +
4203 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4204 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4205 set_value = false;
4206 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4207 indirect_symbol_names.insert(
4208 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4209 } else
4210 type = eSymbolTypeUndefined;
4211 } break;
4212
4213 case N_UNDF:
4214 if (symbol_name && symbol_name[0]) {
4215 ConstString undefined_name(symbol_name +
4216 ((symbol_name[0] == '_') ? 1 : 0));
4217 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4218 }
4219 LLVM_FALLTHROUGH;
4220
4221 case N_PBUD:
4222 type = eSymbolTypeUndefined;
4223 break;
4224
4225 case N_ABS:
4226 type = eSymbolTypeAbsolute;
4227 break;
4228
4229 case N_SECT: {
4230 symbol_section =
4231 section_info.GetSection(nlist.n_sect, nlist.n_value);
4232
4233 if (!symbol_section) {
4234 // TODO: warn about this?
4235 add_nlist = false;
4236 break;
4237 }
4238
4239 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4240 type = eSymbolTypeException;
4241 } else {
4242 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4243
4244 switch (section_type) {
4245 case S_CSTRING_LITERALS:
4246 type = eSymbolTypeData;
4247 break; // section with only literal C strings
4248 case S_4BYTE_LITERALS:
4249 type = eSymbolTypeData;
4250 break; // section with only 4 byte literals
4251 case S_8BYTE_LITERALS:
4252 type = eSymbolTypeData;
4253 break; // section with only 8 byte literals
4254 case S_LITERAL_POINTERS:
4255 type = eSymbolTypeTrampoline;
4256 break; // section with only pointers to literals
4257 case S_NON_LAZY_SYMBOL_POINTERS:
4258 type = eSymbolTypeTrampoline;
4259 break; // section with only non-lazy symbol pointers
4260 case S_LAZY_SYMBOL_POINTERS:
4261 type = eSymbolTypeTrampoline;
4262 break; // section with only lazy symbol pointers
4263 case S_SYMBOL_STUBS:
4264 type = eSymbolTypeTrampoline;
4265 break; // section with only symbol stubs, byte size of stub in
4266 // the reserved2 field
4267 case S_MOD_INIT_FUNC_POINTERS:
4268 type = eSymbolTypeCode;
4269 break; // section with only function pointers for initialization
4270 case S_MOD_TERM_FUNC_POINTERS:
4271 type = eSymbolTypeCode;
4272 break; // section with only function pointers for termination
4273 case S_INTERPOSING:
4274 type = eSymbolTypeTrampoline;
4275 break; // section with only pairs of function pointers for
4276 // interposing
4277 case S_16BYTE_LITERALS:
4278 type = eSymbolTypeData;
4279 break; // section with only 16 byte literals
4280 case S_DTRACE_DOF:
4281 type = eSymbolTypeInstrumentation;
4282 break;
4283 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4284 type = eSymbolTypeTrampoline;
4285 break;
4286 default:
4287 switch (symbol_section->GetType()) {
4288 case lldb::eSectionTypeCode:
4289 type = eSymbolTypeCode;
4290 break;
4291 case eSectionTypeData:
4292 case eSectionTypeDataCString: // Inlined C string data
4293 case eSectionTypeDataCStringPointers: // Pointers to C string
4294 // data
4295 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4296 // the symbol table
4297 case eSectionTypeData4:
4298 case eSectionTypeData8:
4299 case eSectionTypeData16:
4300 type = eSymbolTypeData;
4301 break;
4302 default:
4303 break;
4304 }
4305 break;
4306 }
4307
4308 if (type == eSymbolTypeInvalid) {
4309 const char *symbol_sect_name =
4310 symbol_section->GetName().AsCString();
4311 if (symbol_section->IsDescendant(text_section_sp.get())) {
4312 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4313 S_ATTR_SELF_MODIFYING_CODE |
4314 S_ATTR_SOME_INSTRUCTIONS))
4315 type = eSymbolTypeData;
4316 else
4317 type = eSymbolTypeCode;
4318 } else if (symbol_section->IsDescendant(
4319 data_section_sp.get()) ||
4320 symbol_section->IsDescendant(
4321 data_dirty_section_sp.get()) ||
4322 symbol_section->IsDescendant(
4323 data_const_section_sp.get())) {
4324 if (symbol_sect_name &&
4325 ::strstr(symbol_sect_name, "__objc") ==
4326 symbol_sect_name) {
4327 type = eSymbolTypeRuntime;
4328
4329 if (symbol_name) {
4330 llvm::StringRef symbol_name_ref(symbol_name);
4331 if (symbol_name_ref.startswith("_OBJC_")) {
4332 static const llvm::StringRef g_objc_v2_prefix_class(
4333 "_OBJC_CLASS_$_");
4334 static const llvm::StringRef g_objc_v2_prefix_metaclass(
4335 "_OBJC_METACLASS_$_");
4336 static const llvm::StringRef g_objc_v2_prefix_ivar(
4337 "_OBJC_IVAR_$_");
4338 if (symbol_name_ref.startswith(
4339 g_objc_v2_prefix_class)) {
4340 symbol_name_non_abi_mangled = symbol_name + 1;
4341 symbol_name =
4342 symbol_name + g_objc_v2_prefix_class.size();
4343 type = eSymbolTypeObjCClass;
4344 demangled_is_synthesized = true;
4345 } else if (symbol_name_ref.startswith(
4346 g_objc_v2_prefix_metaclass)) {
4347 symbol_name_non_abi_mangled = symbol_name + 1;
4348 symbol_name =
4349 symbol_name + g_objc_v2_prefix_metaclass.size();
4350 type = eSymbolTypeObjCMetaClass;
4351 demangled_is_synthesized = true;
4352 } else if (symbol_name_ref.startswith(
4353 g_objc_v2_prefix_ivar)) {
4354 symbol_name_non_abi_mangled = symbol_name + 1;
4355 symbol_name =
4356 symbol_name + g_objc_v2_prefix_ivar.size();
4357 type = eSymbolTypeObjCIVar;
4358 demangled_is_synthesized = true;
4359 }
4360 }
4361 }
4362 } else if (symbol_sect_name &&
4363 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4364 symbol_sect_name) {
4365 type = eSymbolTypeException;
4366 } else {
4367 type = eSymbolTypeData;
4368 }
4369 } else if (symbol_sect_name &&
4370 ::strstr(symbol_sect_name, "__IMPORT") ==
4371 symbol_sect_name) {
4372 type = eSymbolTypeTrampoline;
4373 } else if (symbol_section->IsDescendant(
4374 objc_section_sp.get())) {
4375 type = eSymbolTypeRuntime;
4376 if (symbol_name && symbol_name[0] == '.') {
4377 llvm::StringRef symbol_name_ref(symbol_name);
4378 static const llvm::StringRef g_objc_v1_prefix_class(
4379 ".objc_class_name_");
4380 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4381 symbol_name_non_abi_mangled = symbol_name;
4382 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4383 type = eSymbolTypeObjCClass;
4384 demangled_is_synthesized = true;
4385 }
4386 }
4387 }
4388 }
4389 }
4390 } break;
4391 }
4392 }
4393
4394 if (add_nlist) {
4395 uint64_t symbol_value = nlist.n_value;
4396
4397 if (symbol_name_non_abi_mangled) {
4398 sym[sym_idx].GetMangled().SetMangledName(
4399 ConstString(symbol_name_non_abi_mangled));
4400 sym[sym_idx].GetMangled().SetDemangledName(
4401 ConstString(symbol_name));
4402 } else {
4403 bool symbol_name_is_mangled = false;
4404
4405 if (symbol_name && symbol_name[0] == '_') {
4406 symbol_name_is_mangled = symbol_name[1] == '_';
4407 symbol_name++; // Skip the leading underscore
4408 }
4409
4410 if (symbol_name) {
4411 ConstString const_symbol_name(symbol_name);
4412 sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4413 symbol_name_is_mangled);
4414 }
4415 }
4416
4417 if (is_gsym) {
4418 const char *gsym_name = sym[sym_idx]
4419 .GetMangled()
4420 .GetName(lldb::eLanguageTypeUnknown,
4421 Mangled::ePreferMangled)
4422 .GetCString();
4423 if (gsym_name)
4424 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4425 }
4426
4427 if (symbol_section) {
4428 const addr_t section_file_addr = symbol_section->GetFileAddress();
4429 if (symbol_byte_size == 0 && function_starts_count > 0) {
4430 addr_t symbol_lookup_file_addr = nlist.n_value;
4431 // Do an exact address match for non-ARM addresses, else get the
Adrian Prantl05097242018-04-30 16:49:04 +00004432 // closest since the symbol might be a thumb symbol which has an
4433 // address with bit zero set
Kate Stoneb9c1b512016-09-06 20:57:50 +00004434 FunctionStarts::Entry *func_start_entry =
4435 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4436 if (is_arm && func_start_entry) {
4437 // Verify that the function start address is the symbol address
Adrian Prantl05097242018-04-30 16:49:04 +00004438 // (ARM) or the symbol address + 1 (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004439 if (func_start_entry->addr != symbol_lookup_file_addr &&
4440 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4441 // Not the right entry, NULL it out...
4442 func_start_entry = NULL;
4443 }
4444 }
4445 if (func_start_entry) {
4446 func_start_entry->data = true;
4447
4448 addr_t symbol_file_addr = func_start_entry->addr;
4449 if (is_arm)
4450 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4451
4452 const FunctionStarts::Entry *next_func_start_entry =
4453 function_starts.FindNextEntry(func_start_entry);
4454 const addr_t section_end_file_addr =
4455 section_file_addr + symbol_section->GetByteSize();
4456 if (next_func_start_entry) {
4457 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4458 // Be sure the clear the Thumb address bit when we calculate
Adrian Prantl05097242018-04-30 16:49:04 +00004459 // the size from the current and next address
Kate Stoneb9c1b512016-09-06 20:57:50 +00004460 if (is_arm)
4461 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4462 symbol_byte_size = std::min<lldb::addr_t>(
4463 next_symbol_file_addr - symbol_file_addr,
4464 section_end_file_addr - symbol_file_addr);
4465 } else {
4466 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4467 }
4468 }
4469 }
4470 symbol_value -= section_file_addr;
4471 }
4472
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004473 if (!is_debug) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474 if (type == eSymbolTypeCode) {
Adrian Prantl05097242018-04-30 16:49:04 +00004475 // See if we can find a N_FUN entry for any code symbols. If we
4476 // do find a match, and the name matches, then we can merge the
4477 // two into just the function symbol to avoid duplicate entries
4478 // in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004479 std::pair<ValueToSymbolIndexMap::const_iterator,
4480 ValueToSymbolIndexMap::const_iterator>
4481 range;
4482 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4483 if (range.first != range.second) {
4484 bool found_it = false;
4485 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4486 pos != range.second; ++pos) {
4487 if (sym[sym_idx].GetMangled().GetName(
4488 lldb::eLanguageTypeUnknown,
4489 Mangled::ePreferMangled) ==
4490 sym[pos->second].GetMangled().GetName(
4491 lldb::eLanguageTypeUnknown,
4492 Mangled::ePreferMangled)) {
4493 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4494 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004495 // these flags into the N_FUN flags to avoid duplicate
4496 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004497 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4498 sym[pos->second].SetFlags(nlist.n_type << 16 |
4499 nlist.n_desc);
4500 if (resolver_addresses.find(nlist.n_value) !=
4501 resolver_addresses.end())
4502 sym[pos->second].SetType(eSymbolTypeResolver);
4503 sym[sym_idx].Clear();
4504 found_it = true;
4505 break;
4506 }
4507 }
4508 if (found_it)
4509 continue;
4510 } else {
4511 if (resolver_addresses.find(nlist.n_value) !=
4512 resolver_addresses.end())
4513 type = eSymbolTypeResolver;
4514 }
4515 } else if (type == eSymbolTypeData ||
4516 type == eSymbolTypeObjCClass ||
4517 type == eSymbolTypeObjCMetaClass ||
4518 type == eSymbolTypeObjCIVar) {
Adrian Prantl05097242018-04-30 16:49:04 +00004519 // See if we can find a N_STSYM entry for any data symbols. If we
4520 // do find a match, and the name matches, then we can merge the
4521 // two into just the Static symbol to avoid duplicate entries in
4522 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004523 std::pair<ValueToSymbolIndexMap::const_iterator,
4524 ValueToSymbolIndexMap::const_iterator>
4525 range;
4526 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4527 if (range.first != range.second) {
4528 bool found_it = false;
4529 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4530 pos != range.second; ++pos) {
4531 if (sym[sym_idx].GetMangled().GetName(
4532 lldb::eLanguageTypeUnknown,
4533 Mangled::ePreferMangled) ==
4534 sym[pos->second].GetMangled().GetName(
4535 lldb::eLanguageTypeUnknown,
4536 Mangled::ePreferMangled)) {
4537 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4538 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004539 // these flags into the N_STSYM flags to avoid duplicate
4540 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004541 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4542 sym[pos->second].SetFlags(nlist.n_type << 16 |
4543 nlist.n_desc);
4544 sym[sym_idx].Clear();
4545 found_it = true;
4546 break;
4547 }
4548 }
4549 if (found_it)
4550 continue;
4551 } else {
4552 // Combine N_GSYM stab entries with the non stab symbol
4553 const char *gsym_name = sym[sym_idx]
4554 .GetMangled()
4555 .GetName(lldb::eLanguageTypeUnknown,
4556 Mangled::ePreferMangled)
4557 .GetCString();
4558 if (gsym_name) {
4559 ConstNameToSymbolIndexMap::const_iterator pos =
4560 N_GSYM_name_to_sym_idx.find(gsym_name);
4561 if (pos != N_GSYM_name_to_sym_idx.end()) {
4562 const uint32_t GSYM_sym_idx = pos->second;
4563 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00004564 // Copy the address, because often the N_GSYM address has
4565 // an invalid address of zero when the global is a common
4566 // symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00004567 sym[GSYM_sym_idx].GetAddressRef().SetSection(
4568 symbol_section);
4569 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4570 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004571 // these flags into the N_GSYM flags to avoid duplicate
4572 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004573 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
4574 nlist.n_desc);
4575 sym[sym_idx].Clear();
4576 continue;
4577 }
4578 }
4579 }
4580 }
4581 }
4582
4583 sym[sym_idx].SetID(nlist_idx);
4584 sym[sym_idx].SetType(type);
4585 if (set_value) {
4586 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4587 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4588 }
4589 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4590
4591 if (symbol_byte_size > 0)
4592 sym[sym_idx].SetByteSize(symbol_byte_size);
4593
4594 if (demangled_is_synthesized)
4595 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4596
4597 ++sym_idx;
4598 } else {
4599 sym[sym_idx].Clear();
4600 }
4601 }
4602
4603 for (const auto &pos : reexport_shlib_needs_fixup) {
4604 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4605 if (undef_pos != undefined_name_to_desc.end()) {
4606 const uint8_t dylib_ordinal =
4607 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4608 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4609 sym[pos.first].SetReExportedSymbolSharedLibrary(
4610 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4611 }
4612 }
4613 }
4614
4615 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4616
4617 if (function_starts_count > 0) {
4618 uint32_t num_synthetic_function_symbols = 0;
4619 for (i = 0; i < function_starts_count; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004620 if (!function_starts.GetEntryRef(i).data)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004621 ++num_synthetic_function_symbols;
4622 }
4623
4624 if (num_synthetic_function_symbols > 0) {
4625 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4626 num_syms = sym_idx + num_synthetic_function_symbols;
4627 sym = symtab->Resize(num_syms);
4628 }
4629 for (i = 0; i < function_starts_count; ++i) {
4630 const FunctionStarts::Entry *func_start_entry =
4631 function_starts.GetEntryAtIndex(i);
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004632 if (!func_start_entry->data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004633 addr_t symbol_file_addr = func_start_entry->addr;
4634 uint32_t symbol_flags = 0;
4635 if (is_arm) {
4636 if (symbol_file_addr & 1)
4637 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4638 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4639 }
4640 Address symbol_addr;
4641 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4642 SectionSP symbol_section(symbol_addr.GetSection());
4643 uint32_t symbol_byte_size = 0;
4644 if (symbol_section) {
4645 const addr_t section_file_addr =
4646 symbol_section->GetFileAddress();
4647 const FunctionStarts::Entry *next_func_start_entry =
4648 function_starts.FindNextEntry(func_start_entry);
4649 const addr_t section_end_file_addr =
4650 section_file_addr + symbol_section->GetByteSize();
4651 if (next_func_start_entry) {
4652 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4653 if (is_arm)
4654 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4655 symbol_byte_size = std::min<lldb::addr_t>(
4656 next_symbol_file_addr - symbol_file_addr,
4657 section_end_file_addr - symbol_file_addr);
4658 } else {
4659 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4660 }
4661 sym[sym_idx].SetID(synthetic_sym_id++);
4662 sym[sym_idx].GetMangled().SetDemangledName(
4663 GetNextSyntheticSymbolName());
4664 sym[sym_idx].SetType(eSymbolTypeCode);
4665 sym[sym_idx].SetIsSynthetic(true);
4666 sym[sym_idx].GetAddressRef() = symbol_addr;
4667 if (symbol_flags)
4668 sym[sym_idx].SetFlags(symbol_flags);
4669 if (symbol_byte_size)
4670 sym[sym_idx].SetByteSize(symbol_byte_size);
4671 ++sym_idx;
4672 }
4673 }
4674 }
4675 }
4676 }
4677 }
4678
Adrian Prantl05097242018-04-30 16:49:04 +00004679 // Trim our symbols down to just what we ended up with after removing any
4680 // symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004681 if (sym_idx < num_syms) {
4682 num_syms = sym_idx;
4683 sym = symtab->Resize(num_syms);
4684 }
4685
4686 // Now synthesize indirect symbols
4687 if (m_dysymtab.nindirectsyms != 0) {
4688 if (indirect_symbol_index_data.GetByteSize()) {
4689 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4690 m_nlist_idx_to_sym_idx.end();
4691
4692 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4693 ++sect_idx) {
4694 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4695 S_SYMBOL_STUBS) {
4696 uint32_t symbol_stub_byte_size =
4697 m_mach_sections[sect_idx].reserved2;
4698 if (symbol_stub_byte_size == 0)
4699 continue;
4700
4701 const uint32_t num_symbol_stubs =
4702 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4703
4704 if (num_symbol_stubs == 0)
4705 continue;
4706
4707 const uint32_t symbol_stub_index_offset =
4708 m_mach_sections[sect_idx].reserved1;
4709 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs;
4710 ++stub_idx) {
4711 const uint32_t symbol_stub_index =
4712 symbol_stub_index_offset + stub_idx;
4713 const lldb::addr_t symbol_stub_addr =
4714 m_mach_sections[sect_idx].addr +
4715 (stub_idx * symbol_stub_byte_size);
4716 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4717 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4718 symbol_stub_offset, 4)) {
4719 const uint32_t stub_sym_id =
4720 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4721 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4722 continue;
4723
4724 NListIndexToSymbolIndexMap::const_iterator index_pos =
4725 m_nlist_idx_to_sym_idx.find(stub_sym_id);
4726 Symbol *stub_symbol = NULL;
4727 if (index_pos != end_index_pos) {
Adrian Prantl05097242018-04-30 16:49:04 +00004728 // We have a remapping from the original nlist index to a
4729 // current symbol index, so just look this up by index
Kate Stoneb9c1b512016-09-06 20:57:50 +00004730 stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4731 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004732 // We need to lookup a symbol using the original nlist symbol
4733 // index since this index is coming from the S_SYMBOL_STUBS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004734 stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4735 }
4736
4737 if (stub_symbol) {
4738 Address so_addr(symbol_stub_addr, section_list);
4739
4740 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4741 // Change the external symbol into a trampoline that makes
Adrian Prantl05097242018-04-30 16:49:04 +00004742 // sense These symbols were N_UNDF N_EXT, and are useless
4743 // to us, so we can re-use them so we don't have to make up
4744 // a synthetic symbol for no good reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004745 if (resolver_addresses.find(symbol_stub_addr) ==
4746 resolver_addresses.end())
4747 stub_symbol->SetType(eSymbolTypeTrampoline);
4748 else
4749 stub_symbol->SetType(eSymbolTypeResolver);
4750 stub_symbol->SetExternal(false);
4751 stub_symbol->GetAddressRef() = so_addr;
4752 stub_symbol->SetByteSize(symbol_stub_byte_size);
4753 } else {
4754 // Make a synthetic symbol to describe the trampoline stub
4755 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4756 if (sym_idx >= num_syms) {
4757 sym = symtab->Resize(++num_syms);
4758 stub_symbol = NULL; // this pointer no longer valid
4759 }
4760 sym[sym_idx].SetID(synthetic_sym_id++);
4761 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4762 if (resolver_addresses.find(symbol_stub_addr) ==
4763 resolver_addresses.end())
4764 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4765 else
4766 sym[sym_idx].SetType(eSymbolTypeResolver);
4767 sym[sym_idx].SetIsSynthetic(true);
4768 sym[sym_idx].GetAddressRef() = so_addr;
4769 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4770 ++sym_idx;
4771 }
4772 } else {
4773 if (log)
4774 log->Warning("symbol stub referencing symbol table symbol "
4775 "%u that isn't in our minimal symbol table, "
4776 "fix this!!!",
4777 stub_sym_id);
4778 }
4779 }
4780 }
4781 }
4782 }
4783 }
4784 }
4785
4786 if (!trie_entries.empty()) {
4787 for (const auto &e : trie_entries) {
4788 if (e.entry.import_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00004789 // Only add indirect symbols from the Trie entries if we didn't have
4790 // a N_INDR nlist entry for this already
Kate Stoneb9c1b512016-09-06 20:57:50 +00004791 if (indirect_symbol_names.find(e.entry.name) ==
4792 indirect_symbol_names.end()) {
4793 // Make a synthetic symbol to describe re-exported symbol.
4794 if (sym_idx >= num_syms)
4795 sym = symtab->Resize(++num_syms);
4796 sym[sym_idx].SetID(synthetic_sym_id++);
4797 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4798 sym[sym_idx].SetType(eSymbolTypeReExported);
4799 sym[sym_idx].SetIsSynthetic(true);
4800 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4801 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4802 sym[sym_idx].SetReExportedSymbolSharedLibrary(
4803 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4804 }
4805 ++sym_idx;
4806 }
4807 }
4808 }
4809 }
4810
Davide Italiano407c6912018-11-02 21:59:14 +00004811 // StreamFile s(stdout, false);
4812 // s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4813 // symtab->Dump(&s, NULL, eSortOrderNone);
4814 // Set symbol byte sizes correctly since mach-o nlist entries don't have
4815 // sizes
4816 symtab->CalculateSymbolSizes();
4817
4818 // s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4819 // symtab->Dump(&s, NULL, eSortOrderNone);
4820
Kate Stoneb9c1b512016-09-06 20:57:50 +00004821 return symtab->GetNumSymbols();
4822 }
4823 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004824}
4825
Kate Stoneb9c1b512016-09-06 20:57:50 +00004826void ObjectFileMachO::Dump(Stream *s) {
4827 ModuleSP module_sp(GetModule());
4828 if (module_sp) {
4829 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4830 s->Printf("%p: ", static_cast<void *>(this));
4831 s->Indent();
4832 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4833 s->PutCString("ObjectFileMachO64");
4834 else
4835 s->PutCString("ObjectFileMachO32");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004836
Pavel Labathf760f5a2019-01-03 10:37:19 +00004837 ArchSpec header_arch = GetArchitecture();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004838
Kate Stoneb9c1b512016-09-06 20:57:50 +00004839 *s << ", file = '" << m_file
Adrian Prantl9702c962018-05-11 00:41:20 +00004840 << "', triple = " << header_arch.GetTriple().getTriple() << "\n";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004841
Kate Stoneb9c1b512016-09-06 20:57:50 +00004842 SectionList *sections = GetSectionList();
4843 if (sections)
4844 sections->Dump(s, NULL, true, UINT32_MAX);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004845
Kate Stoneb9c1b512016-09-06 20:57:50 +00004846 if (m_symtab_ap.get())
4847 m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4848 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004849}
4850
Kate Stoneb9c1b512016-09-06 20:57:50 +00004851bool ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4852 const lldb_private::DataExtractor &data,
4853 lldb::offset_t lc_offset,
4854 lldb_private::UUID &uuid) {
4855 uint32_t i;
4856 struct uuid_command load_cmd;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004857
Kate Stoneb9c1b512016-09-06 20:57:50 +00004858 lldb::offset_t offset = lc_offset;
4859 for (i = 0; i < header.ncmds; ++i) {
4860 const lldb::offset_t cmd_offset = offset;
4861 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4862 break;
4863
4864 if (load_cmd.cmd == LC_UUID) {
4865 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4866
4867 if (uuid_bytes) {
4868 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4869 // We pretend these object files have no UUID to prevent crashing.
4870
4871 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4872 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4873 0xbb, 0x14, 0xf0, 0x0d};
4874
4875 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4876 return false;
4877
Pavel Labath2f93fd12018-06-26 15:12:20 +00004878 uuid = UUID::fromOptionalData(uuid_bytes, 16);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004879 return true;
4880 }
4881 return false;
4882 }
4883 offset = cmd_offset + load_cmd.cmdsize;
4884 }
4885 return false;
4886}
4887
Jason Molenda32762fd2018-10-11 00:28:35 +00004888static llvm::StringRef GetOSName(uint32_t cmd) {
Adrian Prantl9702c962018-05-11 00:41:20 +00004889 switch (cmd) {
4890 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004891 return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004892 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Jason Molenda32762fd2018-10-11 00:28:35 +00004893 return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
Adrian Prantl9702c962018-05-11 00:41:20 +00004894 case llvm::MachO::LC_VERSION_MIN_TVOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004895 return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004896 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004897 return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004898 default:
4899 llvm_unreachable("unexpected LC_VERSION load command");
4900 }
4901}
4902
Jason Molenda32762fd2018-10-11 00:28:35 +00004903namespace {
4904 struct OSEnv {
4905 llvm::StringRef os_type;
4906 llvm::StringRef environment;
4907 OSEnv(uint32_t cmd) {
4908 switch (cmd) {
4909 case PLATFORM_MACOS:
4910 os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4911 return;
4912 case PLATFORM_IOS:
4913 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4914 return;
4915 case PLATFORM_TVOS:
4916 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4917 return;
4918 case PLATFORM_WATCHOS:
4919 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4920 return;
4921// NEED_BRIDGEOS_TRIPLE case PLATFORM_BRIDGEOS:
4922// NEED_BRIDGEOS_TRIPLE os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4923// NEED_BRIDGEOS_TRIPLE return;
4924#if defined (PLATFORM_IOSSIMULATOR) && defined (PLATFORM_TVOSSIMULATOR) && defined (PLATFORM_WATCHOSSIMULATOR)
4925 case PLATFORM_IOSSIMULATOR:
4926 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4927 environment =
4928 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4929 return;
4930 case PLATFORM_TVOSSIMULATOR:
4931 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4932 environment =
4933 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4934 return;
4935 case PLATFORM_WATCHOSSIMULATOR:
4936 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4937 environment =
4938 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4939 return;
4940#endif
4941 default: {
4942 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
4943 LIBLLDB_LOG_PROCESS));
4944 if (log)
4945 log->Printf("unsupported platform in LC_BUILD_VERSION");
4946 }
4947 }
4948 }
4949 };
4950
4951 struct MinOS {
Eric Liu7d2f7832018-10-11 14:44:12 +00004952 uint32_t major_version, minor_version, patch_version;
Jason Molenda32762fd2018-10-11 00:28:35 +00004953 MinOS(uint32_t version)
Eric Liu7d2f7832018-10-11 14:44:12 +00004954 : major_version(version >> 16),
4955 minor_version((version >> 8) & 0xffu),
4956 patch_version(version & 0xffu) {}
Jason Molenda32762fd2018-10-11 00:28:35 +00004957 };
4958} // namespace
4959
Pavel Labathf760f5a2019-01-03 10:37:19 +00004960ArchSpec
4961ObjectFileMachO::GetArchitecture(const llvm::MachO::mach_header &header,
4962 const lldb_private::DataExtractor &data,
4963 lldb::offset_t lc_offset) {
4964 ArchSpec arch;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004965 arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4966
4967 if (arch.IsValid()) {
4968 llvm::Triple &triple = arch.GetTriple();
4969
4970 // Set OS to an unspecified unknown or a "*" so it can match any OS
4971 triple.setOS(llvm::Triple::UnknownOS);
4972 triple.setOSName(llvm::StringRef());
4973
4974 if (header.filetype == MH_PRELOAD) {
4975 if (header.cputype == CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00004976 // If this is a 32-bit arm binary, and it's a standalone binary, force
4977 // the Vendor to Apple so we don't accidentally pick up the generic
4978 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4979 // frame pointer register; most other armv7 ABIs use a combination of
4980 // r7 and r11.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004981 triple.setVendor(llvm::Triple::Apple);
4982 } else {
4983 // Set vendor to an unspecified unknown or a "*" so it can match any
Adrian Prantl05097242018-04-30 16:49:04 +00004984 // vendor This is required for correct behavior of EFI debugging on
4985 // x86_64
Kate Stoneb9c1b512016-09-06 20:57:50 +00004986 triple.setVendor(llvm::Triple::UnknownVendor);
4987 triple.setVendorName(llvm::StringRef());
4988 }
Pavel Labathf760f5a2019-01-03 10:37:19 +00004989 return arch;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004990 } else {
4991 struct load_command load_cmd;
Jason Molenda32762fd2018-10-11 00:28:35 +00004992 llvm::SmallString<16> os_name;
4993 llvm::raw_svector_ostream os(os_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004994
Jason Molenda32762fd2018-10-11 00:28:35 +00004995 // See if there is an LC_VERSION_MIN_* load command that can give
4996 // us the OS type.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004997 lldb::offset_t offset = lc_offset;
4998 for (uint32_t i = 0; i < header.ncmds; ++i) {
Greg Claytonf4d6de62013-04-24 22:29:28 +00004999 const lldb::offset_t cmd_offset = offset;
5000 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005001 break;
5002
Adrian Prantl9702c962018-05-11 00:41:20 +00005003 struct version_min_command version_min;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005004 switch (load_cmd.cmd) {
5005 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005006 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005007 case llvm::MachO::LC_VERSION_MIN_TVOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00005008 case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
Adrian Prantl9702c962018-05-11 00:41:20 +00005009 if (load_cmd.cmdsize != sizeof(version_min))
5010 break;
Jason Molenda32762fd2018-10-11 00:28:35 +00005011 if (data.ExtractBytes(cmd_offset, sizeof(version_min),
5012 data.GetByteOrder(), &version_min) == 0)
5013 break;
5014 MinOS min_os(version_min.version);
Eric Liu7d2f7832018-10-11 14:44:12 +00005015 os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
5016 << min_os.minor_version << '.' << min_os.patch_version;
Adrian Prantl9702c962018-05-11 00:41:20 +00005017 triple.setOSName(os.str());
Pavel Labathf760f5a2019-01-03 10:37:19 +00005018 return arch;
Jason Molenda32762fd2018-10-11 00:28:35 +00005019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005020 default:
5021 break;
Greg Claytonf4d6de62013-04-24 22:29:28 +00005022 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005023
Greg Claytonf4d6de62013-04-24 22:29:28 +00005024 offset = cmd_offset + load_cmd.cmdsize;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005025 }
5026
Jason Molenda32762fd2018-10-11 00:28:35 +00005027 // See if there is an LC_BUILD_VERSION load command that can give
5028 // us the OS type.
5029
5030 offset = lc_offset;
5031 for (uint32_t i = 0; i < header.ncmds; ++i) {
5032 const lldb::offset_t cmd_offset = offset;
5033 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
5034 break;
Adrian Prantl874e32d2018-11-13 23:14:37 +00005035 do {
5036 if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
5037 struct build_version_command build_version;
5038 if (load_cmd.cmdsize < sizeof(build_version)) {
5039 // Malformed load command.
5040 break;
5041 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005042 if (data.ExtractBytes(cmd_offset, sizeof(build_version),
5043 data.GetByteOrder(), &build_version) == 0)
Adrian Prantl874e32d2018-11-13 23:14:37 +00005044 break;
5045 MinOS min_os(build_version.minos);
5046 OSEnv os_env(build_version.platform);
5047 if (os_env.os_type.empty())
5048 break;
5049 os << os_env.os_type << min_os.major_version << '.'
5050 << min_os.minor_version << '.' << min_os.patch_version;
5051 triple.setOSName(os.str());
5052 if (!os_env.environment.empty())
5053 triple.setEnvironmentName(os_env.environment);
Pavel Labathf760f5a2019-01-03 10:37:19 +00005054 return arch;
Adrian Prantl874e32d2018-11-13 23:14:37 +00005055 }
5056 } while (0);
Jason Molenda32762fd2018-10-11 00:28:35 +00005057 offset = cmd_offset + load_cmd.cmdsize;
5058 }
5059
Kate Stoneb9c1b512016-09-06 20:57:50 +00005060 if (header.filetype != MH_KEXT_BUNDLE) {
5061 // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
5062 // so lets not say our Vendor is Apple, leave it as an unspecified
5063 // unknown
5064 triple.setVendor(llvm::Triple::UnknownVendor);
5065 triple.setVendorName(llvm::StringRef());
5066 }
Greg Claytonf4d6de62013-04-24 22:29:28 +00005067 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005068 }
Pavel Labathf760f5a2019-01-03 10:37:19 +00005069 return arch;
Greg Claytonf4d6de62013-04-24 22:29:28 +00005070}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005071
Kate Stoneb9c1b512016-09-06 20:57:50 +00005072bool ObjectFileMachO::GetUUID(lldb_private::UUID *uuid) {
5073 ModuleSP module_sp(GetModule());
5074 if (module_sp) {
5075 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5076 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5077 return GetUUID(m_header, m_data, offset, *uuid);
5078 }
5079 return false;
Greg Clayton7ab7f892014-05-29 21:33:45 +00005080}
5081
Kate Stoneb9c1b512016-09-06 20:57:50 +00005082uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
5083 uint32_t count = 0;
5084 ModuleSP module_sp(GetModule());
5085 if (module_sp) {
5086 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5087 struct load_command load_cmd;
5088 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5089 std::vector<std::string> rpath_paths;
5090 std::vector<std::string> rpath_relative_paths;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005091 std::vector<std::string> at_exec_relative_paths;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005092 uint32_t i;
5093 for (i = 0; i < m_header.ncmds; ++i) {
5094 const uint32_t cmd_offset = offset;
5095 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5096 break;
5097
5098 switch (load_cmd.cmd) {
5099 case LC_RPATH:
5100 case LC_LOAD_DYLIB:
5101 case LC_LOAD_WEAK_DYLIB:
5102 case LC_REEXPORT_DYLIB:
5103 case LC_LOAD_DYLINKER:
5104 case LC_LOADFVMLIB:
5105 case LC_LOAD_UPWARD_DYLIB: {
5106 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5107 const char *path = m_data.PeekCStr(name_offset);
5108 if (path) {
5109 if (load_cmd.cmd == LC_RPATH)
5110 rpath_paths.push_back(path);
5111 else {
5112 if (path[0] == '@') {
5113 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5114 rpath_relative_paths.push_back(path + strlen("@rpath"));
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005115 else if (strncmp(path, "@executable_path",
5116 strlen("@executable_path")) == 0)
5117 at_exec_relative_paths.push_back(path
5118 + strlen("@executable_path"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005119 } else {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005120 FileSpec file_spec(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005121 if (files.AppendIfUnique(file_spec))
5122 count++;
5123 }
5124 }
5125 }
5126 } break;
5127
5128 default:
5129 break;
5130 }
5131 offset = cmd_offset + load_cmd.cmdsize;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005132 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005133
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005134 FileSpec this_file_spec(m_file);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005135 FileSystem::Instance().Resolve(this_file_spec);
5136
Kate Stoneb9c1b512016-09-06 20:57:50 +00005137 if (!rpath_paths.empty()) {
5138 // Fixup all LC_RPATH values to be absolute paths
Kate Stoneb9c1b512016-09-06 20:57:50 +00005139 std::string loader_path("@loader_path");
5140 std::string executable_path("@executable_path");
5141 for (auto &rpath : rpath_paths) {
5142 if (rpath.find(loader_path) == 0) {
5143 rpath.erase(0, loader_path.size());
5144 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5145 } else if (rpath.find(executable_path) == 0) {
5146 rpath.erase(0, executable_path.size());
5147 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5148 }
5149 }
5150
5151 for (const auto &rpath_relative_path : rpath_relative_paths) {
5152 for (const auto &rpath : rpath_paths) {
5153 std::string path = rpath;
5154 path += rpath_relative_path;
Adrian Prantl05097242018-04-30 16:49:04 +00005155 // It is OK to resolve this path because we must find a file on disk
5156 // for us to accept it anyway if it is rpath relative.
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005157 FileSpec file_spec(path);
5158 FileSystem::Instance().Resolve(file_spec);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00005159 if (FileSystem::Instance().Exists(file_spec) &&
5160 files.AppendIfUnique(file_spec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005161 count++;
5162 break;
5163 }
5164 }
5165 }
5166 }
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005167
5168 // We may have @executable_paths but no RPATHS. Figure those out here.
5169 // Only do this if this object file is the executable. We have no way to
5170 // get back to the actual executable otherwise, so we won't get the right
5171 // path.
5172 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5173 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5174 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5175 FileSpec file_spec =
5176 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00005177 if (FileSystem::Instance().Exists(file_spec) &&
5178 files.AppendIfUnique(file_spec))
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005179 count++;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005180 }
5181 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005182 }
5183 return count;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005184}
5185
Kate Stoneb9c1b512016-09-06 20:57:50 +00005186lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5187 // If the object file is not an executable it can't hold the entry point.
Adrian Prantl05097242018-04-30 16:49:04 +00005188 // m_entry_point_address is initialized to an invalid address, so we can just
5189 // return that. If m_entry_point_address is valid it means we've found it
5190 // already, so return the cached value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005191
Kate Stoneb9c1b512016-09-06 20:57:50 +00005192 if (!IsExecutable() || m_entry_point_address.IsValid())
Jim Ingham672e6f52011-03-07 23:44:08 +00005193 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00005194
Kate Stoneb9c1b512016-09-06 20:57:50 +00005195 // Otherwise, look for the UnixThread or Thread command. The data for the
Adrian Prantl05097242018-04-30 16:49:04 +00005196 // Thread command is given in /usr/include/mach-o.h, but it is basically:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005197 //
5198 // uint32_t flavor - this is the flavor argument you would pass to
5199 // thread_get_state
5200 // uint32_t count - this is the count of longs in the thread state data
5201 // struct XXX_thread_state state - this is the structure from
5202 // <machine/thread_status.h> corresponding to the flavor.
5203 // <repeat this trio>
5204 //
5205 // So we just keep reading the various register flavors till we find the GPR
5206 // one, then read the PC out of there.
5207 // FIXME: We will need to have a "RegisterContext data provider" class at some
5208 // point that can get all the registers
5209 // out of data in this form & attach them to a given thread. That should
Adrian Prantl05097242018-04-30 16:49:04 +00005210 // underlie the MacOS X User process plugin, and we'll also need it for the
5211 // MacOS X Core File process plugin. When we have that we can also use it
5212 // here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005213 //
5214 // For now we hard-code the offsets and flavors we need:
5215 //
5216 //
Greg Claytonc9660542012-02-05 02:38:54 +00005217
Kate Stoneb9c1b512016-09-06 20:57:50 +00005218 ModuleSP module_sp(GetModule());
5219 if (module_sp) {
5220 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5221 struct load_command load_cmd;
5222 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5223 uint32_t i;
5224 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5225 bool done = false;
5226
5227 for (i = 0; i < m_header.ncmds; ++i) {
5228 const lldb::offset_t cmd_offset = offset;
5229 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5230 break;
5231
5232 switch (load_cmd.cmd) {
5233 case LC_UNIXTHREAD:
5234 case LC_THREAD: {
5235 while (offset < cmd_offset + load_cmd.cmdsize) {
5236 uint32_t flavor = m_data.GetU32(&offset);
5237 uint32_t count = m_data.GetU32(&offset);
5238 if (count == 0) {
5239 // We've gotten off somehow, log and exit;
5240 return m_entry_point_address;
5241 }
5242
5243 switch (m_header.cputype) {
5244 case llvm::MachO::CPU_TYPE_ARM:
5245 if (flavor == 1 ||
5246 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 from
5247 // mach/arm/thread_status.h
Greg Claytonc3776bf2012-02-09 06:16:32 +00005248 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005249 offset += 60; // This is the offset of pc in the GPR thread state
5250 // data structure.
5251 start_address = m_data.GetU32(&offset);
5252 done = true;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005253 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005254 break;
5255 case llvm::MachO::CPU_TYPE_ARM64:
5256 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5257 {
5258 offset += 256; // This is the offset of pc in the GPR thread state
5259 // data structure.
5260 start_address = m_data.GetU64(&offset);
5261 done = true;
5262 }
5263 break;
5264 case llvm::MachO::CPU_TYPE_I386:
5265 if (flavor ==
5266 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5267 {
5268 offset += 40; // This is the offset of eip in the GPR thread state
5269 // data structure.
5270 start_address = m_data.GetU32(&offset);
5271 done = true;
5272 }
5273 break;
5274 case llvm::MachO::CPU_TYPE_X86_64:
5275 if (flavor ==
5276 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5277 {
5278 offset += 16 * 8; // This is the offset of rip in the GPR thread
5279 // state data structure.
5280 start_address = m_data.GetU64(&offset);
5281 done = true;
5282 }
5283 break;
5284 default:
5285 return m_entry_point_address;
5286 }
5287 // Haven't found the GPR flavor yet, skip over the data for this
5288 // flavor:
5289 if (done)
5290 break;
5291 offset += count * 4;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005292 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005293 } break;
5294 case LC_MAIN: {
5295 ConstString text_segment_name("__TEXT");
5296 uint64_t entryoffset = m_data.GetU64(&offset);
5297 SectionSP text_segment_sp =
5298 GetSectionList()->FindSectionByName(text_segment_name);
5299 if (text_segment_sp) {
5300 done = true;
5301 start_address = text_segment_sp->GetFileAddress() + entryoffset;
5302 }
5303 } break;
5304
5305 default:
5306 break;
5307 }
5308 if (done)
5309 break;
5310
5311 // Go to the next load command:
5312 offset = cmd_offset + load_cmd.cmdsize;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005313 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005314
5315 if (start_address != LLDB_INVALID_ADDRESS) {
5316 // We got the start address from the load commands, so now resolve that
Adrian Prantl05097242018-04-30 16:49:04 +00005317 // address in the sections of this ObjectFile:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005318 if (!m_entry_point_address.ResolveAddressUsingFileSections(
5319 start_address, GetSectionList())) {
5320 m_entry_point_address.Clear();
5321 }
5322 } else {
5323 // We couldn't read the UnixThread load command - maybe it wasn't there.
Adrian Prantl05097242018-04-30 16:49:04 +00005324 // As a fallback look for the "start" symbol in the main executable.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005325
5326 ModuleSP module_sp(GetModule());
5327
5328 if (module_sp) {
5329 SymbolContextList contexts;
5330 SymbolContext context;
5331 if (module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5332 eSymbolTypeCode, contexts)) {
5333 if (contexts.GetContextAtIndex(0, context))
5334 m_entry_point_address = context.symbol->GetAddress();
5335 }
5336 }
5337 }
5338 }
5339
5340 return m_entry_point_address;
5341}
5342
Pavel Labathd1e3fe22018-12-11 15:21:15 +00005343lldb_private::Address ObjectFileMachO::GetBaseAddress() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005344 lldb_private::Address header_addr;
5345 SectionList *section_list = GetSectionList();
5346 if (section_list) {
5347 SectionSP text_segment_sp(
5348 section_list->FindSectionByName(GetSegmentNameTEXT()));
5349 if (text_segment_sp) {
5350 header_addr.SetSection(text_segment_sp);
5351 header_addr.SetOffset(0);
5352 }
5353 }
5354 return header_addr;
5355}
5356
5357uint32_t ObjectFileMachO::GetNumThreadContexts() {
5358 ModuleSP module_sp(GetModule());
5359 if (module_sp) {
5360 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5361 if (!m_thread_context_offsets_valid) {
5362 m_thread_context_offsets_valid = true;
5363 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5364 FileRangeArray::Entry file_range;
5365 thread_command thread_cmd;
5366 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5367 const uint32_t cmd_offset = offset;
5368 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5369 break;
5370
5371 if (thread_cmd.cmd == LC_THREAD) {
5372 file_range.SetRangeBase(offset);
5373 file_range.SetByteSize(thread_cmd.cmdsize - 8);
5374 m_thread_context_offsets.Append(file_range);
5375 }
5376 offset = cmd_offset + thread_cmd.cmdsize;
5377 }
5378 }
5379 }
5380 return m_thread_context_offsets.GetSize();
Greg Claytonc3776bf2012-02-09 06:16:32 +00005381}
5382
Jason Molenda3533cec2017-04-06 01:50:11 +00005383std::string ObjectFileMachO::GetIdentifierString() {
5384 std::string result;
5385 ModuleSP module_sp(GetModule());
5386 if (module_sp) {
5387 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005388
Adrian Prantl05097242018-04-30 16:49:04 +00005389 // First, look over the load commands for an LC_NOTE load command with
5390 // data_owner string "kern ver str" & use that if found.
Jason Molenda3533cec2017-04-06 01:50:11 +00005391 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5392 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5393 const uint32_t cmd_offset = offset;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005394 load_command lc;
5395 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5396 break;
5397 if (lc.cmd == LC_NOTE)
5398 {
5399 char data_owner[17];
5400 m_data.CopyData (offset, 16, data_owner);
5401 data_owner[16] = '\0';
5402 offset += 16;
5403 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5404 uint64_t size = m_data.GetU64_unchecked (&offset);
5405
Adrian Prantl05097242018-04-30 16:49:04 +00005406 // "kern ver str" has a uint32_t version and then a nul terminated
5407 // c-string.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005408 if (strcmp ("kern ver str", data_owner) == 0)
5409 {
5410 offset = fileoff;
5411 uint32_t version;
5412 if (m_data.GetU32 (&offset, &version, 1) != nullptr)
5413 {
5414 if (version == 1)
5415 {
5416 uint32_t strsize = size - sizeof (uint32_t);
5417 char *buf = (char*) malloc (strsize);
5418 if (buf)
5419 {
5420 m_data.CopyData (offset, strsize, buf);
5421 buf[strsize - 1] = '\0';
5422 result = buf;
5423 if (buf)
5424 free (buf);
5425 return result;
5426 }
5427 }
5428 }
5429 }
5430 }
5431 offset = cmd_offset + lc.cmdsize;
5432 }
5433
Adrian Prantl05097242018-04-30 16:49:04 +00005434 // Second, make a pass over the load commands looking for an obsolete
5435 // LC_IDENT load command.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005436 offset = MachHeaderSizeFromMagic(m_header.magic);
5437 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5438 const uint32_t cmd_offset = offset;
Jason Molenda3533cec2017-04-06 01:50:11 +00005439 struct ident_command ident_command;
5440 if (m_data.GetU32(&offset, &ident_command, 2) == NULL)
5441 break;
5442 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005443 char *buf = (char *) malloc (ident_command.cmdsize);
Jason Molenda3533cec2017-04-06 01:50:11 +00005444 if (buf != nullptr
5445 && m_data.CopyData (offset, ident_command.cmdsize, buf) == ident_command.cmdsize) {
5446 buf[ident_command.cmdsize - 1] = '\0';
5447 result = buf;
5448 }
5449 if (buf)
5450 free (buf);
5451 }
5452 offset = cmd_offset + ident_command.cmdsize;
5453 }
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005454
Jason Molenda3533cec2017-04-06 01:50:11 +00005455 }
5456 return result;
5457}
5458
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005459bool ObjectFileMachO::GetCorefileMainBinaryInfo (addr_t &address, UUID &uuid) {
5460 address = LLDB_INVALID_ADDRESS;
5461 uuid.Clear();
5462 ModuleSP module_sp(GetModule());
5463 if (module_sp) {
5464 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5465 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5466 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5467 const uint32_t cmd_offset = offset;
5468 load_command lc;
5469 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5470 break;
5471 if (lc.cmd == LC_NOTE)
5472 {
5473 char data_owner[17];
5474 memset (data_owner, 0, sizeof (data_owner));
5475 m_data.CopyData (offset, 16, data_owner);
5476 offset += 16;
5477 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5478 uint64_t size = m_data.GetU64_unchecked (&offset);
5479
Adrian Prantl05097242018-04-30 16:49:04 +00005480 // "main bin spec" (main binary specification) data payload is
5481 // formatted:
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005482 // uint32_t version [currently 1]
5483 // uint32_t type [0 == unspecified, 1 == kernel, 2 == user process]
5484 // uint64_t address [ UINT64_MAX if address not specified ]
5485 // uuid_t uuid [ all zero's if uuid not specified ]
5486 // uint32_t log2_pagesize [ process page size in log base 2, e.g. 4k pages are 12. 0 for unspecified ]
5487
5488 if (strcmp ("main bin spec", data_owner) == 0 && size >= 32)
5489 {
5490 offset = fileoff;
5491 uint32_t version;
5492 if (m_data.GetU32 (&offset, &version, 1) != nullptr && version == 1)
5493 {
5494 uint32_t type = 0;
5495 uuid_t raw_uuid;
Jason Molenda3f608292017-04-13 02:12:32 +00005496 memset (raw_uuid, 0, sizeof (uuid_t));
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005497
Pavel Labath2f93fd12018-06-26 15:12:20 +00005498 if (m_data.GetU32(&offset, &type, 1) &&
5499 m_data.GetU64(&offset, &address, 1) &&
5500 m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
5501 uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t));
5502 return true;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005503 }
5504 }
5505 }
5506 }
5507 offset = cmd_offset + lc.cmdsize;
5508 }
5509 }
5510 return false;
5511}
5512
Greg Claytonc3776bf2012-02-09 06:16:32 +00005513lldb::RegisterContextSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005514ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5515 lldb_private::Thread &thread) {
5516 lldb::RegisterContextSP reg_ctx_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00005517
Kate Stoneb9c1b512016-09-06 20:57:50 +00005518 ModuleSP module_sp(GetModule());
5519 if (module_sp) {
5520 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5521 if (!m_thread_context_offsets_valid)
5522 GetNumThreadContexts();
Greg Claytona1743492012-03-13 23:14:29 +00005523
Kate Stoneb9c1b512016-09-06 20:57:50 +00005524 const FileRangeArray::Entry *thread_context_file_range =
5525 m_thread_context_offsets.GetEntryAtIndex(idx);
5526 if (thread_context_file_range) {
Jason Molenda4e7511e2013-03-06 23:19:17 +00005527
Kate Stoneb9c1b512016-09-06 20:57:50 +00005528 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5529 thread_context_file_range->GetByteSize());
Jim Ingham28eb5712012-10-12 17:34:26 +00005530
Kate Stoneb9c1b512016-09-06 20:57:50 +00005531 switch (m_header.cputype) {
5532 case llvm::MachO::CPU_TYPE_ARM64:
5533 reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data));
5534 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005535
Kate Stoneb9c1b512016-09-06 20:57:50 +00005536 case llvm::MachO::CPU_TYPE_ARM:
5537 reg_ctx_sp.reset(new RegisterContextDarwin_arm_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_I386:
5541 reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data));
5542 break;
5543
5544 case llvm::MachO::CPU_TYPE_X86_64:
5545 reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data));
5546 break;
5547 }
Greg Claytonc3776bf2012-02-09 06:16:32 +00005548 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005549 }
5550 return reg_ctx_sp;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005551}
5552
Kate Stoneb9c1b512016-09-06 20:57:50 +00005553ObjectFile::Type ObjectFileMachO::CalculateType() {
5554 switch (m_header.filetype) {
5555 case MH_OBJECT: // 0x1u
5556 if (GetAddressByteSize() == 4) {
5557 // 32 bit kexts are just object files, but they do have a valid
5558 // UUID load command.
5559 UUID uuid;
5560 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005561 // this checking for the UUID load command is not enough we could
5562 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5563 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005564 if (m_strata == eStrataInvalid)
5565 m_strata = eStrataKernel;
5566 return eTypeSharedLibrary;
5567 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005568 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005569 return eTypeObjectFile;
5570
5571 case MH_EXECUTE:
5572 return eTypeExecutable; // 0x2u
5573 case MH_FVMLIB:
5574 return eTypeSharedLibrary; // 0x3u
5575 case MH_CORE:
5576 return eTypeCoreFile; // 0x4u
5577 case MH_PRELOAD:
5578 return eTypeSharedLibrary; // 0x5u
5579 case MH_DYLIB:
5580 return eTypeSharedLibrary; // 0x6u
5581 case MH_DYLINKER:
5582 return eTypeDynamicLinker; // 0x7u
5583 case MH_BUNDLE:
5584 return eTypeSharedLibrary; // 0x8u
5585 case MH_DYLIB_STUB:
5586 return eTypeStubLibrary; // 0x9u
5587 case MH_DSYM:
5588 return eTypeDebugInfo; // 0xAu
5589 case MH_KEXT_BUNDLE:
5590 return eTypeSharedLibrary; // 0xBu
5591 default:
5592 break;
5593 }
5594 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005595}
5596
Kate Stoneb9c1b512016-09-06 20:57:50 +00005597ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5598 switch (m_header.filetype) {
5599 case MH_OBJECT: // 0x1u
5600 {
5601 // 32 bit kexts are just object files, but they do have a valid
5602 // UUID load command.
5603 UUID uuid;
5604 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005605 // this checking for the UUID load command is not enough we could
5606 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5607 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005608 if (m_type == eTypeInvalid)
5609 m_type = eTypeSharedLibrary;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005610
Kate Stoneb9c1b512016-09-06 20:57:50 +00005611 return eStrataKernel;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005612 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005613 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005614 return eStrataUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005615
5616 case MH_EXECUTE: // 0x2u
5617 // Check for the MH_DYLDLINK bit in the flags
5618 if (m_header.flags & MH_DYLDLINK) {
5619 return eStrataUser;
5620 } else {
5621 SectionList *section_list = GetSectionList();
5622 if (section_list) {
5623 static ConstString g_kld_section_name("__KLD");
5624 if (section_list->FindSectionByName(g_kld_section_name))
5625 return eStrataKernel;
5626 }
5627 }
5628 return eStrataRawImage;
5629
5630 case MH_FVMLIB:
5631 return eStrataUser; // 0x3u
5632 case MH_CORE:
5633 return eStrataUnknown; // 0x4u
5634 case MH_PRELOAD:
5635 return eStrataRawImage; // 0x5u
5636 case MH_DYLIB:
5637 return eStrataUser; // 0x6u
5638 case MH_DYLINKER:
5639 return eStrataUser; // 0x7u
5640 case MH_BUNDLE:
5641 return eStrataUser; // 0x8u
5642 case MH_DYLIB_STUB:
5643 return eStrataUser; // 0x9u
5644 case MH_DSYM:
5645 return eStrataUnknown; // 0xAu
5646 case MH_KEXT_BUNDLE:
5647 return eStrataKernel; // 0xBu
5648 default:
5649 break;
5650 }
5651 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005652}
5653
Pavel Labath2272c482018-06-18 15:02:23 +00005654llvm::VersionTuple ObjectFileMachO::GetVersion() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005655 ModuleSP module_sp(GetModule());
5656 if (module_sp) {
5657 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5658 struct dylib_command load_cmd;
5659 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5660 uint32_t version_cmd = 0;
5661 uint64_t version = 0;
5662 uint32_t i;
5663 for (i = 0; i < m_header.ncmds; ++i) {
5664 const lldb::offset_t cmd_offset = offset;
5665 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5666 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005667
Kate Stoneb9c1b512016-09-06 20:57:50 +00005668 if (load_cmd.cmd == LC_ID_DYLIB) {
5669 if (version_cmd == 0) {
5670 version_cmd = load_cmd.cmd;
5671 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5672 break;
5673 version = load_cmd.dylib.current_version;
Greg Claytonc2ff9312012-02-22 19:41:02 +00005674 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005675 break; // Break for now unless there is another more complete version
5676 // number load command in the future.
5677 }
5678 offset = cmd_offset + load_cmd.cmdsize;
5679 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00005680
Kate Stoneb9c1b512016-09-06 20:57:50 +00005681 if (version_cmd == LC_ID_DYLIB) {
Pavel Labath2272c482018-06-18 15:02:23 +00005682 unsigned major = (version & 0xFFFF0000ull) >> 16;
5683 unsigned minor = (version & 0x0000FF00ull) >> 8;
5684 unsigned subminor = (version & 0x000000FFull);
5685 return llvm::VersionTuple(major, minor, subminor);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005686 }
5687 }
Pavel Labath2272c482018-06-18 15:02:23 +00005688 return llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005689}
5690
Pavel Labathf760f5a2019-01-03 10:37:19 +00005691ArchSpec ObjectFileMachO::GetArchitecture() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005692 ModuleSP module_sp(GetModule());
Pavel Labathf760f5a2019-01-03 10:37:19 +00005693 ArchSpec arch;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005694 if (module_sp) {
5695 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Pavel Labathf760f5a2019-01-03 10:37:19 +00005696
Kate Stoneb9c1b512016-09-06 20:57:50 +00005697 return GetArchitecture(m_header, m_data,
Pavel Labathf760f5a2019-01-03 10:37:19 +00005698 MachHeaderSizeFromMagic(m_header.magic));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005699 }
Pavel Labathf760f5a2019-01-03 10:37:19 +00005700 return arch;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005701}
5702
Jason Molenda07580ff2018-05-04 00:59:37 +00005703void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process, addr_t &base_addr, UUID &uuid) {
5704 uuid.Clear();
5705 base_addr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005706 if (process && process->GetDynamicLoader()) {
5707 DynamicLoader *dl = process->GetDynamicLoader();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005708 LazyBool using_shared_cache;
5709 LazyBool private_shared_cache;
Jason Molenda07580ff2018-05-04 00:59:37 +00005710 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005711 private_shared_cache);
5712 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005713 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005714 if (log)
Jason Molenda07580ff2018-05-04 00:59:37 +00005715 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 +00005716}
5717
Jason Molenda07580ff2018-05-04 00:59:37 +00005718// From dyld SPI header dyld_process_info.h
5719typedef void *dyld_process_info;
5720struct lldb_copy__dyld_process_cache_info {
5721 uuid_t cacheUUID; // UUID of cache used by process
5722 uint64_t cacheBaseAddress; // load address of dyld shared cache
5723 bool noCache; // process is running without a dyld cache
5724 bool privateCache; // process is using a private copy of its dyld cache
5725};
5726
5727// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with llvm
5728// enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile errors.
5729// So we need to use the actual underlying types of task_t and kern_return_t
5730// below.
5731extern "C" unsigned int /*task_t*/ mach_task_self();
5732
5733void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5734 uuid.Clear();
5735 base_addr = LLDB_INVALID_ADDRESS;
5736
Kate Stoneb9c1b512016-09-06 20:57:50 +00005737#if defined(__APPLE__) && \
5738 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5739 uint8_t *(*dyld_get_all_image_infos)(void);
5740 dyld_get_all_image_infos =
5741 (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5742 if (dyld_get_all_image_infos) {
5743 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5744 if (dyld_all_image_infos_address) {
5745 uint32_t *version = (uint32_t *)
5746 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5747 if (*version >= 13) {
5748 uuid_t *sharedCacheUUID_address = 0;
5749 int wordsize = sizeof(uint8_t *);
5750 if (wordsize == 8) {
5751 sharedCacheUUID_address =
5752 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5753 160); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005754 if (*version >= 15)
5755 base_addr = *(uint64_t *) ((uint8_t *) dyld_all_image_infos_address
5756 + 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +00005757 } else {
5758 sharedCacheUUID_address =
5759 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5760 84); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005761 if (*version >= 15) {
5762 base_addr = 0;
5763 base_addr = *(uint32_t *) ((uint8_t *) dyld_all_image_infos_address
5764 + 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5765 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005766 }
Pavel Labath2f93fd12018-06-26 15:12:20 +00005767 uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005768 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005769 }
Jason Molendafd443e92018-02-07 01:28:29 +00005770 } else {
5771 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
Jason Molenda07580ff2018-05-04 00:59:37 +00005772 dyld_process_info (*dyld_process_info_create)(unsigned int /* task_t */ task, uint64_t timestamp, unsigned int /*kern_return_t*/ *kernelError);
5773 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5774 void (*dyld_process_info_release)(dyld_process_info info);
5775
5776 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, unsigned int /*kern_return_t*/ *))
5777 dlsym (RTLD_DEFAULT, "_dyld_process_info_create");
5778 dyld_process_info_get_cache = (void (*)(void *, void *))
5779 dlsym (RTLD_DEFAULT, "_dyld_process_info_get_cache");
5780 dyld_process_info_release = (void (*)(void *))
5781 dlsym (RTLD_DEFAULT, "_dyld_process_info_release");
5782
5783 if (dyld_process_info_create && dyld_process_info_get_cache) {
5784 unsigned int /*kern_return_t */ kern_ret;
5785 dyld_process_info process_info = dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5786 if (process_info) {
5787 struct lldb_copy__dyld_process_cache_info sc_info;
5788 memset (&sc_info, 0, sizeof (struct lldb_copy__dyld_process_cache_info));
5789 dyld_process_info_get_cache (process_info, &sc_info);
5790 if (sc_info.cacheBaseAddress != 0) {
5791 base_addr = sc_info.cacheBaseAddress;
Pavel Labath2f93fd12018-06-26 15:12:20 +00005792 uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
Jason Molenda07580ff2018-05-04 00:59:37 +00005793 }
5794 dyld_process_info_release (process_info);
5795 }
Jason Molendafd443e92018-02-07 01:28:29 +00005796 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005797 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005798 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005799 if (log && uuid.IsValid())
Jason Molenda07580ff2018-05-04 00:59:37 +00005800 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 +00005801#endif
Jason Molenda0e0954c2013-04-16 06:24:42 +00005802}
5803
Pavel Labath2272c482018-06-18 15:02:23 +00005804llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5805 if (!m_min_os_version) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005806 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labath2272c482018-06-18 15:02:23 +00005807 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005808 const lldb::offset_t load_cmd_offset = offset;
5809
5810 version_min_command lc;
5811 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5812 break;
5813 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5814 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5815 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5816 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5817 if (m_data.GetU32(&offset, &lc.version,
5818 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5819 const uint32_t xxxx = lc.version >> 16;
5820 const uint32_t yy = (lc.version >> 8) & 0xffu;
5821 const uint32_t zz = lc.version & 0xffu;
5822 if (xxxx) {
Pavel Labath2272c482018-06-18 15:02:23 +00005823 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5824 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005825 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005826 }
5827 } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5828 // struct build_version_command {
5829 // uint32_t cmd; /* LC_BUILD_VERSION */
5830 // uint32_t cmdsize; /* sizeof(struct build_version_command) plus */
5831 // /* ntools * sizeof(struct build_tool_version) */
5832 // uint32_t platform; /* platform */
5833 // uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5834 // uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5835 // uint32_t ntools; /* number of tool entries following this */
5836 // };
5837
5838 offset += 4; // skip platform
5839 uint32_t minos = m_data.GetU32(&offset);
5840
5841 const uint32_t xxxx = minos >> 16;
5842 const uint32_t yy = (minos >> 8) & 0xffu;
5843 const uint32_t zz = minos & 0xffu;
5844 if (xxxx) {
5845 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5846 break;
Greg Clayton9b234982013-10-24 22:54:08 +00005847 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005848 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005849
Kate Stoneb9c1b512016-09-06 20:57:50 +00005850 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005851 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005852
Pavel Labath2272c482018-06-18 15:02:23 +00005853 if (!m_min_os_version) {
5854 // Set version to an empty value so we don't keep trying to
5855 m_min_os_version = llvm::VersionTuple();
Greg Clayton9b234982013-10-24 22:54:08 +00005856 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005857 }
5858
Pavel Labath2272c482018-06-18 15:02:23 +00005859 return *m_min_os_version;
Greg Clayton9b234982013-10-24 22:54:08 +00005860}
5861
Kate Stoneb9c1b512016-09-06 20:57:50 +00005862uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions,
5863 uint32_t num_versions) {
5864 if (m_sdk_versions.empty()) {
5865 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5866 bool success = false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005867 for (uint32_t i = 0; !success && i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005868 const lldb::offset_t load_cmd_offset = offset;
5869
5870 version_min_command lc;
5871 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5872 break;
5873 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5874 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5875 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5876 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5877 if (m_data.GetU32(&offset, &lc.version,
5878 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5879 const uint32_t xxxx = lc.sdk >> 16;
5880 const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5881 const uint32_t zz = lc.sdk & 0xffu;
5882 if (xxxx) {
5883 m_sdk_versions.push_back(xxxx);
5884 m_sdk_versions.push_back(yy);
5885 m_sdk_versions.push_back(zz);
Jason Molenda32a91422018-06-25 23:45:39 +00005886 success = true;
5887 } else {
5888 GetModule()->ReportWarning(
5889 "minimum OS version load command with invalid (0) version found.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005890 }
Greg Clayton9b234982013-10-24 22:54:08 +00005891 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005892 }
5893 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005894 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005895
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005896 if (!success) {
5897 offset = MachHeaderSizeFromMagic(m_header.magic);
5898 for (uint32_t i = 0; !success && i < m_header.ncmds; ++i) {
5899 const lldb::offset_t load_cmd_offset = offset;
Jason Molenda32762fd2018-10-11 00:28:35 +00005900
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005901 version_min_command lc;
5902 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5903 break;
5904 if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5905 // struct build_version_command {
5906 // uint32_t cmd; /* LC_BUILD_VERSION */
5907 // uint32_t cmdsize; /* sizeof(struct
5908 // build_version_command) plus */
5909 // /* ntools * sizeof(struct
5910 // build_tool_version) */
5911 // uint32_t platform; /* platform */
5912 // uint32_t minos; /* X.Y.Z is encoded in nibbles
5913 // xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded
5914 // in nibbles xxxx.yy.zz */ uint32_t ntools; /* number
5915 // of tool entries following this */
5916 // };
Jason Molenda32762fd2018-10-11 00:28:35 +00005917
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005918 offset += 4; // skip platform
5919 uint32_t minos = m_data.GetU32(&offset);
Jason Molenda32762fd2018-10-11 00:28:35 +00005920
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005921 const uint32_t xxxx = minos >> 16;
5922 const uint32_t yy = (minos >> 8) & 0xffu;
5923 const uint32_t zz = minos & 0xffu;
5924 if (xxxx) {
5925 m_sdk_versions.push_back(xxxx);
5926 m_sdk_versions.push_back(yy);
5927 m_sdk_versions.push_back(zz);
5928 success = true;
5929 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005930 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005931 offset = load_cmd_offset + lc.cmdsize;
5932 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005933 }
5934
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005935 if (!success) {
Jason Molenda32a91422018-06-25 23:45:39 +00005936 // Push an invalid value so we don't try to find
5937 // the version # again on the next call to this
5938 // method.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005939 m_sdk_versions.push_back(UINT32_MAX);
Greg Clayton9b234982013-10-24 22:54:08 +00005940 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005941 }
5942
Jason Molenda32a91422018-06-25 23:45:39 +00005943 // Legitimate version numbers will have 3 entries pushed
5944 // on to m_sdk_versions. If we only have one value, it's
5945 // the sentinel value indicating that this object file
5946 // does not have a valid minimum os version #.
5947 if (m_sdk_versions.size() > 1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005948 if (versions != NULL && num_versions > 0) {
5949 for (size_t i = 0; i < num_versions; ++i) {
5950 if (i < m_sdk_versions.size())
5951 versions[i] = m_sdk_versions[i];
5952 else
5953 versions[i] = 0;
5954 }
5955 }
5956 return m_sdk_versions.size();
5957 }
5958 // Call the superclasses version that will empty out the data
5959 return ObjectFile::GetSDKVersion(versions, num_versions);
Greg Clayton9b234982013-10-24 22:54:08 +00005960}
5961
Kate Stoneb9c1b512016-09-06 20:57:50 +00005962bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5963 return m_header.filetype == llvm::MachO::MH_DYLINKER;
Greg Clayton08928f32015-02-05 02:01:34 +00005964}
5965
Kate Stoneb9c1b512016-09-06 20:57:50 +00005966bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5967 return m_allow_assembly_emulation_unwind_plans;
Jason Molenda955dcf22016-05-04 03:09:40 +00005968}
5969
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005970//------------------------------------------------------------------
5971// PluginInterface protocol
5972//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00005973lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5974 return GetPluginNameStatic();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005975}
5976
Kate Stoneb9c1b512016-09-06 20:57:50 +00005977uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005978
Kate Stoneb9c1b512016-09-06 20:57:50 +00005979Section *ObjectFileMachO::GetMachHeaderSection() {
Adrian Prantl05097242018-04-30 16:49:04 +00005980 // Find the first address of the mach header which is the first non-zero file
5981 // sized section whose file offset is zero. This is the base file address of
5982 // the mach-o file which can be subtracted from the vmaddr of the other
Kate Stoneb9c1b512016-09-06 20:57:50 +00005983 // segments found in memory and added to the load address
5984 ModuleSP module_sp = GetModule();
Greg Clayton57577c02018-12-21 17:04:18 +00005985 if (!module_sp)
5986 return nullptr;
5987 SectionList *section_list = GetSectionList();
5988 if (!section_list)
5989 return nullptr;
5990 const size_t num_sections = section_list->GetSize();
5991 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5992 Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5993 if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
5994 return section;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005995 }
5996 return nullptr;
Greg Clayton07347372015-06-08 21:53:11 +00005997}
5998
Greg Clayton57577c02018-12-21 17:04:18 +00005999bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
6000 if (!section)
6001 return false;
6002 const bool is_dsym = (m_header.filetype == MH_DSYM);
6003 if (section->GetFileSize() == 0 && !is_dsym)
6004 return false;
6005 if (section->IsThreadSpecific())
6006 return false;
6007 if (GetModule().get() != section->GetModule().get())
6008 return false;
6009 // Be careful with __LINKEDIT and __DWARF segments
6010 if (section->GetName() == GetSegmentNameLINKEDIT() ||
6011 section->GetName() == GetSegmentNameDWARF()) {
6012 // Only map __LINKEDIT and __DWARF if we have an in memory image and
6013 // this isn't a kernel binary like a kext or mach_kernel.
6014 const bool is_memory_image = (bool)m_process_wp.lock();
6015 const Strata strata = GetStrata();
6016 if (is_memory_image == false || strata == eStrataKernel)
6017 return false;
6018 }
6019 return true;
6020}
6021
Kate Stoneb9c1b512016-09-06 20:57:50 +00006022lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
Greg Clayton57577c02018-12-21 17:04:18 +00006023 lldb::addr_t header_load_address, const Section *header_section,
Kate Stoneb9c1b512016-09-06 20:57:50 +00006024 const Section *section) {
6025 ModuleSP module_sp = GetModule();
Greg Clayton57577c02018-12-21 17:04:18 +00006026 if (module_sp && header_section && section &&
6027 header_load_address != LLDB_INVALID_ADDRESS) {
6028 lldb::addr_t file_addr = header_section->GetFileAddress();
6029 if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
6030 return section->GetFileAddress() - file_addr + header_load_address;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006031 }
6032 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00006033}
6034
Kate Stoneb9c1b512016-09-06 20:57:50 +00006035bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
6036 bool value_is_offset) {
6037 ModuleSP module_sp = GetModule();
6038 if (module_sp) {
6039 size_t num_loaded_sections = 0;
6040 SectionList *section_list = GetSectionList();
6041 if (section_list) {
6042 const size_t num_sections = section_list->GetSize();
Greg Clayton7524e092014-02-06 20:10:16 +00006043
Kate Stoneb9c1b512016-09-06 20:57:50 +00006044 if (value_is_offset) {
6045 // "value" is an offset to apply to each top level segment
6046 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +00006047 // Iterate through the object file sections to find all of the
6048 // sections that size on disk (to avoid __PAGEZERO) and load them
Kate Stoneb9c1b512016-09-06 20:57:50 +00006049 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
Greg Clayton57577c02018-12-21 17:04:18 +00006050 if (SectionIsLoadable(section_sp.get()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00006051 if (target.GetSectionLoadList().SetSectionLoadAddress(
6052 section_sp, section_sp->GetFileAddress() + value))
6053 ++num_loaded_sections;
Greg Clayton7524e092014-02-06 20:10:16 +00006054 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006055 } else {
6056 // "value" is the new base address of the mach_header, adjust each
6057 // section accordingly
6058
6059 Section *mach_header_section = GetMachHeaderSection();
6060 if (mach_header_section) {
6061 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6062 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6063
6064 lldb::addr_t section_load_addr =
6065 CalculateSectionLoadAddressForMemoryImage(
6066 value, mach_header_section, section_sp.get());
6067 if (section_load_addr != LLDB_INVALID_ADDRESS) {
6068 if (target.GetSectionLoadList().SetSectionLoadAddress(
6069 section_sp, section_load_addr))
6070 ++num_loaded_sections;
6071 }
6072 }
6073 }
6074 }
Greg Clayton7524e092014-02-06 20:10:16 +00006075 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006076 return num_loaded_sections > 0;
6077 }
6078 return false;
Greg Clayton7524e092014-02-06 20:10:16 +00006079}
6080
Kate Stoneb9c1b512016-09-06 20:57:50 +00006081bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00006082 const FileSpec &outfile, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00006083 if (process_sp) {
6084 Target &target = process_sp->GetTarget();
6085 const ArchSpec target_arch = target.GetArchitecture();
6086 const llvm::Triple &target_triple = target_arch.GetTriple();
6087 if (target_triple.getVendor() == llvm::Triple::Apple &&
6088 (target_triple.getOS() == llvm::Triple::MacOSX ||
6089 target_triple.getOS() == llvm::Triple::IOS ||
6090 target_triple.getOS() == llvm::Triple::WatchOS ||
6091 target_triple.getOS() == llvm::Triple::TvOS)) {
Jason Molenda32762fd2018-10-11 00:28:35 +00006092 // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00006093 bool make_core = false;
6094 switch (target_arch.GetMachine()) {
6095 case llvm::Triple::aarch64:
6096 case llvm::Triple::arm:
6097 case llvm::Triple::thumb:
6098 case llvm::Triple::x86:
6099 case llvm::Triple::x86_64:
6100 make_core = true;
6101 break;
6102 default:
6103 error.SetErrorStringWithFormat("unsupported core architecture: %s",
6104 target_triple.str().c_str());
6105 break;
6106 }
6107
6108 if (make_core) {
6109 std::vector<segment_command_64> segment_load_commands;
6110 // uint32_t range_info_idx = 0;
6111 MemoryRegionInfo range_info;
Zachary Turner97206d52017-05-12 04:51:55 +00006112 Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006113 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6114 const ByteOrder byte_order = target_arch.GetByteOrder();
6115 if (range_error.Success()) {
6116 while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
6117 const addr_t addr = range_info.GetRange().GetRangeBase();
6118 const addr_t size = range_info.GetRange().GetByteSize();
6119
6120 if (size == 0)
6121 break;
6122
6123 // Calculate correct protections
6124 uint32_t prot = 0;
6125 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
6126 prot |= VM_PROT_READ;
6127 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
6128 prot |= VM_PROT_WRITE;
6129 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
6130 prot |= VM_PROT_EXECUTE;
6131
6132 // printf ("[%3u] [0x%16.16" PRIx64 " -
6133 // 0x%16.16" PRIx64 ") %c%c%c\n",
6134 // range_info_idx,
6135 // addr,
6136 // size,
6137 // (prot & VM_PROT_READ ) ? 'r' :
6138 // '-',
6139 // (prot & VM_PROT_WRITE ) ? 'w' :
6140 // '-',
6141 // (prot & VM_PROT_EXECUTE) ? 'x' :
6142 // '-');
6143
6144 if (prot != 0) {
6145 uint32_t cmd_type = LC_SEGMENT_64;
6146 uint32_t segment_size = sizeof(segment_command_64);
6147 if (addr_byte_size == 4) {
6148 cmd_type = LC_SEGMENT;
6149 segment_size = sizeof(segment_command);
6150 }
6151 segment_command_64 segment = {
6152 cmd_type, // uint32_t cmd;
6153 segment_size, // uint32_t cmdsize;
6154 {0}, // char segname[16];
6155 addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
6156 size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
6157 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
6158 size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
6159 prot, // uint32_t maxprot;
6160 prot, // uint32_t initprot;
6161 0, // uint32_t nsects;
6162 0}; // uint32_t flags;
6163 segment_load_commands.push_back(segment);
6164 } else {
6165 // No protections and a size of 1 used to be returned from old
6166 // debugservers when we asked about a region that was past the
6167 // last memory region and it indicates the end...
6168 if (size == 1)
6169 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006170 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006171
Kate Stoneb9c1b512016-09-06 20:57:50 +00006172 range_error = process_sp->GetMemoryRegionInfo(
6173 range_info.GetRange().GetRangeEnd(), range_info);
6174 if (range_error.Fail())
6175 break;
6176 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006177
Kate Stoneb9c1b512016-09-06 20:57:50 +00006178 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
Greg Claytona2715cf2014-06-13 00:54:12 +00006179
Kate Stoneb9c1b512016-09-06 20:57:50 +00006180 mach_header_64 mach_header;
6181 if (addr_byte_size == 8) {
6182 mach_header.magic = MH_MAGIC_64;
6183 } else {
6184 mach_header.magic = MH_MAGIC;
6185 }
6186 mach_header.cputype = target_arch.GetMachOCPUType();
6187 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6188 mach_header.filetype = MH_CORE;
6189 mach_header.ncmds = segment_load_commands.size();
6190 mach_header.flags = 0;
6191 mach_header.reserved = 0;
6192 ThreadList &thread_list = process_sp->GetThreadList();
6193 const uint32_t num_threads = thread_list.GetSize();
Greg Claytona2715cf2014-06-13 00:54:12 +00006194
Adrian Prantl05097242018-04-30 16:49:04 +00006195 // Make an array of LC_THREAD data items. Each one contains the
6196 // contents of the LC_THREAD load command. The data doesn't contain
6197 // the load command + load command size, we will add the load command
6198 // and load command size as we emit the data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006199 std::vector<StreamString> LC_THREAD_datas(num_threads);
6200 for (auto &LC_THREAD_data : LC_THREAD_datas) {
6201 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6202 LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6203 LC_THREAD_data.SetByteOrder(byte_order);
6204 }
6205 for (uint32_t thread_idx = 0; thread_idx < num_threads;
6206 ++thread_idx) {
6207 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6208 if (thread_sp) {
6209 switch (mach_header.cputype) {
6210 case llvm::MachO::CPU_TYPE_ARM64:
6211 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6212 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6213 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006214
Kate Stoneb9c1b512016-09-06 20:57:50 +00006215 case llvm::MachO::CPU_TYPE_ARM:
6216 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6217 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6218 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006219
Kate Stoneb9c1b512016-09-06 20:57:50 +00006220 case llvm::MachO::CPU_TYPE_I386:
6221 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6222 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6223 break;
Jason Molenda22952582014-11-12 01:11:36 +00006224
Kate Stoneb9c1b512016-09-06 20:57:50 +00006225 case llvm::MachO::CPU_TYPE_X86_64:
6226 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6227 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6228 break;
6229 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006230 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006231 }
6232
6233 // The size of the load command is the size of the segments...
6234 if (addr_byte_size == 8) {
6235 mach_header.sizeofcmds = segment_load_commands.size() *
6236 sizeof(struct segment_command_64);
6237 } else {
6238 mach_header.sizeofcmds =
6239 segment_load_commands.size() * sizeof(struct segment_command);
6240 }
6241
6242 // and the size of all LC_THREAD load command
6243 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6244 ++mach_header.ncmds;
6245 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6246 }
6247
6248 printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x "
6249 "0x%8.8x 0x%8.8x\n",
6250 mach_header.magic, mach_header.cputype, mach_header.cpusubtype,
6251 mach_header.filetype, mach_header.ncmds,
6252 mach_header.sizeofcmds, mach_header.flags,
6253 mach_header.reserved);
6254
6255 // Write the mach header
6256 buffer.PutHex32(mach_header.magic);
6257 buffer.PutHex32(mach_header.cputype);
6258 buffer.PutHex32(mach_header.cpusubtype);
6259 buffer.PutHex32(mach_header.filetype);
6260 buffer.PutHex32(mach_header.ncmds);
6261 buffer.PutHex32(mach_header.sizeofcmds);
6262 buffer.PutHex32(mach_header.flags);
6263 if (addr_byte_size == 8) {
6264 buffer.PutHex32(mach_header.reserved);
6265 }
6266
6267 // Skip the mach header and all load commands and align to the next
6268 // 0x1000 byte boundary
6269 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6270 if (file_offset & 0x00000fff) {
6271 file_offset += 0x00001000ull;
6272 file_offset &= (~0x00001000ull + 1);
6273 }
6274
6275 for (auto &segment : segment_load_commands) {
6276 segment.fileoff = file_offset;
6277 file_offset += segment.filesize;
6278 }
6279
6280 // Write out all of the LC_THREAD load commands
6281 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6282 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6283 buffer.PutHex32(LC_THREAD);
6284 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
Zachary Turnerc1564272016-11-16 21:15:24 +00006285 buffer.Write(LC_THREAD_data.GetString().data(),
6286 LC_THREAD_data_size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006287 }
6288
6289 // Write out all of the segment load commands
6290 for (const auto &segment : segment_load_commands) {
6291 printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6292 ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6293 ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6294 segment.cmd, segment.cmdsize, segment.vmaddr,
6295 segment.vmaddr + segment.vmsize, segment.fileoff,
6296 segment.filesize, segment.maxprot, segment.initprot,
6297 segment.nsects, segment.flags);
6298
6299 buffer.PutHex32(segment.cmd);
6300 buffer.PutHex32(segment.cmdsize);
6301 buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6302 if (addr_byte_size == 8) {
6303 buffer.PutHex64(segment.vmaddr);
6304 buffer.PutHex64(segment.vmsize);
6305 buffer.PutHex64(segment.fileoff);
6306 buffer.PutHex64(segment.filesize);
6307 } else {
6308 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6309 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6310 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6311 buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6312 }
6313 buffer.PutHex32(segment.maxprot);
6314 buffer.PutHex32(segment.initprot);
6315 buffer.PutHex32(segment.nsects);
6316 buffer.PutHex32(segment.flags);
6317 }
6318
6319 File core_file;
6320 std::string core_file_path(outfile.GetPath());
Jonas Devlieghere50bc1ed2018-11-02 22:34:51 +00006321 error = FileSystem::Instance().Open(core_file, outfile,
6322 File::eOpenOptionWrite |
6323 File::eOpenOptionTruncate |
6324 File::eOpenOptionCanCreate);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006325 if (error.Success()) {
6326 // Read 1 page at a time
6327 uint8_t bytes[0x1000];
6328 // Write the mach header and load commands out to the core file
6329 size_t bytes_written = buffer.GetString().size();
6330 error = core_file.Write(buffer.GetString().data(), bytes_written);
6331 if (error.Success()) {
6332 // Now write the file data for all memory segments in the process
6333 for (const auto &segment : segment_load_commands) {
6334 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6335 error.SetErrorStringWithFormat(
6336 "unable to seek to offset 0x%" PRIx64 " in '%s'",
6337 segment.fileoff, core_file_path.c_str());
6338 break;
6339 }
6340
6341 printf("Saving %" PRId64
6342 " bytes of data for memory region at 0x%" PRIx64 "\n",
6343 segment.vmsize, segment.vmaddr);
6344 addr_t bytes_left = segment.vmsize;
6345 addr_t addr = segment.vmaddr;
Zachary Turner97206d52017-05-12 04:51:55 +00006346 Status memory_read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006347 while (bytes_left > 0 && error.Success()) {
6348 const size_t bytes_to_read =
6349 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6350 const size_t bytes_read = process_sp->ReadMemory(
6351 addr, bytes, bytes_to_read, memory_read_error);
6352 if (bytes_read == bytes_to_read) {
6353 size_t bytes_written = bytes_read;
6354 error = core_file.Write(bytes, bytes_written);
6355 bytes_left -= bytes_read;
6356 addr += bytes_read;
6357 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00006358 // Some pages within regions are not readable, those should
6359 // be zero filled
Kate Stoneb9c1b512016-09-06 20:57:50 +00006360 memset(bytes, 0, bytes_to_read);
6361 size_t bytes_written = bytes_to_read;
6362 error = core_file.Write(bytes, bytes_written);
6363 bytes_left -= bytes_to_read;
6364 addr += bytes_to_read;
6365 }
6366 }
6367 }
6368 }
6369 }
6370 } else {
6371 error.SetErrorString(
6372 "process doesn't support getting memory region info");
Greg Claytona2715cf2014-06-13 00:54:12 +00006373 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006374 }
6375 return true; // This is the right plug to handle saving core files for
6376 // this process
Greg Claytona2715cf2014-06-13 00:54:12 +00006377 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006378 }
6379 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00006380}