blob: afe3777c45826e9ced8e90fdea8e3629c62e1d1f [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- ObjectFileMachO.cpp -------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Kate Stoneb9c1b512016-09-06 20:57:50 +00009#include "llvm/ADT/StringRef.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010
Kate Stoneb9c1b512016-09-06 20:57:50 +000011#include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
12#include "Plugins/Process/Utility/RegisterContextDarwin_arm64.h"
13#include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
14#include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
Jason Molendaf6ce26f2013-04-10 05:58:57 +000015#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000016#include "lldb/Core/FileSpecList.h"
17#include "lldb/Core/Module.h"
Greg Claytonf4d6de62013-04-24 22:29:28 +000018#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Core/PluginManager.h"
Greg Clayton1eac0c72012-04-24 03:06:13 +000020#include "lldb/Core/RangeMap.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Core/Section.h"
22#include "lldb/Core/StreamFile.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000023#include "lldb/Host/Host.h"
Jason Molenda5635f772013-03-21 03:36:01 +000024#include "lldb/Symbol/DWARFCallFrameInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Symbol/ObjectFile.h"
Jason Molenda13becd42016-07-29 00:18:39 +000026#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000027#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton26b47e22012-04-18 05:19:20 +000028#include "lldb/Target/Platform.h"
Greg Claytonc9660542012-02-05 02:38:54 +000029#include "lldb/Target/Process.h"
Greg Clayton7524e092014-02-06 20:10:16 +000030#include "lldb/Target/SectionLoadList.h"
Greg Clayton26b47e22012-04-18 05:19:20 +000031#include "lldb/Target/Target.h"
Greg Claytona2715cf2014-06-13 00:54:12 +000032#include "lldb/Target/Thread.h"
33#include "lldb/Target/ThreadList.h"
Pavel Labath5f19b902017-11-13 16:16:33 +000034#include "lldb/Utility/ArchSpec.h"
Pavel Labath50251fc2017-12-21 10:54:30 +000035#include "lldb/Utility/DataBuffer.h"
Zachary Turner5713a052017-03-22 18:40:07 +000036#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000037#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000038#include "lldb/Utility/RegisterValue.h"
Zachary Turner97206d52017-05-12 04:51:55 +000039#include "lldb/Utility/Status.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000040#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000041#include "lldb/Utility/Timer.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000042#include "lldb/Utility/UUID.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Pavel Labath77044732018-09-12 12:26:05 +000044#include "lldb/Host/SafeMachO.h"
Jim Ingham46d005d2014-04-02 22:53:21 +000045
Zachary Turner3f4a4b32017-02-24 18:56:49 +000046#include "llvm/Support/MemoryBuffer.h"
47
Jim Ingham46d005d2014-04-02 22:53:21 +000048#include "ObjectFileMachO.h"
49
Kate Stoneb9c1b512016-09-06 20:57:50 +000050#if defined(__APPLE__) && \
51 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Jason Molenda0e0954c2013-04-16 06:24:42 +000052// GetLLDBSharedCacheUUID() needs to call dlsym()
53#include <dlfcn.h>
54#endif
55
Daniel Maleaffeb4b62013-04-17 19:24:22 +000056#ifndef __APPLE__
57#include "Utility/UuidCompatibility.h"
Jason Molenda9b7fcdc2017-04-12 23:33:30 +000058#else
59#include <uuid/uuid.h>
Daniel Maleaffeb4b62013-04-17 19:24:22 +000060#endif
61
Greg Claytonb887da12015-07-16 19:50:57 +000062#define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063using namespace lldb;
64using namespace lldb_private;
Greg Claytone1a916a2010-07-21 22:12:05 +000065using namespace llvm::MachO;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066
Jason Molenda649a6072015-11-10 05:21:54 +000067// Some structure definitions needed for parsing the dyld shared cache files
68// found on iOS devices.
69
Kate Stoneb9c1b512016-09-06 20:57:50 +000070struct lldb_copy_dyld_cache_header_v1 {
71 char magic[16]; // e.g. "dyld_v0 i386", "dyld_v1 armv7", etc.
72 uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info
73 uint32_t mappingCount; // number of dyld_cache_mapping_info entries
74 uint32_t imagesOffset;
75 uint32_t imagesCount;
76 uint64_t dyldBaseAddress;
77 uint64_t codeSignatureOffset;
78 uint64_t codeSignatureSize;
79 uint64_t slideInfoOffset;
80 uint64_t slideInfoSize;
81 uint64_t localSymbolsOffset;
82 uint64_t localSymbolsSize;
83 uint8_t uuid[16]; // v1 and above, also recorded in dyld_all_image_infos v13
84 // and later
Jason Molenda649a6072015-11-10 05:21:54 +000085};
86
Kate Stoneb9c1b512016-09-06 20:57:50 +000087struct lldb_copy_dyld_cache_mapping_info {
88 uint64_t address;
89 uint64_t size;
90 uint64_t fileOffset;
91 uint32_t maxProt;
92 uint32_t initProt;
Jason Molenda649a6072015-11-10 05:21:54 +000093};
94
Kate Stoneb9c1b512016-09-06 20:57:50 +000095struct lldb_copy_dyld_cache_local_symbols_info {
96 uint32_t nlistOffset;
97 uint32_t nlistCount;
98 uint32_t stringsOffset;
99 uint32_t stringsSize;
100 uint32_t entriesOffset;
101 uint32_t entriesCount;
Jason Molenda649a6072015-11-10 05:21:54 +0000102};
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103struct lldb_copy_dyld_cache_local_symbols_entry {
104 uint32_t dylibOffset;
105 uint32_t nlistStartIndex;
106 uint32_t nlistCount;
Jason Molenda649a6072015-11-10 05:21:54 +0000107};
108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000110public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread,
112 const DataExtractor &data)
113 : RegisterContextDarwin_x86_64(thread, 0) {
114 SetRegisterDataFrom_LC_THREAD(data);
115 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000116
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 void InvalidateAllRegisters() override {
118 // Do nothing... registers are always valid...
119 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000120
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
122 lldb::offset_t offset = 0;
123 SetError(GPRRegSet, Read, -1);
124 SetError(FPURegSet, Read, -1);
125 SetError(EXCRegSet, Read, -1);
126 bool done = false;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 while (!done) {
129 int flavor = data.GetU32(&offset);
130 if (flavor == 0)
131 done = true;
132 else {
133 uint32_t i;
134 uint32_t count = data.GetU32(&offset);
135 switch (flavor) {
136 case GPRRegSet:
137 for (i = 0; i < count; ++i)
138 (&gpr.rax)[i] = data.GetU64(&offset);
139 SetError(GPRRegSet, Read, 0);
140 done = true;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 break;
143 case FPURegSet:
144 // TODO: fill in FPU regs....
145 // SetError (FPURegSet, Read, -1);
146 done = true;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 break;
149 case EXCRegSet:
150 exc.trapno = data.GetU32(&offset);
151 exc.err = data.GetU32(&offset);
152 exc.faultvaddr = data.GetU64(&offset);
153 SetError(EXCRegSet, Read, 0);
154 done = true;
155 break;
156 case 7:
157 case 8:
158 case 9:
Adrian Prantl05097242018-04-30 16:49:04 +0000159 // fancy flavors that encapsulate of the above flavors...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000161
Greg Clayton9aae0a12013-05-15 19:52:08 +0000162 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 done = true;
164 break;
165 }
166 }
Greg Clayton9aae0a12013-05-15 19:52:08 +0000167 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168 }
169
170 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
171 const char *alt_name, size_t reg_byte_size,
172 Stream &data) {
173 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
174 if (reg_info == NULL)
175 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
176 if (reg_info) {
177 lldb_private::RegisterValue reg_value;
178 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
179 if (reg_info->byte_size >= reg_byte_size)
180 data.Write(reg_value.GetBytes(), reg_byte_size);
181 else {
182 data.Write(reg_value.GetBytes(), reg_info->byte_size);
183 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
184 ++i)
185 data.PutChar(0);
186 }
187 return reg_byte_size;
188 }
189 }
190 // Just write zeros if all else fails
191 for (size_t i = 0; i < reg_byte_size; ++i)
192 data.PutChar(0);
193 return reg_byte_size;
194 }
195
196 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
197 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
198 if (reg_ctx_sp) {
199 RegisterContext *reg_ctx = reg_ctx_sp.get();
200
201 data.PutHex32(GPRRegSet); // Flavor
202 data.PutHex32(GPRWordCount);
203 WriteRegister(reg_ctx, "rax", NULL, 8, data);
204 WriteRegister(reg_ctx, "rbx", NULL, 8, data);
205 WriteRegister(reg_ctx, "rcx", NULL, 8, data);
206 WriteRegister(reg_ctx, "rdx", NULL, 8, data);
207 WriteRegister(reg_ctx, "rdi", NULL, 8, data);
208 WriteRegister(reg_ctx, "rsi", NULL, 8, data);
209 WriteRegister(reg_ctx, "rbp", NULL, 8, data);
210 WriteRegister(reg_ctx, "rsp", NULL, 8, data);
211 WriteRegister(reg_ctx, "r8", NULL, 8, data);
212 WriteRegister(reg_ctx, "r9", NULL, 8, data);
213 WriteRegister(reg_ctx, "r10", NULL, 8, data);
214 WriteRegister(reg_ctx, "r11", NULL, 8, data);
215 WriteRegister(reg_ctx, "r12", NULL, 8, data);
216 WriteRegister(reg_ctx, "r13", NULL, 8, data);
217 WriteRegister(reg_ctx, "r14", NULL, 8, data);
218 WriteRegister(reg_ctx, "r15", NULL, 8, data);
219 WriteRegister(reg_ctx, "rip", NULL, 8, data);
220 WriteRegister(reg_ctx, "rflags", NULL, 8, data);
221 WriteRegister(reg_ctx, "cs", NULL, 8, data);
222 WriteRegister(reg_ctx, "fs", NULL, 8, data);
223 WriteRegister(reg_ctx, "gs", NULL, 8, data);
224
225 // // Write out the FPU registers
226 // const size_t fpu_byte_size = sizeof(FPU);
227 // size_t bytes_written = 0;
228 // data.PutHex32 (FPURegSet);
229 // data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
230 // bytes_written += data.PutHex32(0); // uint32_t pad[0]
231 // bytes_written += data.PutHex32(0); // uint32_t pad[1]
232 // bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
233 // data); // uint16_t fcw; // "fctrl"
234 // bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
235 // data); // uint16_t fsw; // "fstat"
236 // bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
237 // data); // uint8_t ftw; // "ftag"
238 // bytes_written += data.PutHex8 (0); // uint8_t pad1;
239 // bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
240 // data); // uint16_t fop; // "fop"
241 // bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
242 // data); // uint32_t ip; // "fioff"
243 // bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
244 // data); // uint16_t cs; // "fiseg"
245 // bytes_written += data.PutHex16 (0); // uint16_t pad2;
246 // bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
247 // data); // uint32_t dp; // "fooff"
248 // bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
249 // data); // uint16_t ds; // "foseg"
250 // bytes_written += data.PutHex16 (0); // uint16_t pad3;
251 // bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
252 // data); // uint32_t mxcsr;
253 // bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
254 // 4, data);// uint32_t mxcsrmask;
255 // bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
256 // sizeof(MMSReg), data);
257 // bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
258 // sizeof(MMSReg), data);
259 // bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
260 // sizeof(MMSReg), data);
261 // bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
262 // sizeof(MMSReg), data);
263 // bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
264 // sizeof(MMSReg), data);
265 // bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
266 // sizeof(MMSReg), data);
267 // bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
268 // sizeof(MMSReg), data);
269 // bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
270 // sizeof(MMSReg), data);
271 // bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
272 // sizeof(XMMReg), data);
273 // bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
274 // sizeof(XMMReg), data);
275 // bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
276 // sizeof(XMMReg), data);
277 // bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
278 // sizeof(XMMReg), data);
279 // bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
280 // sizeof(XMMReg), data);
281 // bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
282 // sizeof(XMMReg), data);
283 // bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
284 // sizeof(XMMReg), data);
285 // bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
286 // sizeof(XMMReg), data);
287 // bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
288 // sizeof(XMMReg), data);
289 // bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
290 // sizeof(XMMReg), data);
291 // bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
292 // sizeof(XMMReg), data);
293 // bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
294 // sizeof(XMMReg), data);
295 // bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
296 // sizeof(XMMReg), data);
297 // bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
298 // sizeof(XMMReg), data);
299 // bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
300 // sizeof(XMMReg), data);
301 // bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
302 // sizeof(XMMReg), data);
303 //
304 // // Fill rest with zeros
305 // for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
306 // i)
307 // data.PutChar(0);
308
309 // Write out the EXC registers
310 data.PutHex32(EXCRegSet);
311 data.PutHex32(EXCWordCount);
312 WriteRegister(reg_ctx, "trapno", NULL, 4, data);
313 WriteRegister(reg_ctx, "err", NULL, 4, data);
314 WriteRegister(reg_ctx, "faultvaddr", NULL, 8, data);
315 return true;
316 }
317 return false;
318 }
319
320protected:
321 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
322
323 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
324
325 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
326
327 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
Greg Clayton9aae0a12013-05-15 19:52:08 +0000328 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 }
330
331 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
332 return 0;
333 }
334
335 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
336 return 0;
337 }
338};
339
340class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 {
341public:
342 RegisterContextDarwin_i386_Mach(lldb_private::Thread &thread,
343 const DataExtractor &data)
344 : RegisterContextDarwin_i386(thread, 0) {
345 SetRegisterDataFrom_LC_THREAD(data);
346 }
347
348 void InvalidateAllRegisters() override {
349 // Do nothing... registers are always valid...
350 }
351
352 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
353 lldb::offset_t offset = 0;
354 SetError(GPRRegSet, Read, -1);
355 SetError(FPURegSet, Read, -1);
356 SetError(EXCRegSet, Read, -1);
357 bool done = false;
358
359 while (!done) {
360 int flavor = data.GetU32(&offset);
361 if (flavor == 0)
362 done = true;
363 else {
364 uint32_t i;
365 uint32_t count = data.GetU32(&offset);
366 switch (flavor) {
367 case GPRRegSet:
368 for (i = 0; i < count; ++i)
369 (&gpr.eax)[i] = data.GetU32(&offset);
370 SetError(GPRRegSet, Read, 0);
371 done = true;
372
373 break;
374 case FPURegSet:
375 // TODO: fill in FPU regs....
376 // SetError (FPURegSet, Read, -1);
377 done = true;
378
379 break;
380 case EXCRegSet:
381 exc.trapno = data.GetU32(&offset);
382 exc.err = data.GetU32(&offset);
383 exc.faultvaddr = data.GetU32(&offset);
384 SetError(EXCRegSet, Read, 0);
385 done = true;
386 break;
387 case 7:
388 case 8:
389 case 9:
Adrian Prantl05097242018-04-30 16:49:04 +0000390 // fancy flavors that encapsulate of the above flavors...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 break;
392
393 default:
394 done = true;
395 break;
396 }
397 }
398 }
399 }
400
401 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
402 const char *alt_name, size_t reg_byte_size,
403 Stream &data) {
404 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
405 if (reg_info == NULL)
406 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
407 if (reg_info) {
408 lldb_private::RegisterValue reg_value;
409 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
410 if (reg_info->byte_size >= reg_byte_size)
411 data.Write(reg_value.GetBytes(), reg_byte_size);
412 else {
413 data.Write(reg_value.GetBytes(), reg_info->byte_size);
414 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
415 ++i)
416 data.PutChar(0);
417 }
418 return reg_byte_size;
419 }
420 }
421 // Just write zeros if all else fails
422 for (size_t i = 0; i < reg_byte_size; ++i)
423 data.PutChar(0);
424 return reg_byte_size;
425 }
426
427 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
428 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
429 if (reg_ctx_sp) {
430 RegisterContext *reg_ctx = reg_ctx_sp.get();
431
432 data.PutHex32(GPRRegSet); // Flavor
433 data.PutHex32(GPRWordCount);
434 WriteRegister(reg_ctx, "eax", NULL, 4, data);
435 WriteRegister(reg_ctx, "ebx", NULL, 4, data);
436 WriteRegister(reg_ctx, "ecx", NULL, 4, data);
437 WriteRegister(reg_ctx, "edx", NULL, 4, data);
438 WriteRegister(reg_ctx, "edi", NULL, 4, data);
439 WriteRegister(reg_ctx, "esi", NULL, 4, data);
440 WriteRegister(reg_ctx, "ebp", NULL, 4, data);
441 WriteRegister(reg_ctx, "esp", NULL, 4, data);
442 WriteRegister(reg_ctx, "ss", NULL, 4, data);
443 WriteRegister(reg_ctx, "eflags", NULL, 4, data);
444 WriteRegister(reg_ctx, "eip", NULL, 4, data);
445 WriteRegister(reg_ctx, "cs", NULL, 4, data);
446 WriteRegister(reg_ctx, "ds", NULL, 4, data);
447 WriteRegister(reg_ctx, "es", NULL, 4, data);
448 WriteRegister(reg_ctx, "fs", NULL, 4, data);
449 WriteRegister(reg_ctx, "gs", NULL, 4, data);
450
451 // Write out the EXC registers
452 data.PutHex32(EXCRegSet);
453 data.PutHex32(EXCWordCount);
454 WriteRegister(reg_ctx, "trapno", NULL, 4, data);
455 WriteRegister(reg_ctx, "err", NULL, 4, data);
456 WriteRegister(reg_ctx, "faultvaddr", NULL, 4, data);
457 return true;
458 }
459 return false;
460 }
461
462protected:
463 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
464
465 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
466
467 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
468
469 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
470 return 0;
471 }
472
473 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
474 return 0;
475 }
476
477 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
478 return 0;
479 }
480};
481
482class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm {
483public:
484 RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread,
485 const DataExtractor &data)
486 : RegisterContextDarwin_arm(thread, 0) {
487 SetRegisterDataFrom_LC_THREAD(data);
488 }
489
490 void InvalidateAllRegisters() override {
491 // Do nothing... registers are always valid...
492 }
493
494 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
495 lldb::offset_t offset = 0;
496 SetError(GPRRegSet, Read, -1);
497 SetError(FPURegSet, Read, -1);
498 SetError(EXCRegSet, Read, -1);
499 bool done = false;
500
501 while (!done) {
502 int flavor = data.GetU32(&offset);
503 uint32_t count = data.GetU32(&offset);
504 lldb::offset_t next_thread_state = offset + (count * 4);
505 switch (flavor) {
506 case GPRAltRegSet:
507 case GPRRegSet:
508 for (uint32_t i = 0; i < count; ++i) {
509 gpr.r[i] = data.GetU32(&offset);
510 }
511
512 // Note that gpr.cpsr is also copied by the above loop; this loop
Adrian Prantl05097242018-04-30 16:49:04 +0000513 // technically extends one element past the end of the gpr.r[] array.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514
515 SetError(GPRRegSet, Read, 0);
516 offset = next_thread_state;
517 break;
518
519 case FPURegSet: {
520 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats.s[0];
521 const int fpu_reg_buf_size = sizeof(fpu.floats);
522 if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
523 fpu_reg_buf) == fpu_reg_buf_size) {
524 offset += fpu_reg_buf_size;
525 fpu.fpscr = data.GetU32(&offset);
526 SetError(FPURegSet, Read, 0);
527 } else {
528 done = true;
529 }
530 }
531 offset = next_thread_state;
532 break;
533
534 case EXCRegSet:
535 if (count == 3) {
536 exc.exception = data.GetU32(&offset);
537 exc.fsr = data.GetU32(&offset);
538 exc.far = data.GetU32(&offset);
539 SetError(EXCRegSet, Read, 0);
540 }
541 done = true;
542 offset = next_thread_state;
543 break;
544
545 // Unknown register set flavor, stop trying to parse.
546 default:
547 done = true;
548 }
549 }
550 }
551
552 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
553 const char *alt_name, size_t reg_byte_size,
554 Stream &data) {
555 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
556 if (reg_info == NULL)
557 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
558 if (reg_info) {
559 lldb_private::RegisterValue reg_value;
560 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
561 if (reg_info->byte_size >= reg_byte_size)
562 data.Write(reg_value.GetBytes(), reg_byte_size);
563 else {
564 data.Write(reg_value.GetBytes(), reg_info->byte_size);
565 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
566 ++i)
567 data.PutChar(0);
568 }
569 return reg_byte_size;
570 }
571 }
572 // Just write zeros if all else fails
573 for (size_t i = 0; i < reg_byte_size; ++i)
574 data.PutChar(0);
575 return reg_byte_size;
576 }
577
578 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
579 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
580 if (reg_ctx_sp) {
581 RegisterContext *reg_ctx = reg_ctx_sp.get();
582
583 data.PutHex32(GPRRegSet); // Flavor
584 data.PutHex32(GPRWordCount);
585 WriteRegister(reg_ctx, "r0", NULL, 4, data);
586 WriteRegister(reg_ctx, "r1", NULL, 4, data);
587 WriteRegister(reg_ctx, "r2", NULL, 4, data);
588 WriteRegister(reg_ctx, "r3", NULL, 4, data);
589 WriteRegister(reg_ctx, "r4", NULL, 4, data);
590 WriteRegister(reg_ctx, "r5", NULL, 4, data);
591 WriteRegister(reg_ctx, "r6", NULL, 4, data);
592 WriteRegister(reg_ctx, "r7", NULL, 4, data);
593 WriteRegister(reg_ctx, "r8", NULL, 4, data);
594 WriteRegister(reg_ctx, "r9", NULL, 4, data);
595 WriteRegister(reg_ctx, "r10", NULL, 4, data);
596 WriteRegister(reg_ctx, "r11", NULL, 4, data);
597 WriteRegister(reg_ctx, "r12", NULL, 4, data);
598 WriteRegister(reg_ctx, "sp", NULL, 4, data);
599 WriteRegister(reg_ctx, "lr", NULL, 4, data);
600 WriteRegister(reg_ctx, "pc", NULL, 4, data);
601 WriteRegister(reg_ctx, "cpsr", NULL, 4, data);
602
603 // Write out the EXC registers
604 // data.PutHex32 (EXCRegSet);
605 // data.PutHex32 (EXCWordCount);
606 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
607 // WriteRegister (reg_ctx, "fsr", NULL, 4, data);
608 // WriteRegister (reg_ctx, "far", NULL, 4, data);
609 return true;
610 }
611 return false;
612 }
613
614protected:
615 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
616
617 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
618
619 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
620
621 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
622
623 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
624 return 0;
625 }
626
627 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
628 return 0;
629 }
630
631 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
632 return 0;
633 }
634
635 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
636 return -1;
637 }
638};
639
640class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 {
641public:
642 RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread,
643 const DataExtractor &data)
644 : RegisterContextDarwin_arm64(thread, 0) {
645 SetRegisterDataFrom_LC_THREAD(data);
646 }
647
648 void InvalidateAllRegisters() override {
649 // Do nothing... registers are always valid...
650 }
651
652 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
653 lldb::offset_t offset = 0;
654 SetError(GPRRegSet, Read, -1);
655 SetError(FPURegSet, Read, -1);
656 SetError(EXCRegSet, Read, -1);
657 bool done = false;
658 while (!done) {
659 int flavor = data.GetU32(&offset);
660 uint32_t count = data.GetU32(&offset);
661 lldb::offset_t next_thread_state = offset + (count * 4);
662 switch (flavor) {
663 case GPRRegSet:
664 // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
665 // 32-bit register)
666 if (count >= (33 * 2) + 1) {
Vedant Kumar6ba1db92016-11-07 02:39:37 +0000667 for (uint32_t i = 0; i < 29; ++i)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 gpr.x[i] = data.GetU64(&offset);
Vedant Kumar6ba1db92016-11-07 02:39:37 +0000669 gpr.fp = data.GetU64(&offset);
670 gpr.lr = data.GetU64(&offset);
671 gpr.sp = data.GetU64(&offset);
672 gpr.pc = data.GetU64(&offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 gpr.cpsr = data.GetU32(&offset);
674 SetError(GPRRegSet, Read, 0);
675 }
676 offset = next_thread_state;
677 break;
678 case FPURegSet: {
679 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
680 const int fpu_reg_buf_size = sizeof(fpu);
Jason Molenda4f346142017-11-16 00:50:29 +0000681 if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682 data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
683 fpu_reg_buf) == fpu_reg_buf_size) {
684 SetError(FPURegSet, Read, 0);
685 } else {
686 done = true;
687 }
688 }
689 offset = next_thread_state;
690 break;
691 case EXCRegSet:
692 if (count == 4) {
693 exc.far = data.GetU64(&offset);
694 exc.esr = data.GetU32(&offset);
695 exc.exception = data.GetU32(&offset);
696 SetError(EXCRegSet, Read, 0);
697 }
698 offset = next_thread_state;
699 break;
700 default:
701 done = true;
702 break;
703 }
704 }
705 }
706
707 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
708 const char *alt_name, size_t reg_byte_size,
709 Stream &data) {
710 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
711 if (reg_info == NULL)
712 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
713 if (reg_info) {
714 lldb_private::RegisterValue reg_value;
715 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
716 if (reg_info->byte_size >= reg_byte_size)
717 data.Write(reg_value.GetBytes(), reg_byte_size);
718 else {
719 data.Write(reg_value.GetBytes(), reg_info->byte_size);
720 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
721 ++i)
722 data.PutChar(0);
723 }
724 return reg_byte_size;
725 }
726 }
727 // Just write zeros if all else fails
728 for (size_t i = 0; i < reg_byte_size; ++i)
729 data.PutChar(0);
730 return reg_byte_size;
731 }
732
733 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
734 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
735 if (reg_ctx_sp) {
736 RegisterContext *reg_ctx = reg_ctx_sp.get();
737
738 data.PutHex32(GPRRegSet); // Flavor
739 data.PutHex32(GPRWordCount);
740 WriteRegister(reg_ctx, "x0", NULL, 8, data);
741 WriteRegister(reg_ctx, "x1", NULL, 8, data);
742 WriteRegister(reg_ctx, "x2", NULL, 8, data);
743 WriteRegister(reg_ctx, "x3", NULL, 8, data);
744 WriteRegister(reg_ctx, "x4", NULL, 8, data);
745 WriteRegister(reg_ctx, "x5", NULL, 8, data);
746 WriteRegister(reg_ctx, "x6", NULL, 8, data);
747 WriteRegister(reg_ctx, "x7", NULL, 8, data);
748 WriteRegister(reg_ctx, "x8", NULL, 8, data);
749 WriteRegister(reg_ctx, "x9", NULL, 8, data);
750 WriteRegister(reg_ctx, "x10", NULL, 8, data);
751 WriteRegister(reg_ctx, "x11", NULL, 8, data);
752 WriteRegister(reg_ctx, "x12", NULL, 8, data);
753 WriteRegister(reg_ctx, "x13", NULL, 8, data);
754 WriteRegister(reg_ctx, "x14", NULL, 8, data);
755 WriteRegister(reg_ctx, "x15", NULL, 8, data);
756 WriteRegister(reg_ctx, "x16", NULL, 8, data);
757 WriteRegister(reg_ctx, "x17", NULL, 8, data);
758 WriteRegister(reg_ctx, "x18", NULL, 8, data);
759 WriteRegister(reg_ctx, "x19", NULL, 8, data);
760 WriteRegister(reg_ctx, "x20", NULL, 8, data);
761 WriteRegister(reg_ctx, "x21", NULL, 8, data);
762 WriteRegister(reg_ctx, "x22", NULL, 8, data);
763 WriteRegister(reg_ctx, "x23", NULL, 8, data);
764 WriteRegister(reg_ctx, "x24", NULL, 8, data);
765 WriteRegister(reg_ctx, "x25", NULL, 8, data);
766 WriteRegister(reg_ctx, "x26", NULL, 8, data);
767 WriteRegister(reg_ctx, "x27", NULL, 8, data);
768 WriteRegister(reg_ctx, "x28", NULL, 8, data);
769 WriteRegister(reg_ctx, "fp", NULL, 8, data);
770 WriteRegister(reg_ctx, "lr", NULL, 8, data);
771 WriteRegister(reg_ctx, "sp", NULL, 8, data);
772 WriteRegister(reg_ctx, "pc", NULL, 8, data);
773 WriteRegister(reg_ctx, "cpsr", NULL, 4, data);
774
775 // Write out the EXC registers
776 // data.PutHex32 (EXCRegSet);
777 // data.PutHex32 (EXCWordCount);
778 // WriteRegister (reg_ctx, "far", NULL, 8, data);
779 // WriteRegister (reg_ctx, "esr", NULL, 4, data);
780 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
781 return true;
782 }
783 return false;
784 }
785
786protected:
787 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
788
789 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
790
791 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
792
793 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
794
795 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
796 return 0;
797 }
798
799 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
800 return 0;
801 }
802
803 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
804 return 0;
805 }
806
807 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
808 return -1;
809 }
810};
811
812static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
813 switch (magic) {
814 case MH_MAGIC:
815 case MH_CIGAM:
816 return sizeof(struct mach_header);
817
818 case MH_MAGIC_64:
819 case MH_CIGAM_64:
820 return sizeof(struct mach_header_64);
821 break;
822
823 default:
824 break;
825 }
826 return 0;
Greg Clayton9aae0a12013-05-15 19:52:08 +0000827}
828
Greg Claytonded470d2011-03-19 01:12:21 +0000829#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831void ObjectFileMachO::Initialize() {
832 PluginManager::RegisterPlugin(
833 GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
834 CreateMemoryInstance, GetModuleSpecifications, SaveCore);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835}
836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837void ObjectFileMachO::Terminate() {
838 PluginManager::UnregisterPlugin(CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839}
840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841lldb_private::ConstString ObjectFileMachO::GetPluginNameStatic() {
842 static ConstString g_name("mach-o");
843 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000844}
845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846const char *ObjectFileMachO::GetPluginDescriptionStatic() {
847 return "Mach-o object file reader (32 and 64 bit)";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848}
849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850ObjectFile *ObjectFileMachO::CreateInstance(const lldb::ModuleSP &module_sp,
851 DataBufferSP &data_sp,
852 lldb::offset_t data_offset,
853 const FileSpec *file,
854 lldb::offset_t file_offset,
855 lldb::offset_t length) {
856 if (!data_sp) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000857 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000858 if (!data_sp)
859 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 data_offset = 0;
861 }
862
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000863 if (!ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
864 return nullptr;
865
866 // Update the data to contain the entire file if it doesn't already
867 if (data_sp->GetByteSize() < length) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000868 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000869 if (!data_sp)
870 return nullptr;
871 data_offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 }
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000873 auto objfile_ap = llvm::make_unique<ObjectFileMachO>(
874 module_sp, data_sp, data_offset, file, file_offset, length);
875 if (!objfile_ap || !objfile_ap->ParseHeader())
876 return nullptr;
877
878 return objfile_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000879}
880
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881ObjectFile *ObjectFileMachO::CreateMemoryInstance(
882 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
883 const ProcessSP &process_sp, lldb::addr_t header_addr) {
884 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
885 std::unique_ptr<ObjectFile> objfile_ap(
886 new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
887 if (objfile_ap.get() && objfile_ap->ParseHeader())
888 return objfile_ap.release();
889 }
890 return NULL;
Greg Claytonc9660542012-02-05 02:38:54 +0000891}
892
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893size_t ObjectFileMachO::GetModuleSpecifications(
894 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
895 lldb::offset_t data_offset, lldb::offset_t file_offset,
896 lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
897 const size_t initial_count = specs.GetSize();
Oleksiy Vyalov63acdfd2015-03-10 01:15:28 +0000898
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
Greg Clayton44435ed2012-01-12 05:25:17 +0000900 DataExtractor data;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 data.SetData(data_sp);
902 llvm::MachO::mach_header header;
903 if (ParseHeader(data, &data_offset, header)) {
904 size_t header_and_load_cmds =
905 header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
906 if (header_and_load_cmds >= data_sp->GetByteSize()) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000907 data_sp = MapFileData(file, header_and_load_cmds, file_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 data.SetData(data_sp);
909 data_offset = MachHeaderSizeFromMagic(header.magic);
910 }
911 if (data_sp) {
912 ModuleSpec spec;
913 spec.GetFileSpec() = file;
914 spec.SetObjectOffset(file_offset);
915 spec.SetObjectSize(length);
916
Pavel Labathf760f5a2019-01-03 10:37:19 +0000917 spec.GetArchitecture() = GetArchitecture(header, data, data_offset);
918 if (spec.GetArchitecture().IsValid()) {
919 GetUUID(header, data, data_offset, spec.GetUUID());
920 specs.Append(spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921 }
922 }
923 }
924 }
925 return specs.GetSize() - initial_count;
926}
927
928const ConstString &ObjectFileMachO::GetSegmentNameTEXT() {
929 static ConstString g_segment_name_TEXT("__TEXT");
930 return g_segment_name_TEXT;
931}
932
933const ConstString &ObjectFileMachO::GetSegmentNameDATA() {
934 static ConstString g_segment_name_DATA("__DATA");
935 return g_segment_name_DATA;
936}
937
938const ConstString &ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
939 static ConstString g_segment_name("__DATA_DIRTY");
940 return g_segment_name;
941}
942
943const ConstString &ObjectFileMachO::GetSegmentNameDATA_CONST() {
944 static ConstString g_segment_name("__DATA_CONST");
945 return g_segment_name;
946}
947
948const ConstString &ObjectFileMachO::GetSegmentNameOBJC() {
949 static ConstString g_segment_name_OBJC("__OBJC");
950 return g_segment_name_OBJC;
951}
952
953const ConstString &ObjectFileMachO::GetSegmentNameLINKEDIT() {
954 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
955 return g_section_name_LINKEDIT;
956}
957
Greg Clayton57577c02018-12-21 17:04:18 +0000958const ConstString &ObjectFileMachO::GetSegmentNameDWARF() {
959 static ConstString g_section_name("__DWARF");
960 return g_section_name;
961}
962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963const ConstString &ObjectFileMachO::GetSectionNameEHFrame() {
964 static ConstString g_section_name_eh_frame("__eh_frame");
965 return g_section_name_eh_frame;
966}
967
968bool ObjectFileMachO::MagicBytesMatch(DataBufferSP &data_sp,
969 lldb::addr_t data_offset,
970 lldb::addr_t data_length) {
971 DataExtractor data;
972 data.SetData(data_sp, data_offset, data_length);
973 lldb::offset_t offset = 0;
974 uint32_t magic = data.GetU32(&offset);
975 return MachHeaderSizeFromMagic(magic) != 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976}
977
Greg Clayton5ce9c562013-02-06 17:22:03 +0000978ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979 DataBufferSP &data_sp,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000980 lldb::offset_t data_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 const FileSpec *file,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000982 lldb::offset_t file_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 lldb::offset_t length)
984 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
985 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
986 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
987 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
988 ::memset(&m_header, 0, sizeof(m_header));
989 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990}
991
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
993 lldb::DataBufferSP &header_data_sp,
994 const lldb::ProcessSP &process_sp,
995 lldb::addr_t header_addr)
996 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
997 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
998 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
999 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
1000 ::memset(&m_header, 0, sizeof(m_header));
1001 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Greg Claytonc9660542012-02-05 02:38:54 +00001002}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004bool ObjectFileMachO::ParseHeader(DataExtractor &data,
1005 lldb::offset_t *data_offset_ptr,
1006 llvm::MachO::mach_header &header) {
1007 data.SetByteOrder(endian::InlHostByteOrder());
1008 // Leave magic in the original byte order
1009 header.magic = data.GetU32(data_offset_ptr);
1010 bool can_parse = false;
1011 bool is_64_bit = false;
1012 switch (header.magic) {
1013 case MH_MAGIC:
1014 data.SetByteOrder(endian::InlHostByteOrder());
1015 data.SetAddressByteSize(4);
1016 can_parse = true;
1017 break;
1018
1019 case MH_MAGIC_64:
1020 data.SetByteOrder(endian::InlHostByteOrder());
1021 data.SetAddressByteSize(8);
1022 can_parse = true;
1023 is_64_bit = true;
1024 break;
1025
1026 case MH_CIGAM:
1027 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1028 ? eByteOrderLittle
1029 : eByteOrderBig);
1030 data.SetAddressByteSize(4);
1031 can_parse = true;
1032 break;
1033
1034 case MH_CIGAM_64:
1035 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1036 ? eByteOrderLittle
1037 : eByteOrderBig);
1038 data.SetAddressByteSize(8);
1039 is_64_bit = true;
1040 can_parse = true;
1041 break;
1042
1043 default:
1044 break;
1045 }
1046
1047 if (can_parse) {
1048 data.GetU32(data_offset_ptr, &header.cputype, 6);
1049 if (is_64_bit)
1050 *data_offset_ptr += 4;
1051 return true;
1052 } else {
1053 memset(&header, 0, sizeof(header));
1054 }
1055 return false;
1056}
1057
1058bool ObjectFileMachO::ParseHeader() {
1059 ModuleSP module_sp(GetModule());
1060 if (module_sp) {
1061 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Greg Claytonf4d6de62013-04-24 22:29:28 +00001062 bool can_parse = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 lldb::offset_t offset = 0;
1064 m_data.SetByteOrder(endian::InlHostByteOrder());
1065 // Leave magic in the original byte order
1066 m_header.magic = m_data.GetU32(&offset);
1067 switch (m_header.magic) {
1068 case MH_MAGIC:
1069 m_data.SetByteOrder(endian::InlHostByteOrder());
1070 m_data.SetAddressByteSize(4);
1071 can_parse = true;
1072 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 case MH_MAGIC_64:
1075 m_data.SetByteOrder(endian::InlHostByteOrder());
1076 m_data.SetAddressByteSize(8);
1077 can_parse = true;
1078 break;
Greg Claytona1743492012-03-13 23:14:29 +00001079
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 case MH_CIGAM:
1081 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1082 ? eByteOrderLittle
1083 : eByteOrderBig);
1084 m_data.SetAddressByteSize(4);
1085 can_parse = true;
1086 break;
Greg Claytona1743492012-03-13 23:14:29 +00001087
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 case MH_CIGAM_64:
1089 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1090 ? eByteOrderLittle
1091 : eByteOrderBig);
1092 m_data.SetAddressByteSize(8);
1093 can_parse = true;
1094 break;
Greg Claytona1743492012-03-13 23:14:29 +00001095
Kate Stoneb9c1b512016-09-06 20:57:50 +00001096 default:
1097 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 }
1099
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 if (can_parse) {
1101 m_data.GetU32(&offset, &m_header.cputype, 6);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102
Pavel Labathf760f5a2019-01-03 10:37:19 +00001103 if (ArchSpec mach_arch = GetArchitecture()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104 // Check if the module has a required architecture
1105 const ArchSpec &module_arch = module_sp->GetArchitecture();
1106 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1107 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 if (SetModulesArchitecture(mach_arch)) {
1110 const size_t header_and_lc_size =
1111 m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1112 if (m_data.GetByteSize() < header_and_lc_size) {
1113 DataBufferSP data_sp;
1114 ProcessSP process_sp(m_process_wp.lock());
1115 if (process_sp) {
1116 data_sp =
1117 ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1118 } else {
1119 // Read in all only the load command data from the file on disk
Pavel Labath50251fc2017-12-21 10:54:30 +00001120 data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 if (data_sp->GetByteSize() != header_and_lc_size)
Greg Clayton8f265f72015-10-28 20:49:34 +00001122 return false;
1123 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 if (data_sp)
1125 m_data.SetData(data_sp);
1126 }
Greg Clayton9191db42013-10-21 18:40:51 +00001127 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 return true;
1129 }
1130 } else {
1131 memset(&m_header, 0, sizeof(struct mach_header));
1132 }
1133 }
1134 return false;
1135}
1136
1137ByteOrder ObjectFileMachO::GetByteOrder() const {
1138 return m_data.GetByteOrder();
1139}
1140
1141bool ObjectFileMachO::IsExecutable() const {
1142 return m_header.filetype == MH_EXECUTE;
1143}
1144
1145uint32_t ObjectFileMachO::GetAddressByteSize() const {
1146 return m_data.GetAddressByteSize();
1147}
1148
1149AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
1150 Symtab *symtab = GetSymtab();
1151 if (symtab) {
1152 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1153 if (symbol) {
1154 if (symbol->ValueIsAddress()) {
1155 SectionSP section_sp(symbol->GetAddressRef().GetSection());
1156 if (section_sp) {
1157 const lldb::SectionType section_type = section_sp->GetType();
1158 switch (section_type) {
1159 case eSectionTypeInvalid:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001160 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161
1162 case eSectionTypeCode:
1163 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001164 // For ARM we have a bit in the n_desc field of the symbol that
1165 // tells us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001167 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001169 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170
1171 case eSectionTypeContainer:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001172 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173
1174 case eSectionTypeData:
1175 case eSectionTypeDataCString:
1176 case eSectionTypeDataCStringPointers:
1177 case eSectionTypeDataSymbolAddress:
1178 case eSectionTypeData4:
1179 case eSectionTypeData8:
1180 case eSectionTypeData16:
1181 case eSectionTypeDataPointers:
1182 case eSectionTypeZeroFill:
1183 case eSectionTypeDataObjCMessageRefs:
1184 case eSectionTypeDataObjCCFStrings:
1185 case eSectionTypeGoSymtab:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001186 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001187
1188 case eSectionTypeDebug:
1189 case eSectionTypeDWARFDebugAbbrev:
George Rimar004bcb72018-11-14 13:01:15 +00001190 case eSectionTypeDWARFDebugAbbrevDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191 case eSectionTypeDWARFDebugAddr:
1192 case eSectionTypeDWARFDebugAranges:
Tamas Berghammer963ce482017-08-25 13:56:14 +00001193 case eSectionTypeDWARFDebugCuIndex:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194 case eSectionTypeDWARFDebugFrame:
1195 case eSectionTypeDWARFDebugInfo:
George Rimar004bcb72018-11-14 13:01:15 +00001196 case eSectionTypeDWARFDebugInfoDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 case eSectionTypeDWARFDebugLine:
George Rimarc6c7bfc2018-09-13 17:06:47 +00001198 case eSectionTypeDWARFDebugLineStr:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 case eSectionTypeDWARFDebugLoc:
George Rimare4dee262018-10-23 09:46:15 +00001200 case eSectionTypeDWARFDebugLocLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 case eSectionTypeDWARFDebugMacInfo:
1202 case eSectionTypeDWARFDebugMacro:
Pavel Labatha041d842018-06-01 12:06:45 +00001203 case eSectionTypeDWARFDebugNames:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 case eSectionTypeDWARFDebugPubNames:
1205 case eSectionTypeDWARFDebugPubTypes:
1206 case eSectionTypeDWARFDebugRanges:
George Rimar6e357122018-10-10 08:11:15 +00001207 case eSectionTypeDWARFDebugRngLists:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208 case eSectionTypeDWARFDebugStr:
George Rimar004bcb72018-11-14 13:01:15 +00001209 case eSectionTypeDWARFDebugStrDwo:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 case eSectionTypeDWARFDebugStrOffsets:
George Rimar004bcb72018-11-14 13:01:15 +00001211 case eSectionTypeDWARFDebugStrOffsetsDwo:
Greg Clayton2550ca12018-05-08 17:19:24 +00001212 case eSectionTypeDWARFDebugTypes:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 case eSectionTypeDWARFAppleNames:
1214 case eSectionTypeDWARFAppleTypes:
1215 case eSectionTypeDWARFAppleNamespaces:
1216 case eSectionTypeDWARFAppleObjC:
Jan Kratochvile4777a92018-04-29 19:47:48 +00001217 case eSectionTypeDWARFGNUDebugAltLink:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001218 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219
1220 case eSectionTypeEHFrame:
1221 case eSectionTypeARMexidx:
1222 case eSectionTypeARMextab:
1223 case eSectionTypeCompactUnwind:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001224 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225
1226 case eSectionTypeAbsoluteAddress:
1227 case eSectionTypeELFSymbolTable:
1228 case eSectionTypeELFDynamicSymbols:
1229 case eSectionTypeELFRelocationEntries:
1230 case eSectionTypeELFDynamicLinkInfo:
1231 case eSectionTypeOther:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001232 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 }
1234 }
1235 }
1236
1237 const SymbolType symbol_type = symbol->GetType();
1238 switch (symbol_type) {
1239 case eSymbolTypeAny:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001240 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 case eSymbolTypeAbsolute:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001242 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243
1244 case eSymbolTypeCode:
1245 case eSymbolTypeTrampoline:
1246 case eSymbolTypeResolver:
1247 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001248 // For ARM we have a bit in the n_desc field of the symbol that tells
1249 // us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001251 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001253 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254
1255 case eSymbolTypeData:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001256 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 case eSymbolTypeRuntime:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001258 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259 case eSymbolTypeException:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001260 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 case eSymbolTypeSourceFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001262 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 case eSymbolTypeHeaderFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001264 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 case eSymbolTypeObjectFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001266 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267 case eSymbolTypeCommonBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001268 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 case eSymbolTypeBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001270 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 case eSymbolTypeLocal:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001272 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 case eSymbolTypeParam:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001274 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001275 case eSymbolTypeVariable:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001276 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277 case eSymbolTypeVariableType:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001278 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 case eSymbolTypeLineEntry:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001280 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 case eSymbolTypeLineHeader:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001282 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283 case eSymbolTypeScopeBegin:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001284 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 case eSymbolTypeScopeEnd:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001286 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 case eSymbolTypeAdditional:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001288 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 case eSymbolTypeCompiler:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001290 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 case eSymbolTypeInstrumentation:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001292 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 case eSymbolTypeUndefined:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001294 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001295 case eSymbolTypeObjCClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001296 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297 case eSymbolTypeObjCMetaClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001298 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 case eSymbolTypeObjCIVar:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001300 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 case eSymbolTypeReExported:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001302 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 }
1304 }
1305 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001306 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307}
1308
1309Symtab *ObjectFileMachO::GetSymtab() {
1310 ModuleSP module_sp(GetModule());
1311 if (module_sp) {
1312 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1313 if (m_symtab_ap.get() == NULL) {
1314 m_symtab_ap.reset(new Symtab(this));
1315 std::lock_guard<std::recursive_mutex> symtab_guard(
1316 m_symtab_ap->GetMutex());
1317 ParseSymtab();
Davide Italiano407c6912018-11-02 21:59:14 +00001318 m_symtab_ap->Finalize();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319 }
1320 }
1321 return m_symtab_ap.get();
1322}
1323
1324bool ObjectFileMachO::IsStripped() {
1325 if (m_dysymtab.cmd == 0) {
1326 ModuleSP module_sp(GetModule());
1327 if (module_sp) {
1328 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1329 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1330 const lldb::offset_t load_cmd_offset = offset;
1331
1332 load_command lc;
1333 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
1334 break;
1335 if (lc.cmd == LC_DYSYMTAB) {
1336 m_dysymtab.cmd = lc.cmd;
1337 m_dysymtab.cmdsize = lc.cmdsize;
1338 if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1339 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1340 NULL) {
1341 // Clear m_dysymtab if we were unable to read all items from the
1342 // load command
1343 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1344 }
1345 }
1346 offset = load_cmd_offset + lc.cmdsize;
1347 }
1348 }
1349 }
1350 if (m_dysymtab.cmd)
1351 return m_dysymtab.nlocalsym <= 1;
1352 return false;
1353}
1354
Pavel Labathb417eea2018-03-06 13:53:26 +00001355ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
1356 EncryptedFileRanges result;
Pavel Labathf90054d2018-03-03 22:07:47 +00001357 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labathb417eea2018-03-06 13:53:26 +00001358
Pavel Labathf90054d2018-03-03 22:07:47 +00001359 encryption_info_command encryption_cmd;
Pavel Labathb417eea2018-03-06 13:53:26 +00001360 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001361 const lldb::offset_t load_cmd_offset = offset;
1362 if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL)
1363 break;
1364
Adrian Prantl05097242018-04-30 16:49:04 +00001365 // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1366 // 3 fields we care about, so treat them the same.
Pavel Labathf90054d2018-03-03 22:07:47 +00001367 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1368 encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1369 if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1370 if (encryption_cmd.cryptid != 0) {
1371 EncryptedFileRanges::Entry entry;
1372 entry.SetRangeBase(encryption_cmd.cryptoff);
1373 entry.SetByteSize(encryption_cmd.cryptsize);
Pavel Labathb417eea2018-03-06 13:53:26 +00001374 result.Append(entry);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375 }
1376 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001377 }
Pavel Labathf90054d2018-03-03 22:07:47 +00001378 offset = load_cmd_offset + encryption_cmd.cmdsize;
1379 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380
Pavel Labathb417eea2018-03-06 13:53:26 +00001381 return result;
1382}
1383
1384void ObjectFileMachO::SanitizeSegmentCommand(segment_command_64 &seg_cmd,
1385 uint32_t cmd_idx) {
1386 if (m_length == 0 || seg_cmd.filesize == 0)
1387 return;
1388
1389 if (seg_cmd.fileoff > m_length) {
1390 // We have a load command that says it extends past the end of the file.
1391 // This is likely a corrupt file. We don't have any way to return an error
1392 // condition here (this method was likely invoked from something like
1393 // ObjectFile::GetSectionList()), so we just null out the section contents,
1394 // and dump a message to stdout. The most common case here is core file
1395 // debugging with a truncated file.
1396 const char *lc_segment_name =
1397 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1398 GetModule()->ReportWarning(
1399 "load command %u %s has a fileoff (0x%" PRIx64
1400 ") that extends beyond the end of the file (0x%" PRIx64
1401 "), ignoring this section",
1402 cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
1403
1404 seg_cmd.fileoff = 0;
1405 seg_cmd.filesize = 0;
1406 }
1407
1408 if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1409 // We have a load command that says it extends past the end of the file.
1410 // This is likely a corrupt file. We don't have any way to return an error
1411 // condition here (this method was likely invoked from something like
1412 // ObjectFile::GetSectionList()), so we just null out the section contents,
1413 // and dump a message to stdout. The most common case here is core file
1414 // debugging with a truncated file.
1415 const char *lc_segment_name =
1416 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1417 GetModule()->ReportWarning(
1418 "load command %u %s has a fileoff + filesize (0x%" PRIx64
1419 ") that extends beyond the end of the file (0x%" PRIx64
1420 "), the segment will be truncated to match",
1421 cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
1422
1423 // Truncate the length
1424 seg_cmd.filesize = m_length - seg_cmd.fileoff;
1425 }
1426}
1427
1428static uint32_t GetSegmentPermissions(const segment_command_64 &seg_cmd) {
1429 uint32_t result = 0;
1430 if (seg_cmd.initprot & VM_PROT_READ)
1431 result |= ePermissionsReadable;
1432 if (seg_cmd.initprot & VM_PROT_WRITE)
1433 result |= ePermissionsWritable;
1434 if (seg_cmd.initprot & VM_PROT_EXECUTE)
1435 result |= ePermissionsExecutable;
1436 return result;
1437}
1438
1439static lldb::SectionType GetSectionType(uint32_t flags,
1440 ConstString section_name) {
1441
1442 if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1443 return eSectionTypeCode;
1444
1445 uint32_t mach_sect_type = flags & SECTION_TYPE;
1446 static ConstString g_sect_name_objc_data("__objc_data");
1447 static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1448 static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1449 static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
1450 static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
1451 static ConstString g_sect_name_objc_const("__objc_const");
1452 static ConstString g_sect_name_objc_classlist("__objc_classlist");
1453 static ConstString g_sect_name_cfstring("__cfstring");
1454
1455 static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
1456 static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1457 static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1458 static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1459 static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1460 static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
George Rimare4dee262018-10-23 09:46:15 +00001461 static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
Pavel Labathb417eea2018-03-06 13:53:26 +00001462 static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
Pavel Labatha041d842018-06-01 12:06:45 +00001463 static ConstString g_sect_name_dwarf_debug_names("__debug_names");
Pavel Labathb417eea2018-03-06 13:53:26 +00001464 static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1465 static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1466 static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1467 static ConstString g_sect_name_dwarf_debug_str("__debug_str");
Greg Clayton2550ca12018-05-08 17:19:24 +00001468 static ConstString g_sect_name_dwarf_debug_types("__debug_types");
Pavel Labathb417eea2018-03-06 13:53:26 +00001469 static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1470 static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1471 static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1472 static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1473 static ConstString g_sect_name_eh_frame("__eh_frame");
1474 static ConstString g_sect_name_compact_unwind("__unwind_info");
1475 static ConstString g_sect_name_text("__text");
1476 static ConstString g_sect_name_data("__data");
1477 static ConstString g_sect_name_go_symtab("__gosymtab");
1478
1479 if (section_name == g_sect_name_dwarf_debug_abbrev)
1480 return eSectionTypeDWARFDebugAbbrev;
1481 if (section_name == g_sect_name_dwarf_debug_aranges)
1482 return eSectionTypeDWARFDebugAranges;
1483 if (section_name == g_sect_name_dwarf_debug_frame)
1484 return eSectionTypeDWARFDebugFrame;
1485 if (section_name == g_sect_name_dwarf_debug_info)
1486 return eSectionTypeDWARFDebugInfo;
1487 if (section_name == g_sect_name_dwarf_debug_line)
1488 return eSectionTypeDWARFDebugLine;
1489 if (section_name == g_sect_name_dwarf_debug_loc)
1490 return eSectionTypeDWARFDebugLoc;
George Rimare4dee262018-10-23 09:46:15 +00001491 if (section_name == g_sect_name_dwarf_debug_loclists)
1492 return eSectionTypeDWARFDebugLocLists;
Pavel Labathb417eea2018-03-06 13:53:26 +00001493 if (section_name == g_sect_name_dwarf_debug_macinfo)
1494 return eSectionTypeDWARFDebugMacInfo;
Pavel Labatha041d842018-06-01 12:06:45 +00001495 if (section_name == g_sect_name_dwarf_debug_names)
1496 return eSectionTypeDWARFDebugNames;
Pavel Labathb417eea2018-03-06 13:53:26 +00001497 if (section_name == g_sect_name_dwarf_debug_pubnames)
1498 return eSectionTypeDWARFDebugPubNames;
1499 if (section_name == g_sect_name_dwarf_debug_pubtypes)
1500 return eSectionTypeDWARFDebugPubTypes;
1501 if (section_name == g_sect_name_dwarf_debug_ranges)
George Rimar6e357122018-10-10 08:11:15 +00001502 return eSectionTypeDWARFDebugRanges;
Pavel Labathb417eea2018-03-06 13:53:26 +00001503 if (section_name == g_sect_name_dwarf_debug_str)
1504 return eSectionTypeDWARFDebugStr;
Greg Clayton2550ca12018-05-08 17:19:24 +00001505 if (section_name == g_sect_name_dwarf_debug_types)
1506 return eSectionTypeDWARFDebugTypes;
Pavel Labathb417eea2018-03-06 13:53:26 +00001507 if (section_name == g_sect_name_dwarf_apple_names)
1508 return eSectionTypeDWARFAppleNames;
1509 if (section_name == g_sect_name_dwarf_apple_types)
1510 return eSectionTypeDWARFAppleTypes;
1511 if (section_name == g_sect_name_dwarf_apple_namespaces)
1512 return eSectionTypeDWARFAppleNamespaces;
1513 if (section_name == g_sect_name_dwarf_apple_objc)
1514 return eSectionTypeDWARFAppleObjC;
1515 if (section_name == g_sect_name_objc_selrefs)
1516 return eSectionTypeDataCStringPointers;
1517 if (section_name == g_sect_name_objc_msgrefs)
1518 return eSectionTypeDataObjCMessageRefs;
1519 if (section_name == g_sect_name_eh_frame)
1520 return eSectionTypeEHFrame;
1521 if (section_name == g_sect_name_compact_unwind)
1522 return eSectionTypeCompactUnwind;
1523 if (section_name == g_sect_name_cfstring)
1524 return eSectionTypeDataObjCCFStrings;
1525 if (section_name == g_sect_name_go_symtab)
1526 return eSectionTypeGoSymtab;
1527 if (section_name == g_sect_name_objc_data ||
1528 section_name == g_sect_name_objc_classrefs ||
1529 section_name == g_sect_name_objc_superrefs ||
1530 section_name == g_sect_name_objc_const ||
1531 section_name == g_sect_name_objc_classlist) {
1532 return eSectionTypeDataPointers;
1533 }
1534
1535 switch (mach_sect_type) {
1536 // TODO: categorize sections by other flags for regular sections
1537 case S_REGULAR:
1538 if (section_name == g_sect_name_text)
1539 return eSectionTypeCode;
1540 if (section_name == g_sect_name_data)
1541 return eSectionTypeData;
1542 return eSectionTypeOther;
1543 case S_ZEROFILL:
1544 return eSectionTypeZeroFill;
1545 case S_CSTRING_LITERALS: // section with only literal C strings
1546 return eSectionTypeDataCString;
1547 case S_4BYTE_LITERALS: // section with only 4 byte literals
1548 return eSectionTypeData4;
1549 case S_8BYTE_LITERALS: // section with only 8 byte literals
1550 return eSectionTypeData8;
1551 case S_LITERAL_POINTERS: // section with only pointers to literals
1552 return eSectionTypeDataPointers;
1553 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1554 return eSectionTypeDataPointers;
1555 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1556 return eSectionTypeDataPointers;
1557 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1558 // the reserved2 field
1559 return eSectionTypeCode;
1560 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1561 // initialization
1562 return eSectionTypeDataPointers;
1563 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1564 // termination
1565 return eSectionTypeDataPointers;
1566 case S_COALESCED:
1567 return eSectionTypeOther;
1568 case S_GB_ZEROFILL:
1569 return eSectionTypeZeroFill;
1570 case S_INTERPOSING: // section with only pairs of function pointers for
1571 // interposing
1572 return eSectionTypeCode;
1573 case S_16BYTE_LITERALS: // section with only 16 byte literals
1574 return eSectionTypeData16;
1575 case S_DTRACE_DOF:
1576 return eSectionTypeDebug;
1577 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1578 return eSectionTypeDataPointers;
1579 default:
1580 return eSectionTypeOther;
1581 }
1582}
1583
1584struct ObjectFileMachO::SegmentParsingContext {
1585 const EncryptedFileRanges EncryptedRanges;
1586 lldb_private::SectionList &UnifiedList;
1587 uint32_t NextSegmentIdx = 0;
1588 uint32_t NextSectionIdx = 0;
1589 bool FileAddressesChanged = false;
1590
1591 SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
1592 lldb_private::SectionList &UnifiedList)
1593 : EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
1594};
1595
1596void ObjectFileMachO::ProcessSegmentCommand(const load_command &load_cmd_,
1597 lldb::offset_t offset,
1598 uint32_t cmd_idx,
1599 SegmentParsingContext &context) {
1600 segment_command_64 load_cmd;
1601 memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1602
1603 if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1604 return;
1605
1606 ModuleSP module_sp = GetModule();
1607 const bool is_core = GetType() == eTypeCoreFile;
1608 const bool is_dsym = (m_header.filetype == MH_DSYM);
1609 bool add_section = true;
1610 bool add_to_unified = true;
1611 ConstString const_segname(
1612 load_cmd.segname,
1613 std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname)));
1614
1615 SectionSP unified_section_sp(
1616 context.UnifiedList.FindSectionByName(const_segname));
1617 if (is_dsym && unified_section_sp) {
1618 if (const_segname == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001619 // We need to keep the __LINKEDIT segment private to this object file
1620 // only
Pavel Labathb417eea2018-03-06 13:53:26 +00001621 add_to_unified = false;
1622 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001623 // This is the dSYM file and this section has already been created by the
1624 // object file, no need to create it.
Pavel Labathb417eea2018-03-06 13:53:26 +00001625 add_section = false;
1626 }
1627 }
1628 load_cmd.vmaddr = m_data.GetAddress(&offset);
1629 load_cmd.vmsize = m_data.GetAddress(&offset);
1630 load_cmd.fileoff = m_data.GetAddress(&offset);
1631 load_cmd.filesize = m_data.GetAddress(&offset);
1632 if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1633 return;
1634
1635 SanitizeSegmentCommand(load_cmd, cmd_idx);
1636
1637 const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1638 const bool segment_is_encrypted =
1639 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1640
Adrian Prantl05097242018-04-30 16:49:04 +00001641 // Keep a list of mach segments around in case we need to get at data that
1642 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001643 m_mach_segments.push_back(load_cmd);
1644
Adrian Prantl05097242018-04-30 16:49:04 +00001645 // Use a segment ID of the segment index shifted left by 8 so they never
1646 // conflict with any of the sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001647 SectionSP segment_sp;
1648 if (add_section && (const_segname || is_core)) {
1649 segment_sp.reset(new Section(
1650 module_sp, // Module to which this section belongs
1651 this, // Object file to which this sections belongs
1652 ++context.NextSegmentIdx
1653 << 8, // Section ID is the 1 based segment index
Adrian Prantl05097242018-04-30 16:49:04 +00001654 // shifted right by 8 bits as not to collide with any of the 256
1655 // section IDs that are possible
Pavel Labathb417eea2018-03-06 13:53:26 +00001656 const_segname, // Name of this section
1657 eSectionTypeContainer, // This section is a container of other
1658 // sections.
1659 load_cmd.vmaddr, // File VM address == addresses as they are
1660 // found in the object file
1661 load_cmd.vmsize, // VM size in bytes of this section
1662 load_cmd.fileoff, // Offset to the data for this section in
1663 // the file
1664 load_cmd.filesize, // Size in bytes of this section as found
1665 // in the file
1666 0, // Segments have no alignment information
1667 load_cmd.flags)); // Flags for this section
1668
1669 segment_sp->SetIsEncrypted(segment_is_encrypted);
1670 m_sections_ap->AddSection(segment_sp);
1671 segment_sp->SetPermissions(segment_permissions);
1672 if (add_to_unified)
1673 context.UnifiedList.AddSection(segment_sp);
1674 } else if (unified_section_sp) {
1675 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1676 // Check to see if the module was read from memory?
Pavel Labathd1e3fe22018-12-11 15:21:15 +00001677 if (module_sp->GetObjectFile()->GetBaseAddress().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001678 // We have a module that is in memory and needs to have its file
1679 // address adjusted. We need to do this because when we load a file
1680 // from memory, its addresses will be slid already, yet the addresses
1681 // in the new symbol file will still be unslid. Since everything is
1682 // stored as section offset, this shouldn't cause any problems.
Pavel Labathb417eea2018-03-06 13:53:26 +00001683
Adrian Prantl05097242018-04-30 16:49:04 +00001684 // Make sure we've parsed the symbol table from the ObjectFile before
1685 // we go around changing its Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001686 module_sp->GetObjectFile()->GetSymtab();
Adrian Prantl05097242018-04-30 16:49:04 +00001687 // eh_frame would present the same problems but we parse that on a per-
1688 // function basis as-needed so it's more difficult to remove its use of
1689 // the Sections. Realistically, the environments where this code path
1690 // will be taken will not have eh_frame sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001691
1692 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1693
Adrian Prantl05097242018-04-30 16:49:04 +00001694 // Notify the module that the section addresses have been changed once
1695 // we're done so any file-address caches can be updated.
Pavel Labathb417eea2018-03-06 13:53:26 +00001696 context.FileAddressesChanged = true;
1697 }
1698 }
1699 m_sections_ap->AddSection(unified_section_sp);
1700 }
1701
1702 struct section_64 sect64;
1703 ::memset(&sect64, 0, sizeof(sect64));
Adrian Prantl05097242018-04-30 16:49:04 +00001704 // Push a section into our mach sections for the section at index zero
1705 // (NO_SECT) if we don't have any mach sections yet...
Pavel Labathb417eea2018-03-06 13:53:26 +00001706 if (m_mach_sections.empty())
1707 m_mach_sections.push_back(sect64);
1708 uint32_t segment_sect_idx;
1709 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1710
1711 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1712 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1713 ++segment_sect_idx) {
1714 if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1715 sizeof(sect64.sectname)) == NULL)
1716 break;
1717 if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1718 sizeof(sect64.segname)) == NULL)
1719 break;
1720 sect64.addr = m_data.GetAddress(&offset);
1721 sect64.size = m_data.GetAddress(&offset);
1722
1723 if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
1724 break;
1725
Adrian Prantl05097242018-04-30 16:49:04 +00001726 // Keep a list of mach sections around in case we need to get at data that
1727 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001728 m_mach_sections.push_back(sect64);
1729
1730 if (add_section) {
1731 ConstString section_name(
1732 sect64.sectname,
1733 std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname)));
1734 if (!const_segname) {
Adrian Prantl05097242018-04-30 16:49:04 +00001735 // We have a segment with no name so we need to conjure up segments
1736 // that correspond to the section's segname if there isn't already such
1737 // a section. If there is such a section, we resize the section so that
1738 // it spans all sections. We also mark these sections as fake so
1739 // address matches don't hit if they land in the gaps between the child
1740 // sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001741 const_segname.SetTrimmedCStringWithLength(sect64.segname,
1742 sizeof(sect64.segname));
1743 segment_sp = context.UnifiedList.FindSectionByName(const_segname);
1744 if (segment_sp.get()) {
1745 Section *segment = segment_sp.get();
1746 // Grow the section size as needed.
1747 const lldb::addr_t sect64_min_addr = sect64.addr;
1748 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1749 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1750 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1751 const lldb::addr_t curr_seg_max_addr =
1752 curr_seg_min_addr + curr_seg_byte_size;
1753 if (sect64_min_addr >= curr_seg_min_addr) {
1754 const lldb::addr_t new_seg_byte_size =
1755 sect64_max_addr - curr_seg_min_addr;
1756 // Only grow the section size if needed
1757 if (new_seg_byte_size > curr_seg_byte_size)
1758 segment->SetByteSize(new_seg_byte_size);
1759 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001760 // We need to change the base address of the segment and adjust the
1761 // child section offsets for all existing children.
Pavel Labathb417eea2018-03-06 13:53:26 +00001762 const lldb::addr_t slide_amount =
1763 sect64_min_addr - curr_seg_min_addr;
1764 segment->Slide(slide_amount, false);
1765 segment->GetChildren().Slide(-slide_amount, false);
1766 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1767 }
1768
1769 // Grow the section size as needed.
1770 if (sect64.offset) {
1771 const lldb::addr_t segment_min_file_offset =
1772 segment->GetFileOffset();
1773 const lldb::addr_t segment_max_file_offset =
1774 segment_min_file_offset + segment->GetFileSize();
1775
1776 const lldb::addr_t section_min_file_offset = sect64.offset;
1777 const lldb::addr_t section_max_file_offset =
1778 section_min_file_offset + sect64.size;
1779 const lldb::addr_t new_file_offset =
1780 std::min(section_min_file_offset, segment_min_file_offset);
1781 const lldb::addr_t new_file_size =
1782 std::max(section_max_file_offset, segment_max_file_offset) -
1783 new_file_offset;
1784 segment->SetFileOffset(new_file_offset);
1785 segment->SetFileSize(new_file_size);
1786 }
1787 } else {
1788 // Create a fake section for the section's named segment
1789 segment_sp.reset(new Section(
1790 segment_sp, // Parent section
1791 module_sp, // Module to which this section belongs
1792 this, // Object file to which this section belongs
1793 ++context.NextSegmentIdx
1794 << 8, // Section ID is the 1 based segment index
1795 // shifted right by 8 bits as not to
1796 // collide with any of the 256 section IDs
1797 // that are possible
1798 const_segname, // Name of this section
1799 eSectionTypeContainer, // This section is a container of
1800 // other sections.
1801 sect64.addr, // File VM address == addresses as they are
1802 // found in the object file
1803 sect64.size, // VM size in bytes of this section
1804 sect64.offset, // Offset to the data for this section in
1805 // the file
1806 sect64.offset ? sect64.size : 0, // Size in bytes of
1807 // this section as
1808 // found in the file
1809 sect64.align,
1810 load_cmd.flags)); // Flags for this section
1811 segment_sp->SetIsFake(true);
1812 segment_sp->SetPermissions(segment_permissions);
1813 m_sections_ap->AddSection(segment_sp);
1814 if (add_to_unified)
1815 context.UnifiedList.AddSection(segment_sp);
1816 segment_sp->SetIsEncrypted(segment_is_encrypted);
1817 }
1818 }
1819 assert(segment_sp.get());
1820
1821 lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1822
1823 SectionSP section_sp(new Section(
1824 segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1825 sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1826 sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1827 sect64.flags));
1828 // Set the section to be encrypted to match the segment
1829
1830 bool section_is_encrypted = false;
1831 if (!segment_is_encrypted && load_cmd.filesize != 0)
1832 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1833 sect64.offset) != NULL;
1834
1835 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1836 section_sp->SetPermissions(segment_permissions);
1837 segment_sp->GetChildren().AddSection(section_sp);
1838
1839 if (segment_sp->IsFake()) {
1840 segment_sp.reset();
1841 const_segname.Clear();
1842 }
1843 }
1844 }
1845 if (segment_sp && is_dsym) {
1846 if (first_segment_sectID <= context.NextSectionIdx) {
1847 lldb::user_id_t sect_uid;
1848 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1849 ++sect_uid) {
1850 SectionSP curr_section_sp(
1851 segment_sp->GetChildren().FindSectionByID(sect_uid));
1852 SectionSP next_section_sp;
1853 if (sect_uid + 1 <= context.NextSectionIdx)
1854 next_section_sp =
1855 segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1856
1857 if (curr_section_sp.get()) {
1858 if (curr_section_sp->GetByteSize() == 0) {
1859 if (next_section_sp.get() != NULL)
1860 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1861 curr_section_sp->GetFileAddress());
1862 else
1863 curr_section_sp->SetByteSize(load_cmd.vmsize);
1864 }
1865 }
1866 }
1867 }
1868 }
1869}
1870
1871void ObjectFileMachO::ProcessDysymtabCommand(const load_command &load_cmd,
1872 lldb::offset_t offset) {
1873 m_dysymtab.cmd = load_cmd.cmd;
1874 m_dysymtab.cmdsize = load_cmd.cmdsize;
1875 m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1876 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1877}
1878
1879void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1880 if (m_sections_ap)
1881 return;
1882
1883 m_sections_ap.reset(new SectionList());
1884
1885 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1886 // bool dump_sections = false;
1887 ModuleSP module_sp(GetModule());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001888
Pavel Labathf90054d2018-03-03 22:07:47 +00001889 offset = MachHeaderSizeFromMagic(m_header.magic);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001890
Pavel Labathb417eea2018-03-06 13:53:26 +00001891 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1892 struct load_command load_cmd;
1893 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001894 const lldb::offset_t load_cmd_offset = offset;
1895 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
1896 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001897
Pavel Labathb417eea2018-03-06 13:53:26 +00001898 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1899 ProcessSegmentCommand(load_cmd, offset, i, context);
1900 else if (load_cmd.cmd == LC_DYSYMTAB)
1901 ProcessDysymtabCommand(load_cmd, offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001902
Pavel Labathf90054d2018-03-03 22:07:47 +00001903 offset = load_cmd_offset + load_cmd.cmdsize;
1904 }
1905
Pavel Labathb417eea2018-03-06 13:53:26 +00001906 if (context.FileAddressesChanged && module_sp)
Pavel Labathf90054d2018-03-03 22:07:47 +00001907 module_sp->SectionFileAddressesChanged();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001908}
1909
1910class MachSymtabSectionInfo {
1911public:
1912 MachSymtabSectionInfo(SectionList *section_list)
1913 : m_section_list(section_list), m_section_infos() {
Adrian Prantl05097242018-04-30 16:49:04 +00001914 // Get the number of sections down to a depth of 1 to include all segments
1915 // and their sections, but no other sections that may be added for debug
1916 // map or
Kate Stoneb9c1b512016-09-06 20:57:50 +00001917 m_section_infos.resize(section_list->GetNumSections(1));
1918 }
1919
1920 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1921 if (n_sect == 0)
1922 return SectionSP();
1923 if (n_sect < m_section_infos.size()) {
1924 if (!m_section_infos[n_sect].section_sp) {
1925 SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1926 m_section_infos[n_sect].section_sp = section_sp;
1927 if (section_sp) {
1928 m_section_infos[n_sect].vm_range.SetBaseAddress(
1929 section_sp->GetFileAddress());
1930 m_section_infos[n_sect].vm_range.SetByteSize(
1931 section_sp->GetByteSize());
1932 } else {
1933 Host::SystemLog(Host::eSystemLogError,
1934 "error: unable to find section for section %u\n",
1935 n_sect);
1936 }
1937 }
1938 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1939 // Symbol is in section.
1940 return m_section_infos[n_sect].section_sp;
1941 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1942 m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1943 file_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001944 // Symbol is in section with zero size, but has the same start address
1945 // as the section. This can happen with linker symbols (symbols that
1946 // start with the letter 'l' or 'L'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001947 return m_section_infos[n_sect].section_sp;
1948 }
1949 }
1950 return m_section_list->FindSectionContainingFileAddress(file_addr);
1951 }
1952
1953protected:
1954 struct SectionInfo {
1955 SectionInfo() : vm_range(), section_sp() {}
1956
1957 VMRange vm_range;
1958 SectionSP section_sp;
1959 };
1960 SectionList *m_section_list;
1961 std::vector<SectionInfo> m_section_infos;
1962};
1963
1964struct TrieEntry {
1965 TrieEntry()
1966 : name(), address(LLDB_INVALID_ADDRESS), flags(0), other(0),
1967 import_name() {}
1968
1969 void Clear() {
1970 name.Clear();
1971 address = LLDB_INVALID_ADDRESS;
1972 flags = 0;
1973 other = 0;
1974 import_name.Clear();
1975 }
1976
1977 void Dump() const {
1978 printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
1979 static_cast<unsigned long long>(address),
1980 static_cast<unsigned long long>(flags),
1981 static_cast<unsigned long long>(other), name.GetCString());
1982 if (import_name)
1983 printf(" -> \"%s\"\n", import_name.GetCString());
1984 else
1985 printf("\n");
1986 }
1987 ConstString name;
1988 uint64_t address;
1989 uint64_t flags;
1990 uint64_t other;
1991 ConstString import_name;
1992};
1993
1994struct TrieEntryWithOffset {
1995 lldb::offset_t nodeOffset;
1996 TrieEntry entry;
1997
1998 TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
1999
2000 void Dump(uint32_t idx) const {
2001 printf("[%3u] 0x%16.16llx: ", idx,
2002 static_cast<unsigned long long>(nodeOffset));
2003 entry.Dump();
2004 }
2005
2006 bool operator<(const TrieEntryWithOffset &other) const {
2007 return (nodeOffset < other.nodeOffset);
2008 }
2009};
2010
2011static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
2012 const bool is_arm,
2013 std::vector<llvm::StringRef> &nameSlices,
2014 std::set<lldb::addr_t> &resolver_addresses,
2015 std::vector<TrieEntryWithOffset> &output) {
2016 if (!data.ValidOffset(offset))
Greg Clayton8f265f72015-10-28 20:49:34 +00002017 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002018
2019 const uint64_t terminalSize = data.GetULEB128(&offset);
2020 lldb::offset_t children_offset = offset + terminalSize;
2021 if (terminalSize != 0) {
2022 TrieEntryWithOffset e(offset);
2023 e.entry.flags = data.GetULEB128(&offset);
2024 const char *import_name = NULL;
2025 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2026 e.entry.address = 0;
2027 e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2028 import_name = data.GetCStr(&offset);
2029 } else {
2030 e.entry.address = data.GetULEB128(&offset);
2031 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2032 e.entry.other = data.GetULEB128(&offset);
2033 uint64_t resolver_addr = e.entry.other;
2034 if (is_arm)
2035 resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2036 resolver_addresses.insert(resolver_addr);
2037 } else
2038 e.entry.other = 0;
2039 }
2040 // Only add symbols that are reexport symbols with a valid import name
2041 if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name &&
2042 import_name[0]) {
2043 std::string name;
2044 if (!nameSlices.empty()) {
2045 for (auto name_slice : nameSlices)
2046 name.append(name_slice.data(), name_slice.size());
2047 }
2048 if (name.size() > 1) {
2049 // Skip the leading '_'
2050 e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2051 }
2052 if (import_name) {
2053 // Skip the leading '_'
2054 e.entry.import_name.SetCString(import_name + 1);
2055 }
2056 output.push_back(e);
2057 }
2058 }
2059
2060 const uint8_t childrenCount = data.GetU8(&children_offset);
2061 for (uint8_t i = 0; i < childrenCount; ++i) {
2062 const char *cstr = data.GetCStr(&children_offset);
2063 if (cstr)
2064 nameSlices.push_back(llvm::StringRef(cstr));
2065 else
2066 return false; // Corrupt data
2067 lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2068 if (childNodeOffset) {
2069 if (!ParseTrieEntries(data, childNodeOffset, is_arm, nameSlices,
2070 resolver_addresses, output)) {
2071 return false;
2072 }
2073 }
2074 nameSlices.pop_back();
2075 }
2076 return true;
Greg Clayton9191db42013-10-21 18:40:51 +00002077}
2078
Jason Molenda649a6072015-11-10 05:21:54 +00002079// Read the UUID out of a dyld_shared_cache file on-disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
2081 const ByteOrder byte_order,
2082 const uint32_t addr_byte_size) {
2083 UUID dsc_uuid;
Pavel Labath50251fc2017-12-21 10:54:30 +00002084 DataBufferSP DscData = MapFileData(
2085 dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002086 if (!DscData)
2087 return dsc_uuid;
2088 DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
Jason Molenda649a6072015-11-10 05:21:54 +00002089
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002090 char version_str[7];
2091 lldb::offset_t offset = 0;
2092 memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
2093 version_str[6] = '\0';
2094 if (strcmp(version_str, "dyld_v") == 0) {
2095 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
Pavel Labath2f93fd12018-06-26 15:12:20 +00002096 dsc_uuid = UUID::fromOptionalData(
2097 dsc_header_data.GetData(&offset, sizeof(uuid_t)), sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098 }
Jason Molendafd443e92018-02-07 01:28:29 +00002099 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2100 if (log && dsc_uuid.IsValid()) {
2101 log->Printf("Shared cache %s has UUID %s", dyld_shared_cache.GetPath().c_str(),
2102 dsc_uuid.GetAsString().c_str());
2103 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104 return dsc_uuid;
Jason Molenda649a6072015-11-10 05:21:54 +00002105}
2106
Kate Stoneb9c1b512016-09-06 20:57:50 +00002107size_t ObjectFileMachO::ParseSymtab() {
Pavel Labathf9d16472017-05-15 13:02:37 +00002108 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2109 Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110 m_file.GetFilename().AsCString(""));
2111 ModuleSP module_sp(GetModule());
2112 if (!module_sp)
2113 return 0;
2114
2115 struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2116 struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2117 struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2118 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2119 FunctionStarts function_starts;
2120 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2121 uint32_t i;
2122 FileSpecList dylib_files;
2123 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2124 static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2125 static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2126 static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2127
2128 for (i = 0; i < m_header.ncmds; ++i) {
2129 const lldb::offset_t cmd_offset = offset;
2130 // Read in the load command and load command size
2131 struct load_command lc;
2132 if (m_data.GetU32(&offset, &lc, 2) == NULL)
2133 break;
2134 // Watch for the symbol table load command
2135 switch (lc.cmd) {
2136 case LC_SYMTAB:
2137 symtab_load_command.cmd = lc.cmd;
2138 symtab_load_command.cmdsize = lc.cmdsize;
2139 // Read in the rest of the symtab load command
2140 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2141 0) // fill in symoff, nsyms, stroff, strsize fields
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002142 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 if (symtab_load_command.symoff == 0) {
2144 if (log)
2145 module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2146 return 0;
2147 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002148
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149 if (symtab_load_command.stroff == 0) {
2150 if (log)
2151 module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2152 return 0;
2153 }
Greg Clayton77ccca72011-12-30 00:32:24 +00002154
Kate Stoneb9c1b512016-09-06 20:57:50 +00002155 if (symtab_load_command.nsyms == 0) {
2156 if (log)
2157 module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
2158 return 0;
2159 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002160
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161 if (symtab_load_command.strsize == 0) {
2162 if (log)
2163 module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2164 return 0;
2165 }
2166 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002167
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168 case LC_DYLD_INFO:
2169 case LC_DYLD_INFO_ONLY:
2170 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2171 dyld_info.cmd = lc.cmd;
2172 dyld_info.cmdsize = lc.cmdsize;
2173 } else {
2174 memset(&dyld_info, 0, sizeof(dyld_info));
2175 }
2176 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002177
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 case LC_LOAD_DYLIB:
2179 case LC_LOAD_WEAK_DYLIB:
2180 case LC_REEXPORT_DYLIB:
2181 case LC_LOADFVMLIB:
2182 case LC_LOAD_UPWARD_DYLIB: {
2183 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2184 const char *path = m_data.PeekCStr(name_offset);
2185 if (path) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00002186 FileSpec file_spec(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187 // Strip the path if there is @rpath, @executable, etc so we just use
2188 // the basename
2189 if (path[0] == '@')
2190 file_spec.GetDirectory().Clear();
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002191
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192 if (lc.cmd == LC_REEXPORT_DYLIB) {
2193 m_reexported_dylibs.AppendIfUnique(file_spec);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002194 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002195
2196 dylib_files.Append(file_spec);
2197 }
2198 } break;
2199
2200 case LC_FUNCTION_STARTS:
2201 function_starts_load_command.cmd = lc.cmd;
2202 function_starts_load_command.cmdsize = lc.cmdsize;
2203 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2204 NULL) // fill in symoff, nsyms, stroff, strsize fields
2205 memset(&function_starts_load_command, 0,
2206 sizeof(function_starts_load_command));
2207 break;
2208
2209 default:
2210 break;
2211 }
2212 offset = cmd_offset + lc.cmdsize;
2213 }
2214
2215 if (symtab_load_command.cmd) {
2216 Symtab *symtab = m_symtab_ap.get();
2217 SectionList *section_list = GetSectionList();
2218 if (section_list == NULL)
2219 return 0;
2220
2221 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2222 const ByteOrder byte_order = m_data.GetByteOrder();
2223 bool bit_width_32 = addr_byte_size == 4;
2224 const size_t nlist_byte_size =
2225 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2226
2227 DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size);
2228 DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size);
2229 DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size);
2230 DataExtractor indirect_symbol_index_data(NULL, 0, byte_order,
2231 addr_byte_size);
2232 DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size);
2233
2234 const addr_t nlist_data_byte_size =
2235 symtab_load_command.nsyms * nlist_byte_size;
2236 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2237 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2238
2239 ProcessSP process_sp(m_process_wp.lock());
2240 Process *process = process_sp.get();
2241
2242 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2243
2244 if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2245 Target &target = process->GetTarget();
2246
2247 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2248
2249 SectionSP linkedit_section_sp(
2250 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2251 // Reading mach file from memory in a process or core file...
2252
2253 if (linkedit_section_sp) {
2254 addr_t linkedit_load_addr =
2255 linkedit_section_sp->GetLoadBaseAddress(&target);
2256 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2257 // We might be trying to access the symbol table before the
Adrian Prantl05097242018-04-30 16:49:04 +00002258 // __LINKEDIT's load address has been set in the target. We can't
2259 // fail to read the symbol table, so calculate the right address
2260 // manually
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2262 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2263 }
2264
2265 const addr_t linkedit_file_offset =
2266 linkedit_section_sp->GetFileOffset();
2267 const addr_t symoff_addr = linkedit_load_addr +
2268 symtab_load_command.symoff -
2269 linkedit_file_offset;
2270 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2271 linkedit_file_offset;
2272
2273 bool data_was_read = false;
2274
2275#if defined(__APPLE__) && \
2276 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2277 if (m_header.flags & 0x80000000u &&
2278 process->GetAddressByteSize() == sizeof(void *)) {
2279 // This mach-o memory file is in the dyld shared cache. If this
2280 // program is not remote and this is iOS, then this process will
Adrian Prantl05097242018-04-30 16:49:04 +00002281 // share the same shared cache as the process we are debugging and we
2282 // can read the entire __LINKEDIT from the address space in this
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283 // process. This is a needed optimization that is used for local iOS
2284 // debugging only since all shared libraries in the shared cache do
2285 // not have corresponding files that exist in the file system of the
2286 // device. They have been combined into a single file. This means we
2287 // always have to load these files from memory. All of the symbol and
2288 // string tables from all of the __LINKEDIT sections from the shared
2289 // libraries in the shared cache have been merged into a single large
2290 // symbol and string table. Reading all of this symbol and string
Adrian Prantl05097242018-04-30 16:49:04 +00002291 // table data across can slow down debug launch times, so we optimize
2292 // this by reading the memory for the __LINKEDIT section from this
2293 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294
Jason Molenda07580ff2018-05-04 00:59:37 +00002295 UUID lldb_shared_cache;
2296 addr_t lldb_shared_cache_addr;
2297 GetLLDBSharedCacheUUID (lldb_shared_cache_addr, lldb_shared_cache);
2298 UUID process_shared_cache;
2299 addr_t process_shared_cache_addr;
2300 GetProcessSharedCacheUUID(process, process_shared_cache_addr, process_shared_cache);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301 bool use_lldb_cache = true;
2302 if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
Jason Molenda07580ff2018-05-04 00:59:37 +00002303 (lldb_shared_cache != process_shared_cache
2304 || process_shared_cache_addr != lldb_shared_cache_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002305 use_lldb_cache = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306 }
2307
2308 PlatformSP platform_sp(target.GetPlatform());
2309 if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2310 data_was_read = true;
2311 nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2312 eByteOrderLittle);
2313 strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2314 eByteOrderLittle);
2315 if (function_starts_load_command.cmd) {
2316 const addr_t func_start_addr =
2317 linkedit_load_addr + function_starts_load_command.dataoff -
2318 linkedit_file_offset;
2319 function_starts_data.SetData(
2320 (void *)func_start_addr,
2321 function_starts_load_command.datasize, eByteOrderLittle);
2322 }
2323 }
2324 }
2325#endif
2326
2327 if (!data_was_read) {
2328 // Always load dyld - the dynamic linker - from memory if we didn't
Adrian Prantl05097242018-04-30 16:49:04 +00002329 // find a binary anywhere else. lldb will not register
2330 // dylib/framework/bundle loads/unloads if we don't have the dyld
2331 // symbols, we force dyld to load from memory despite the user's
Kate Stoneb9c1b512016-09-06 20:57:50 +00002332 // target.memory-module-load-level setting.
2333 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2334 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2335 DataBufferSP nlist_data_sp(
2336 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2337 if (nlist_data_sp)
2338 nlist_data.SetData(nlist_data_sp, 0,
2339 nlist_data_sp->GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340 if (m_dysymtab.nindirectsyms != 0) {
2341 const addr_t indirect_syms_addr = linkedit_load_addr +
2342 m_dysymtab.indirectsymoff -
2343 linkedit_file_offset;
2344 DataBufferSP indirect_syms_data_sp(
2345 ReadMemory(process_sp, indirect_syms_addr,
2346 m_dysymtab.nindirectsyms * 4));
2347 if (indirect_syms_data_sp)
2348 indirect_symbol_index_data.SetData(
2349 indirect_syms_data_sp, 0,
2350 indirect_syms_data_sp->GetByteSize());
Jason Molendab0d33e92018-09-06 00:55:27 +00002351 // If this binary is outside the shared cache,
2352 // cache the string table.
2353 // Binaries in the shared cache all share a giant string table, and
2354 // we can't share the string tables across multiple ObjectFileMachO's,
2355 // so we'd end up re-reading this mega-strtab for every binary
2356 // in the shared cache - it would be a big perf problem.
2357 // For binaries outside the shared cache, it's faster to read the
2358 // entire strtab at once instead of piece-by-piece as we process
2359 // the nlist records.
2360 if ((m_header.flags & 0x80000000u) == 0) {
2361 DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr,
2362 strtab_data_byte_size));
2363 if (strtab_data_sp) {
2364 strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
2365 }
2366 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002367 }
Jim Ingham8a5d7a22018-08-15 23:10:32 +00002368 }
2369 if (memory_module_load_level >=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002370 eMemoryModuleLoadLevelPartial) {
2371 if (function_starts_load_command.cmd) {
2372 const addr_t func_start_addr =
2373 linkedit_load_addr + function_starts_load_command.dataoff -
2374 linkedit_file_offset;
2375 DataBufferSP func_start_data_sp(
2376 ReadMemory(process_sp, func_start_addr,
2377 function_starts_load_command.datasize));
2378 if (func_start_data_sp)
2379 function_starts_data.SetData(func_start_data_sp, 0,
2380 func_start_data_sp->GetByteSize());
2381 }
2382 }
2383 }
2384 }
2385 } else {
2386 nlist_data.SetData(m_data, symtab_load_command.symoff,
2387 nlist_data_byte_size);
2388 strtab_data.SetData(m_data, symtab_load_command.stroff,
2389 strtab_data_byte_size);
2390
2391 if (dyld_info.export_size > 0) {
2392 dyld_trie_data.SetData(m_data, dyld_info.export_off,
2393 dyld_info.export_size);
2394 }
2395
2396 if (m_dysymtab.nindirectsyms != 0) {
2397 indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2398 m_dysymtab.nindirectsyms * 4);
2399 }
2400 if (function_starts_load_command.cmd) {
2401 function_starts_data.SetData(m_data,
2402 function_starts_load_command.dataoff,
2403 function_starts_load_command.datasize);
2404 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002405 }
2406
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407 if (nlist_data.GetByteSize() == 0 &&
2408 memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2409 if (log)
2410 module_sp->LogMessage(log, "failed to read nlist data");
2411 return 0;
2412 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002413
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2415 if (!have_strtab_data) {
2416 if (process) {
2417 if (strtab_addr == LLDB_INVALID_ADDRESS) {
2418 if (log)
2419 module_sp->LogMessage(log, "failed to locate the strtab in memory");
2420 return 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002421 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002422 } else {
2423 if (log)
2424 module_sp->LogMessage(log, "failed to read strtab data");
2425 return 0;
2426 }
2427 }
Greg Clayton9191db42013-10-21 18:40:51 +00002428
Kate Stoneb9c1b512016-09-06 20:57:50 +00002429 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2430 const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2431 const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2432 const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2433 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2434 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2435 SectionSP text_section_sp(
2436 section_list->FindSectionByName(g_segment_name_TEXT));
2437 SectionSP data_section_sp(
2438 section_list->FindSectionByName(g_segment_name_DATA));
2439 SectionSP data_dirty_section_sp(
2440 section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2441 SectionSP data_const_section_sp(
2442 section_list->FindSectionByName(g_segment_name_DATA_CONST));
2443 SectionSP objc_section_sp(
2444 section_list->FindSectionByName(g_segment_name_OBJC));
2445 SectionSP eh_frame_section_sp;
2446 if (text_section_sp.get())
2447 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2448 g_section_name_eh_frame);
2449 else
2450 eh_frame_section_sp =
2451 section_list->FindSectionByName(g_section_name_eh_frame);
Greg Clayton77ccca72011-12-30 00:32:24 +00002452
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
Greg Clayton86eac942013-08-13 21:32:34 +00002454
Kate Stoneb9c1b512016-09-06 20:57:50 +00002455 // lldb works best if it knows the start address of all functions in a
Adrian Prantl05097242018-04-30 16:49:04 +00002456 // module. Linker symbols or debug info are normally the best source of
2457 // information for start addr / size but they may be stripped in a released
2458 // binary. Two additional sources of information exist in Mach-O binaries:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002459 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2460 // function's start address in the
2461 // binary, relative to the text section.
2462 // eh_frame - the eh_frame FDEs have the start addr & size of
2463 // each function
2464 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2465 // all modern binaries.
2466 // Binaries built to run on older releases may need to use eh_frame
2467 // information.
Greg Clayton4c82d422012-05-18 23:20:01 +00002468
Kate Stoneb9c1b512016-09-06 20:57:50 +00002469 if (text_section_sp && function_starts_data.GetByteSize()) {
2470 FunctionStarts::Entry function_start_entry;
2471 function_start_entry.data = false;
2472 lldb::offset_t function_start_offset = 0;
2473 function_start_entry.addr = text_section_sp->GetFileAddress();
2474 uint64_t delta;
2475 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2476 0) {
2477 // Now append the current entry
2478 function_start_entry.addr += delta;
2479 function_starts.Append(function_start_entry);
2480 }
2481 } else {
2482 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
Adrian Prantl05097242018-04-30 16:49:04 +00002483 // load command claiming an eh_frame but it doesn't actually have the
2484 // eh_frame content. And if we have a dSYM, we don't need to do any of
2485 // this fill-in-the-missing-symbols works anyway - the debug info should
2486 // give us all the functions in the module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002487 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2488 m_type != eTypeDebugInfo) {
2489 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
Pavel Labath3f2a0812017-06-28 09:09:19 +00002490 DWARFCallFrameInfo::EH);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2492 eh_frame.GetFunctionAddressAndSizeVector(functions);
2493 addr_t text_base_addr = text_section_sp->GetFileAddress();
2494 size_t count = functions.GetSize();
2495 for (size_t i = 0; i < count; ++i) {
2496 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2497 functions.GetEntryAtIndex(i);
2498 if (func) {
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002499 FunctionStarts::Entry function_start_entry;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 function_start_entry.addr = func->base - text_base_addr;
2501 function_starts.Append(function_start_entry);
2502 }
Jason Molendad63d3c72013-04-16 00:18:44 +00002503 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002504 }
2505 }
2506
2507 const size_t function_starts_count = function_starts.GetSize();
2508
2509 // For user process binaries (executables, dylibs, frameworks, bundles), if
Adrian Prantl05097242018-04-30 16:49:04 +00002510 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2511 // going to assume the binary has been stripped. Don't allow assembly
2512 // language instruction emulation because we don't know proper function
2513 // start boundaries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 //
2515 // For all other types of binaries (kernels, stand-alone bare board
Adrian Prantl05097242018-04-30 16:49:04 +00002516 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2517 // sections - we should not make any assumptions about them based on that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002518 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2519 m_allow_assembly_emulation_unwind_plans = false;
2520 Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2521 LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2522
2523 if (unwind_or_symbol_log)
2524 module_sp->LogMessage(
2525 unwind_or_symbol_log,
2526 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2527 }
2528
2529 const user_id_t TEXT_eh_frame_sectID =
2530 eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2531 : static_cast<user_id_t>(NO_SECT);
2532
2533 lldb::offset_t nlist_data_offset = 0;
2534
2535 uint32_t N_SO_index = UINT32_MAX;
2536
2537 MachSymtabSectionInfo section_info(section_list);
2538 std::vector<uint32_t> N_FUN_indexes;
2539 std::vector<uint32_t> N_NSYM_indexes;
2540 std::vector<uint32_t> N_INCL_indexes;
2541 std::vector<uint32_t> N_BRAC_indexes;
2542 std::vector<uint32_t> N_COMM_indexes;
2543 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2544 typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2545 typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2546 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2547 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2548 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00002549 // Any symbols that get merged into another will get an entry in this map
2550 // so we know
Kate Stoneb9c1b512016-09-06 20:57:50 +00002551 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2552 uint32_t nlist_idx = 0;
2553 Symbol *symbol_ptr = NULL;
2554
2555 uint32_t sym_idx = 0;
2556 Symbol *sym = NULL;
2557 size_t num_syms = 0;
2558 std::string memory_symbol_name;
2559 uint32_t unmapped_local_symbols_found = 0;
2560
2561 std::vector<TrieEntryWithOffset> trie_entries;
2562 std::set<lldb::addr_t> resolver_addresses;
2563
2564 if (dyld_trie_data.GetByteSize() > 0) {
2565 std::vector<llvm::StringRef> nameSlices;
2566 ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2567 resolver_addresses, trie_entries);
2568
2569 ConstString text_segment_name("__TEXT");
2570 SectionSP text_segment_sp =
2571 GetSectionList()->FindSectionByName(text_segment_name);
2572 if (text_segment_sp) {
2573 const lldb::addr_t text_segment_file_addr =
2574 text_segment_sp->GetFileAddress();
2575 if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2576 for (auto &e : trie_entries)
2577 e.entry.address += text_segment_file_addr;
2578 }
2579 }
2580 }
2581
2582 typedef std::set<ConstString> IndirectSymbols;
2583 IndirectSymbols indirect_symbol_names;
2584
2585#if defined(__APPLE__) && \
2586 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2587
2588 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
Adrian Prantl05097242018-04-30 16:49:04 +00002589 // optimized by moving LOCAL symbols out of the memory mapped portion of
2590 // the DSC. The symbol information has all been retained, but it isn't
2591 // available in the normal nlist data. However, there *are* duplicate
2592 // entries of *some*
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593 // LOCAL symbols in the normal nlist data. To handle this situation
2594 // correctly, we must first attempt
2595 // to parse any DSC unmapped symbol information. If we find any, we set a
Adrian Prantl05097242018-04-30 16:49:04 +00002596 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002597
2598 if (m_header.flags & 0x80000000u) {
Adrian Prantl05097242018-04-30 16:49:04 +00002599 // Before we can start mapping the DSC, we need to make certain the
2600 // target process is actually using the cache we can find.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002601
2602 // Next we need to determine the correct path for the dyld shared cache.
2603
2604 ArchSpec header_arch;
2605 GetArchitecture(header_arch);
2606 char dsc_path[PATH_MAX];
2607 char dsc_path_development[PATH_MAX];
2608
2609 snprintf(
2610 dsc_path, sizeof(dsc_path), "%s%s%s",
2611 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2612 */
2613 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2614 header_arch.GetArchitectureName());
2615
2616 snprintf(
2617 dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2618 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2619 */
2620 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
Ilia K4f730dc2016-09-12 05:25:33 +00002621 header_arch.GetArchitectureName(), ".development");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002622
2623 FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2624 FileSpec dsc_development_filespec(dsc_path_development, false);
2625 FileSpec dsc_filespec;
2626
2627 UUID dsc_uuid;
2628 UUID process_shared_cache_uuid;
Jason Molenda07580ff2018-05-04 00:59:37 +00002629 addr_t process_shared_cache_base_addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002630
2631 if (process) {
Jason Molenda07580ff2018-05-04 00:59:37 +00002632 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, process_shared_cache_uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002633 }
2634
Adrian Prantl05097242018-04-30 16:49:04 +00002635 // First see if we can find an exact match for the inferior process
2636 // shared cache UUID in the development or non-development shared caches
2637 // on disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002638 if (process_shared_cache_uuid.IsValid()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002639 if (FileSystem::Instance().Exists(dsc_development_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002640 UUID dsc_development_uuid = GetSharedCacheUUID(
2641 dsc_development_filespec, byte_order, addr_byte_size);
2642 if (dsc_development_uuid.IsValid() &&
2643 dsc_development_uuid == process_shared_cache_uuid) {
2644 dsc_filespec = dsc_development_filespec;
2645 dsc_uuid = dsc_development_uuid;
2646 }
2647 }
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002648 if (!dsc_uuid.IsValid() &&
2649 FileSystem::Instance().Exists(dsc_nondevelopment_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002650 UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2651 dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2652 if (dsc_nondevelopment_uuid.IsValid() &&
2653 dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2654 dsc_filespec = dsc_nondevelopment_filespec;
2655 dsc_uuid = dsc_nondevelopment_uuid;
2656 }
2657 }
2658 }
2659
2660 // Failing a UUID match, prefer the development dyld_shared cache if both
2661 // are present.
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002662 if (!FileSystem::Instance().Exists(dsc_filespec)) {
2663 if (FileSystem::Instance().Exists(dsc_development_filespec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002664 dsc_filespec = dsc_development_filespec;
2665 } else {
2666 dsc_filespec = dsc_nondevelopment_filespec;
2667 }
2668 }
2669
2670 /* The dyld_cache_header has a pointer to the
2671 dyld_cache_local_symbols_info structure (localSymbolsOffset).
2672 The dyld_cache_local_symbols_info structure gives us three things:
2673 1. The start and count of the nlist records in the dyld_shared_cache
2674 file
2675 2. The start and size of the strings for these nlist records
2676 3. The start and count of dyld_cache_local_symbols_entry entries
2677
2678 There is one dyld_cache_local_symbols_entry per dylib/framework in the
2679 dyld shared cache.
2680 The "dylibOffset" field is the Mach-O header of this dylib/framework in
2681 the dyld shared cache.
2682 The dyld_cache_local_symbols_entry also lists the start of this
2683 dylib/framework's nlist records
2684 and the count of how many nlist records there are for this
2685 dylib/framework.
2686 */
2687
2688 // Process the dyld shared cache header to find the unmapped symbols
2689
Pavel Labath50251fc2017-12-21 10:54:30 +00002690 DataBufferSP dsc_data_sp = MapFileData(
2691 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002692 if (!dsc_uuid.IsValid()) {
2693 dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2694 }
2695 if (dsc_data_sp) {
2696 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2697
2698 bool uuid_match = true;
2699 if (dsc_uuid.IsValid() && process) {
2700 if (process_shared_cache_uuid.IsValid() &&
2701 dsc_uuid != process_shared_cache_uuid) {
2702 // The on-disk dyld_shared_cache file is not the same as the one in
Adrian Prantl05097242018-04-30 16:49:04 +00002703 // this process' memory, don't use it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704 uuid_match = false;
2705 ModuleSP module_sp(GetModule());
2706 if (module_sp)
2707 module_sp->ReportWarning("process shared cache does not match "
2708 "on-disk dyld_shared_cache file, some "
2709 "symbol names will be missing.");
2710 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002711 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00002712
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002714
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
Jason Molenda955dcf22016-05-04 03:09:40 +00002716
Kate Stoneb9c1b512016-09-06 20:57:50 +00002717 // If the mappingOffset points to a location inside the header, we've
2718 // opened an old dyld shared cache, and should not proceed further.
2719 if (uuid_match &&
2720 mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
Jason Molenda955dcf22016-05-04 03:09:40 +00002721
Pavel Labath50251fc2017-12-21 10:54:30 +00002722 DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2723 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2724 mappingOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002725
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2727 byte_order, addr_byte_size);
2728 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002729
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 // The File addresses (from the in-memory Mach-O load commands) for
Adrian Prantl05097242018-04-30 16:49:04 +00002731 // the shared libraries in the shared library cache need to be
2732 // adjusted by an offset to match up with the dylibOffset identifying
2733 // field in the dyld_cache_local_symbol_entry's. This offset is
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 // recorded in mapping_offset_value.
2735 const uint64_t mapping_offset_value =
2736 dsc_mapping_info_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002737
Kate Stoneb9c1b512016-09-06 20:57:50 +00002738 offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2739 localSymbolsOffset);
2740 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2741 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002742
Kate Stoneb9c1b512016-09-06 20:57:50 +00002743 if (localSymbolsOffset && localSymbolsSize) {
2744 // Map the local symbols
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002745 DataBufferSP dsc_local_symbols_data_sp =
Pavel Labath50251fc2017-12-21 10:54:30 +00002746 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002747
2748 if (dsc_local_symbols_data_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2750 byte_order, addr_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002751
Kate Stoneb9c1b512016-09-06 20:57:50 +00002752 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002753
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2755 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2756 UndefinedNameToDescMap undefined_name_to_desc;
2757 SymbolIndexToName reexport_shlib_needs_fixup;
Jim Inghamea3ac272014-01-10 22:55:37 +00002758
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759 // Read the local_symbols_infos struct in one shot
2760 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2761 dsc_local_symbols_data.GetU32(&offset,
2762 &local_symbols_info.nlistOffset, 6);
Jim Inghamea3ac272014-01-10 22:55:37 +00002763
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 SectionSP text_section_sp(
2765 section_list->FindSectionByName(GetSegmentNameTEXT()));
Greg Claytonb65c6292015-02-20 22:20:05 +00002766
Kate Stoneb9c1b512016-09-06 20:57:50 +00002767 uint32_t header_file_offset =
2768 (text_section_sp->GetFileAddress() - mapping_offset_value);
Jason Molendaa5609c82012-06-21 01:51:02 +00002769
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 offset = local_symbols_info.entriesOffset;
2771 for (uint32_t entry_index = 0;
2772 entry_index < local_symbols_info.entriesCount;
2773 entry_index++) {
2774 struct lldb_copy_dyld_cache_local_symbols_entry
2775 local_symbols_entry;
2776 local_symbols_entry.dylibOffset =
2777 dsc_local_symbols_data.GetU32(&offset);
2778 local_symbols_entry.nlistStartIndex =
2779 dsc_local_symbols_data.GetU32(&offset);
2780 local_symbols_entry.nlistCount =
2781 dsc_local_symbols_data.GetU32(&offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002782
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 if (header_file_offset == local_symbols_entry.dylibOffset) {
2784 unmapped_local_symbols_found = local_symbols_entry.nlistCount;
Jason Molendaa5609c82012-06-21 01:51:02 +00002785
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 // The normal nlist code cannot correctly size the Symbols
2787 // array, we need to allocate it here.
2788 sym = symtab->Resize(
2789 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2790 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2791 num_syms = symtab->GetNumSymbols();
Jason Molendaa5609c82012-06-21 01:51:02 +00002792
Kate Stoneb9c1b512016-09-06 20:57:50 +00002793 nlist_data_offset =
2794 local_symbols_info.nlistOffset +
2795 (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2796 uint32_t string_table_offset =
2797 local_symbols_info.stringsOffset;
Jason Molendaa5609c82012-06-21 01:51:02 +00002798
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 for (uint32_t nlist_index = 0;
2800 nlist_index < local_symbols_entry.nlistCount;
2801 nlist_index++) {
2802 /////////////////////////////
Jason Molenda649a6072015-11-10 05:21:54 +00002803 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 struct nlist_64 nlist;
2805 if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(
2806 nlist_data_offset, nlist_byte_size))
2807 break;
Eugene Zelenko8157a882015-10-23 16:56:07 +00002808
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(
2810 &nlist_data_offset);
2811 nlist.n_type = dsc_local_symbols_data.GetU8_unchecked(
2812 &nlist_data_offset);
2813 nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked(
2814 &nlist_data_offset);
2815 nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked(
2816 &nlist_data_offset);
2817 nlist.n_value =
2818 dsc_local_symbols_data.GetAddress_unchecked(
2819 &nlist_data_offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002820
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 SymbolType type = eSymbolTypeInvalid;
2822 const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2823 string_table_offset + nlist.n_strx);
Jason Molendaf8130862012-06-22 03:28:35 +00002824
Kate Stoneb9c1b512016-09-06 20:57:50 +00002825 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002826 // No symbol should be NULL, even the symbols with no
Adrian Prantl05097242018-04-30 16:49:04 +00002827 // string values should have an offset zero which
2828 // points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00002829 Host::SystemLog(
2830 Host::eSystemLogError,
2831 "error: DSC unmapped local symbol[%u] has invalid "
2832 "string table offset 0x%x in %s, ignoring symbol\n",
2833 entry_index, nlist.n_strx,
2834 module_sp->GetFileSpec().GetPath().c_str());
Greg Claytonfd814c52013-08-13 01:42:25 +00002835 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836 }
2837 if (symbol_name[0] == '\0')
Greg Claytonfd814c52013-08-13 01:42:25 +00002838 symbol_name = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002839
Kate Stoneb9c1b512016-09-06 20:57:50 +00002840 const char *symbol_name_non_abi_mangled = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002841
Kate Stoneb9c1b512016-09-06 20:57:50 +00002842 SectionSP symbol_section;
2843 uint32_t symbol_byte_size = 0;
2844 bool add_nlist = true;
2845 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2846 bool demangled_is_synthesized = false;
2847 bool is_gsym = false;
2848 bool set_value = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00002849
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 assert(sym_idx < num_syms);
Jason Molenda4e7511e2013-03-06 23:19:17 +00002851
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852 sym[sym_idx].SetDebug(is_debug);
Greg Clayton29e08cb2012-03-14 01:53:24 +00002853
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854 if (is_debug) {
2855 switch (nlist.n_type) {
2856 case N_GSYM:
2857 // global symbol: name,,NO_SECT,type,0
2858 // Sometimes the N_GSYM value contains the address.
2859
2860 // FIXME: In the .o files, we have a GSYM and a debug
2861 // symbol for all the ObjC data. They
2862 // have the same address, but we want to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +00002863 // we always find only the real symbol, 'cause we
2864 // don't currently correctly attribute the
Kate Stoneb9c1b512016-09-06 20:57:50 +00002865 // GSYM one to the ObjCClass/Ivar/MetaClass
Adrian Prantl05097242018-04-30 16:49:04 +00002866 // symbol type. This is a temporary hack to make
2867 // sure the ObjectiveC symbols get treated correctly.
2868 // To do this right, we should coalesce all the GSYM
2869 // & global symbols that have the same address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002870
2871 is_gsym = true;
2872 sym[sym_idx].SetExternal(true);
2873
2874 if (symbol_name && symbol_name[0] == '_' &&
2875 symbol_name[1] == 'O') {
Greg Clayton1e28adf2015-02-25 17:25:02 +00002876 llvm::StringRef symbol_name_ref(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877 if (symbol_name_ref.startswith(
2878 g_objc_v2_prefix_class)) {
2879 symbol_name_non_abi_mangled = symbol_name + 1;
2880 symbol_name =
2881 symbol_name + g_objc_v2_prefix_class.size();
2882 type = eSymbolTypeObjCClass;
2883 demangled_is_synthesized = true;
2884
2885 } else if (symbol_name_ref.startswith(
2886 g_objc_v2_prefix_metaclass)) {
2887 symbol_name_non_abi_mangled = symbol_name + 1;
2888 symbol_name = symbol_name +
2889 g_objc_v2_prefix_metaclass.size();
2890 type = eSymbolTypeObjCMetaClass;
2891 demangled_is_synthesized = true;
2892 } else if (symbol_name_ref.startswith(
2893 g_objc_v2_prefix_ivar)) {
2894 symbol_name_non_abi_mangled = symbol_name + 1;
2895 symbol_name =
2896 symbol_name + g_objc_v2_prefix_ivar.size();
2897 type = eSymbolTypeObjCIVar;
2898 demangled_is_synthesized = true;
Greg Clayton1e28adf2015-02-25 17:25:02 +00002899 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002900 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002901 if (nlist.n_value != 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 symbol_section = section_info.GetSection(
2903 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002904 type = eSymbolTypeData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 }
2906 break;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002907
Kate Stoneb9c1b512016-09-06 20:57:50 +00002908 case N_FNAME:
2909 // procedure name (f77 kludge): name,,NO_SECT,0,0
2910 type = eSymbolTypeCompiler;
2911 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002912
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 case N_FUN:
2914 // procedure: name,,n_sect,linenumber,address
2915 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002916 type = eSymbolTypeCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002917 symbol_section = section_info.GetSection(
2918 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002919
Kate Stoneb9c1b512016-09-06 20:57:50 +00002920 N_FUN_addr_to_sym_idx.insert(
2921 std::make_pair(nlist.n_value, sym_idx));
2922 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00002923 // symbol table in lieu of using nlist_idx in case
2924 // we ever start trimming entries out
Greg Claytonfd814c52013-08-13 01:42:25 +00002925 N_FUN_indexes.push_back(sym_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002926 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002927 type = eSymbolTypeCompiler;
2928
Kate Stoneb9c1b512016-09-06 20:57:50 +00002929 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00002930 // Copy the size of the function into the
2931 // original
Kate Stoneb9c1b512016-09-06 20:57:50 +00002932 // STAB entry so we don't have
2933 // to hunt for it later
2934 symtab->SymbolAtIndex(N_FUN_indexes.back())
2935 ->SetByteSize(nlist.n_value);
2936 N_FUN_indexes.pop_back();
2937 // We don't really need the end function STAB as
Adrian Prantl05097242018-04-30 16:49:04 +00002938 // it contains the size which we already placed
2939 // with the original symbol, so don't add it if
2940 // we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00002941 add_nlist = false;
Greg Claytondacc4a92013-05-14 22:19:37 +00002942 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002943 }
2944 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002945
Kate Stoneb9c1b512016-09-06 20:57:50 +00002946 case N_STSYM:
2947 // static symbol: name,,n_sect,type,address
2948 N_STSYM_addr_to_sym_idx.insert(
2949 std::make_pair(nlist.n_value, sym_idx));
2950 symbol_section = section_info.GetSection(
2951 nlist.n_sect, nlist.n_value);
2952 if (symbol_name && symbol_name[0]) {
2953 type = ObjectFile::GetSymbolTypeFromName(
2954 symbol_name + 1, eSymbolTypeData);
2955 }
2956 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002957
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 case N_LCSYM:
2959 // .lcomm symbol: name,,n_sect,type,address
2960 symbol_section = section_info.GetSection(
2961 nlist.n_sect, nlist.n_value);
2962 type = eSymbolTypeCommonBlock;
2963 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002964
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965 case N_BNSYM:
2966 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00002967 // table in lieu of using nlist_idx in case we ever
2968 // start trimming entries out Skip these if we want
2969 // minimal symbol tables
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 add_nlist = false;
2971 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002972
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 case N_ENSYM:
2974 // Set the size of the N_BNSYM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002975 // index of this N_ENSYM so that we can always skip
2976 // the entire symbol if we need to navigate more
2977 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00002978 // Skip these if we want minimal symbol tables
2979 add_nlist = false;
2980 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002981
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 case N_OPT:
2983 // emitted with gcc2_compiled and in gcc source
2984 type = eSymbolTypeCompiler;
2985 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002986
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 case N_RSYM:
2988 // register sym: name,,NO_SECT,type,register
2989 type = eSymbolTypeVariable;
2990 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002991
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 case N_SLINE:
2993 // src line: 0,,n_sect,linenumber,address
2994 symbol_section = section_info.GetSection(
2995 nlist.n_sect, nlist.n_value);
2996 type = eSymbolTypeLineEntry;
2997 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002998
Kate Stoneb9c1b512016-09-06 20:57:50 +00002999 case N_SSYM:
3000 // structure elt: name,,NO_SECT,type,struct_offset
3001 type = eSymbolTypeVariableType;
3002 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003003
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004 case N_SO:
3005 // source file name
3006 type = eSymbolTypeSourceFile;
3007 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003008 add_nlist = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 if (N_SO_index != UINT32_MAX) {
3010 // Set the size of the N_SO to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003011 // index of this N_SO so that we can always skip
3012 // the entire N_SO if we need to navigate more
3013 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003014 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3015 symbol_ptr->SetByteSize(sym_idx);
3016 symbol_ptr->SetSizeIsSibling(true);
Greg Claytonfd814c52013-08-13 01:42:25 +00003017 }
3018 N_NSYM_indexes.clear();
3019 N_INCL_indexes.clear();
3020 N_BRAC_indexes.clear();
3021 N_COMM_indexes.clear();
3022 N_FUN_indexes.clear();
3023 N_SO_index = UINT32_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003024 } else {
3025 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00003026 // symbol table in lieu of using nlist_idx in case
3027 // we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028 const bool N_SO_has_full_path =
3029 symbol_name[0] == '/';
3030 if (N_SO_has_full_path) {
3031 if ((N_SO_index == sym_idx - 1) &&
3032 ((sym_idx - 1) < num_syms)) {
3033 // We have two consecutive N_SO entries where
Adrian Prantl05097242018-04-30 16:49:04 +00003034 // the first contains a directory and the
3035 // second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003036 sym[sym_idx - 1].GetMangled().SetValue(
3037 ConstString(symbol_name), false);
3038 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3039 add_nlist = false;
3040 } else {
3041 // This is the first entry in a N_SO that
3042 // contains a directory or
3043 // a full path to the source file
Greg Claytonfd814c52013-08-13 01:42:25 +00003044 N_SO_index = sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003045 }
3046 } else if ((N_SO_index == sym_idx - 1) &&
3047 ((sym_idx - 1) < num_syms)) {
3048 // This is usually the second N_SO entry that
Adrian Prantl05097242018-04-30 16:49:04 +00003049 // contains just the filename, so here we combine
3050 // it with the first one if we are minimizing the
3051 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052 const char *so_path =
3053 sym[sym_idx - 1]
3054 .GetMangled()
3055 .GetDemangledName(
3056 lldb::eLanguageTypeUnknown)
3057 .AsCString();
3058 if (so_path && so_path[0]) {
3059 std::string full_so_path(so_path);
3060 const size_t double_slash_pos =
3061 full_so_path.find("//");
3062 if (double_slash_pos != std::string::npos) {
3063 // The linker has been generating bad N_SO
3064 // entries with doubled up paths
Adrian Prantl05097242018-04-30 16:49:04 +00003065 // in the format "%s%s" where the first
3066 // string in the DW_AT_comp_dir, and the
3067 // second is the directory for the source
3068 // file so you end up with a path that looks
3069 // like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00003070 FileSpec so_dir(so_path, false);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00003071 if (!FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003072 so_dir.SetFile(
3073 &full_so_path[double_slash_pos + 1],
3074 false);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00003075 if (FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003076 // Trim off the incorrect path
3077 full_so_path.erase(0,
3078 double_slash_pos + 1);
3079 }
3080 }
3081 }
3082 if (*full_so_path.rbegin() != '/')
3083 full_so_path += '/';
3084 full_so_path += symbol_name;
3085 sym[sym_idx - 1].GetMangled().SetValue(
3086 ConstString(full_so_path.c_str()), false);
3087 add_nlist = false;
3088 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3089 }
3090 } else {
3091 // This could be a relative path to a N_SO
3092 N_SO_index = sym_idx;
Greg Claytonfd814c52013-08-13 01:42:25 +00003093 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 }
3095 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003096
Kate Stoneb9c1b512016-09-06 20:57:50 +00003097 case N_OSO:
3098 // object file name: name,,0,0,st_mtime
3099 type = eSymbolTypeObjectFile;
3100 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003101
Kate Stoneb9c1b512016-09-06 20:57:50 +00003102 case N_LSYM:
3103 // local sym: name,,NO_SECT,type,offset
3104 type = eSymbolTypeLocal;
3105 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003106
Kate Stoneb9c1b512016-09-06 20:57:50 +00003107 //----------------------------------------------------------------------
3108 // INCL scopes
3109 //----------------------------------------------------------------------
3110 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00003111 // include file beginning: name,,NO_SECT,0,sum We use
3112 // the current number of symbols in the symbol table
3113 // in lieu of using nlist_idx in case we ever start
3114 // trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 N_INCL_indexes.push_back(sym_idx);
3116 type = eSymbolTypeScopeBegin;
3117 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003118
Kate Stoneb9c1b512016-09-06 20:57:50 +00003119 case N_EINCL:
3120 // include file end: name,,NO_SECT,0,0
3121 // Set the size of the N_BINCL to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003122 // index of this N_EINCL so that we can always skip
3123 // the entire symbol if we need to navigate more
3124 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003125 if (!N_INCL_indexes.empty()) {
3126 symbol_ptr =
3127 symtab->SymbolAtIndex(N_INCL_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003128 symbol_ptr->SetByteSize(sym_idx + 1);
3129 symbol_ptr->SetSizeIsSibling(true);
3130 N_INCL_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131 }
3132 type = eSymbolTypeScopeEnd;
3133 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003134
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135 case N_SOL:
3136 // #included file name: name,,n_sect,0,address
3137 type = eSymbolTypeHeaderFile;
Greg Claytonfd814c52013-08-13 01:42:25 +00003138
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 // We currently don't use the header files on darwin
3140 add_nlist = false;
3141 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003142
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143 case N_PARAMS:
3144 // compiler parameters: name,,NO_SECT,0,0
3145 type = eSymbolTypeCompiler;
3146 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003147
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 case N_VERSION:
3149 // compiler version: name,,NO_SECT,0,0
3150 type = eSymbolTypeCompiler;
3151 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003152
Kate Stoneb9c1b512016-09-06 20:57:50 +00003153 case N_OLEVEL:
3154 // compiler -O level: name,,NO_SECT,0,0
3155 type = eSymbolTypeCompiler;
3156 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003157
Kate Stoneb9c1b512016-09-06 20:57:50 +00003158 case N_PSYM:
3159 // parameter: name,,NO_SECT,type,offset
3160 type = eSymbolTypeVariable;
3161 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003162
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163 case N_ENTRY:
3164 // alternate entry: name,,n_sect,linenumber,address
3165 symbol_section = section_info.GetSection(
3166 nlist.n_sect, nlist.n_value);
3167 type = eSymbolTypeLineEntry;
3168 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003169
Kate Stoneb9c1b512016-09-06 20:57:50 +00003170 //----------------------------------------------------------------------
3171 // Left and Right Braces
3172 //----------------------------------------------------------------------
3173 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00003174 // left bracket: 0,,NO_SECT,nesting level,address We
3175 // use the current number of symbols in the symbol
3176 // table in lieu of using nlist_idx in case we ever
3177 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003178 symbol_section = section_info.GetSection(
3179 nlist.n_sect, nlist.n_value);
3180 N_BRAC_indexes.push_back(sym_idx);
3181 type = eSymbolTypeScopeBegin;
3182 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003183
Kate Stoneb9c1b512016-09-06 20:57:50 +00003184 case N_RBRAC:
3185 // right bracket: 0,,NO_SECT,nesting level,address
3186 // Set the size of the N_LBRAC to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003187 // index of this N_RBRAC so that we can always skip
3188 // the entire symbol if we need to navigate more
3189 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003190 symbol_section = section_info.GetSection(
3191 nlist.n_sect, nlist.n_value);
3192 if (!N_BRAC_indexes.empty()) {
3193 symbol_ptr =
3194 symtab->SymbolAtIndex(N_BRAC_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003195 symbol_ptr->SetByteSize(sym_idx + 1);
3196 symbol_ptr->SetSizeIsSibling(true);
3197 N_BRAC_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003198 }
3199 type = eSymbolTypeScopeEnd;
3200 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003201
Kate Stoneb9c1b512016-09-06 20:57:50 +00003202 case N_EXCL:
3203 // deleted include file: name,,NO_SECT,0,sum
3204 type = eSymbolTypeHeaderFile;
3205 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003206
Kate Stoneb9c1b512016-09-06 20:57:50 +00003207 //----------------------------------------------------------------------
3208 // COMM scopes
3209 //----------------------------------------------------------------------
3210 case N_BCOMM:
3211 // begin common: name,,NO_SECT,0,0
3212 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00003213 // table in lieu of using nlist_idx in case we ever
3214 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003215 type = eSymbolTypeScopeBegin;
3216 N_COMM_indexes.push_back(sym_idx);
3217 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003218
Kate Stoneb9c1b512016-09-06 20:57:50 +00003219 case N_ECOML:
3220 // end common (local name): 0,,n_sect,0,address
3221 symbol_section = section_info.GetSection(
3222 nlist.n_sect, nlist.n_value);
3223 // Fall through
Greg Claytonfd814c52013-08-13 01:42:25 +00003224
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225 case N_ECOMM:
3226 // end common: name,,n_sect,0,0
3227 // Set the size of the N_BCOMM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003228 // index of this N_ECOMM/N_ECOML so that we can
3229 // always skip the entire symbol if we need to
3230 // navigate more quickly at the source level when
3231 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003232 if (!N_COMM_indexes.empty()) {
3233 symbol_ptr =
3234 symtab->SymbolAtIndex(N_COMM_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003235 symbol_ptr->SetByteSize(sym_idx + 1);
3236 symbol_ptr->SetSizeIsSibling(true);
3237 N_COMM_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238 }
3239 type = eSymbolTypeScopeEnd;
3240 break;
3241
3242 case N_LENG:
3243 // second stab entry with length information
3244 type = eSymbolTypeAdditional;
3245 break;
3246
3247 default:
3248 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003249 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003250 } else {
3251 // uint8_t n_pext = N_PEXT & nlist.n_type;
3252 uint8_t n_type = N_TYPE & nlist.n_type;
3253 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
Greg Claytonfd814c52013-08-13 01:42:25 +00003254
Kate Stoneb9c1b512016-09-06 20:57:50 +00003255 switch (n_type) {
3256 case N_INDR: {
3257 const char *reexport_name_cstr =
3258 strtab_data.PeekCStr(nlist.n_value);
3259 if (reexport_name_cstr && reexport_name_cstr[0]) {
3260 type = eSymbolTypeReExported;
3261 ConstString reexport_name(
3262 reexport_name_cstr +
3263 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3264 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3265 set_value = false;
3266 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3267 indirect_symbol_names.insert(
3268 ConstString(symbol_name +
3269 ((symbol_name[0] == '_') ? 1 : 0)));
3270 } else
3271 type = eSymbolTypeUndefined;
3272 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003273
Kate Stoneb9c1b512016-09-06 20:57:50 +00003274 case N_UNDF:
3275 if (symbol_name && symbol_name[0]) {
3276 ConstString undefined_name(
3277 symbol_name +
3278 ((symbol_name[0] == '_') ? 1 : 0));
3279 undefined_name_to_desc[undefined_name] =
3280 nlist.n_desc;
3281 }
3282 // Fall through
3283 case N_PBUD:
3284 type = eSymbolTypeUndefined;
3285 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003286
Kate Stoneb9c1b512016-09-06 20:57:50 +00003287 case N_ABS:
3288 type = eSymbolTypeAbsolute;
3289 break;
Greg Clayton60038be2015-02-14 00:51:13 +00003290
Kate Stoneb9c1b512016-09-06 20:57:50 +00003291 case N_SECT: {
3292 symbol_section = section_info.GetSection(
3293 nlist.n_sect, nlist.n_value);
Jason Molenda62e06812016-02-16 04:14:33 +00003294
Kate Stoneb9c1b512016-09-06 20:57:50 +00003295 if (symbol_section == NULL) {
3296 // TODO: warn about this?
3297 add_nlist = false;
3298 break;
3299 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003300
Kate Stoneb9c1b512016-09-06 20:57:50 +00003301 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3302 type = eSymbolTypeException;
3303 } else {
3304 uint32_t section_type =
3305 symbol_section->Get() & SECTION_TYPE;
Greg Claytonfd814c52013-08-13 01:42:25 +00003306
Kate Stoneb9c1b512016-09-06 20:57:50 +00003307 switch (section_type) {
3308 case S_CSTRING_LITERALS:
3309 type = eSymbolTypeData;
3310 break; // section with only literal C strings
3311 case S_4BYTE_LITERALS:
3312 type = eSymbolTypeData;
3313 break; // section with only 4 byte literals
3314 case S_8BYTE_LITERALS:
3315 type = eSymbolTypeData;
3316 break; // section with only 8 byte literals
3317 case S_LITERAL_POINTERS:
3318 type = eSymbolTypeTrampoline;
3319 break; // section with only pointers to literals
3320 case S_NON_LAZY_SYMBOL_POINTERS:
3321 type = eSymbolTypeTrampoline;
3322 break; // section with only non-lazy symbol
3323 // pointers
3324 case S_LAZY_SYMBOL_POINTERS:
3325 type = eSymbolTypeTrampoline;
3326 break; // section with only lazy symbol pointers
3327 case S_SYMBOL_STUBS:
3328 type = eSymbolTypeTrampoline;
3329 break; // section with only symbol stubs, byte
3330 // size of stub in the reserved2 field
3331 case S_MOD_INIT_FUNC_POINTERS:
3332 type = eSymbolTypeCode;
3333 break; // section with only function pointers for
3334 // initialization
3335 case S_MOD_TERM_FUNC_POINTERS:
3336 type = eSymbolTypeCode;
3337 break; // section with only function pointers for
3338 // termination
3339 case S_INTERPOSING:
3340 type = eSymbolTypeTrampoline;
3341 break; // section with only pairs of function
3342 // pointers for interposing
3343 case S_16BYTE_LITERALS:
3344 type = eSymbolTypeData;
3345 break; // section with only 16 byte literals
3346 case S_DTRACE_DOF:
3347 type = eSymbolTypeInstrumentation;
3348 break;
3349 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3350 type = eSymbolTypeTrampoline;
3351 break;
3352 default:
3353 switch (symbol_section->GetType()) {
3354 case lldb::eSectionTypeCode:
3355 type = eSymbolTypeCode;
Greg Claytonfd814c52013-08-13 01:42:25 +00003356 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003357 case eSectionTypeData:
3358 case eSectionTypeDataCString: // Inlined C string
3359 // data
3360 case eSectionTypeDataCStringPointers: // Pointers
3361 // to C
3362 // string
3363 // data
3364 case eSectionTypeDataSymbolAddress: // Address of
3365 // a symbol in
3366 // the symbol
3367 // table
3368 case eSectionTypeData4:
3369 case eSectionTypeData8:
3370 case eSectionTypeData16:
3371 type = eSymbolTypeData;
3372 break;
3373 default:
3374 break;
3375 }
3376 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003377 }
3378
Kate Stoneb9c1b512016-09-06 20:57:50 +00003379 if (type == eSymbolTypeInvalid) {
3380 const char *symbol_sect_name =
3381 symbol_section->GetName().AsCString();
3382 if (symbol_section->IsDescendant(
3383 text_section_sp.get())) {
3384 if (symbol_section->IsClear(
3385 S_ATTR_PURE_INSTRUCTIONS |
3386 S_ATTR_SELF_MODIFYING_CODE |
3387 S_ATTR_SOME_INSTRUCTIONS))
3388 type = eSymbolTypeData;
3389 else
3390 type = eSymbolTypeCode;
3391 } else if (symbol_section->IsDescendant(
3392 data_section_sp.get()) ||
3393 symbol_section->IsDescendant(
3394 data_dirty_section_sp.get()) ||
3395 symbol_section->IsDescendant(
3396 data_const_section_sp.get())) {
3397 if (symbol_sect_name &&
3398 ::strstr(symbol_sect_name, "__objc") ==
3399 symbol_sect_name) {
3400 type = eSymbolTypeRuntime;
Greg Claytonfd814c52013-08-13 01:42:25 +00003401
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402 if (symbol_name) {
3403 llvm::StringRef symbol_name_ref(
3404 symbol_name);
3405 if (symbol_name_ref.startswith("_OBJC_")) {
3406 static const llvm::StringRef
3407 g_objc_v2_prefix_class(
3408 "_OBJC_CLASS_$_");
3409 static const llvm::StringRef
3410 g_objc_v2_prefix_metaclass(
3411 "_OBJC_METACLASS_$_");
3412 static const llvm::StringRef
3413 g_objc_v2_prefix_ivar(
3414 "_OBJC_IVAR_$_");
3415 if (symbol_name_ref.startswith(
3416 g_objc_v2_prefix_class)) {
3417 symbol_name_non_abi_mangled =
3418 symbol_name + 1;
3419 symbol_name =
3420 symbol_name +
3421 g_objc_v2_prefix_class.size();
3422 type = eSymbolTypeObjCClass;
3423 demangled_is_synthesized = true;
3424 } else if (
3425 symbol_name_ref.startswith(
3426 g_objc_v2_prefix_metaclass)) {
3427 symbol_name_non_abi_mangled =
3428 symbol_name + 1;
3429 symbol_name =
3430 symbol_name +
3431 g_objc_v2_prefix_metaclass.size();
3432 type = eSymbolTypeObjCMetaClass;
3433 demangled_is_synthesized = true;
3434 } else if (symbol_name_ref.startswith(
3435 g_objc_v2_prefix_ivar)) {
3436 symbol_name_non_abi_mangled =
3437 symbol_name + 1;
3438 symbol_name =
3439 symbol_name +
3440 g_objc_v2_prefix_ivar.size();
3441 type = eSymbolTypeObjCIVar;
3442 demangled_is_synthesized = true;
3443 }
Greg Clayton38f9cc42014-06-16 22:53:16 +00003444 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003445 }
3446 } else if (symbol_sect_name &&
3447 ::strstr(symbol_sect_name,
3448 "__gcc_except_tab") ==
3449 symbol_sect_name) {
3450 type = eSymbolTypeException;
3451 } else {
3452 type = eSymbolTypeData;
Greg Claytonfd814c52013-08-13 01:42:25 +00003453 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003454 } else if (symbol_sect_name &&
3455 ::strstr(symbol_sect_name,
3456 "__IMPORT") ==
3457 symbol_sect_name) {
3458 type = eSymbolTypeTrampoline;
3459 } else if (symbol_section->IsDescendant(
3460 objc_section_sp.get())) {
3461 type = eSymbolTypeRuntime;
3462 if (symbol_name && symbol_name[0] == '.') {
3463 llvm::StringRef symbol_name_ref(symbol_name);
3464 static const llvm::StringRef
3465 g_objc_v1_prefix_class(
3466 ".objc_class_name_");
3467 if (symbol_name_ref.startswith(
3468 g_objc_v1_prefix_class)) {
3469 symbol_name_non_abi_mangled = symbol_name;
3470 symbol_name = symbol_name +
3471 g_objc_v1_prefix_class.size();
3472 type = eSymbolTypeObjCClass;
3473 demangled_is_synthesized = true;
3474 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003475 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003476 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003477 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003478 }
3479 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003480 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003481 }
Greg Claytondacc4a92013-05-14 22:19:37 +00003482
Kate Stoneb9c1b512016-09-06 20:57:50 +00003483 if (add_nlist) {
3484 uint64_t symbol_value = nlist.n_value;
3485 if (symbol_name_non_abi_mangled) {
3486 sym[sym_idx].GetMangled().SetMangledName(
3487 ConstString(symbol_name_non_abi_mangled));
3488 sym[sym_idx].GetMangled().SetDemangledName(
3489 ConstString(symbol_name));
3490 } else {
3491 bool symbol_name_is_mangled = false;
Greg Claytonfd814c52013-08-13 01:42:25 +00003492
Kate Stoneb9c1b512016-09-06 20:57:50 +00003493 if (symbol_name && symbol_name[0] == '_') {
Greg Claytonfd814c52013-08-13 01:42:25 +00003494 symbol_name_is_mangled = symbol_name[1] == '_';
Kate Stoneb9c1b512016-09-06 20:57:50 +00003495 symbol_name++; // Skip the leading underscore
3496 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003497
Kate Stoneb9c1b512016-09-06 20:57:50 +00003498 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003499 ConstString const_symbol_name(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003500 sym[sym_idx].GetMangled().SetValue(
3501 const_symbol_name, symbol_name_is_mangled);
3502 if (is_gsym && is_debug) {
3503 const char *gsym_name =
3504 sym[sym_idx]
3505 .GetMangled()
3506 .GetName(lldb::eLanguageTypeUnknown,
3507 Mangled::ePreferMangled)
3508 .GetCString();
3509 if (gsym_name)
3510 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3511 }
3512 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003513 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003514 if (symbol_section) {
3515 const addr_t section_file_addr =
3516 symbol_section->GetFileAddress();
3517 if (symbol_byte_size == 0 &&
3518 function_starts_count > 0) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003519 addr_t symbol_lookup_file_addr = nlist.n_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003520 // Do an exact address match for non-ARM addresses,
Adrian Prantl05097242018-04-30 16:49:04 +00003521 // else get the closest since the symbol might be a
3522 // thumb symbol which has an address with bit zero
3523 // set
Kate Stoneb9c1b512016-09-06 20:57:50 +00003524 FunctionStarts::Entry *func_start_entry =
3525 function_starts.FindEntry(
3526 symbol_lookup_file_addr, !is_arm);
3527 if (is_arm && func_start_entry) {
3528 // Verify that the function start address is the
Adrian Prantl05097242018-04-30 16:49:04 +00003529 // symbol address (ARM) or the symbol address + 1
3530 // (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003531 if (func_start_entry->addr !=
3532 symbol_lookup_file_addr &&
3533 func_start_entry->addr !=
3534 (symbol_lookup_file_addr + 1)) {
3535 // Not the right entry, NULL it out...
3536 func_start_entry = NULL;
3537 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003538 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003539 if (func_start_entry) {
3540 func_start_entry->data = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00003541
Kate Stoneb9c1b512016-09-06 20:57:50 +00003542 addr_t symbol_file_addr = func_start_entry->addr;
3543 uint32_t symbol_flags = 0;
3544 if (is_arm) {
3545 if (symbol_file_addr & 1)
3546 symbol_flags =
3547 MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3548 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3549 }
3550
3551 const FunctionStarts::Entry
3552 *next_func_start_entry =
3553 function_starts.FindNextEntry(
3554 func_start_entry);
3555 const addr_t section_end_file_addr =
3556 section_file_addr +
3557 symbol_section->GetByteSize();
3558 if (next_func_start_entry) {
3559 addr_t next_symbol_file_addr =
3560 next_func_start_entry->addr;
3561 // Be sure the clear the Thumb address bit when
Adrian Prantl05097242018-04-30 16:49:04 +00003562 // we calculate the size from the current and
3563 // next address
Greg Claytonfd814c52013-08-13 01:42:25 +00003564 if (is_arm)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003565 next_symbol_file_addr &=
3566 THUMB_ADDRESS_BIT_MASK;
3567 symbol_byte_size = std::min<lldb::addr_t>(
3568 next_symbol_file_addr - symbol_file_addr,
3569 section_end_file_addr - symbol_file_addr);
3570 } else {
3571 symbol_byte_size =
3572 section_end_file_addr - symbol_file_addr;
3573 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003574 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003575 }
3576 symbol_value -= section_file_addr;
Greg Claytonfd814c52013-08-13 01:42:25 +00003577 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003578
Kate Stoneb9c1b512016-09-06 20:57:50 +00003579 if (is_debug == false) {
3580 if (type == eSymbolTypeCode) {
3581 // See if we can find a N_FUN entry for any code
Adrian Prantl05097242018-04-30 16:49:04 +00003582 // symbols. If we do find a match, and the name
3583 // matches, then we can merge the two into just the
3584 // function symbol to avoid duplicate entries in
3585 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003586 std::pair<ValueToSymbolIndexMap::const_iterator,
3587 ValueToSymbolIndexMap::const_iterator>
3588 range;
3589 range = N_FUN_addr_to_sym_idx.equal_range(
3590 nlist.n_value);
3591 if (range.first != range.second) {
3592 bool found_it = false;
3593 for (ValueToSymbolIndexMap::const_iterator pos =
3594 range.first;
3595 pos != range.second; ++pos) {
3596 if (sym[sym_idx].GetMangled().GetName(
3597 lldb::eLanguageTypeUnknown,
3598 Mangled::ePreferMangled) ==
3599 sym[pos->second].GetMangled().GetName(
3600 lldb::eLanguageTypeUnknown,
3601 Mangled::ePreferMangled)) {
3602 m_nlist_idx_to_sym_idx[nlist_idx] =
3603 pos->second;
3604 // We just need the flags from the linker
3605 // symbol, so put these flags
3606 // into the N_FUN flags to avoid duplicate
3607 // symbols in the symbol table
3608 sym[pos->second].SetExternal(
3609 sym[sym_idx].IsExternal());
3610 sym[pos->second].SetFlags(nlist.n_type << 16 |
3611 nlist.n_desc);
3612 if (resolver_addresses.find(nlist.n_value) !=
3613 resolver_addresses.end())
3614 sym[pos->second].SetType(
3615 eSymbolTypeResolver);
3616 sym[sym_idx].Clear();
3617 found_it = true;
3618 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003619 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003620 }
3621 if (found_it)
3622 continue;
3623 } else {
3624 if (resolver_addresses.find(nlist.n_value) !=
3625 resolver_addresses.end())
3626 type = eSymbolTypeResolver;
Greg Claytonfd814c52013-08-13 01:42:25 +00003627 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003628 } else if (type == eSymbolTypeData ||
3629 type == eSymbolTypeObjCClass ||
3630 type == eSymbolTypeObjCMetaClass ||
3631 type == eSymbolTypeObjCIVar) {
3632 // See if we can find a N_STSYM entry for any data
Adrian Prantl05097242018-04-30 16:49:04 +00003633 // symbols. If we do find a match, and the name
3634 // matches, then we can merge the two into just the
3635 // Static symbol to avoid duplicate entries in the
3636 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003637 std::pair<ValueToSymbolIndexMap::const_iterator,
3638 ValueToSymbolIndexMap::const_iterator>
3639 range;
3640 range = N_STSYM_addr_to_sym_idx.equal_range(
3641 nlist.n_value);
3642 if (range.first != range.second) {
3643 bool found_it = false;
3644 for (ValueToSymbolIndexMap::const_iterator pos =
3645 range.first;
3646 pos != range.second; ++pos) {
3647 if (sym[sym_idx].GetMangled().GetName(
3648 lldb::eLanguageTypeUnknown,
3649 Mangled::ePreferMangled) ==
3650 sym[pos->second].GetMangled().GetName(
3651 lldb::eLanguageTypeUnknown,
3652 Mangled::ePreferMangled)) {
3653 m_nlist_idx_to_sym_idx[nlist_idx] =
3654 pos->second;
3655 // We just need the flags from the linker
3656 // symbol, so put these flags
3657 // into the N_STSYM flags to avoid duplicate
3658 // symbols in the symbol table
3659 sym[pos->second].SetExternal(
3660 sym[sym_idx].IsExternal());
3661 sym[pos->second].SetFlags(nlist.n_type << 16 |
3662 nlist.n_desc);
3663 sym[sym_idx].Clear();
3664 found_it = true;
3665 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003666 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003667 }
3668 if (found_it)
3669 continue;
3670 } else {
3671 const char *gsym_name =
3672 sym[sym_idx]
3673 .GetMangled()
3674 .GetName(lldb::eLanguageTypeUnknown,
3675 Mangled::ePreferMangled)
3676 .GetCString();
3677 if (gsym_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00003678 // Combine N_GSYM stab entries with the non
3679 // stab symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00003680 ConstNameToSymbolIndexMap::const_iterator pos =
3681 N_GSYM_name_to_sym_idx.find(gsym_name);
3682 if (pos != N_GSYM_name_to_sym_idx.end()) {
3683 const uint32_t GSYM_sym_idx = pos->second;
3684 m_nlist_idx_to_sym_idx[nlist_idx] =
3685 GSYM_sym_idx;
3686 // Copy the address, because often the N_GSYM
3687 // address has an invalid address of zero
3688 // when the global is a common symbol
3689 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3690 symbol_section);
3691 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3692 symbol_value);
3693 // We just need the flags from the linker
3694 // symbol, so put these flags
3695 // into the N_GSYM flags to avoid duplicate
3696 // symbols in the symbol table
3697 sym[GSYM_sym_idx].SetFlags(
3698 nlist.n_type << 16 | nlist.n_desc);
3699 sym[sym_idx].Clear();
3700 continue;
3701 }
3702 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003703 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003704 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003705 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003706
Kate Stoneb9c1b512016-09-06 20:57:50 +00003707 sym[sym_idx].SetID(nlist_idx);
3708 sym[sym_idx].SetType(type);
3709 if (set_value) {
3710 sym[sym_idx].GetAddressRef().SetSection(
3711 symbol_section);
3712 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
Greg Clayton29e08cb2012-03-14 01:53:24 +00003713 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003714 sym[sym_idx].SetFlags(nlist.n_type << 16 |
3715 nlist.n_desc);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003716
Kate Stoneb9c1b512016-09-06 20:57:50 +00003717 if (symbol_byte_size > 0)
3718 sym[sym_idx].SetByteSize(symbol_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003719
Kate Stoneb9c1b512016-09-06 20:57:50 +00003720 if (demangled_is_synthesized)
3721 sym[sym_idx].SetDemangledNameIsSynthesized(true);
Greg Clayton60038be2015-02-14 00:51:13 +00003722 ++sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723 } else {
3724 sym[sym_idx].Clear();
3725 }
Greg Clayton9191db42013-10-21 18:40:51 +00003726 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003727 /////////////////////////////
3728 }
3729 break; // No more entries to consider
Greg Clayton9191db42013-10-21 18:40:51 +00003730 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731 }
3732
3733 for (const auto &pos : reexport_shlib_needs_fixup) {
3734 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3735 if (undef_pos != undefined_name_to_desc.end()) {
3736 const uint8_t dylib_ordinal =
3737 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3738 if (dylib_ordinal > 0 &&
3739 dylib_ordinal < dylib_files.GetSize())
3740 sym[pos.first].SetReExportedSymbolSharedLibrary(
3741 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3742 }
3743 }
Greg Clayton9191db42013-10-21 18:40:51 +00003744 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003745 }
Greg Clayton9191db42013-10-21 18:40:51 +00003746 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003747 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003748 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003749
3750 // Must reset this in case it was mutated above!
3751 nlist_data_offset = 0;
3752#endif
3753
3754 if (nlist_data.GetByteSize() > 0) {
3755
3756 // If the sym array was not created while parsing the DSC unmapped
3757 // symbols, create it now.
3758 if (sym == NULL) {
3759 sym = symtab->Resize(symtab_load_command.nsyms +
3760 m_dysymtab.nindirectsyms);
3761 num_syms = symtab->GetNumSymbols();
3762 }
3763
3764 if (unmapped_local_symbols_found) {
3765 assert(m_dysymtab.ilocalsym == 0);
3766 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3767 nlist_idx = m_dysymtab.nlocalsym;
3768 } else {
3769 nlist_idx = 0;
3770 }
3771
3772 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3773 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3774 UndefinedNameToDescMap undefined_name_to_desc;
3775 SymbolIndexToName reexport_shlib_needs_fixup;
3776 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
3777 struct nlist_64 nlist;
3778 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset,
3779 nlist_byte_size))
3780 break;
3781
3782 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
3783 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
3784 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
3785 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
3786 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
3787
3788 SymbolType type = eSymbolTypeInvalid;
3789 const char *symbol_name = NULL;
3790
3791 if (have_strtab_data) {
3792 symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3793
3794 if (symbol_name == NULL) {
Adrian Prantl05097242018-04-30 16:49:04 +00003795 // No symbol should be NULL, even the symbols with no string values
3796 // should have an offset zero which points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00003797 Host::SystemLog(Host::eSystemLogError,
3798 "error: symbol[%u] has invalid string table offset "
3799 "0x%x in %s, ignoring symbol\n",
3800 nlist_idx, nlist.n_strx,
3801 module_sp->GetFileSpec().GetPath().c_str());
3802 continue;
3803 }
3804 if (symbol_name[0] == '\0')
3805 symbol_name = NULL;
3806 } else {
3807 const addr_t str_addr = strtab_addr + nlist.n_strx;
Zachary Turner97206d52017-05-12 04:51:55 +00003808 Status str_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003809 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3810 str_error))
3811 symbol_name = memory_symbol_name.c_str();
3812 }
3813 const char *symbol_name_non_abi_mangled = NULL;
3814
3815 SectionSP symbol_section;
3816 lldb::addr_t symbol_byte_size = 0;
3817 bool add_nlist = true;
3818 bool is_gsym = false;
3819 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3820 bool demangled_is_synthesized = false;
3821 bool set_value = true;
3822 assert(sym_idx < num_syms);
3823
3824 sym[sym_idx].SetDebug(is_debug);
3825
3826 if (is_debug) {
3827 switch (nlist.n_type) {
3828 case N_GSYM:
3829 // global symbol: name,,NO_SECT,type,0
3830 // Sometimes the N_GSYM value contains the address.
3831
3832 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3833 // the ObjC data. They
3834 // have the same address, but we want to ensure that we always find
Adrian Prantl05097242018-04-30 16:49:04 +00003835 // only the real symbol, 'cause we don't currently correctly
3836 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3837 // type. This is a temporary hack to make sure the ObjectiveC
3838 // symbols get treated correctly. To do this right, we should
3839 // coalesce all the GSYM & global symbols that have the same
3840 // address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003841 is_gsym = true;
3842 sym[sym_idx].SetExternal(true);
3843
3844 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3845 llvm::StringRef symbol_name_ref(symbol_name);
3846 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3847 symbol_name_non_abi_mangled = symbol_name + 1;
3848 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3849 type = eSymbolTypeObjCClass;
3850 demangled_is_synthesized = true;
3851
3852 } else if (symbol_name_ref.startswith(
3853 g_objc_v2_prefix_metaclass)) {
3854 symbol_name_non_abi_mangled = symbol_name + 1;
3855 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3856 type = eSymbolTypeObjCMetaClass;
3857 demangled_is_synthesized = true;
3858 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3859 symbol_name_non_abi_mangled = symbol_name + 1;
3860 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3861 type = eSymbolTypeObjCIVar;
3862 demangled_is_synthesized = true;
3863 }
3864 } else {
3865 if (nlist.n_value != 0)
3866 symbol_section =
3867 section_info.GetSection(nlist.n_sect, nlist.n_value);
3868 type = eSymbolTypeData;
3869 }
3870 break;
3871
3872 case N_FNAME:
3873 // procedure name (f77 kludge): name,,NO_SECT,0,0
3874 type = eSymbolTypeCompiler;
3875 break;
3876
3877 case N_FUN:
3878 // procedure: name,,n_sect,linenumber,address
3879 if (symbol_name) {
3880 type = eSymbolTypeCode;
3881 symbol_section =
3882 section_info.GetSection(nlist.n_sect, nlist.n_value);
3883
3884 N_FUN_addr_to_sym_idx.insert(
3885 std::make_pair(nlist.n_value, sym_idx));
3886 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003887 // lieu of using nlist_idx in case we ever start trimming entries
3888 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003889 N_FUN_indexes.push_back(sym_idx);
3890 } else {
3891 type = eSymbolTypeCompiler;
3892
3893 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003894 // Copy the size of the function into the original STAB entry
3895 // so we don't have to hunt for it later
Kate Stoneb9c1b512016-09-06 20:57:50 +00003896 symtab->SymbolAtIndex(N_FUN_indexes.back())
3897 ->SetByteSize(nlist.n_value);
3898 N_FUN_indexes.pop_back();
Adrian Prantl05097242018-04-30 16:49:04 +00003899 // We don't really need the end function STAB as it contains
3900 // the size which we already placed with the original symbol,
3901 // so don't add it if we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003902 add_nlist = false;
3903 }
3904 }
3905 break;
3906
3907 case N_STSYM:
3908 // static symbol: name,,n_sect,type,address
3909 N_STSYM_addr_to_sym_idx.insert(
3910 std::make_pair(nlist.n_value, sym_idx));
3911 symbol_section =
3912 section_info.GetSection(nlist.n_sect, nlist.n_value);
3913 if (symbol_name && symbol_name[0]) {
3914 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3915 eSymbolTypeData);
3916 }
3917 break;
3918
3919 case N_LCSYM:
3920 // .lcomm symbol: name,,n_sect,type,address
3921 symbol_section =
3922 section_info.GetSection(nlist.n_sect, nlist.n_value);
3923 type = eSymbolTypeCommonBlock;
3924 break;
3925
3926 case N_BNSYM:
3927 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00003928 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003929 // Skip these if we want minimal symbol tables
3930 add_nlist = false;
3931 break;
3932
3933 case N_ENSYM:
3934 // Set the size of the N_BNSYM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003935 // N_ENSYM so that we can always skip the entire symbol if we need
3936 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003937 // Skip these if we want minimal symbol tables
3938 add_nlist = false;
3939 break;
3940
3941 case N_OPT:
3942 // emitted with gcc2_compiled and in gcc source
3943 type = eSymbolTypeCompiler;
3944 break;
3945
3946 case N_RSYM:
3947 // register sym: name,,NO_SECT,type,register
3948 type = eSymbolTypeVariable;
3949 break;
3950
3951 case N_SLINE:
3952 // src line: 0,,n_sect,linenumber,address
3953 symbol_section =
3954 section_info.GetSection(nlist.n_sect, nlist.n_value);
3955 type = eSymbolTypeLineEntry;
3956 break;
3957
3958 case N_SSYM:
3959 // structure elt: name,,NO_SECT,type,struct_offset
3960 type = eSymbolTypeVariableType;
3961 break;
3962
3963 case N_SO:
3964 // source file name
3965 type = eSymbolTypeSourceFile;
3966 if (symbol_name == NULL) {
3967 add_nlist = false;
3968 if (N_SO_index != UINT32_MAX) {
3969 // Set the size of the N_SO to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003970 // N_SO so that we can always skip the entire N_SO if we need
3971 // to navigate more quickly at the source level when parsing
3972 // STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003973 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3974 symbol_ptr->SetByteSize(sym_idx);
3975 symbol_ptr->SetSizeIsSibling(true);
3976 }
3977 N_NSYM_indexes.clear();
3978 N_INCL_indexes.clear();
3979 N_BRAC_indexes.clear();
3980 N_COMM_indexes.clear();
3981 N_FUN_indexes.clear();
3982 N_SO_index = UINT32_MAX;
3983 } else {
3984 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003985 // lieu of using nlist_idx in case we ever start trimming entries
3986 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003987 const bool N_SO_has_full_path = symbol_name[0] == '/';
3988 if (N_SO_has_full_path) {
3989 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3990 // We have two consecutive N_SO entries where the first
Adrian Prantl05097242018-04-30 16:49:04 +00003991 // contains a directory and the second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992 sym[sym_idx - 1].GetMangled().SetValue(
3993 ConstString(symbol_name), false);
3994 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3995 add_nlist = false;
3996 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003997 // This is the first entry in a N_SO that contains a
3998 // directory or a full path to the source file
Kate Stoneb9c1b512016-09-06 20:57:50 +00003999 N_SO_index = sym_idx;
4000 }
4001 } else if ((N_SO_index == sym_idx - 1) &&
4002 ((sym_idx - 1) < num_syms)) {
4003 // This is usually the second N_SO entry that contains just the
Adrian Prantl05097242018-04-30 16:49:04 +00004004 // filename, so here we combine it with the first one if we are
4005 // minimizing the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004006 const char *so_path =
4007 sym[sym_idx - 1]
4008 .GetMangled()
4009 .GetDemangledName(lldb::eLanguageTypeUnknown)
4010 .AsCString();
4011 if (so_path && so_path[0]) {
4012 std::string full_so_path(so_path);
4013 const size_t double_slash_pos = full_so_path.find("//");
4014 if (double_slash_pos != std::string::npos) {
4015 // The linker has been generating bad N_SO entries with
Adrian Prantl05097242018-04-30 16:49:04 +00004016 // doubled up paths in the format "%s%s" where the first
4017 // string in the DW_AT_comp_dir, and the second is the
4018 // directory for the source file so you end up with a path
4019 // that looks like "/tmp/src//tmp/src/"
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004020 FileSpec so_dir(so_path);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00004021 if (!FileSystem::Instance().Exists(so_dir)) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00004022 so_dir.SetFile(&full_so_path[double_slash_pos + 1],
Jonas Devlieghere937348c2018-06-13 22:08:14 +00004023 FileSpec::Style::native);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00004024 if (FileSystem::Instance().Exists(so_dir)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004025 // Trim off the incorrect path
4026 full_so_path.erase(0, double_slash_pos + 1);
4027 }
4028 }
4029 }
4030 if (*full_so_path.rbegin() != '/')
4031 full_so_path += '/';
4032 full_so_path += symbol_name;
4033 sym[sym_idx - 1].GetMangled().SetValue(
4034 ConstString(full_so_path.c_str()), false);
4035 add_nlist = false;
4036 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4037 }
4038 } else {
4039 // This could be a relative path to a N_SO
4040 N_SO_index = sym_idx;
4041 }
4042 }
4043 break;
4044
4045 case N_OSO:
4046 // object file name: name,,0,0,st_mtime
4047 type = eSymbolTypeObjectFile;
4048 break;
4049
4050 case N_LSYM:
4051 // local sym: name,,NO_SECT,type,offset
4052 type = eSymbolTypeLocal;
4053 break;
4054
4055 //----------------------------------------------------------------------
4056 // INCL scopes
4057 //----------------------------------------------------------------------
4058 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00004059 // include file beginning: name,,NO_SECT,0,sum We use the current
4060 // number of symbols in the symbol table in lieu of using nlist_idx
4061 // in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004062 N_INCL_indexes.push_back(sym_idx);
4063 type = eSymbolTypeScopeBegin;
4064 break;
4065
4066 case N_EINCL:
4067 // include file end: name,,NO_SECT,0,0
4068 // Set the size of the N_BINCL to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004069 // N_EINCL so that we can always skip the entire symbol if we need
4070 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004071 if (!N_INCL_indexes.empty()) {
4072 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
4073 symbol_ptr->SetByteSize(sym_idx + 1);
4074 symbol_ptr->SetSizeIsSibling(true);
4075 N_INCL_indexes.pop_back();
4076 }
4077 type = eSymbolTypeScopeEnd;
4078 break;
4079
4080 case N_SOL:
4081 // #included file name: name,,n_sect,0,address
4082 type = eSymbolTypeHeaderFile;
4083
4084 // We currently don't use the header files on darwin
4085 add_nlist = false;
4086 break;
4087
4088 case N_PARAMS:
4089 // compiler parameters: name,,NO_SECT,0,0
4090 type = eSymbolTypeCompiler;
4091 break;
4092
4093 case N_VERSION:
4094 // compiler version: name,,NO_SECT,0,0
4095 type = eSymbolTypeCompiler;
4096 break;
4097
4098 case N_OLEVEL:
4099 // compiler -O level: name,,NO_SECT,0,0
4100 type = eSymbolTypeCompiler;
4101 break;
4102
4103 case N_PSYM:
4104 // parameter: name,,NO_SECT,type,offset
4105 type = eSymbolTypeVariable;
4106 break;
4107
4108 case N_ENTRY:
4109 // alternate entry: name,,n_sect,linenumber,address
4110 symbol_section =
4111 section_info.GetSection(nlist.n_sect, nlist.n_value);
4112 type = eSymbolTypeLineEntry;
4113 break;
4114
4115 //----------------------------------------------------------------------
4116 // Left and Right Braces
4117 //----------------------------------------------------------------------
4118 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004119 // left bracket: 0,,NO_SECT,nesting level,address We use the
4120 // current number of symbols in the symbol table in lieu of using
4121 // nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004122 symbol_section =
4123 section_info.GetSection(nlist.n_sect, nlist.n_value);
4124 N_BRAC_indexes.push_back(sym_idx);
4125 type = eSymbolTypeScopeBegin;
4126 break;
4127
4128 case N_RBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004129 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4130 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4131 // can always skip the entire symbol if we need to navigate more
4132 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004133 symbol_section =
4134 section_info.GetSection(nlist.n_sect, nlist.n_value);
4135 if (!N_BRAC_indexes.empty()) {
4136 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4137 symbol_ptr->SetByteSize(sym_idx + 1);
4138 symbol_ptr->SetSizeIsSibling(true);
4139 N_BRAC_indexes.pop_back();
4140 }
4141 type = eSymbolTypeScopeEnd;
4142 break;
4143
4144 case N_EXCL:
4145 // deleted include file: name,,NO_SECT,0,sum
4146 type = eSymbolTypeHeaderFile;
4147 break;
4148
4149 //----------------------------------------------------------------------
4150 // COMM scopes
4151 //----------------------------------------------------------------------
4152 case N_BCOMM:
4153 // begin common: name,,NO_SECT,0,0
4154 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00004155 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004156 type = eSymbolTypeScopeBegin;
4157 N_COMM_indexes.push_back(sym_idx);
4158 break;
4159
4160 case N_ECOML:
4161 // end common (local name): 0,,n_sect,0,address
4162 symbol_section =
4163 section_info.GetSection(nlist.n_sect, nlist.n_value);
4164 LLVM_FALLTHROUGH;
4165
4166 case N_ECOMM:
4167 // end common: name,,n_sect,0,0
4168 // Set the size of the N_BCOMM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004169 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4170 // we need to navigate more quickly at the source level when
4171 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004172 if (!N_COMM_indexes.empty()) {
4173 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4174 symbol_ptr->SetByteSize(sym_idx + 1);
4175 symbol_ptr->SetSizeIsSibling(true);
4176 N_COMM_indexes.pop_back();
4177 }
4178 type = eSymbolTypeScopeEnd;
4179 break;
4180
4181 case N_LENG:
4182 // second stab entry with length information
4183 type = eSymbolTypeAdditional;
4184 break;
4185
4186 default:
4187 break;
4188 }
4189 } else {
4190 // uint8_t n_pext = N_PEXT & nlist.n_type;
4191 uint8_t n_type = N_TYPE & nlist.n_type;
4192 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4193
4194 switch (n_type) {
4195 case N_INDR: {
4196 const char *reexport_name_cstr =
4197 strtab_data.PeekCStr(nlist.n_value);
4198 if (reexport_name_cstr && reexport_name_cstr[0]) {
4199 type = eSymbolTypeReExported;
4200 ConstString reexport_name(
4201 reexport_name_cstr +
4202 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4203 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4204 set_value = false;
4205 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4206 indirect_symbol_names.insert(
4207 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4208 } else
4209 type = eSymbolTypeUndefined;
4210 } break;
4211
4212 case N_UNDF:
4213 if (symbol_name && symbol_name[0]) {
4214 ConstString undefined_name(symbol_name +
4215 ((symbol_name[0] == '_') ? 1 : 0));
4216 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4217 }
4218 LLVM_FALLTHROUGH;
4219
4220 case N_PBUD:
4221 type = eSymbolTypeUndefined;
4222 break;
4223
4224 case N_ABS:
4225 type = eSymbolTypeAbsolute;
4226 break;
4227
4228 case N_SECT: {
4229 symbol_section =
4230 section_info.GetSection(nlist.n_sect, nlist.n_value);
4231
4232 if (!symbol_section) {
4233 // TODO: warn about this?
4234 add_nlist = false;
4235 break;
4236 }
4237
4238 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4239 type = eSymbolTypeException;
4240 } else {
4241 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4242
4243 switch (section_type) {
4244 case S_CSTRING_LITERALS:
4245 type = eSymbolTypeData;
4246 break; // section with only literal C strings
4247 case S_4BYTE_LITERALS:
4248 type = eSymbolTypeData;
4249 break; // section with only 4 byte literals
4250 case S_8BYTE_LITERALS:
4251 type = eSymbolTypeData;
4252 break; // section with only 8 byte literals
4253 case S_LITERAL_POINTERS:
4254 type = eSymbolTypeTrampoline;
4255 break; // section with only pointers to literals
4256 case S_NON_LAZY_SYMBOL_POINTERS:
4257 type = eSymbolTypeTrampoline;
4258 break; // section with only non-lazy symbol pointers
4259 case S_LAZY_SYMBOL_POINTERS:
4260 type = eSymbolTypeTrampoline;
4261 break; // section with only lazy symbol pointers
4262 case S_SYMBOL_STUBS:
4263 type = eSymbolTypeTrampoline;
4264 break; // section with only symbol stubs, byte size of stub in
4265 // the reserved2 field
4266 case S_MOD_INIT_FUNC_POINTERS:
4267 type = eSymbolTypeCode;
4268 break; // section with only function pointers for initialization
4269 case S_MOD_TERM_FUNC_POINTERS:
4270 type = eSymbolTypeCode;
4271 break; // section with only function pointers for termination
4272 case S_INTERPOSING:
4273 type = eSymbolTypeTrampoline;
4274 break; // section with only pairs of function pointers for
4275 // interposing
4276 case S_16BYTE_LITERALS:
4277 type = eSymbolTypeData;
4278 break; // section with only 16 byte literals
4279 case S_DTRACE_DOF:
4280 type = eSymbolTypeInstrumentation;
4281 break;
4282 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4283 type = eSymbolTypeTrampoline;
4284 break;
4285 default:
4286 switch (symbol_section->GetType()) {
4287 case lldb::eSectionTypeCode:
4288 type = eSymbolTypeCode;
4289 break;
4290 case eSectionTypeData:
4291 case eSectionTypeDataCString: // Inlined C string data
4292 case eSectionTypeDataCStringPointers: // Pointers to C string
4293 // data
4294 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4295 // the symbol table
4296 case eSectionTypeData4:
4297 case eSectionTypeData8:
4298 case eSectionTypeData16:
4299 type = eSymbolTypeData;
4300 break;
4301 default:
4302 break;
4303 }
4304 break;
4305 }
4306
4307 if (type == eSymbolTypeInvalid) {
4308 const char *symbol_sect_name =
4309 symbol_section->GetName().AsCString();
4310 if (symbol_section->IsDescendant(text_section_sp.get())) {
4311 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4312 S_ATTR_SELF_MODIFYING_CODE |
4313 S_ATTR_SOME_INSTRUCTIONS))
4314 type = eSymbolTypeData;
4315 else
4316 type = eSymbolTypeCode;
4317 } else if (symbol_section->IsDescendant(
4318 data_section_sp.get()) ||
4319 symbol_section->IsDescendant(
4320 data_dirty_section_sp.get()) ||
4321 symbol_section->IsDescendant(
4322 data_const_section_sp.get())) {
4323 if (symbol_sect_name &&
4324 ::strstr(symbol_sect_name, "__objc") ==
4325 symbol_sect_name) {
4326 type = eSymbolTypeRuntime;
4327
4328 if (symbol_name) {
4329 llvm::StringRef symbol_name_ref(symbol_name);
4330 if (symbol_name_ref.startswith("_OBJC_")) {
4331 static const llvm::StringRef g_objc_v2_prefix_class(
4332 "_OBJC_CLASS_$_");
4333 static const llvm::StringRef g_objc_v2_prefix_metaclass(
4334 "_OBJC_METACLASS_$_");
4335 static const llvm::StringRef g_objc_v2_prefix_ivar(
4336 "_OBJC_IVAR_$_");
4337 if (symbol_name_ref.startswith(
4338 g_objc_v2_prefix_class)) {
4339 symbol_name_non_abi_mangled = symbol_name + 1;
4340 symbol_name =
4341 symbol_name + g_objc_v2_prefix_class.size();
4342 type = eSymbolTypeObjCClass;
4343 demangled_is_synthesized = true;
4344 } else if (symbol_name_ref.startswith(
4345 g_objc_v2_prefix_metaclass)) {
4346 symbol_name_non_abi_mangled = symbol_name + 1;
4347 symbol_name =
4348 symbol_name + g_objc_v2_prefix_metaclass.size();
4349 type = eSymbolTypeObjCMetaClass;
4350 demangled_is_synthesized = true;
4351 } else if (symbol_name_ref.startswith(
4352 g_objc_v2_prefix_ivar)) {
4353 symbol_name_non_abi_mangled = symbol_name + 1;
4354 symbol_name =
4355 symbol_name + g_objc_v2_prefix_ivar.size();
4356 type = eSymbolTypeObjCIVar;
4357 demangled_is_synthesized = true;
4358 }
4359 }
4360 }
4361 } else if (symbol_sect_name &&
4362 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4363 symbol_sect_name) {
4364 type = eSymbolTypeException;
4365 } else {
4366 type = eSymbolTypeData;
4367 }
4368 } else if (symbol_sect_name &&
4369 ::strstr(symbol_sect_name, "__IMPORT") ==
4370 symbol_sect_name) {
4371 type = eSymbolTypeTrampoline;
4372 } else if (symbol_section->IsDescendant(
4373 objc_section_sp.get())) {
4374 type = eSymbolTypeRuntime;
4375 if (symbol_name && symbol_name[0] == '.') {
4376 llvm::StringRef symbol_name_ref(symbol_name);
4377 static const llvm::StringRef g_objc_v1_prefix_class(
4378 ".objc_class_name_");
4379 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4380 symbol_name_non_abi_mangled = symbol_name;
4381 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4382 type = eSymbolTypeObjCClass;
4383 demangled_is_synthesized = true;
4384 }
4385 }
4386 }
4387 }
4388 }
4389 } break;
4390 }
4391 }
4392
4393 if (add_nlist) {
4394 uint64_t symbol_value = nlist.n_value;
4395
4396 if (symbol_name_non_abi_mangled) {
4397 sym[sym_idx].GetMangled().SetMangledName(
4398 ConstString(symbol_name_non_abi_mangled));
4399 sym[sym_idx].GetMangled().SetDemangledName(
4400 ConstString(symbol_name));
4401 } else {
4402 bool symbol_name_is_mangled = false;
4403
4404 if (symbol_name && symbol_name[0] == '_') {
4405 symbol_name_is_mangled = symbol_name[1] == '_';
4406 symbol_name++; // Skip the leading underscore
4407 }
4408
4409 if (symbol_name) {
4410 ConstString const_symbol_name(symbol_name);
4411 sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4412 symbol_name_is_mangled);
4413 }
4414 }
4415
4416 if (is_gsym) {
4417 const char *gsym_name = sym[sym_idx]
4418 .GetMangled()
4419 .GetName(lldb::eLanguageTypeUnknown,
4420 Mangled::ePreferMangled)
4421 .GetCString();
4422 if (gsym_name)
4423 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4424 }
4425
4426 if (symbol_section) {
4427 const addr_t section_file_addr = symbol_section->GetFileAddress();
4428 if (symbol_byte_size == 0 && function_starts_count > 0) {
4429 addr_t symbol_lookup_file_addr = nlist.n_value;
4430 // Do an exact address match for non-ARM addresses, else get the
Adrian Prantl05097242018-04-30 16:49:04 +00004431 // closest since the symbol might be a thumb symbol which has an
4432 // address with bit zero set
Kate Stoneb9c1b512016-09-06 20:57:50 +00004433 FunctionStarts::Entry *func_start_entry =
4434 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4435 if (is_arm && func_start_entry) {
4436 // Verify that the function start address is the symbol address
Adrian Prantl05097242018-04-30 16:49:04 +00004437 // (ARM) or the symbol address + 1 (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004438 if (func_start_entry->addr != symbol_lookup_file_addr &&
4439 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4440 // Not the right entry, NULL it out...
4441 func_start_entry = NULL;
4442 }
4443 }
4444 if (func_start_entry) {
4445 func_start_entry->data = true;
4446
4447 addr_t symbol_file_addr = func_start_entry->addr;
4448 if (is_arm)
4449 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4450
4451 const FunctionStarts::Entry *next_func_start_entry =
4452 function_starts.FindNextEntry(func_start_entry);
4453 const addr_t section_end_file_addr =
4454 section_file_addr + symbol_section->GetByteSize();
4455 if (next_func_start_entry) {
4456 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4457 // Be sure the clear the Thumb address bit when we calculate
Adrian Prantl05097242018-04-30 16:49:04 +00004458 // the size from the current and next address
Kate Stoneb9c1b512016-09-06 20:57:50 +00004459 if (is_arm)
4460 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4461 symbol_byte_size = std::min<lldb::addr_t>(
4462 next_symbol_file_addr - symbol_file_addr,
4463 section_end_file_addr - symbol_file_addr);
4464 } else {
4465 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4466 }
4467 }
4468 }
4469 symbol_value -= section_file_addr;
4470 }
4471
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004472 if (!is_debug) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004473 if (type == eSymbolTypeCode) {
Adrian Prantl05097242018-04-30 16:49:04 +00004474 // See if we can find a N_FUN entry for any code symbols. If we
4475 // do find a match, and the name matches, then we can merge the
4476 // two into just the function symbol to avoid duplicate entries
4477 // in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004478 std::pair<ValueToSymbolIndexMap::const_iterator,
4479 ValueToSymbolIndexMap::const_iterator>
4480 range;
4481 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4482 if (range.first != range.second) {
4483 bool found_it = false;
4484 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4485 pos != range.second; ++pos) {
4486 if (sym[sym_idx].GetMangled().GetName(
4487 lldb::eLanguageTypeUnknown,
4488 Mangled::ePreferMangled) ==
4489 sym[pos->second].GetMangled().GetName(
4490 lldb::eLanguageTypeUnknown,
4491 Mangled::ePreferMangled)) {
4492 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4493 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004494 // these flags into the N_FUN flags to avoid duplicate
4495 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004496 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4497 sym[pos->second].SetFlags(nlist.n_type << 16 |
4498 nlist.n_desc);
4499 if (resolver_addresses.find(nlist.n_value) !=
4500 resolver_addresses.end())
4501 sym[pos->second].SetType(eSymbolTypeResolver);
4502 sym[sym_idx].Clear();
4503 found_it = true;
4504 break;
4505 }
4506 }
4507 if (found_it)
4508 continue;
4509 } else {
4510 if (resolver_addresses.find(nlist.n_value) !=
4511 resolver_addresses.end())
4512 type = eSymbolTypeResolver;
4513 }
4514 } else if (type == eSymbolTypeData ||
4515 type == eSymbolTypeObjCClass ||
4516 type == eSymbolTypeObjCMetaClass ||
4517 type == eSymbolTypeObjCIVar) {
Adrian Prantl05097242018-04-30 16:49:04 +00004518 // See if we can find a N_STSYM entry for any data symbols. If we
4519 // do find a match, and the name matches, then we can merge the
4520 // two into just the Static symbol to avoid duplicate entries in
4521 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004522 std::pair<ValueToSymbolIndexMap::const_iterator,
4523 ValueToSymbolIndexMap::const_iterator>
4524 range;
4525 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4526 if (range.first != range.second) {
4527 bool found_it = false;
4528 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4529 pos != range.second; ++pos) {
4530 if (sym[sym_idx].GetMangled().GetName(
4531 lldb::eLanguageTypeUnknown,
4532 Mangled::ePreferMangled) ==
4533 sym[pos->second].GetMangled().GetName(
4534 lldb::eLanguageTypeUnknown,
4535 Mangled::ePreferMangled)) {
4536 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4537 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004538 // these flags into the N_STSYM flags to avoid duplicate
4539 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004540 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4541 sym[pos->second].SetFlags(nlist.n_type << 16 |
4542 nlist.n_desc);
4543 sym[sym_idx].Clear();
4544 found_it = true;
4545 break;
4546 }
4547 }
4548 if (found_it)
4549 continue;
4550 } else {
4551 // Combine N_GSYM stab entries with the non stab symbol
4552 const char *gsym_name = sym[sym_idx]
4553 .GetMangled()
4554 .GetName(lldb::eLanguageTypeUnknown,
4555 Mangled::ePreferMangled)
4556 .GetCString();
4557 if (gsym_name) {
4558 ConstNameToSymbolIndexMap::const_iterator pos =
4559 N_GSYM_name_to_sym_idx.find(gsym_name);
4560 if (pos != N_GSYM_name_to_sym_idx.end()) {
4561 const uint32_t GSYM_sym_idx = pos->second;
4562 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00004563 // Copy the address, because often the N_GSYM address has
4564 // an invalid address of zero when the global is a common
4565 // symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00004566 sym[GSYM_sym_idx].GetAddressRef().SetSection(
4567 symbol_section);
4568 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4569 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004570 // these flags into the N_GSYM flags to avoid duplicate
4571 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004572 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
4573 nlist.n_desc);
4574 sym[sym_idx].Clear();
4575 continue;
4576 }
4577 }
4578 }
4579 }
4580 }
4581
4582 sym[sym_idx].SetID(nlist_idx);
4583 sym[sym_idx].SetType(type);
4584 if (set_value) {
4585 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4586 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4587 }
4588 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4589
4590 if (symbol_byte_size > 0)
4591 sym[sym_idx].SetByteSize(symbol_byte_size);
4592
4593 if (demangled_is_synthesized)
4594 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4595
4596 ++sym_idx;
4597 } else {
4598 sym[sym_idx].Clear();
4599 }
4600 }
4601
4602 for (const auto &pos : reexport_shlib_needs_fixup) {
4603 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4604 if (undef_pos != undefined_name_to_desc.end()) {
4605 const uint8_t dylib_ordinal =
4606 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4607 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4608 sym[pos.first].SetReExportedSymbolSharedLibrary(
4609 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4610 }
4611 }
4612 }
4613
4614 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4615
4616 if (function_starts_count > 0) {
4617 uint32_t num_synthetic_function_symbols = 0;
4618 for (i = 0; i < function_starts_count; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004619 if (!function_starts.GetEntryRef(i).data)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004620 ++num_synthetic_function_symbols;
4621 }
4622
4623 if (num_synthetic_function_symbols > 0) {
4624 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4625 num_syms = sym_idx + num_synthetic_function_symbols;
4626 sym = symtab->Resize(num_syms);
4627 }
4628 for (i = 0; i < function_starts_count; ++i) {
4629 const FunctionStarts::Entry *func_start_entry =
4630 function_starts.GetEntryAtIndex(i);
Jonas Devliegherea6682a42018-12-15 00:15:33 +00004631 if (!func_start_entry->data) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004632 addr_t symbol_file_addr = func_start_entry->addr;
4633 uint32_t symbol_flags = 0;
4634 if (is_arm) {
4635 if (symbol_file_addr & 1)
4636 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4637 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4638 }
4639 Address symbol_addr;
4640 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4641 SectionSP symbol_section(symbol_addr.GetSection());
4642 uint32_t symbol_byte_size = 0;
4643 if (symbol_section) {
4644 const addr_t section_file_addr =
4645 symbol_section->GetFileAddress();
4646 const FunctionStarts::Entry *next_func_start_entry =
4647 function_starts.FindNextEntry(func_start_entry);
4648 const addr_t section_end_file_addr =
4649 section_file_addr + symbol_section->GetByteSize();
4650 if (next_func_start_entry) {
4651 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4652 if (is_arm)
4653 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4654 symbol_byte_size = std::min<lldb::addr_t>(
4655 next_symbol_file_addr - symbol_file_addr,
4656 section_end_file_addr - symbol_file_addr);
4657 } else {
4658 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4659 }
4660 sym[sym_idx].SetID(synthetic_sym_id++);
4661 sym[sym_idx].GetMangled().SetDemangledName(
4662 GetNextSyntheticSymbolName());
4663 sym[sym_idx].SetType(eSymbolTypeCode);
4664 sym[sym_idx].SetIsSynthetic(true);
4665 sym[sym_idx].GetAddressRef() = symbol_addr;
4666 if (symbol_flags)
4667 sym[sym_idx].SetFlags(symbol_flags);
4668 if (symbol_byte_size)
4669 sym[sym_idx].SetByteSize(symbol_byte_size);
4670 ++sym_idx;
4671 }
4672 }
4673 }
4674 }
4675 }
4676 }
4677
Adrian Prantl05097242018-04-30 16:49:04 +00004678 // Trim our symbols down to just what we ended up with after removing any
4679 // symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004680 if (sym_idx < num_syms) {
4681 num_syms = sym_idx;
4682 sym = symtab->Resize(num_syms);
4683 }
4684
4685 // Now synthesize indirect symbols
4686 if (m_dysymtab.nindirectsyms != 0) {
4687 if (indirect_symbol_index_data.GetByteSize()) {
4688 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4689 m_nlist_idx_to_sym_idx.end();
4690
4691 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4692 ++sect_idx) {
4693 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4694 S_SYMBOL_STUBS) {
4695 uint32_t symbol_stub_byte_size =
4696 m_mach_sections[sect_idx].reserved2;
4697 if (symbol_stub_byte_size == 0)
4698 continue;
4699
4700 const uint32_t num_symbol_stubs =
4701 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4702
4703 if (num_symbol_stubs == 0)
4704 continue;
4705
4706 const uint32_t symbol_stub_index_offset =
4707 m_mach_sections[sect_idx].reserved1;
4708 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs;
4709 ++stub_idx) {
4710 const uint32_t symbol_stub_index =
4711 symbol_stub_index_offset + stub_idx;
4712 const lldb::addr_t symbol_stub_addr =
4713 m_mach_sections[sect_idx].addr +
4714 (stub_idx * symbol_stub_byte_size);
4715 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4716 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4717 symbol_stub_offset, 4)) {
4718 const uint32_t stub_sym_id =
4719 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4720 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4721 continue;
4722
4723 NListIndexToSymbolIndexMap::const_iterator index_pos =
4724 m_nlist_idx_to_sym_idx.find(stub_sym_id);
4725 Symbol *stub_symbol = NULL;
4726 if (index_pos != end_index_pos) {
Adrian Prantl05097242018-04-30 16:49:04 +00004727 // We have a remapping from the original nlist index to a
4728 // current symbol index, so just look this up by index
Kate Stoneb9c1b512016-09-06 20:57:50 +00004729 stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4730 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004731 // We need to lookup a symbol using the original nlist symbol
4732 // index since this index is coming from the S_SYMBOL_STUBS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004733 stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4734 }
4735
4736 if (stub_symbol) {
4737 Address so_addr(symbol_stub_addr, section_list);
4738
4739 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4740 // Change the external symbol into a trampoline that makes
Adrian Prantl05097242018-04-30 16:49:04 +00004741 // sense These symbols were N_UNDF N_EXT, and are useless
4742 // to us, so we can re-use them so we don't have to make up
4743 // a synthetic symbol for no good reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004744 if (resolver_addresses.find(symbol_stub_addr) ==
4745 resolver_addresses.end())
4746 stub_symbol->SetType(eSymbolTypeTrampoline);
4747 else
4748 stub_symbol->SetType(eSymbolTypeResolver);
4749 stub_symbol->SetExternal(false);
4750 stub_symbol->GetAddressRef() = so_addr;
4751 stub_symbol->SetByteSize(symbol_stub_byte_size);
4752 } else {
4753 // Make a synthetic symbol to describe the trampoline stub
4754 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4755 if (sym_idx >= num_syms) {
4756 sym = symtab->Resize(++num_syms);
4757 stub_symbol = NULL; // this pointer no longer valid
4758 }
4759 sym[sym_idx].SetID(synthetic_sym_id++);
4760 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4761 if (resolver_addresses.find(symbol_stub_addr) ==
4762 resolver_addresses.end())
4763 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4764 else
4765 sym[sym_idx].SetType(eSymbolTypeResolver);
4766 sym[sym_idx].SetIsSynthetic(true);
4767 sym[sym_idx].GetAddressRef() = so_addr;
4768 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4769 ++sym_idx;
4770 }
4771 } else {
4772 if (log)
4773 log->Warning("symbol stub referencing symbol table symbol "
4774 "%u that isn't in our minimal symbol table, "
4775 "fix this!!!",
4776 stub_sym_id);
4777 }
4778 }
4779 }
4780 }
4781 }
4782 }
4783 }
4784
4785 if (!trie_entries.empty()) {
4786 for (const auto &e : trie_entries) {
4787 if (e.entry.import_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00004788 // Only add indirect symbols from the Trie entries if we didn't have
4789 // a N_INDR nlist entry for this already
Kate Stoneb9c1b512016-09-06 20:57:50 +00004790 if (indirect_symbol_names.find(e.entry.name) ==
4791 indirect_symbol_names.end()) {
4792 // Make a synthetic symbol to describe re-exported symbol.
4793 if (sym_idx >= num_syms)
4794 sym = symtab->Resize(++num_syms);
4795 sym[sym_idx].SetID(synthetic_sym_id++);
4796 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4797 sym[sym_idx].SetType(eSymbolTypeReExported);
4798 sym[sym_idx].SetIsSynthetic(true);
4799 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4800 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4801 sym[sym_idx].SetReExportedSymbolSharedLibrary(
4802 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4803 }
4804 ++sym_idx;
4805 }
4806 }
4807 }
4808 }
4809
Davide Italiano407c6912018-11-02 21:59:14 +00004810 // StreamFile s(stdout, false);
4811 // s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4812 // symtab->Dump(&s, NULL, eSortOrderNone);
4813 // Set symbol byte sizes correctly since mach-o nlist entries don't have
4814 // sizes
4815 symtab->CalculateSymbolSizes();
4816
4817 // s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4818 // symtab->Dump(&s, NULL, eSortOrderNone);
4819
Kate Stoneb9c1b512016-09-06 20:57:50 +00004820 return symtab->GetNumSymbols();
4821 }
4822 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004823}
4824
Kate Stoneb9c1b512016-09-06 20:57:50 +00004825void ObjectFileMachO::Dump(Stream *s) {
4826 ModuleSP module_sp(GetModule());
4827 if (module_sp) {
4828 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4829 s->Printf("%p: ", static_cast<void *>(this));
4830 s->Indent();
4831 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4832 s->PutCString("ObjectFileMachO64");
4833 else
4834 s->PutCString("ObjectFileMachO32");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004835
Pavel Labathf760f5a2019-01-03 10:37:19 +00004836 ArchSpec header_arch = GetArchitecture();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004837
Kate Stoneb9c1b512016-09-06 20:57:50 +00004838 *s << ", file = '" << m_file
Adrian Prantl9702c962018-05-11 00:41:20 +00004839 << "', triple = " << header_arch.GetTriple().getTriple() << "\n";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004840
Kate Stoneb9c1b512016-09-06 20:57:50 +00004841 SectionList *sections = GetSectionList();
4842 if (sections)
4843 sections->Dump(s, NULL, true, UINT32_MAX);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004844
Kate Stoneb9c1b512016-09-06 20:57:50 +00004845 if (m_symtab_ap.get())
4846 m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4847 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004848}
4849
Kate Stoneb9c1b512016-09-06 20:57:50 +00004850bool ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4851 const lldb_private::DataExtractor &data,
4852 lldb::offset_t lc_offset,
4853 lldb_private::UUID &uuid) {
4854 uint32_t i;
4855 struct uuid_command load_cmd;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004856
Kate Stoneb9c1b512016-09-06 20:57:50 +00004857 lldb::offset_t offset = lc_offset;
4858 for (i = 0; i < header.ncmds; ++i) {
4859 const lldb::offset_t cmd_offset = offset;
4860 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4861 break;
4862
4863 if (load_cmd.cmd == LC_UUID) {
4864 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4865
4866 if (uuid_bytes) {
4867 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4868 // We pretend these object files have no UUID to prevent crashing.
4869
4870 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4871 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4872 0xbb, 0x14, 0xf0, 0x0d};
4873
4874 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4875 return false;
4876
Pavel Labath2f93fd12018-06-26 15:12:20 +00004877 uuid = UUID::fromOptionalData(uuid_bytes, 16);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004878 return true;
4879 }
4880 return false;
4881 }
4882 offset = cmd_offset + load_cmd.cmdsize;
4883 }
4884 return false;
4885}
4886
Jason Molenda32762fd2018-10-11 00:28:35 +00004887static llvm::StringRef GetOSName(uint32_t cmd) {
Adrian Prantl9702c962018-05-11 00:41:20 +00004888 switch (cmd) {
4889 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004890 return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004891 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Jason Molenda32762fd2018-10-11 00:28:35 +00004892 return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
Adrian Prantl9702c962018-05-11 00:41:20 +00004893 case llvm::MachO::LC_VERSION_MIN_TVOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004894 return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004895 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00004896 return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
Adrian Prantl9702c962018-05-11 00:41:20 +00004897 default:
4898 llvm_unreachable("unexpected LC_VERSION load command");
4899 }
4900}
4901
Jason Molenda32762fd2018-10-11 00:28:35 +00004902namespace {
4903 struct OSEnv {
4904 llvm::StringRef os_type;
4905 llvm::StringRef environment;
4906 OSEnv(uint32_t cmd) {
4907 switch (cmd) {
4908 case PLATFORM_MACOS:
4909 os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4910 return;
4911 case PLATFORM_IOS:
4912 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4913 return;
4914 case PLATFORM_TVOS:
4915 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4916 return;
4917 case PLATFORM_WATCHOS:
4918 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4919 return;
4920// NEED_BRIDGEOS_TRIPLE case PLATFORM_BRIDGEOS:
4921// NEED_BRIDGEOS_TRIPLE os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4922// NEED_BRIDGEOS_TRIPLE return;
4923#if defined (PLATFORM_IOSSIMULATOR) && defined (PLATFORM_TVOSSIMULATOR) && defined (PLATFORM_WATCHOSSIMULATOR)
4924 case PLATFORM_IOSSIMULATOR:
4925 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4926 environment =
4927 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4928 return;
4929 case PLATFORM_TVOSSIMULATOR:
4930 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4931 environment =
4932 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4933 return;
4934 case PLATFORM_WATCHOSSIMULATOR:
4935 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4936 environment =
4937 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4938 return;
4939#endif
4940 default: {
4941 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
4942 LIBLLDB_LOG_PROCESS));
4943 if (log)
4944 log->Printf("unsupported platform in LC_BUILD_VERSION");
4945 }
4946 }
4947 }
4948 };
4949
4950 struct MinOS {
Eric Liu7d2f7832018-10-11 14:44:12 +00004951 uint32_t major_version, minor_version, patch_version;
Jason Molenda32762fd2018-10-11 00:28:35 +00004952 MinOS(uint32_t version)
Eric Liu7d2f7832018-10-11 14:44:12 +00004953 : major_version(version >> 16),
4954 minor_version((version >> 8) & 0xffu),
4955 patch_version(version & 0xffu) {}
Jason Molenda32762fd2018-10-11 00:28:35 +00004956 };
4957} // namespace
4958
Pavel Labathf760f5a2019-01-03 10:37:19 +00004959ArchSpec
4960ObjectFileMachO::GetArchitecture(const llvm::MachO::mach_header &header,
4961 const lldb_private::DataExtractor &data,
4962 lldb::offset_t lc_offset) {
4963 ArchSpec arch;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004964 arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4965
4966 if (arch.IsValid()) {
4967 llvm::Triple &triple = arch.GetTriple();
4968
4969 // Set OS to an unspecified unknown or a "*" so it can match any OS
4970 triple.setOS(llvm::Triple::UnknownOS);
4971 triple.setOSName(llvm::StringRef());
4972
4973 if (header.filetype == MH_PRELOAD) {
4974 if (header.cputype == CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00004975 // If this is a 32-bit arm binary, and it's a standalone binary, force
4976 // the Vendor to Apple so we don't accidentally pick up the generic
4977 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4978 // frame pointer register; most other armv7 ABIs use a combination of
4979 // r7 and r11.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004980 triple.setVendor(llvm::Triple::Apple);
4981 } else {
4982 // Set vendor to an unspecified unknown or a "*" so it can match any
Adrian Prantl05097242018-04-30 16:49:04 +00004983 // vendor This is required for correct behavior of EFI debugging on
4984 // x86_64
Kate Stoneb9c1b512016-09-06 20:57:50 +00004985 triple.setVendor(llvm::Triple::UnknownVendor);
4986 triple.setVendorName(llvm::StringRef());
4987 }
Pavel Labathf760f5a2019-01-03 10:37:19 +00004988 return arch;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004989 } else {
4990 struct load_command load_cmd;
Jason Molenda32762fd2018-10-11 00:28:35 +00004991 llvm::SmallString<16> os_name;
4992 llvm::raw_svector_ostream os(os_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004993
Jason Molenda32762fd2018-10-11 00:28:35 +00004994 // See if there is an LC_VERSION_MIN_* load command that can give
4995 // us the OS type.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996 lldb::offset_t offset = lc_offset;
4997 for (uint32_t i = 0; i < header.ncmds; ++i) {
Greg Claytonf4d6de62013-04-24 22:29:28 +00004998 const lldb::offset_t cmd_offset = offset;
4999 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005000 break;
5001
Adrian Prantl9702c962018-05-11 00:41:20 +00005002 struct version_min_command version_min;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005003 switch (load_cmd.cmd) {
5004 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005005 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005006 case llvm::MachO::LC_VERSION_MIN_TVOS:
Jason Molenda32762fd2018-10-11 00:28:35 +00005007 case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
Adrian Prantl9702c962018-05-11 00:41:20 +00005008 if (load_cmd.cmdsize != sizeof(version_min))
5009 break;
Jason Molenda32762fd2018-10-11 00:28:35 +00005010 if (data.ExtractBytes(cmd_offset, sizeof(version_min),
5011 data.GetByteOrder(), &version_min) == 0)
5012 break;
5013 MinOS min_os(version_min.version);
Eric Liu7d2f7832018-10-11 14:44:12 +00005014 os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
5015 << min_os.minor_version << '.' << min_os.patch_version;
Adrian Prantl9702c962018-05-11 00:41:20 +00005016 triple.setOSName(os.str());
Pavel Labathf760f5a2019-01-03 10:37:19 +00005017 return arch;
Jason Molenda32762fd2018-10-11 00:28:35 +00005018 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005019 default:
5020 break;
Greg Claytonf4d6de62013-04-24 22:29:28 +00005021 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005022
Greg Claytonf4d6de62013-04-24 22:29:28 +00005023 offset = cmd_offset + load_cmd.cmdsize;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005024 }
5025
Jason Molenda32762fd2018-10-11 00:28:35 +00005026 // See if there is an LC_BUILD_VERSION load command that can give
5027 // us the OS type.
5028
5029 offset = lc_offset;
5030 for (uint32_t i = 0; i < header.ncmds; ++i) {
5031 const lldb::offset_t cmd_offset = offset;
5032 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
5033 break;
Adrian Prantl874e32d2018-11-13 23:14:37 +00005034 do {
5035 if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
5036 struct build_version_command build_version;
5037 if (load_cmd.cmdsize < sizeof(build_version)) {
5038 // Malformed load command.
5039 break;
5040 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005041 if (data.ExtractBytes(cmd_offset, sizeof(build_version),
5042 data.GetByteOrder(), &build_version) == 0)
Adrian Prantl874e32d2018-11-13 23:14:37 +00005043 break;
5044 MinOS min_os(build_version.minos);
5045 OSEnv os_env(build_version.platform);
5046 if (os_env.os_type.empty())
5047 break;
5048 os << os_env.os_type << min_os.major_version << '.'
5049 << min_os.minor_version << '.' << min_os.patch_version;
5050 triple.setOSName(os.str());
5051 if (!os_env.environment.empty())
5052 triple.setEnvironmentName(os_env.environment);
Pavel Labathf760f5a2019-01-03 10:37:19 +00005053 return arch;
Adrian Prantl874e32d2018-11-13 23:14:37 +00005054 }
5055 } while (0);
Jason Molenda32762fd2018-10-11 00:28:35 +00005056 offset = cmd_offset + load_cmd.cmdsize;
5057 }
5058
Kate Stoneb9c1b512016-09-06 20:57:50 +00005059 if (header.filetype != MH_KEXT_BUNDLE) {
5060 // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
5061 // so lets not say our Vendor is Apple, leave it as an unspecified
5062 // unknown
5063 triple.setVendor(llvm::Triple::UnknownVendor);
5064 triple.setVendorName(llvm::StringRef());
5065 }
Greg Claytonf4d6de62013-04-24 22:29:28 +00005066 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005067 }
Pavel Labathf760f5a2019-01-03 10:37:19 +00005068 return arch;
Greg Claytonf4d6de62013-04-24 22:29:28 +00005069}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005070
Kate Stoneb9c1b512016-09-06 20:57:50 +00005071bool ObjectFileMachO::GetUUID(lldb_private::UUID *uuid) {
5072 ModuleSP module_sp(GetModule());
5073 if (module_sp) {
5074 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5075 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5076 return GetUUID(m_header, m_data, offset, *uuid);
5077 }
5078 return false;
Greg Clayton7ab7f892014-05-29 21:33:45 +00005079}
5080
Kate Stoneb9c1b512016-09-06 20:57:50 +00005081uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
5082 uint32_t count = 0;
5083 ModuleSP module_sp(GetModule());
5084 if (module_sp) {
5085 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5086 struct load_command load_cmd;
5087 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5088 std::vector<std::string> rpath_paths;
5089 std::vector<std::string> rpath_relative_paths;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005090 std::vector<std::string> at_exec_relative_paths;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005091 uint32_t i;
5092 for (i = 0; i < m_header.ncmds; ++i) {
5093 const uint32_t cmd_offset = offset;
5094 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5095 break;
5096
5097 switch (load_cmd.cmd) {
5098 case LC_RPATH:
5099 case LC_LOAD_DYLIB:
5100 case LC_LOAD_WEAK_DYLIB:
5101 case LC_REEXPORT_DYLIB:
5102 case LC_LOAD_DYLINKER:
5103 case LC_LOADFVMLIB:
5104 case LC_LOAD_UPWARD_DYLIB: {
5105 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5106 const char *path = m_data.PeekCStr(name_offset);
5107 if (path) {
5108 if (load_cmd.cmd == LC_RPATH)
5109 rpath_paths.push_back(path);
5110 else {
5111 if (path[0] == '@') {
5112 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5113 rpath_relative_paths.push_back(path + strlen("@rpath"));
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005114 else if (strncmp(path, "@executable_path",
5115 strlen("@executable_path")) == 0)
5116 at_exec_relative_paths.push_back(path
5117 + strlen("@executable_path"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005118 } else {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005119 FileSpec file_spec(path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005120 if (files.AppendIfUnique(file_spec))
5121 count++;
5122 }
5123 }
5124 }
5125 } break;
5126
5127 default:
5128 break;
5129 }
5130 offset = cmd_offset + load_cmd.cmdsize;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005131 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005132
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005133 FileSpec this_file_spec(m_file);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005134 FileSystem::Instance().Resolve(this_file_spec);
5135
Kate Stoneb9c1b512016-09-06 20:57:50 +00005136 if (!rpath_paths.empty()) {
5137 // Fixup all LC_RPATH values to be absolute paths
Kate Stoneb9c1b512016-09-06 20:57:50 +00005138 std::string loader_path("@loader_path");
5139 std::string executable_path("@executable_path");
5140 for (auto &rpath : rpath_paths) {
5141 if (rpath.find(loader_path) == 0) {
5142 rpath.erase(0, loader_path.size());
5143 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5144 } else if (rpath.find(executable_path) == 0) {
5145 rpath.erase(0, executable_path.size());
5146 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5147 }
5148 }
5149
5150 for (const auto &rpath_relative_path : rpath_relative_paths) {
5151 for (const auto &rpath : rpath_paths) {
5152 std::string path = rpath;
5153 path += rpath_relative_path;
Adrian Prantl05097242018-04-30 16:49:04 +00005154 // It is OK to resolve this path because we must find a file on disk
5155 // for us to accept it anyway if it is rpath relative.
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00005156 FileSpec file_spec(path);
5157 FileSystem::Instance().Resolve(file_spec);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00005158 if (FileSystem::Instance().Exists(file_spec) &&
5159 files.AppendIfUnique(file_spec)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005160 count++;
5161 break;
5162 }
5163 }
5164 }
5165 }
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005166
5167 // We may have @executable_paths but no RPATHS. Figure those out here.
5168 // Only do this if this object file is the executable. We have no way to
5169 // get back to the actual executable otherwise, so we won't get the right
5170 // path.
5171 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5172 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5173 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5174 FileSpec file_spec =
5175 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00005176 if (FileSystem::Instance().Exists(file_spec) &&
5177 files.AppendIfUnique(file_spec))
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005178 count++;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005179 }
5180 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005181 }
5182 return count;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005183}
5184
Kate Stoneb9c1b512016-09-06 20:57:50 +00005185lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5186 // If the object file is not an executable it can't hold the entry point.
Adrian Prantl05097242018-04-30 16:49:04 +00005187 // m_entry_point_address is initialized to an invalid address, so we can just
5188 // return that. If m_entry_point_address is valid it means we've found it
5189 // already, so return the cached value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005190
Kate Stoneb9c1b512016-09-06 20:57:50 +00005191 if (!IsExecutable() || m_entry_point_address.IsValid())
Jim Ingham672e6f52011-03-07 23:44:08 +00005192 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00005193
Kate Stoneb9c1b512016-09-06 20:57:50 +00005194 // Otherwise, look for the UnixThread or Thread command. The data for the
Adrian Prantl05097242018-04-30 16:49:04 +00005195 // Thread command is given in /usr/include/mach-o.h, but it is basically:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005196 //
5197 // uint32_t flavor - this is the flavor argument you would pass to
5198 // thread_get_state
5199 // uint32_t count - this is the count of longs in the thread state data
5200 // struct XXX_thread_state state - this is the structure from
5201 // <machine/thread_status.h> corresponding to the flavor.
5202 // <repeat this trio>
5203 //
5204 // So we just keep reading the various register flavors till we find the GPR
5205 // one, then read the PC out of there.
5206 // FIXME: We will need to have a "RegisterContext data provider" class at some
5207 // point that can get all the registers
5208 // out of data in this form & attach them to a given thread. That should
Adrian Prantl05097242018-04-30 16:49:04 +00005209 // underlie the MacOS X User process plugin, and we'll also need it for the
5210 // MacOS X Core File process plugin. When we have that we can also use it
5211 // here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005212 //
5213 // For now we hard-code the offsets and flavors we need:
5214 //
5215 //
Greg Claytonc9660542012-02-05 02:38:54 +00005216
Kate Stoneb9c1b512016-09-06 20:57:50 +00005217 ModuleSP module_sp(GetModule());
5218 if (module_sp) {
5219 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5220 struct load_command load_cmd;
5221 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5222 uint32_t i;
5223 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5224 bool done = false;
5225
5226 for (i = 0; i < m_header.ncmds; ++i) {
5227 const lldb::offset_t cmd_offset = offset;
5228 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5229 break;
5230
5231 switch (load_cmd.cmd) {
5232 case LC_UNIXTHREAD:
5233 case LC_THREAD: {
5234 while (offset < cmd_offset + load_cmd.cmdsize) {
5235 uint32_t flavor = m_data.GetU32(&offset);
5236 uint32_t count = m_data.GetU32(&offset);
5237 if (count == 0) {
5238 // We've gotten off somehow, log and exit;
5239 return m_entry_point_address;
5240 }
5241
5242 switch (m_header.cputype) {
5243 case llvm::MachO::CPU_TYPE_ARM:
5244 if (flavor == 1 ||
5245 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 from
5246 // mach/arm/thread_status.h
Greg Claytonc3776bf2012-02-09 06:16:32 +00005247 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005248 offset += 60; // This is the offset of pc in the GPR thread state
5249 // data structure.
5250 start_address = m_data.GetU32(&offset);
5251 done = true;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005253 break;
5254 case llvm::MachO::CPU_TYPE_ARM64:
5255 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5256 {
5257 offset += 256; // This is the offset of pc in the GPR thread state
5258 // data structure.
5259 start_address = m_data.GetU64(&offset);
5260 done = true;
5261 }
5262 break;
5263 case llvm::MachO::CPU_TYPE_I386:
5264 if (flavor ==
5265 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5266 {
5267 offset += 40; // This is the offset of eip in the GPR thread state
5268 // data structure.
5269 start_address = m_data.GetU32(&offset);
5270 done = true;
5271 }
5272 break;
5273 case llvm::MachO::CPU_TYPE_X86_64:
5274 if (flavor ==
5275 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5276 {
5277 offset += 16 * 8; // This is the offset of rip in the GPR thread
5278 // state data structure.
5279 start_address = m_data.GetU64(&offset);
5280 done = true;
5281 }
5282 break;
5283 default:
5284 return m_entry_point_address;
5285 }
5286 // Haven't found the GPR flavor yet, skip over the data for this
5287 // flavor:
5288 if (done)
5289 break;
5290 offset += count * 4;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005291 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005292 } break;
5293 case LC_MAIN: {
5294 ConstString text_segment_name("__TEXT");
5295 uint64_t entryoffset = m_data.GetU64(&offset);
5296 SectionSP text_segment_sp =
5297 GetSectionList()->FindSectionByName(text_segment_name);
5298 if (text_segment_sp) {
5299 done = true;
5300 start_address = text_segment_sp->GetFileAddress() + entryoffset;
5301 }
5302 } break;
5303
5304 default:
5305 break;
5306 }
5307 if (done)
5308 break;
5309
5310 // Go to the next load command:
5311 offset = cmd_offset + load_cmd.cmdsize;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005312 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005313
5314 if (start_address != LLDB_INVALID_ADDRESS) {
5315 // We got the start address from the load commands, so now resolve that
Adrian Prantl05097242018-04-30 16:49:04 +00005316 // address in the sections of this ObjectFile:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005317 if (!m_entry_point_address.ResolveAddressUsingFileSections(
5318 start_address, GetSectionList())) {
5319 m_entry_point_address.Clear();
5320 }
5321 } else {
5322 // We couldn't read the UnixThread load command - maybe it wasn't there.
Adrian Prantl05097242018-04-30 16:49:04 +00005323 // As a fallback look for the "start" symbol in the main executable.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005324
5325 ModuleSP module_sp(GetModule());
5326
5327 if (module_sp) {
5328 SymbolContextList contexts;
5329 SymbolContext context;
5330 if (module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5331 eSymbolTypeCode, contexts)) {
5332 if (contexts.GetContextAtIndex(0, context))
5333 m_entry_point_address = context.symbol->GetAddress();
5334 }
5335 }
5336 }
5337 }
5338
5339 return m_entry_point_address;
5340}
5341
Pavel Labathd1e3fe22018-12-11 15:21:15 +00005342lldb_private::Address ObjectFileMachO::GetBaseAddress() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005343 lldb_private::Address header_addr;
5344 SectionList *section_list = GetSectionList();
5345 if (section_list) {
5346 SectionSP text_segment_sp(
5347 section_list->FindSectionByName(GetSegmentNameTEXT()));
5348 if (text_segment_sp) {
5349 header_addr.SetSection(text_segment_sp);
5350 header_addr.SetOffset(0);
5351 }
5352 }
5353 return header_addr;
5354}
5355
5356uint32_t ObjectFileMachO::GetNumThreadContexts() {
5357 ModuleSP module_sp(GetModule());
5358 if (module_sp) {
5359 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5360 if (!m_thread_context_offsets_valid) {
5361 m_thread_context_offsets_valid = true;
5362 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5363 FileRangeArray::Entry file_range;
5364 thread_command thread_cmd;
5365 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5366 const uint32_t cmd_offset = offset;
5367 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5368 break;
5369
5370 if (thread_cmd.cmd == LC_THREAD) {
5371 file_range.SetRangeBase(offset);
5372 file_range.SetByteSize(thread_cmd.cmdsize - 8);
5373 m_thread_context_offsets.Append(file_range);
5374 }
5375 offset = cmd_offset + thread_cmd.cmdsize;
5376 }
5377 }
5378 }
5379 return m_thread_context_offsets.GetSize();
Greg Claytonc3776bf2012-02-09 06:16:32 +00005380}
5381
Jason Molenda3533cec2017-04-06 01:50:11 +00005382std::string ObjectFileMachO::GetIdentifierString() {
5383 std::string result;
5384 ModuleSP module_sp(GetModule());
5385 if (module_sp) {
5386 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005387
Adrian Prantl05097242018-04-30 16:49:04 +00005388 // First, look over the load commands for an LC_NOTE load command with
5389 // data_owner string "kern ver str" & use that if found.
Jason Molenda3533cec2017-04-06 01:50:11 +00005390 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5391 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5392 const uint32_t cmd_offset = offset;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005393 load_command lc;
5394 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5395 break;
5396 if (lc.cmd == LC_NOTE)
5397 {
5398 char data_owner[17];
5399 m_data.CopyData (offset, 16, data_owner);
5400 data_owner[16] = '\0';
5401 offset += 16;
5402 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5403 uint64_t size = m_data.GetU64_unchecked (&offset);
5404
Adrian Prantl05097242018-04-30 16:49:04 +00005405 // "kern ver str" has a uint32_t version and then a nul terminated
5406 // c-string.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005407 if (strcmp ("kern ver str", data_owner) == 0)
5408 {
5409 offset = fileoff;
5410 uint32_t version;
5411 if (m_data.GetU32 (&offset, &version, 1) != nullptr)
5412 {
5413 if (version == 1)
5414 {
5415 uint32_t strsize = size - sizeof (uint32_t);
5416 char *buf = (char*) malloc (strsize);
5417 if (buf)
5418 {
5419 m_data.CopyData (offset, strsize, buf);
5420 buf[strsize - 1] = '\0';
5421 result = buf;
5422 if (buf)
5423 free (buf);
5424 return result;
5425 }
5426 }
5427 }
5428 }
5429 }
5430 offset = cmd_offset + lc.cmdsize;
5431 }
5432
Adrian Prantl05097242018-04-30 16:49:04 +00005433 // Second, make a pass over the load commands looking for an obsolete
5434 // LC_IDENT load command.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005435 offset = MachHeaderSizeFromMagic(m_header.magic);
5436 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5437 const uint32_t cmd_offset = offset;
Jason Molenda3533cec2017-04-06 01:50:11 +00005438 struct ident_command ident_command;
5439 if (m_data.GetU32(&offset, &ident_command, 2) == NULL)
5440 break;
5441 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005442 char *buf = (char *) malloc (ident_command.cmdsize);
Jason Molenda3533cec2017-04-06 01:50:11 +00005443 if (buf != nullptr
5444 && m_data.CopyData (offset, ident_command.cmdsize, buf) == ident_command.cmdsize) {
5445 buf[ident_command.cmdsize - 1] = '\0';
5446 result = buf;
5447 }
5448 if (buf)
5449 free (buf);
5450 }
5451 offset = cmd_offset + ident_command.cmdsize;
5452 }
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005453
Jason Molenda3533cec2017-04-06 01:50:11 +00005454 }
5455 return result;
5456}
5457
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005458bool ObjectFileMachO::GetCorefileMainBinaryInfo (addr_t &address, UUID &uuid) {
5459 address = LLDB_INVALID_ADDRESS;
5460 uuid.Clear();
5461 ModuleSP module_sp(GetModule());
5462 if (module_sp) {
5463 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5464 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5465 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5466 const uint32_t cmd_offset = offset;
5467 load_command lc;
5468 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5469 break;
5470 if (lc.cmd == LC_NOTE)
5471 {
5472 char data_owner[17];
5473 memset (data_owner, 0, sizeof (data_owner));
5474 m_data.CopyData (offset, 16, data_owner);
5475 offset += 16;
5476 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5477 uint64_t size = m_data.GetU64_unchecked (&offset);
5478
Adrian Prantl05097242018-04-30 16:49:04 +00005479 // "main bin spec" (main binary specification) data payload is
5480 // formatted:
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005481 // uint32_t version [currently 1]
5482 // uint32_t type [0 == unspecified, 1 == kernel, 2 == user process]
5483 // uint64_t address [ UINT64_MAX if address not specified ]
5484 // uuid_t uuid [ all zero's if uuid not specified ]
5485 // uint32_t log2_pagesize [ process page size in log base 2, e.g. 4k pages are 12. 0 for unspecified ]
5486
5487 if (strcmp ("main bin spec", data_owner) == 0 && size >= 32)
5488 {
5489 offset = fileoff;
5490 uint32_t version;
5491 if (m_data.GetU32 (&offset, &version, 1) != nullptr && version == 1)
5492 {
5493 uint32_t type = 0;
5494 uuid_t raw_uuid;
Jason Molenda3f608292017-04-13 02:12:32 +00005495 memset (raw_uuid, 0, sizeof (uuid_t));
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005496
Pavel Labath2f93fd12018-06-26 15:12:20 +00005497 if (m_data.GetU32(&offset, &type, 1) &&
5498 m_data.GetU64(&offset, &address, 1) &&
5499 m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
5500 uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t));
5501 return true;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005502 }
5503 }
5504 }
5505 }
5506 offset = cmd_offset + lc.cmdsize;
5507 }
5508 }
5509 return false;
5510}
5511
Greg Claytonc3776bf2012-02-09 06:16:32 +00005512lldb::RegisterContextSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005513ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5514 lldb_private::Thread &thread) {
5515 lldb::RegisterContextSP reg_ctx_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00005516
Kate Stoneb9c1b512016-09-06 20:57:50 +00005517 ModuleSP module_sp(GetModule());
5518 if (module_sp) {
5519 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5520 if (!m_thread_context_offsets_valid)
5521 GetNumThreadContexts();
Greg Claytona1743492012-03-13 23:14:29 +00005522
Kate Stoneb9c1b512016-09-06 20:57:50 +00005523 const FileRangeArray::Entry *thread_context_file_range =
5524 m_thread_context_offsets.GetEntryAtIndex(idx);
5525 if (thread_context_file_range) {
Jason Molenda4e7511e2013-03-06 23:19:17 +00005526
Kate Stoneb9c1b512016-09-06 20:57:50 +00005527 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5528 thread_context_file_range->GetByteSize());
Jim Ingham28eb5712012-10-12 17:34:26 +00005529
Kate Stoneb9c1b512016-09-06 20:57:50 +00005530 switch (m_header.cputype) {
5531 case llvm::MachO::CPU_TYPE_ARM64:
5532 reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data));
5533 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005534
Kate Stoneb9c1b512016-09-06 20:57:50 +00005535 case llvm::MachO::CPU_TYPE_ARM:
5536 reg_ctx_sp.reset(new RegisterContextDarwin_arm_Mach(thread, data));
5537 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005538
Kate Stoneb9c1b512016-09-06 20:57:50 +00005539 case llvm::MachO::CPU_TYPE_I386:
5540 reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data));
5541 break;
5542
5543 case llvm::MachO::CPU_TYPE_X86_64:
5544 reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data));
5545 break;
5546 }
Greg Claytonc3776bf2012-02-09 06:16:32 +00005547 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005548 }
5549 return reg_ctx_sp;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005550}
5551
Kate Stoneb9c1b512016-09-06 20:57:50 +00005552ObjectFile::Type ObjectFileMachO::CalculateType() {
5553 switch (m_header.filetype) {
5554 case MH_OBJECT: // 0x1u
5555 if (GetAddressByteSize() == 4) {
5556 // 32 bit kexts are just object files, but they do have a valid
5557 // UUID load command.
5558 UUID uuid;
5559 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005560 // this checking for the UUID load command is not enough we could
5561 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5562 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005563 if (m_strata == eStrataInvalid)
5564 m_strata = eStrataKernel;
5565 return eTypeSharedLibrary;
5566 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005567 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005568 return eTypeObjectFile;
5569
5570 case MH_EXECUTE:
5571 return eTypeExecutable; // 0x2u
5572 case MH_FVMLIB:
5573 return eTypeSharedLibrary; // 0x3u
5574 case MH_CORE:
5575 return eTypeCoreFile; // 0x4u
5576 case MH_PRELOAD:
5577 return eTypeSharedLibrary; // 0x5u
5578 case MH_DYLIB:
5579 return eTypeSharedLibrary; // 0x6u
5580 case MH_DYLINKER:
5581 return eTypeDynamicLinker; // 0x7u
5582 case MH_BUNDLE:
5583 return eTypeSharedLibrary; // 0x8u
5584 case MH_DYLIB_STUB:
5585 return eTypeStubLibrary; // 0x9u
5586 case MH_DSYM:
5587 return eTypeDebugInfo; // 0xAu
5588 case MH_KEXT_BUNDLE:
5589 return eTypeSharedLibrary; // 0xBu
5590 default:
5591 break;
5592 }
5593 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005594}
5595
Kate Stoneb9c1b512016-09-06 20:57:50 +00005596ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5597 switch (m_header.filetype) {
5598 case MH_OBJECT: // 0x1u
5599 {
5600 // 32 bit kexts are just object files, but they do have a valid
5601 // UUID load command.
5602 UUID uuid;
5603 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005604 // this checking for the UUID load command is not enough we could
5605 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5606 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005607 if (m_type == eTypeInvalid)
5608 m_type = eTypeSharedLibrary;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005609
Kate Stoneb9c1b512016-09-06 20:57:50 +00005610 return eStrataKernel;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005611 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005612 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005613 return eStrataUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005614
5615 case MH_EXECUTE: // 0x2u
5616 // Check for the MH_DYLDLINK bit in the flags
5617 if (m_header.flags & MH_DYLDLINK) {
5618 return eStrataUser;
5619 } else {
5620 SectionList *section_list = GetSectionList();
5621 if (section_list) {
5622 static ConstString g_kld_section_name("__KLD");
5623 if (section_list->FindSectionByName(g_kld_section_name))
5624 return eStrataKernel;
5625 }
5626 }
5627 return eStrataRawImage;
5628
5629 case MH_FVMLIB:
5630 return eStrataUser; // 0x3u
5631 case MH_CORE:
5632 return eStrataUnknown; // 0x4u
5633 case MH_PRELOAD:
5634 return eStrataRawImage; // 0x5u
5635 case MH_DYLIB:
5636 return eStrataUser; // 0x6u
5637 case MH_DYLINKER:
5638 return eStrataUser; // 0x7u
5639 case MH_BUNDLE:
5640 return eStrataUser; // 0x8u
5641 case MH_DYLIB_STUB:
5642 return eStrataUser; // 0x9u
5643 case MH_DSYM:
5644 return eStrataUnknown; // 0xAu
5645 case MH_KEXT_BUNDLE:
5646 return eStrataKernel; // 0xBu
5647 default:
5648 break;
5649 }
5650 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005651}
5652
Pavel Labath2272c482018-06-18 15:02:23 +00005653llvm::VersionTuple ObjectFileMachO::GetVersion() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005654 ModuleSP module_sp(GetModule());
5655 if (module_sp) {
5656 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5657 struct dylib_command load_cmd;
5658 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5659 uint32_t version_cmd = 0;
5660 uint64_t version = 0;
5661 uint32_t i;
5662 for (i = 0; i < m_header.ncmds; ++i) {
5663 const lldb::offset_t cmd_offset = offset;
5664 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5665 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005666
Kate Stoneb9c1b512016-09-06 20:57:50 +00005667 if (load_cmd.cmd == LC_ID_DYLIB) {
5668 if (version_cmd == 0) {
5669 version_cmd = load_cmd.cmd;
5670 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5671 break;
5672 version = load_cmd.dylib.current_version;
Greg Claytonc2ff9312012-02-22 19:41:02 +00005673 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005674 break; // Break for now unless there is another more complete version
5675 // number load command in the future.
5676 }
5677 offset = cmd_offset + load_cmd.cmdsize;
5678 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00005679
Kate Stoneb9c1b512016-09-06 20:57:50 +00005680 if (version_cmd == LC_ID_DYLIB) {
Pavel Labath2272c482018-06-18 15:02:23 +00005681 unsigned major = (version & 0xFFFF0000ull) >> 16;
5682 unsigned minor = (version & 0x0000FF00ull) >> 8;
5683 unsigned subminor = (version & 0x000000FFull);
5684 return llvm::VersionTuple(major, minor, subminor);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005685 }
5686 }
Pavel Labath2272c482018-06-18 15:02:23 +00005687 return llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005688}
5689
Pavel Labathf760f5a2019-01-03 10:37:19 +00005690ArchSpec ObjectFileMachO::GetArchitecture() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005691 ModuleSP module_sp(GetModule());
Pavel Labathf760f5a2019-01-03 10:37:19 +00005692 ArchSpec arch;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005693 if (module_sp) {
5694 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Pavel Labathf760f5a2019-01-03 10:37:19 +00005695
Kate Stoneb9c1b512016-09-06 20:57:50 +00005696 return GetArchitecture(m_header, m_data,
Pavel Labathf760f5a2019-01-03 10:37:19 +00005697 MachHeaderSizeFromMagic(m_header.magic));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005698 }
Pavel Labathf760f5a2019-01-03 10:37:19 +00005699 return arch;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005700}
5701
Jason Molenda07580ff2018-05-04 00:59:37 +00005702void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process, addr_t &base_addr, UUID &uuid) {
5703 uuid.Clear();
5704 base_addr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005705 if (process && process->GetDynamicLoader()) {
5706 DynamicLoader *dl = process->GetDynamicLoader();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005707 LazyBool using_shared_cache;
5708 LazyBool private_shared_cache;
Jason Molenda07580ff2018-05-04 00:59:37 +00005709 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005710 private_shared_cache);
5711 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005712 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005713 if (log)
Jason Molenda07580ff2018-05-04 00:59:37 +00005714 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 +00005715}
5716
Jason Molenda07580ff2018-05-04 00:59:37 +00005717// From dyld SPI header dyld_process_info.h
5718typedef void *dyld_process_info;
5719struct lldb_copy__dyld_process_cache_info {
5720 uuid_t cacheUUID; // UUID of cache used by process
5721 uint64_t cacheBaseAddress; // load address of dyld shared cache
5722 bool noCache; // process is running without a dyld cache
5723 bool privateCache; // process is using a private copy of its dyld cache
5724};
5725
5726// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with llvm
5727// enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile errors.
5728// So we need to use the actual underlying types of task_t and kern_return_t
5729// below.
5730extern "C" unsigned int /*task_t*/ mach_task_self();
5731
5732void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5733 uuid.Clear();
5734 base_addr = LLDB_INVALID_ADDRESS;
5735
Kate Stoneb9c1b512016-09-06 20:57:50 +00005736#if defined(__APPLE__) && \
5737 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5738 uint8_t *(*dyld_get_all_image_infos)(void);
5739 dyld_get_all_image_infos =
5740 (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5741 if (dyld_get_all_image_infos) {
5742 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5743 if (dyld_all_image_infos_address) {
5744 uint32_t *version = (uint32_t *)
5745 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5746 if (*version >= 13) {
5747 uuid_t *sharedCacheUUID_address = 0;
5748 int wordsize = sizeof(uint8_t *);
5749 if (wordsize == 8) {
5750 sharedCacheUUID_address =
5751 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5752 160); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005753 if (*version >= 15)
5754 base_addr = *(uint64_t *) ((uint8_t *) dyld_all_image_infos_address
5755 + 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +00005756 } else {
5757 sharedCacheUUID_address =
5758 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5759 84); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005760 if (*version >= 15) {
5761 base_addr = 0;
5762 base_addr = *(uint32_t *) ((uint8_t *) dyld_all_image_infos_address
5763 + 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5764 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005765 }
Pavel Labath2f93fd12018-06-26 15:12:20 +00005766 uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005767 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005768 }
Jason Molendafd443e92018-02-07 01:28:29 +00005769 } else {
5770 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
Jason Molenda07580ff2018-05-04 00:59:37 +00005771 dyld_process_info (*dyld_process_info_create)(unsigned int /* task_t */ task, uint64_t timestamp, unsigned int /*kern_return_t*/ *kernelError);
5772 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5773 void (*dyld_process_info_release)(dyld_process_info info);
5774
5775 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, unsigned int /*kern_return_t*/ *))
5776 dlsym (RTLD_DEFAULT, "_dyld_process_info_create");
5777 dyld_process_info_get_cache = (void (*)(void *, void *))
5778 dlsym (RTLD_DEFAULT, "_dyld_process_info_get_cache");
5779 dyld_process_info_release = (void (*)(void *))
5780 dlsym (RTLD_DEFAULT, "_dyld_process_info_release");
5781
5782 if (dyld_process_info_create && dyld_process_info_get_cache) {
5783 unsigned int /*kern_return_t */ kern_ret;
5784 dyld_process_info process_info = dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5785 if (process_info) {
5786 struct lldb_copy__dyld_process_cache_info sc_info;
5787 memset (&sc_info, 0, sizeof (struct lldb_copy__dyld_process_cache_info));
5788 dyld_process_info_get_cache (process_info, &sc_info);
5789 if (sc_info.cacheBaseAddress != 0) {
5790 base_addr = sc_info.cacheBaseAddress;
Pavel Labath2f93fd12018-06-26 15:12:20 +00005791 uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
Jason Molenda07580ff2018-05-04 00:59:37 +00005792 }
5793 dyld_process_info_release (process_info);
5794 }
Jason Molendafd443e92018-02-07 01:28:29 +00005795 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005796 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005797 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005798 if (log && uuid.IsValid())
Jason Molenda07580ff2018-05-04 00:59:37 +00005799 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 +00005800#endif
Jason Molenda0e0954c2013-04-16 06:24:42 +00005801}
5802
Pavel Labath2272c482018-06-18 15:02:23 +00005803llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5804 if (!m_min_os_version) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005805 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labath2272c482018-06-18 15:02:23 +00005806 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005807 const lldb::offset_t load_cmd_offset = offset;
5808
5809 version_min_command lc;
5810 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5811 break;
5812 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5813 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5814 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5815 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5816 if (m_data.GetU32(&offset, &lc.version,
5817 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5818 const uint32_t xxxx = lc.version >> 16;
5819 const uint32_t yy = (lc.version >> 8) & 0xffu;
5820 const uint32_t zz = lc.version & 0xffu;
5821 if (xxxx) {
Pavel Labath2272c482018-06-18 15:02:23 +00005822 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5823 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005824 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005825 }
5826 } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5827 // struct build_version_command {
5828 // uint32_t cmd; /* LC_BUILD_VERSION */
5829 // uint32_t cmdsize; /* sizeof(struct build_version_command) plus */
5830 // /* ntools * sizeof(struct build_tool_version) */
5831 // uint32_t platform; /* platform */
5832 // uint32_t minos; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5833 // uint32_t sdk; /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5834 // uint32_t ntools; /* number of tool entries following this */
5835 // };
5836
5837 offset += 4; // skip platform
5838 uint32_t minos = m_data.GetU32(&offset);
5839
5840 const uint32_t xxxx = minos >> 16;
5841 const uint32_t yy = (minos >> 8) & 0xffu;
5842 const uint32_t zz = minos & 0xffu;
5843 if (xxxx) {
5844 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5845 break;
Greg Clayton9b234982013-10-24 22:54:08 +00005846 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005847 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005848
Kate Stoneb9c1b512016-09-06 20:57:50 +00005849 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005850 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005851
Pavel Labath2272c482018-06-18 15:02:23 +00005852 if (!m_min_os_version) {
5853 // Set version to an empty value so we don't keep trying to
5854 m_min_os_version = llvm::VersionTuple();
Greg Clayton9b234982013-10-24 22:54:08 +00005855 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005856 }
5857
Pavel Labath2272c482018-06-18 15:02:23 +00005858 return *m_min_os_version;
Greg Clayton9b234982013-10-24 22:54:08 +00005859}
5860
Kate Stoneb9c1b512016-09-06 20:57:50 +00005861uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions,
5862 uint32_t num_versions) {
5863 if (m_sdk_versions.empty()) {
5864 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5865 bool success = false;
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005866 for (uint32_t i = 0; !success && i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005867 const lldb::offset_t load_cmd_offset = offset;
5868
5869 version_min_command lc;
5870 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5871 break;
5872 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5873 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5874 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5875 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5876 if (m_data.GetU32(&offset, &lc.version,
5877 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5878 const uint32_t xxxx = lc.sdk >> 16;
5879 const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5880 const uint32_t zz = lc.sdk & 0xffu;
5881 if (xxxx) {
5882 m_sdk_versions.push_back(xxxx);
5883 m_sdk_versions.push_back(yy);
5884 m_sdk_versions.push_back(zz);
Jason Molenda32a91422018-06-25 23:45:39 +00005885 success = true;
5886 } else {
5887 GetModule()->ReportWarning(
5888 "minimum OS version load command with invalid (0) version found.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005889 }
Greg Clayton9b234982013-10-24 22:54:08 +00005890 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005891 }
5892 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005893 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005894
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005895 if (!success) {
5896 offset = MachHeaderSizeFromMagic(m_header.magic);
5897 for (uint32_t i = 0; !success && i < m_header.ncmds; ++i) {
5898 const lldb::offset_t load_cmd_offset = offset;
Jason Molenda32762fd2018-10-11 00:28:35 +00005899
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005900 version_min_command lc;
5901 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5902 break;
5903 if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5904 // struct build_version_command {
5905 // uint32_t cmd; /* LC_BUILD_VERSION */
5906 // uint32_t cmdsize; /* sizeof(struct
5907 // build_version_command) plus */
5908 // /* ntools * sizeof(struct
5909 // build_tool_version) */
5910 // uint32_t platform; /* platform */
5911 // uint32_t minos; /* X.Y.Z is encoded in nibbles
5912 // xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded
5913 // in nibbles xxxx.yy.zz */ uint32_t ntools; /* number
5914 // of tool entries following this */
5915 // };
Jason Molenda32762fd2018-10-11 00:28:35 +00005916
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005917 offset += 4; // skip platform
5918 uint32_t minos = m_data.GetU32(&offset);
Jason Molenda32762fd2018-10-11 00:28:35 +00005919
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005920 const uint32_t xxxx = minos >> 16;
5921 const uint32_t yy = (minos >> 8) & 0xffu;
5922 const uint32_t zz = minos & 0xffu;
5923 if (xxxx) {
5924 m_sdk_versions.push_back(xxxx);
5925 m_sdk_versions.push_back(yy);
5926 m_sdk_versions.push_back(zz);
5927 success = true;
5928 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005929 }
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005930 offset = load_cmd_offset + lc.cmdsize;
5931 }
Jason Molenda32762fd2018-10-11 00:28:35 +00005932 }
5933
Jonas Devliegherea6682a42018-12-15 00:15:33 +00005934 if (!success) {
Jason Molenda32a91422018-06-25 23:45:39 +00005935 // Push an invalid value so we don't try to find
5936 // the version # again on the next call to this
5937 // method.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005938 m_sdk_versions.push_back(UINT32_MAX);
Greg Clayton9b234982013-10-24 22:54:08 +00005939 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005940 }
5941
Jason Molenda32a91422018-06-25 23:45:39 +00005942 // Legitimate version numbers will have 3 entries pushed
5943 // on to m_sdk_versions. If we only have one value, it's
5944 // the sentinel value indicating that this object file
5945 // does not have a valid minimum os version #.
5946 if (m_sdk_versions.size() > 1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005947 if (versions != NULL && num_versions > 0) {
5948 for (size_t i = 0; i < num_versions; ++i) {
5949 if (i < m_sdk_versions.size())
5950 versions[i] = m_sdk_versions[i];
5951 else
5952 versions[i] = 0;
5953 }
5954 }
5955 return m_sdk_versions.size();
5956 }
5957 // Call the superclasses version that will empty out the data
5958 return ObjectFile::GetSDKVersion(versions, num_versions);
Greg Clayton9b234982013-10-24 22:54:08 +00005959}
5960
Kate Stoneb9c1b512016-09-06 20:57:50 +00005961bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5962 return m_header.filetype == llvm::MachO::MH_DYLINKER;
Greg Clayton08928f32015-02-05 02:01:34 +00005963}
5964
Kate Stoneb9c1b512016-09-06 20:57:50 +00005965bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5966 return m_allow_assembly_emulation_unwind_plans;
Jason Molenda955dcf22016-05-04 03:09:40 +00005967}
5968
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005969//------------------------------------------------------------------
5970// PluginInterface protocol
5971//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00005972lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5973 return GetPluginNameStatic();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005974}
5975
Kate Stoneb9c1b512016-09-06 20:57:50 +00005976uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005977
Kate Stoneb9c1b512016-09-06 20:57:50 +00005978Section *ObjectFileMachO::GetMachHeaderSection() {
Adrian Prantl05097242018-04-30 16:49:04 +00005979 // Find the first address of the mach header which is the first non-zero file
5980 // sized section whose file offset is zero. This is the base file address of
5981 // the mach-o file which can be subtracted from the vmaddr of the other
Kate Stoneb9c1b512016-09-06 20:57:50 +00005982 // segments found in memory and added to the load address
5983 ModuleSP module_sp = GetModule();
Greg Clayton57577c02018-12-21 17:04:18 +00005984 if (!module_sp)
5985 return nullptr;
5986 SectionList *section_list = GetSectionList();
5987 if (!section_list)
5988 return nullptr;
5989 const size_t num_sections = section_list->GetSize();
5990 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5991 Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5992 if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
5993 return section;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005994 }
5995 return nullptr;
Greg Clayton07347372015-06-08 21:53:11 +00005996}
5997
Greg Clayton57577c02018-12-21 17:04:18 +00005998bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
5999 if (!section)
6000 return false;
6001 const bool is_dsym = (m_header.filetype == MH_DSYM);
6002 if (section->GetFileSize() == 0 && !is_dsym)
6003 return false;
6004 if (section->IsThreadSpecific())
6005 return false;
6006 if (GetModule().get() != section->GetModule().get())
6007 return false;
6008 // Be careful with __LINKEDIT and __DWARF segments
6009 if (section->GetName() == GetSegmentNameLINKEDIT() ||
6010 section->GetName() == GetSegmentNameDWARF()) {
6011 // Only map __LINKEDIT and __DWARF if we have an in memory image and
6012 // this isn't a kernel binary like a kext or mach_kernel.
6013 const bool is_memory_image = (bool)m_process_wp.lock();
6014 const Strata strata = GetStrata();
6015 if (is_memory_image == false || strata == eStrataKernel)
6016 return false;
6017 }
6018 return true;
6019}
6020
Kate Stoneb9c1b512016-09-06 20:57:50 +00006021lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
Greg Clayton57577c02018-12-21 17:04:18 +00006022 lldb::addr_t header_load_address, const Section *header_section,
Kate Stoneb9c1b512016-09-06 20:57:50 +00006023 const Section *section) {
6024 ModuleSP module_sp = GetModule();
Greg Clayton57577c02018-12-21 17:04:18 +00006025 if (module_sp && header_section && section &&
6026 header_load_address != LLDB_INVALID_ADDRESS) {
6027 lldb::addr_t file_addr = header_section->GetFileAddress();
6028 if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
6029 return section->GetFileAddress() - file_addr + header_load_address;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006030 }
6031 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00006032}
6033
Kate Stoneb9c1b512016-09-06 20:57:50 +00006034bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
6035 bool value_is_offset) {
6036 ModuleSP module_sp = GetModule();
6037 if (module_sp) {
6038 size_t num_loaded_sections = 0;
6039 SectionList *section_list = GetSectionList();
6040 if (section_list) {
6041 const size_t num_sections = section_list->GetSize();
Greg Clayton7524e092014-02-06 20:10:16 +00006042
Kate Stoneb9c1b512016-09-06 20:57:50 +00006043 if (value_is_offset) {
6044 // "value" is an offset to apply to each top level segment
6045 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +00006046 // Iterate through the object file sections to find all of the
6047 // sections that size on disk (to avoid __PAGEZERO) and load them
Kate Stoneb9c1b512016-09-06 20:57:50 +00006048 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
Greg Clayton57577c02018-12-21 17:04:18 +00006049 if (SectionIsLoadable(section_sp.get()))
Kate Stoneb9c1b512016-09-06 20:57:50 +00006050 if (target.GetSectionLoadList().SetSectionLoadAddress(
6051 section_sp, section_sp->GetFileAddress() + value))
6052 ++num_loaded_sections;
Greg Clayton7524e092014-02-06 20:10:16 +00006053 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006054 } else {
6055 // "value" is the new base address of the mach_header, adjust each
6056 // section accordingly
6057
6058 Section *mach_header_section = GetMachHeaderSection();
6059 if (mach_header_section) {
6060 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6061 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6062
6063 lldb::addr_t section_load_addr =
6064 CalculateSectionLoadAddressForMemoryImage(
6065 value, mach_header_section, section_sp.get());
6066 if (section_load_addr != LLDB_INVALID_ADDRESS) {
6067 if (target.GetSectionLoadList().SetSectionLoadAddress(
6068 section_sp, section_load_addr))
6069 ++num_loaded_sections;
6070 }
6071 }
6072 }
6073 }
Greg Clayton7524e092014-02-06 20:10:16 +00006074 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006075 return num_loaded_sections > 0;
6076 }
6077 return false;
Greg Clayton7524e092014-02-06 20:10:16 +00006078}
6079
Kate Stoneb9c1b512016-09-06 20:57:50 +00006080bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00006081 const FileSpec &outfile, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00006082 if (process_sp) {
6083 Target &target = process_sp->GetTarget();
6084 const ArchSpec target_arch = target.GetArchitecture();
6085 const llvm::Triple &target_triple = target_arch.GetTriple();
6086 if (target_triple.getVendor() == llvm::Triple::Apple &&
6087 (target_triple.getOS() == llvm::Triple::MacOSX ||
6088 target_triple.getOS() == llvm::Triple::IOS ||
6089 target_triple.getOS() == llvm::Triple::WatchOS ||
6090 target_triple.getOS() == llvm::Triple::TvOS)) {
Jason Molenda32762fd2018-10-11 00:28:35 +00006091 // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00006092 bool make_core = false;
6093 switch (target_arch.GetMachine()) {
6094 case llvm::Triple::aarch64:
6095 case llvm::Triple::arm:
6096 case llvm::Triple::thumb:
6097 case llvm::Triple::x86:
6098 case llvm::Triple::x86_64:
6099 make_core = true;
6100 break;
6101 default:
6102 error.SetErrorStringWithFormat("unsupported core architecture: %s",
6103 target_triple.str().c_str());
6104 break;
6105 }
6106
6107 if (make_core) {
6108 std::vector<segment_command_64> segment_load_commands;
6109 // uint32_t range_info_idx = 0;
6110 MemoryRegionInfo range_info;
Zachary Turner97206d52017-05-12 04:51:55 +00006111 Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006112 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6113 const ByteOrder byte_order = target_arch.GetByteOrder();
6114 if (range_error.Success()) {
6115 while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
6116 const addr_t addr = range_info.GetRange().GetRangeBase();
6117 const addr_t size = range_info.GetRange().GetByteSize();
6118
6119 if (size == 0)
6120 break;
6121
6122 // Calculate correct protections
6123 uint32_t prot = 0;
6124 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
6125 prot |= VM_PROT_READ;
6126 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
6127 prot |= VM_PROT_WRITE;
6128 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
6129 prot |= VM_PROT_EXECUTE;
6130
6131 // printf ("[%3u] [0x%16.16" PRIx64 " -
6132 // 0x%16.16" PRIx64 ") %c%c%c\n",
6133 // range_info_idx,
6134 // addr,
6135 // size,
6136 // (prot & VM_PROT_READ ) ? 'r' :
6137 // '-',
6138 // (prot & VM_PROT_WRITE ) ? 'w' :
6139 // '-',
6140 // (prot & VM_PROT_EXECUTE) ? 'x' :
6141 // '-');
6142
6143 if (prot != 0) {
6144 uint32_t cmd_type = LC_SEGMENT_64;
6145 uint32_t segment_size = sizeof(segment_command_64);
6146 if (addr_byte_size == 4) {
6147 cmd_type = LC_SEGMENT;
6148 segment_size = sizeof(segment_command);
6149 }
6150 segment_command_64 segment = {
6151 cmd_type, // uint32_t cmd;
6152 segment_size, // uint32_t cmdsize;
6153 {0}, // char segname[16];
6154 addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
6155 size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
6156 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
6157 size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
6158 prot, // uint32_t maxprot;
6159 prot, // uint32_t initprot;
6160 0, // uint32_t nsects;
6161 0}; // uint32_t flags;
6162 segment_load_commands.push_back(segment);
6163 } else {
6164 // No protections and a size of 1 used to be returned from old
6165 // debugservers when we asked about a region that was past the
6166 // last memory region and it indicates the end...
6167 if (size == 1)
6168 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006169 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006170
Kate Stoneb9c1b512016-09-06 20:57:50 +00006171 range_error = process_sp->GetMemoryRegionInfo(
6172 range_info.GetRange().GetRangeEnd(), range_info);
6173 if (range_error.Fail())
6174 break;
6175 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006176
Kate Stoneb9c1b512016-09-06 20:57:50 +00006177 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
Greg Claytona2715cf2014-06-13 00:54:12 +00006178
Kate Stoneb9c1b512016-09-06 20:57:50 +00006179 mach_header_64 mach_header;
6180 if (addr_byte_size == 8) {
6181 mach_header.magic = MH_MAGIC_64;
6182 } else {
6183 mach_header.magic = MH_MAGIC;
6184 }
6185 mach_header.cputype = target_arch.GetMachOCPUType();
6186 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6187 mach_header.filetype = MH_CORE;
6188 mach_header.ncmds = segment_load_commands.size();
6189 mach_header.flags = 0;
6190 mach_header.reserved = 0;
6191 ThreadList &thread_list = process_sp->GetThreadList();
6192 const uint32_t num_threads = thread_list.GetSize();
Greg Claytona2715cf2014-06-13 00:54:12 +00006193
Adrian Prantl05097242018-04-30 16:49:04 +00006194 // Make an array of LC_THREAD data items. Each one contains the
6195 // contents of the LC_THREAD load command. The data doesn't contain
6196 // the load command + load command size, we will add the load command
6197 // and load command size as we emit the data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006198 std::vector<StreamString> LC_THREAD_datas(num_threads);
6199 for (auto &LC_THREAD_data : LC_THREAD_datas) {
6200 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6201 LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6202 LC_THREAD_data.SetByteOrder(byte_order);
6203 }
6204 for (uint32_t thread_idx = 0; thread_idx < num_threads;
6205 ++thread_idx) {
6206 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6207 if (thread_sp) {
6208 switch (mach_header.cputype) {
6209 case llvm::MachO::CPU_TYPE_ARM64:
6210 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6211 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6212 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006213
Kate Stoneb9c1b512016-09-06 20:57:50 +00006214 case llvm::MachO::CPU_TYPE_ARM:
6215 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6216 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6217 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006218
Kate Stoneb9c1b512016-09-06 20:57:50 +00006219 case llvm::MachO::CPU_TYPE_I386:
6220 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6221 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6222 break;
Jason Molenda22952582014-11-12 01:11:36 +00006223
Kate Stoneb9c1b512016-09-06 20:57:50 +00006224 case llvm::MachO::CPU_TYPE_X86_64:
6225 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6226 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6227 break;
6228 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006229 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006230 }
6231
6232 // The size of the load command is the size of the segments...
6233 if (addr_byte_size == 8) {
6234 mach_header.sizeofcmds = segment_load_commands.size() *
6235 sizeof(struct segment_command_64);
6236 } else {
6237 mach_header.sizeofcmds =
6238 segment_load_commands.size() * sizeof(struct segment_command);
6239 }
6240
6241 // and the size of all LC_THREAD load command
6242 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6243 ++mach_header.ncmds;
6244 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6245 }
6246
6247 printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x "
6248 "0x%8.8x 0x%8.8x\n",
6249 mach_header.magic, mach_header.cputype, mach_header.cpusubtype,
6250 mach_header.filetype, mach_header.ncmds,
6251 mach_header.sizeofcmds, mach_header.flags,
6252 mach_header.reserved);
6253
6254 // Write the mach header
6255 buffer.PutHex32(mach_header.magic);
6256 buffer.PutHex32(mach_header.cputype);
6257 buffer.PutHex32(mach_header.cpusubtype);
6258 buffer.PutHex32(mach_header.filetype);
6259 buffer.PutHex32(mach_header.ncmds);
6260 buffer.PutHex32(mach_header.sizeofcmds);
6261 buffer.PutHex32(mach_header.flags);
6262 if (addr_byte_size == 8) {
6263 buffer.PutHex32(mach_header.reserved);
6264 }
6265
6266 // Skip the mach header and all load commands and align to the next
6267 // 0x1000 byte boundary
6268 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6269 if (file_offset & 0x00000fff) {
6270 file_offset += 0x00001000ull;
6271 file_offset &= (~0x00001000ull + 1);
6272 }
6273
6274 for (auto &segment : segment_load_commands) {
6275 segment.fileoff = file_offset;
6276 file_offset += segment.filesize;
6277 }
6278
6279 // Write out all of the LC_THREAD load commands
6280 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6281 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6282 buffer.PutHex32(LC_THREAD);
6283 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
Zachary Turnerc1564272016-11-16 21:15:24 +00006284 buffer.Write(LC_THREAD_data.GetString().data(),
6285 LC_THREAD_data_size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006286 }
6287
6288 // Write out all of the segment load commands
6289 for (const auto &segment : segment_load_commands) {
6290 printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6291 ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6292 ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6293 segment.cmd, segment.cmdsize, segment.vmaddr,
6294 segment.vmaddr + segment.vmsize, segment.fileoff,
6295 segment.filesize, segment.maxprot, segment.initprot,
6296 segment.nsects, segment.flags);
6297
6298 buffer.PutHex32(segment.cmd);
6299 buffer.PutHex32(segment.cmdsize);
6300 buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6301 if (addr_byte_size == 8) {
6302 buffer.PutHex64(segment.vmaddr);
6303 buffer.PutHex64(segment.vmsize);
6304 buffer.PutHex64(segment.fileoff);
6305 buffer.PutHex64(segment.filesize);
6306 } else {
6307 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6308 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6309 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6310 buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6311 }
6312 buffer.PutHex32(segment.maxprot);
6313 buffer.PutHex32(segment.initprot);
6314 buffer.PutHex32(segment.nsects);
6315 buffer.PutHex32(segment.flags);
6316 }
6317
6318 File core_file;
6319 std::string core_file_path(outfile.GetPath());
Jonas Devlieghere50bc1ed2018-11-02 22:34:51 +00006320 error = FileSystem::Instance().Open(core_file, outfile,
6321 File::eOpenOptionWrite |
6322 File::eOpenOptionTruncate |
6323 File::eOpenOptionCanCreate);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006324 if (error.Success()) {
6325 // Read 1 page at a time
6326 uint8_t bytes[0x1000];
6327 // Write the mach header and load commands out to the core file
6328 size_t bytes_written = buffer.GetString().size();
6329 error = core_file.Write(buffer.GetString().data(), bytes_written);
6330 if (error.Success()) {
6331 // Now write the file data for all memory segments in the process
6332 for (const auto &segment : segment_load_commands) {
6333 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6334 error.SetErrorStringWithFormat(
6335 "unable to seek to offset 0x%" PRIx64 " in '%s'",
6336 segment.fileoff, core_file_path.c_str());
6337 break;
6338 }
6339
6340 printf("Saving %" PRId64
6341 " bytes of data for memory region at 0x%" PRIx64 "\n",
6342 segment.vmsize, segment.vmaddr);
6343 addr_t bytes_left = segment.vmsize;
6344 addr_t addr = segment.vmaddr;
Zachary Turner97206d52017-05-12 04:51:55 +00006345 Status memory_read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006346 while (bytes_left > 0 && error.Success()) {
6347 const size_t bytes_to_read =
6348 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6349 const size_t bytes_read = process_sp->ReadMemory(
6350 addr, bytes, bytes_to_read, memory_read_error);
6351 if (bytes_read == bytes_to_read) {
6352 size_t bytes_written = bytes_read;
6353 error = core_file.Write(bytes, bytes_written);
6354 bytes_left -= bytes_read;
6355 addr += bytes_read;
6356 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00006357 // Some pages within regions are not readable, those should
6358 // be zero filled
Kate Stoneb9c1b512016-09-06 20:57:50 +00006359 memset(bytes, 0, bytes_to_read);
6360 size_t bytes_written = bytes_to_read;
6361 error = core_file.Write(bytes, bytes_written);
6362 bytes_left -= bytes_to_read;
6363 addr += bytes_to_read;
6364 }
6365 }
6366 }
6367 }
6368 }
6369 } else {
6370 error.SetErrorString(
6371 "process doesn't support getting memory region info");
Greg Claytona2715cf2014-06-13 00:54:12 +00006372 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006373 }
6374 return true; // This is the right plug to handle saving core files for
6375 // this process
Greg Claytona2715cf2014-06-13 00:54:12 +00006376 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006377 }
6378 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00006379}