blob: 5365dbf880e2376175dbb5a5faae3470328de291 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- ObjectFileMachO.cpp -------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko8157a882015-10-23 16:56:07 +000010// C Includes
11// C++ Includes
12// Other libraries and framework includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000013#include "llvm/ADT/StringRef.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014
Eugene Zelenko8157a882015-10-23 16:56:07 +000015// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000016#include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
17#include "Plugins/Process/Utility/RegisterContextDarwin_arm64.h"
18#include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
19#include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
Jason Molendaf6ce26f2013-04-10 05:58:57 +000020#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Core/FileSpecList.h"
22#include "lldb/Core/Module.h"
Greg Claytonf4d6de62013-04-24 22:29:28 +000023#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
Greg Clayton1eac0c72012-04-24 03:06:13 +000025#include "lldb/Core/RangeMap.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000026#include "lldb/Core/RegisterValue.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Core/Section.h"
28#include "lldb/Core/StreamFile.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000029#include "lldb/Host/Host.h"
Jason Molenda5635f772013-03-21 03:36:01 +000030#include "lldb/Symbol/DWARFCallFrameInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031#include "lldb/Symbol/ObjectFile.h"
Jason Molenda13becd42016-07-29 00:18:39 +000032#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000033#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton26b47e22012-04-18 05:19:20 +000034#include "lldb/Target/Platform.h"
Greg Claytonc9660542012-02-05 02:38:54 +000035#include "lldb/Target/Process.h"
Greg Clayton7524e092014-02-06 20:10:16 +000036#include "lldb/Target/SectionLoadList.h"
Greg Clayton26b47e22012-04-18 05:19:20 +000037#include "lldb/Target/Target.h"
Greg Claytona2715cf2014-06-13 00:54:12 +000038#include "lldb/Target/Thread.h"
39#include "lldb/Target/ThreadList.h"
Pavel Labath5f19b902017-11-13 16:16:33 +000040#include "lldb/Utility/ArchSpec.h"
Pavel Labath50251fc2017-12-21 10:54:30 +000041#include "lldb/Utility/DataBuffer.h"
Zachary Turner5713a052017-03-22 18:40:07 +000042#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000043#include "lldb/Utility/Log.h"
Zachary Turner97206d52017-05-12 04:51:55 +000044#include "lldb/Utility/Status.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000045#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000046#include "lldb/Utility/Timer.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000047#include "lldb/Utility/UUID.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048
Jim Ingham46d005d2014-04-02 22:53:21 +000049#include "lldb/Utility/SafeMachO.h"
50
Zachary Turner3f4a4b32017-02-24 18:56:49 +000051#include "llvm/Support/MemoryBuffer.h"
52
Jim Ingham46d005d2014-04-02 22:53:21 +000053#include "ObjectFileMachO.h"
54
Kate Stoneb9c1b512016-09-06 20:57:50 +000055#if defined(__APPLE__) && \
56 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Jason Molenda0e0954c2013-04-16 06:24:42 +000057// GetLLDBSharedCacheUUID() needs to call dlsym()
58#include <dlfcn.h>
59#endif
60
Daniel Maleaffeb4b62013-04-17 19:24:22 +000061#ifndef __APPLE__
62#include "Utility/UuidCompatibility.h"
Jason Molenda9b7fcdc2017-04-12 23:33:30 +000063#else
64#include <uuid/uuid.h>
Daniel Maleaffeb4b62013-04-17 19:24:22 +000065#endif
66
Greg Claytonb887da12015-07-16 19:50:57 +000067#define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068using namespace lldb;
69using namespace lldb_private;
Greg Claytone1a916a2010-07-21 22:12:05 +000070using namespace llvm::MachO;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071
Jason Molenda649a6072015-11-10 05:21:54 +000072// Some structure definitions needed for parsing the dyld shared cache files
73// found on iOS devices.
74
Kate Stoneb9c1b512016-09-06 20:57:50 +000075struct lldb_copy_dyld_cache_header_v1 {
76 char magic[16]; // e.g. "dyld_v0 i386", "dyld_v1 armv7", etc.
77 uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info
78 uint32_t mappingCount; // number of dyld_cache_mapping_info entries
79 uint32_t imagesOffset;
80 uint32_t imagesCount;
81 uint64_t dyldBaseAddress;
82 uint64_t codeSignatureOffset;
83 uint64_t codeSignatureSize;
84 uint64_t slideInfoOffset;
85 uint64_t slideInfoSize;
86 uint64_t localSymbolsOffset;
87 uint64_t localSymbolsSize;
88 uint8_t uuid[16]; // v1 and above, also recorded in dyld_all_image_infos v13
89 // and later
Jason Molenda649a6072015-11-10 05:21:54 +000090};
91
Kate Stoneb9c1b512016-09-06 20:57:50 +000092struct lldb_copy_dyld_cache_mapping_info {
93 uint64_t address;
94 uint64_t size;
95 uint64_t fileOffset;
96 uint32_t maxProt;
97 uint32_t initProt;
Jason Molenda649a6072015-11-10 05:21:54 +000098};
99
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100struct lldb_copy_dyld_cache_local_symbols_info {
101 uint32_t nlistOffset;
102 uint32_t nlistCount;
103 uint32_t stringsOffset;
104 uint32_t stringsSize;
105 uint32_t entriesOffset;
106 uint32_t entriesCount;
Jason Molenda649a6072015-11-10 05:21:54 +0000107};
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108struct lldb_copy_dyld_cache_local_symbols_entry {
109 uint32_t dylibOffset;
110 uint32_t nlistStartIndex;
111 uint32_t nlistCount;
Jason Molenda649a6072015-11-10 05:21:54 +0000112};
113
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000115public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread,
117 const DataExtractor &data)
118 : RegisterContextDarwin_x86_64(thread, 0) {
119 SetRegisterDataFrom_LC_THREAD(data);
120 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000121
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 void InvalidateAllRegisters() override {
123 // Do nothing... registers are always valid...
124 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
127 lldb::offset_t offset = 0;
128 SetError(GPRRegSet, Read, -1);
129 SetError(FPURegSet, Read, -1);
130 SetError(EXCRegSet, Read, -1);
131 bool done = false;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 while (!done) {
134 int flavor = data.GetU32(&offset);
135 if (flavor == 0)
136 done = true;
137 else {
138 uint32_t i;
139 uint32_t count = data.GetU32(&offset);
140 switch (flavor) {
141 case GPRRegSet:
142 for (i = 0; i < count; ++i)
143 (&gpr.rax)[i] = data.GetU64(&offset);
144 SetError(GPRRegSet, Read, 0);
145 done = true;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 break;
148 case FPURegSet:
149 // TODO: fill in FPU regs....
150 // SetError (FPURegSet, Read, -1);
151 done = true;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 break;
154 case EXCRegSet:
155 exc.trapno = data.GetU32(&offset);
156 exc.err = data.GetU32(&offset);
157 exc.faultvaddr = data.GetU64(&offset);
158 SetError(EXCRegSet, Read, 0);
159 done = true;
160 break;
161 case 7:
162 case 8:
163 case 9:
Adrian Prantl05097242018-04-30 16:49:04 +0000164 // fancy flavors that encapsulate of the above flavors...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +0000166
Greg Clayton9aae0a12013-05-15 19:52:08 +0000167 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168 done = true;
169 break;
170 }
171 }
Greg Clayton9aae0a12013-05-15 19:52:08 +0000172 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 }
174
175 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
176 const char *alt_name, size_t reg_byte_size,
177 Stream &data) {
178 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
179 if (reg_info == NULL)
180 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
181 if (reg_info) {
182 lldb_private::RegisterValue reg_value;
183 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
184 if (reg_info->byte_size >= reg_byte_size)
185 data.Write(reg_value.GetBytes(), reg_byte_size);
186 else {
187 data.Write(reg_value.GetBytes(), reg_info->byte_size);
188 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
189 ++i)
190 data.PutChar(0);
191 }
192 return reg_byte_size;
193 }
194 }
195 // Just write zeros if all else fails
196 for (size_t i = 0; i < reg_byte_size; ++i)
197 data.PutChar(0);
198 return reg_byte_size;
199 }
200
201 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
202 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
203 if (reg_ctx_sp) {
204 RegisterContext *reg_ctx = reg_ctx_sp.get();
205
206 data.PutHex32(GPRRegSet); // Flavor
207 data.PutHex32(GPRWordCount);
208 WriteRegister(reg_ctx, "rax", NULL, 8, data);
209 WriteRegister(reg_ctx, "rbx", NULL, 8, data);
210 WriteRegister(reg_ctx, "rcx", NULL, 8, data);
211 WriteRegister(reg_ctx, "rdx", NULL, 8, data);
212 WriteRegister(reg_ctx, "rdi", NULL, 8, data);
213 WriteRegister(reg_ctx, "rsi", NULL, 8, data);
214 WriteRegister(reg_ctx, "rbp", NULL, 8, data);
215 WriteRegister(reg_ctx, "rsp", NULL, 8, data);
216 WriteRegister(reg_ctx, "r8", NULL, 8, data);
217 WriteRegister(reg_ctx, "r9", NULL, 8, data);
218 WriteRegister(reg_ctx, "r10", NULL, 8, data);
219 WriteRegister(reg_ctx, "r11", NULL, 8, data);
220 WriteRegister(reg_ctx, "r12", NULL, 8, data);
221 WriteRegister(reg_ctx, "r13", NULL, 8, data);
222 WriteRegister(reg_ctx, "r14", NULL, 8, data);
223 WriteRegister(reg_ctx, "r15", NULL, 8, data);
224 WriteRegister(reg_ctx, "rip", NULL, 8, data);
225 WriteRegister(reg_ctx, "rflags", NULL, 8, data);
226 WriteRegister(reg_ctx, "cs", NULL, 8, data);
227 WriteRegister(reg_ctx, "fs", NULL, 8, data);
228 WriteRegister(reg_ctx, "gs", NULL, 8, data);
229
230 // // Write out the FPU registers
231 // const size_t fpu_byte_size = sizeof(FPU);
232 // size_t bytes_written = 0;
233 // data.PutHex32 (FPURegSet);
234 // data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
235 // bytes_written += data.PutHex32(0); // uint32_t pad[0]
236 // bytes_written += data.PutHex32(0); // uint32_t pad[1]
237 // bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
238 // data); // uint16_t fcw; // "fctrl"
239 // bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
240 // data); // uint16_t fsw; // "fstat"
241 // bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
242 // data); // uint8_t ftw; // "ftag"
243 // bytes_written += data.PutHex8 (0); // uint8_t pad1;
244 // bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
245 // data); // uint16_t fop; // "fop"
246 // bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
247 // data); // uint32_t ip; // "fioff"
248 // bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
249 // data); // uint16_t cs; // "fiseg"
250 // bytes_written += data.PutHex16 (0); // uint16_t pad2;
251 // bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
252 // data); // uint32_t dp; // "fooff"
253 // bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
254 // data); // uint16_t ds; // "foseg"
255 // bytes_written += data.PutHex16 (0); // uint16_t pad3;
256 // bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
257 // data); // uint32_t mxcsr;
258 // bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
259 // 4, data);// uint32_t mxcsrmask;
260 // bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
261 // sizeof(MMSReg), data);
262 // bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
263 // sizeof(MMSReg), data);
264 // bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
265 // sizeof(MMSReg), data);
266 // bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
267 // sizeof(MMSReg), data);
268 // bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
269 // sizeof(MMSReg), data);
270 // bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
271 // sizeof(MMSReg), data);
272 // bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
273 // sizeof(MMSReg), data);
274 // bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
275 // sizeof(MMSReg), data);
276 // bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
277 // sizeof(XMMReg), data);
278 // bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
279 // sizeof(XMMReg), data);
280 // bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
281 // sizeof(XMMReg), data);
282 // bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
283 // sizeof(XMMReg), data);
284 // bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
285 // sizeof(XMMReg), data);
286 // bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
287 // sizeof(XMMReg), data);
288 // bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
289 // sizeof(XMMReg), data);
290 // bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
291 // sizeof(XMMReg), data);
292 // bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
293 // sizeof(XMMReg), data);
294 // bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
295 // sizeof(XMMReg), data);
296 // bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
297 // sizeof(XMMReg), data);
298 // bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
299 // sizeof(XMMReg), data);
300 // bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
301 // sizeof(XMMReg), data);
302 // bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
303 // sizeof(XMMReg), data);
304 // bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
305 // sizeof(XMMReg), data);
306 // bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
307 // sizeof(XMMReg), data);
308 //
309 // // Fill rest with zeros
310 // for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
311 // i)
312 // data.PutChar(0);
313
314 // Write out the EXC registers
315 data.PutHex32(EXCRegSet);
316 data.PutHex32(EXCWordCount);
317 WriteRegister(reg_ctx, "trapno", NULL, 4, data);
318 WriteRegister(reg_ctx, "err", NULL, 4, data);
319 WriteRegister(reg_ctx, "faultvaddr", NULL, 8, data);
320 return true;
321 }
322 return false;
323 }
324
325protected:
326 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
327
328 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
329
330 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
331
332 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
Greg Clayton9aae0a12013-05-15 19:52:08 +0000333 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334 }
335
336 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
337 return 0;
338 }
339
340 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
341 return 0;
342 }
343};
344
345class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 {
346public:
347 RegisterContextDarwin_i386_Mach(lldb_private::Thread &thread,
348 const DataExtractor &data)
349 : RegisterContextDarwin_i386(thread, 0) {
350 SetRegisterDataFrom_LC_THREAD(data);
351 }
352
353 void InvalidateAllRegisters() override {
354 // Do nothing... registers are always valid...
355 }
356
357 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
358 lldb::offset_t offset = 0;
359 SetError(GPRRegSet, Read, -1);
360 SetError(FPURegSet, Read, -1);
361 SetError(EXCRegSet, Read, -1);
362 bool done = false;
363
364 while (!done) {
365 int flavor = data.GetU32(&offset);
366 if (flavor == 0)
367 done = true;
368 else {
369 uint32_t i;
370 uint32_t count = data.GetU32(&offset);
371 switch (flavor) {
372 case GPRRegSet:
373 for (i = 0; i < count; ++i)
374 (&gpr.eax)[i] = data.GetU32(&offset);
375 SetError(GPRRegSet, Read, 0);
376 done = true;
377
378 break;
379 case FPURegSet:
380 // TODO: fill in FPU regs....
381 // SetError (FPURegSet, Read, -1);
382 done = true;
383
384 break;
385 case EXCRegSet:
386 exc.trapno = data.GetU32(&offset);
387 exc.err = data.GetU32(&offset);
388 exc.faultvaddr = data.GetU32(&offset);
389 SetError(EXCRegSet, Read, 0);
390 done = true;
391 break;
392 case 7:
393 case 8:
394 case 9:
Adrian Prantl05097242018-04-30 16:49:04 +0000395 // fancy flavors that encapsulate of the above flavors...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 break;
397
398 default:
399 done = true;
400 break;
401 }
402 }
403 }
404 }
405
406 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
407 const char *alt_name, size_t reg_byte_size,
408 Stream &data) {
409 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
410 if (reg_info == NULL)
411 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
412 if (reg_info) {
413 lldb_private::RegisterValue reg_value;
414 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
415 if (reg_info->byte_size >= reg_byte_size)
416 data.Write(reg_value.GetBytes(), reg_byte_size);
417 else {
418 data.Write(reg_value.GetBytes(), reg_info->byte_size);
419 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
420 ++i)
421 data.PutChar(0);
422 }
423 return reg_byte_size;
424 }
425 }
426 // Just write zeros if all else fails
427 for (size_t i = 0; i < reg_byte_size; ++i)
428 data.PutChar(0);
429 return reg_byte_size;
430 }
431
432 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
433 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
434 if (reg_ctx_sp) {
435 RegisterContext *reg_ctx = reg_ctx_sp.get();
436
437 data.PutHex32(GPRRegSet); // Flavor
438 data.PutHex32(GPRWordCount);
439 WriteRegister(reg_ctx, "eax", NULL, 4, data);
440 WriteRegister(reg_ctx, "ebx", NULL, 4, data);
441 WriteRegister(reg_ctx, "ecx", NULL, 4, data);
442 WriteRegister(reg_ctx, "edx", NULL, 4, data);
443 WriteRegister(reg_ctx, "edi", NULL, 4, data);
444 WriteRegister(reg_ctx, "esi", NULL, 4, data);
445 WriteRegister(reg_ctx, "ebp", NULL, 4, data);
446 WriteRegister(reg_ctx, "esp", NULL, 4, data);
447 WriteRegister(reg_ctx, "ss", NULL, 4, data);
448 WriteRegister(reg_ctx, "eflags", NULL, 4, data);
449 WriteRegister(reg_ctx, "eip", NULL, 4, data);
450 WriteRegister(reg_ctx, "cs", NULL, 4, data);
451 WriteRegister(reg_ctx, "ds", NULL, 4, data);
452 WriteRegister(reg_ctx, "es", NULL, 4, data);
453 WriteRegister(reg_ctx, "fs", NULL, 4, data);
454 WriteRegister(reg_ctx, "gs", NULL, 4, data);
455
456 // Write out the EXC registers
457 data.PutHex32(EXCRegSet);
458 data.PutHex32(EXCWordCount);
459 WriteRegister(reg_ctx, "trapno", NULL, 4, data);
460 WriteRegister(reg_ctx, "err", NULL, 4, data);
461 WriteRegister(reg_ctx, "faultvaddr", NULL, 4, data);
462 return true;
463 }
464 return false;
465 }
466
467protected:
468 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
469
470 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
471
472 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
473
474 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
475 return 0;
476 }
477
478 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
479 return 0;
480 }
481
482 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
483 return 0;
484 }
485};
486
487class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm {
488public:
489 RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread,
490 const DataExtractor &data)
491 : RegisterContextDarwin_arm(thread, 0) {
492 SetRegisterDataFrom_LC_THREAD(data);
493 }
494
495 void InvalidateAllRegisters() override {
496 // Do nothing... registers are always valid...
497 }
498
499 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
500 lldb::offset_t offset = 0;
501 SetError(GPRRegSet, Read, -1);
502 SetError(FPURegSet, Read, -1);
503 SetError(EXCRegSet, Read, -1);
504 bool done = false;
505
506 while (!done) {
507 int flavor = data.GetU32(&offset);
508 uint32_t count = data.GetU32(&offset);
509 lldb::offset_t next_thread_state = offset + (count * 4);
510 switch (flavor) {
511 case GPRAltRegSet:
512 case GPRRegSet:
513 for (uint32_t i = 0; i < count; ++i) {
514 gpr.r[i] = data.GetU32(&offset);
515 }
516
517 // Note that gpr.cpsr is also copied by the above loop; this loop
Adrian Prantl05097242018-04-30 16:49:04 +0000518 // technically extends one element past the end of the gpr.r[] array.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519
520 SetError(GPRRegSet, Read, 0);
521 offset = next_thread_state;
522 break;
523
524 case FPURegSet: {
525 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats.s[0];
526 const int fpu_reg_buf_size = sizeof(fpu.floats);
527 if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
528 fpu_reg_buf) == fpu_reg_buf_size) {
529 offset += fpu_reg_buf_size;
530 fpu.fpscr = data.GetU32(&offset);
531 SetError(FPURegSet, Read, 0);
532 } else {
533 done = true;
534 }
535 }
536 offset = next_thread_state;
537 break;
538
539 case EXCRegSet:
540 if (count == 3) {
541 exc.exception = data.GetU32(&offset);
542 exc.fsr = data.GetU32(&offset);
543 exc.far = data.GetU32(&offset);
544 SetError(EXCRegSet, Read, 0);
545 }
546 done = true;
547 offset = next_thread_state;
548 break;
549
550 // Unknown register set flavor, stop trying to parse.
551 default:
552 done = true;
553 }
554 }
555 }
556
557 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
558 const char *alt_name, size_t reg_byte_size,
559 Stream &data) {
560 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
561 if (reg_info == NULL)
562 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
563 if (reg_info) {
564 lldb_private::RegisterValue reg_value;
565 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
566 if (reg_info->byte_size >= reg_byte_size)
567 data.Write(reg_value.GetBytes(), reg_byte_size);
568 else {
569 data.Write(reg_value.GetBytes(), reg_info->byte_size);
570 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
571 ++i)
572 data.PutChar(0);
573 }
574 return reg_byte_size;
575 }
576 }
577 // Just write zeros if all else fails
578 for (size_t i = 0; i < reg_byte_size; ++i)
579 data.PutChar(0);
580 return reg_byte_size;
581 }
582
583 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
584 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
585 if (reg_ctx_sp) {
586 RegisterContext *reg_ctx = reg_ctx_sp.get();
587
588 data.PutHex32(GPRRegSet); // Flavor
589 data.PutHex32(GPRWordCount);
590 WriteRegister(reg_ctx, "r0", NULL, 4, data);
591 WriteRegister(reg_ctx, "r1", NULL, 4, data);
592 WriteRegister(reg_ctx, "r2", NULL, 4, data);
593 WriteRegister(reg_ctx, "r3", NULL, 4, data);
594 WriteRegister(reg_ctx, "r4", NULL, 4, data);
595 WriteRegister(reg_ctx, "r5", NULL, 4, data);
596 WriteRegister(reg_ctx, "r6", NULL, 4, data);
597 WriteRegister(reg_ctx, "r7", NULL, 4, data);
598 WriteRegister(reg_ctx, "r8", NULL, 4, data);
599 WriteRegister(reg_ctx, "r9", NULL, 4, data);
600 WriteRegister(reg_ctx, "r10", NULL, 4, data);
601 WriteRegister(reg_ctx, "r11", NULL, 4, data);
602 WriteRegister(reg_ctx, "r12", NULL, 4, data);
603 WriteRegister(reg_ctx, "sp", NULL, 4, data);
604 WriteRegister(reg_ctx, "lr", NULL, 4, data);
605 WriteRegister(reg_ctx, "pc", NULL, 4, data);
606 WriteRegister(reg_ctx, "cpsr", NULL, 4, data);
607
608 // Write out the EXC registers
609 // data.PutHex32 (EXCRegSet);
610 // data.PutHex32 (EXCWordCount);
611 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
612 // WriteRegister (reg_ctx, "fsr", NULL, 4, data);
613 // WriteRegister (reg_ctx, "far", NULL, 4, data);
614 return true;
615 }
616 return false;
617 }
618
619protected:
620 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
621
622 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
623
624 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
625
626 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
627
628 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
629 return 0;
630 }
631
632 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
633 return 0;
634 }
635
636 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
637 return 0;
638 }
639
640 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
641 return -1;
642 }
643};
644
645class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 {
646public:
647 RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread,
648 const DataExtractor &data)
649 : RegisterContextDarwin_arm64(thread, 0) {
650 SetRegisterDataFrom_LC_THREAD(data);
651 }
652
653 void InvalidateAllRegisters() override {
654 // Do nothing... registers are always valid...
655 }
656
657 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
658 lldb::offset_t offset = 0;
659 SetError(GPRRegSet, Read, -1);
660 SetError(FPURegSet, Read, -1);
661 SetError(EXCRegSet, Read, -1);
662 bool done = false;
663 while (!done) {
664 int flavor = data.GetU32(&offset);
665 uint32_t count = data.GetU32(&offset);
666 lldb::offset_t next_thread_state = offset + (count * 4);
667 switch (flavor) {
668 case GPRRegSet:
669 // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
670 // 32-bit register)
671 if (count >= (33 * 2) + 1) {
Vedant Kumar6ba1db92016-11-07 02:39:37 +0000672 for (uint32_t i = 0; i < 29; ++i)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 gpr.x[i] = data.GetU64(&offset);
Vedant Kumar6ba1db92016-11-07 02:39:37 +0000674 gpr.fp = data.GetU64(&offset);
675 gpr.lr = data.GetU64(&offset);
676 gpr.sp = data.GetU64(&offset);
677 gpr.pc = data.GetU64(&offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 gpr.cpsr = data.GetU32(&offset);
679 SetError(GPRRegSet, Read, 0);
680 }
681 offset = next_thread_state;
682 break;
683 case FPURegSet: {
684 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
685 const int fpu_reg_buf_size = sizeof(fpu);
Jason Molenda4f346142017-11-16 00:50:29 +0000686 if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
688 fpu_reg_buf) == fpu_reg_buf_size) {
689 SetError(FPURegSet, Read, 0);
690 } else {
691 done = true;
692 }
693 }
694 offset = next_thread_state;
695 break;
696 case EXCRegSet:
697 if (count == 4) {
698 exc.far = data.GetU64(&offset);
699 exc.esr = data.GetU32(&offset);
700 exc.exception = data.GetU32(&offset);
701 SetError(EXCRegSet, Read, 0);
702 }
703 offset = next_thread_state;
704 break;
705 default:
706 done = true;
707 break;
708 }
709 }
710 }
711
712 static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
713 const char *alt_name, size_t reg_byte_size,
714 Stream &data) {
715 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
716 if (reg_info == NULL)
717 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
718 if (reg_info) {
719 lldb_private::RegisterValue reg_value;
720 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
721 if (reg_info->byte_size >= reg_byte_size)
722 data.Write(reg_value.GetBytes(), reg_byte_size);
723 else {
724 data.Write(reg_value.GetBytes(), reg_info->byte_size);
725 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
726 ++i)
727 data.PutChar(0);
728 }
729 return reg_byte_size;
730 }
731 }
732 // Just write zeros if all else fails
733 for (size_t i = 0; i < reg_byte_size; ++i)
734 data.PutChar(0);
735 return reg_byte_size;
736 }
737
738 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
739 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
740 if (reg_ctx_sp) {
741 RegisterContext *reg_ctx = reg_ctx_sp.get();
742
743 data.PutHex32(GPRRegSet); // Flavor
744 data.PutHex32(GPRWordCount);
745 WriteRegister(reg_ctx, "x0", NULL, 8, data);
746 WriteRegister(reg_ctx, "x1", NULL, 8, data);
747 WriteRegister(reg_ctx, "x2", NULL, 8, data);
748 WriteRegister(reg_ctx, "x3", NULL, 8, data);
749 WriteRegister(reg_ctx, "x4", NULL, 8, data);
750 WriteRegister(reg_ctx, "x5", NULL, 8, data);
751 WriteRegister(reg_ctx, "x6", NULL, 8, data);
752 WriteRegister(reg_ctx, "x7", NULL, 8, data);
753 WriteRegister(reg_ctx, "x8", NULL, 8, data);
754 WriteRegister(reg_ctx, "x9", NULL, 8, data);
755 WriteRegister(reg_ctx, "x10", NULL, 8, data);
756 WriteRegister(reg_ctx, "x11", NULL, 8, data);
757 WriteRegister(reg_ctx, "x12", NULL, 8, data);
758 WriteRegister(reg_ctx, "x13", NULL, 8, data);
759 WriteRegister(reg_ctx, "x14", NULL, 8, data);
760 WriteRegister(reg_ctx, "x15", NULL, 8, data);
761 WriteRegister(reg_ctx, "x16", NULL, 8, data);
762 WriteRegister(reg_ctx, "x17", NULL, 8, data);
763 WriteRegister(reg_ctx, "x18", NULL, 8, data);
764 WriteRegister(reg_ctx, "x19", NULL, 8, data);
765 WriteRegister(reg_ctx, "x20", NULL, 8, data);
766 WriteRegister(reg_ctx, "x21", NULL, 8, data);
767 WriteRegister(reg_ctx, "x22", NULL, 8, data);
768 WriteRegister(reg_ctx, "x23", NULL, 8, data);
769 WriteRegister(reg_ctx, "x24", NULL, 8, data);
770 WriteRegister(reg_ctx, "x25", NULL, 8, data);
771 WriteRegister(reg_ctx, "x26", NULL, 8, data);
772 WriteRegister(reg_ctx, "x27", NULL, 8, data);
773 WriteRegister(reg_ctx, "x28", NULL, 8, data);
774 WriteRegister(reg_ctx, "fp", NULL, 8, data);
775 WriteRegister(reg_ctx, "lr", NULL, 8, data);
776 WriteRegister(reg_ctx, "sp", NULL, 8, data);
777 WriteRegister(reg_ctx, "pc", NULL, 8, data);
778 WriteRegister(reg_ctx, "cpsr", NULL, 4, data);
779
780 // Write out the EXC registers
781 // data.PutHex32 (EXCRegSet);
782 // data.PutHex32 (EXCWordCount);
783 // WriteRegister (reg_ctx, "far", NULL, 8, data);
784 // WriteRegister (reg_ctx, "esr", NULL, 4, data);
785 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
786 return true;
787 }
788 return false;
789 }
790
791protected:
792 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
793
794 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
795
796 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
797
798 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
799
800 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
801 return 0;
802 }
803
804 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
805 return 0;
806 }
807
808 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
809 return 0;
810 }
811
812 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
813 return -1;
814 }
815};
816
817static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
818 switch (magic) {
819 case MH_MAGIC:
820 case MH_CIGAM:
821 return sizeof(struct mach_header);
822
823 case MH_MAGIC_64:
824 case MH_CIGAM_64:
825 return sizeof(struct mach_header_64);
826 break;
827
828 default:
829 break;
830 }
831 return 0;
Greg Clayton9aae0a12013-05-15 19:52:08 +0000832}
833
Greg Claytonded470d2011-03-19 01:12:21 +0000834#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836void ObjectFileMachO::Initialize() {
837 PluginManager::RegisterPlugin(
838 GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
839 CreateMemoryInstance, GetModuleSpecifications, SaveCore);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000840}
841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842void ObjectFileMachO::Terminate() {
843 PluginManager::UnregisterPlugin(CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000844}
845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846lldb_private::ConstString ObjectFileMachO::GetPluginNameStatic() {
847 static ConstString g_name("mach-o");
848 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000849}
850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851const char *ObjectFileMachO::GetPluginDescriptionStatic() {
852 return "Mach-o object file reader (32 and 64 bit)";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853}
854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855ObjectFile *ObjectFileMachO::CreateInstance(const lldb::ModuleSP &module_sp,
856 DataBufferSP &data_sp,
857 lldb::offset_t data_offset,
858 const FileSpec *file,
859 lldb::offset_t file_offset,
860 lldb::offset_t length) {
861 if (!data_sp) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000862 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000863 if (!data_sp)
864 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 data_offset = 0;
866 }
867
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000868 if (!ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
869 return nullptr;
870
871 // Update the data to contain the entire file if it doesn't already
872 if (data_sp->GetByteSize() < length) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000873 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000874 if (!data_sp)
875 return nullptr;
876 data_offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 }
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000878 auto objfile_ap = llvm::make_unique<ObjectFileMachO>(
879 module_sp, data_sp, data_offset, file, file_offset, length);
880 if (!objfile_ap || !objfile_ap->ParseHeader())
881 return nullptr;
882
883 return objfile_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884}
885
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886ObjectFile *ObjectFileMachO::CreateMemoryInstance(
887 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
888 const ProcessSP &process_sp, lldb::addr_t header_addr) {
889 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
890 std::unique_ptr<ObjectFile> objfile_ap(
891 new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
892 if (objfile_ap.get() && objfile_ap->ParseHeader())
893 return objfile_ap.release();
894 }
895 return NULL;
Greg Claytonc9660542012-02-05 02:38:54 +0000896}
897
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898size_t ObjectFileMachO::GetModuleSpecifications(
899 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
900 lldb::offset_t data_offset, lldb::offset_t file_offset,
901 lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
902 const size_t initial_count = specs.GetSize();
Oleksiy Vyalov63acdfd2015-03-10 01:15:28 +0000903
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
Greg Clayton44435ed2012-01-12 05:25:17 +0000905 DataExtractor data;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 data.SetData(data_sp);
907 llvm::MachO::mach_header header;
908 if (ParseHeader(data, &data_offset, header)) {
909 size_t header_and_load_cmds =
910 header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
911 if (header_and_load_cmds >= data_sp->GetByteSize()) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000912 data_sp = MapFileData(file, header_and_load_cmds, file_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913 data.SetData(data_sp);
914 data_offset = MachHeaderSizeFromMagic(header.magic);
915 }
916 if (data_sp) {
917 ModuleSpec spec;
918 spec.GetFileSpec() = file;
919 spec.SetObjectOffset(file_offset);
920 spec.SetObjectSize(length);
921
922 if (GetArchitecture(header, data, data_offset,
923 spec.GetArchitecture())) {
924 if (spec.GetArchitecture().IsValid()) {
925 GetUUID(header, data, data_offset, spec.GetUUID());
926 specs.Append(spec);
927 }
928 }
929 }
930 }
931 }
932 return specs.GetSize() - initial_count;
933}
934
935const ConstString &ObjectFileMachO::GetSegmentNameTEXT() {
936 static ConstString g_segment_name_TEXT("__TEXT");
937 return g_segment_name_TEXT;
938}
939
940const ConstString &ObjectFileMachO::GetSegmentNameDATA() {
941 static ConstString g_segment_name_DATA("__DATA");
942 return g_segment_name_DATA;
943}
944
945const ConstString &ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
946 static ConstString g_segment_name("__DATA_DIRTY");
947 return g_segment_name;
948}
949
950const ConstString &ObjectFileMachO::GetSegmentNameDATA_CONST() {
951 static ConstString g_segment_name("__DATA_CONST");
952 return g_segment_name;
953}
954
955const ConstString &ObjectFileMachO::GetSegmentNameOBJC() {
956 static ConstString g_segment_name_OBJC("__OBJC");
957 return g_segment_name_OBJC;
958}
959
960const ConstString &ObjectFileMachO::GetSegmentNameLINKEDIT() {
961 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
962 return g_section_name_LINKEDIT;
963}
964
965const ConstString &ObjectFileMachO::GetSectionNameEHFrame() {
966 static ConstString g_section_name_eh_frame("__eh_frame");
967 return g_section_name_eh_frame;
968}
969
970bool ObjectFileMachO::MagicBytesMatch(DataBufferSP &data_sp,
971 lldb::addr_t data_offset,
972 lldb::addr_t data_length) {
973 DataExtractor data;
974 data.SetData(data_sp, data_offset, data_length);
975 lldb::offset_t offset = 0;
976 uint32_t magic = data.GetU32(&offset);
977 return MachHeaderSizeFromMagic(magic) != 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978}
979
Greg Clayton5ce9c562013-02-06 17:22:03 +0000980ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 DataBufferSP &data_sp,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000982 lldb::offset_t data_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 const FileSpec *file,
Greg Clayton5ce9c562013-02-06 17:22:03 +0000984 lldb::offset_t file_offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 lldb::offset_t length)
986 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
987 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
988 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
989 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
990 ::memset(&m_header, 0, sizeof(m_header));
991 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000992}
993
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
995 lldb::DataBufferSP &header_data_sp,
996 const lldb::ProcessSP &process_sp,
997 lldb::addr_t header_addr)
998 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
999 m_mach_segments(), m_mach_sections(), m_entry_point_address(),
1000 m_thread_context_offsets(), m_thread_context_offsets_valid(false),
1001 m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
1002 ::memset(&m_header, 0, sizeof(m_header));
1003 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
Greg Claytonc9660542012-02-05 02:38:54 +00001004}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006bool ObjectFileMachO::ParseHeader(DataExtractor &data,
1007 lldb::offset_t *data_offset_ptr,
1008 llvm::MachO::mach_header &header) {
1009 data.SetByteOrder(endian::InlHostByteOrder());
1010 // Leave magic in the original byte order
1011 header.magic = data.GetU32(data_offset_ptr);
1012 bool can_parse = false;
1013 bool is_64_bit = false;
1014 switch (header.magic) {
1015 case MH_MAGIC:
1016 data.SetByteOrder(endian::InlHostByteOrder());
1017 data.SetAddressByteSize(4);
1018 can_parse = true;
1019 break;
1020
1021 case MH_MAGIC_64:
1022 data.SetByteOrder(endian::InlHostByteOrder());
1023 data.SetAddressByteSize(8);
1024 can_parse = true;
1025 is_64_bit = true;
1026 break;
1027
1028 case MH_CIGAM:
1029 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1030 ? eByteOrderLittle
1031 : eByteOrderBig);
1032 data.SetAddressByteSize(4);
1033 can_parse = true;
1034 break;
1035
1036 case MH_CIGAM_64:
1037 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1038 ? eByteOrderLittle
1039 : eByteOrderBig);
1040 data.SetAddressByteSize(8);
1041 is_64_bit = true;
1042 can_parse = true;
1043 break;
1044
1045 default:
1046 break;
1047 }
1048
1049 if (can_parse) {
1050 data.GetU32(data_offset_ptr, &header.cputype, 6);
1051 if (is_64_bit)
1052 *data_offset_ptr += 4;
1053 return true;
1054 } else {
1055 memset(&header, 0, sizeof(header));
1056 }
1057 return false;
1058}
1059
1060bool ObjectFileMachO::ParseHeader() {
1061 ModuleSP module_sp(GetModule());
1062 if (module_sp) {
1063 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Greg Claytonf4d6de62013-04-24 22:29:28 +00001064 bool can_parse = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 lldb::offset_t offset = 0;
1066 m_data.SetByteOrder(endian::InlHostByteOrder());
1067 // Leave magic in the original byte order
1068 m_header.magic = m_data.GetU32(&offset);
1069 switch (m_header.magic) {
1070 case MH_MAGIC:
1071 m_data.SetByteOrder(endian::InlHostByteOrder());
1072 m_data.SetAddressByteSize(4);
1073 can_parse = true;
1074 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 case MH_MAGIC_64:
1077 m_data.SetByteOrder(endian::InlHostByteOrder());
1078 m_data.SetAddressByteSize(8);
1079 can_parse = true;
1080 break;
Greg Claytona1743492012-03-13 23:14:29 +00001081
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 case MH_CIGAM:
1083 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1084 ? eByteOrderLittle
1085 : eByteOrderBig);
1086 m_data.SetAddressByteSize(4);
1087 can_parse = true;
1088 break;
Greg Claytona1743492012-03-13 23:14:29 +00001089
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 case MH_CIGAM_64:
1091 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1092 ? eByteOrderLittle
1093 : eByteOrderBig);
1094 m_data.SetAddressByteSize(8);
1095 can_parse = true;
1096 break;
Greg Claytona1743492012-03-13 23:14:29 +00001097
Kate Stoneb9c1b512016-09-06 20:57:50 +00001098 default:
1099 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100 }
1101
Kate Stoneb9c1b512016-09-06 20:57:50 +00001102 if (can_parse) {
1103 m_data.GetU32(&offset, &m_header.cputype, 6);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105 ArchSpec mach_arch;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107 if (GetArchitecture(mach_arch)) {
1108 // Check if the module has a required architecture
1109 const ArchSpec &module_arch = module_sp->GetArchitecture();
1110 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1111 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113 if (SetModulesArchitecture(mach_arch)) {
1114 const size_t header_and_lc_size =
1115 m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1116 if (m_data.GetByteSize() < header_and_lc_size) {
1117 DataBufferSP data_sp;
1118 ProcessSP process_sp(m_process_wp.lock());
1119 if (process_sp) {
1120 data_sp =
1121 ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1122 } else {
1123 // Read in all only the load command data from the file on disk
Pavel Labath50251fc2017-12-21 10:54:30 +00001124 data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 if (data_sp->GetByteSize() != header_and_lc_size)
Greg Clayton8f265f72015-10-28 20:49:34 +00001126 return false;
1127 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 if (data_sp)
1129 m_data.SetData(data_sp);
1130 }
Greg Clayton9191db42013-10-21 18:40:51 +00001131 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 return true;
1133 }
1134 } else {
1135 memset(&m_header, 0, sizeof(struct mach_header));
1136 }
1137 }
1138 return false;
1139}
1140
1141ByteOrder ObjectFileMachO::GetByteOrder() const {
1142 return m_data.GetByteOrder();
1143}
1144
1145bool ObjectFileMachO::IsExecutable() const {
1146 return m_header.filetype == MH_EXECUTE;
1147}
1148
1149uint32_t ObjectFileMachO::GetAddressByteSize() const {
1150 return m_data.GetAddressByteSize();
1151}
1152
1153AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
1154 Symtab *symtab = GetSymtab();
1155 if (symtab) {
1156 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1157 if (symbol) {
1158 if (symbol->ValueIsAddress()) {
1159 SectionSP section_sp(symbol->GetAddressRef().GetSection());
1160 if (section_sp) {
1161 const lldb::SectionType section_type = section_sp->GetType();
1162 switch (section_type) {
1163 case eSectionTypeInvalid:
1164 return eAddressClassUnknown;
1165
1166 case eSectionTypeCode:
1167 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001168 // For ARM we have a bit in the n_desc field of the symbol that
1169 // tells us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1171 return eAddressClassCodeAlternateISA;
1172 }
1173 return eAddressClassCode;
1174
1175 case eSectionTypeContainer:
1176 return eAddressClassUnknown;
1177
1178 case eSectionTypeData:
1179 case eSectionTypeDataCString:
1180 case eSectionTypeDataCStringPointers:
1181 case eSectionTypeDataSymbolAddress:
1182 case eSectionTypeData4:
1183 case eSectionTypeData8:
1184 case eSectionTypeData16:
1185 case eSectionTypeDataPointers:
1186 case eSectionTypeZeroFill:
1187 case eSectionTypeDataObjCMessageRefs:
1188 case eSectionTypeDataObjCCFStrings:
1189 case eSectionTypeGoSymtab:
1190 return eAddressClassData;
1191
1192 case eSectionTypeDebug:
1193 case eSectionTypeDWARFDebugAbbrev:
1194 case eSectionTypeDWARFDebugAddr:
1195 case eSectionTypeDWARFDebugAranges:
Tamas Berghammer963ce482017-08-25 13:56:14 +00001196 case eSectionTypeDWARFDebugCuIndex:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 case eSectionTypeDWARFDebugFrame:
1198 case eSectionTypeDWARFDebugInfo:
1199 case eSectionTypeDWARFDebugLine:
1200 case eSectionTypeDWARFDebugLoc:
1201 case eSectionTypeDWARFDebugMacInfo:
1202 case eSectionTypeDWARFDebugMacro:
1203 case eSectionTypeDWARFDebugPubNames:
1204 case eSectionTypeDWARFDebugPubTypes:
1205 case eSectionTypeDWARFDebugRanges:
1206 case eSectionTypeDWARFDebugStr:
1207 case eSectionTypeDWARFDebugStrOffsets:
1208 case eSectionTypeDWARFAppleNames:
1209 case eSectionTypeDWARFAppleTypes:
1210 case eSectionTypeDWARFAppleNamespaces:
1211 case eSectionTypeDWARFAppleObjC:
Jan Kratochvile4777a92018-04-29 19:47:48 +00001212 case eSectionTypeDWARFGNUDebugAltLink:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 return eAddressClassDebug;
1214
1215 case eSectionTypeEHFrame:
1216 case eSectionTypeARMexidx:
1217 case eSectionTypeARMextab:
1218 case eSectionTypeCompactUnwind:
1219 return eAddressClassRuntime;
1220
1221 case eSectionTypeAbsoluteAddress:
1222 case eSectionTypeELFSymbolTable:
1223 case eSectionTypeELFDynamicSymbols:
1224 case eSectionTypeELFRelocationEntries:
1225 case eSectionTypeELFDynamicLinkInfo:
1226 case eSectionTypeOther:
1227 return eAddressClassUnknown;
1228 }
1229 }
1230 }
1231
1232 const SymbolType symbol_type = symbol->GetType();
1233 switch (symbol_type) {
1234 case eSymbolTypeAny:
1235 return eAddressClassUnknown;
1236 case eSymbolTypeAbsolute:
1237 return eAddressClassUnknown;
1238
1239 case eSymbolTypeCode:
1240 case eSymbolTypeTrampoline:
1241 case eSymbolTypeResolver:
1242 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001243 // For ARM we have a bit in the n_desc field of the symbol that tells
1244 // us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1246 return eAddressClassCodeAlternateISA;
1247 }
1248 return eAddressClassCode;
1249
1250 case eSymbolTypeData:
1251 return eAddressClassData;
1252 case eSymbolTypeRuntime:
1253 return eAddressClassRuntime;
1254 case eSymbolTypeException:
1255 return eAddressClassRuntime;
1256 case eSymbolTypeSourceFile:
1257 return eAddressClassDebug;
1258 case eSymbolTypeHeaderFile:
1259 return eAddressClassDebug;
1260 case eSymbolTypeObjectFile:
1261 return eAddressClassDebug;
1262 case eSymbolTypeCommonBlock:
1263 return eAddressClassDebug;
1264 case eSymbolTypeBlock:
1265 return eAddressClassDebug;
1266 case eSymbolTypeLocal:
1267 return eAddressClassData;
1268 case eSymbolTypeParam:
1269 return eAddressClassData;
1270 case eSymbolTypeVariable:
1271 return eAddressClassData;
1272 case eSymbolTypeVariableType:
1273 return eAddressClassDebug;
1274 case eSymbolTypeLineEntry:
1275 return eAddressClassDebug;
1276 case eSymbolTypeLineHeader:
1277 return eAddressClassDebug;
1278 case eSymbolTypeScopeBegin:
1279 return eAddressClassDebug;
1280 case eSymbolTypeScopeEnd:
1281 return eAddressClassDebug;
1282 case eSymbolTypeAdditional:
1283 return eAddressClassUnknown;
1284 case eSymbolTypeCompiler:
1285 return eAddressClassDebug;
1286 case eSymbolTypeInstrumentation:
1287 return eAddressClassDebug;
1288 case eSymbolTypeUndefined:
1289 return eAddressClassUnknown;
1290 case eSymbolTypeObjCClass:
1291 return eAddressClassRuntime;
1292 case eSymbolTypeObjCMetaClass:
1293 return eAddressClassRuntime;
1294 case eSymbolTypeObjCIVar:
1295 return eAddressClassRuntime;
1296 case eSymbolTypeReExported:
1297 return eAddressClassRuntime;
1298 }
1299 }
1300 }
1301 return eAddressClassUnknown;
1302}
1303
1304Symtab *ObjectFileMachO::GetSymtab() {
1305 ModuleSP module_sp(GetModule());
1306 if (module_sp) {
1307 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1308 if (m_symtab_ap.get() == NULL) {
1309 m_symtab_ap.reset(new Symtab(this));
1310 std::lock_guard<std::recursive_mutex> symtab_guard(
1311 m_symtab_ap->GetMutex());
1312 ParseSymtab();
1313 m_symtab_ap->Finalize();
1314 }
1315 }
1316 return m_symtab_ap.get();
1317}
1318
1319bool ObjectFileMachO::IsStripped() {
1320 if (m_dysymtab.cmd == 0) {
1321 ModuleSP module_sp(GetModule());
1322 if (module_sp) {
1323 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1324 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1325 const lldb::offset_t load_cmd_offset = offset;
1326
1327 load_command lc;
1328 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
1329 break;
1330 if (lc.cmd == LC_DYSYMTAB) {
1331 m_dysymtab.cmd = lc.cmd;
1332 m_dysymtab.cmdsize = lc.cmdsize;
1333 if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1334 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1335 NULL) {
1336 // Clear m_dysymtab if we were unable to read all items from the
1337 // load command
1338 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1339 }
1340 }
1341 offset = load_cmd_offset + lc.cmdsize;
1342 }
1343 }
1344 }
1345 if (m_dysymtab.cmd)
1346 return m_dysymtab.nlocalsym <= 1;
1347 return false;
1348}
1349
Pavel Labathb417eea2018-03-06 13:53:26 +00001350ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
1351 EncryptedFileRanges result;
Pavel Labathf90054d2018-03-03 22:07:47 +00001352 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labathb417eea2018-03-06 13:53:26 +00001353
Pavel Labathf90054d2018-03-03 22:07:47 +00001354 encryption_info_command encryption_cmd;
Pavel Labathb417eea2018-03-06 13:53:26 +00001355 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001356 const lldb::offset_t load_cmd_offset = offset;
1357 if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL)
1358 break;
1359
Adrian Prantl05097242018-04-30 16:49:04 +00001360 // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1361 // 3 fields we care about, so treat them the same.
Pavel Labathf90054d2018-03-03 22:07:47 +00001362 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1363 encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1364 if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1365 if (encryption_cmd.cryptid != 0) {
1366 EncryptedFileRanges::Entry entry;
1367 entry.SetRangeBase(encryption_cmd.cryptoff);
1368 entry.SetByteSize(encryption_cmd.cryptsize);
Pavel Labathb417eea2018-03-06 13:53:26 +00001369 result.Append(entry);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 }
1371 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372 }
Pavel Labathf90054d2018-03-03 22:07:47 +00001373 offset = load_cmd_offset + encryption_cmd.cmdsize;
1374 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375
Pavel Labathb417eea2018-03-06 13:53:26 +00001376 return result;
1377}
1378
1379void ObjectFileMachO::SanitizeSegmentCommand(segment_command_64 &seg_cmd,
1380 uint32_t cmd_idx) {
1381 if (m_length == 0 || seg_cmd.filesize == 0)
1382 return;
1383
1384 if (seg_cmd.fileoff > m_length) {
1385 // We have a load command that says it extends past the end of the file.
1386 // This is likely a corrupt file. We don't have any way to return an error
1387 // condition here (this method was likely invoked from something like
1388 // ObjectFile::GetSectionList()), so we just null out the section contents,
1389 // and dump a message to stdout. The most common case here is core file
1390 // debugging with a truncated file.
1391 const char *lc_segment_name =
1392 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1393 GetModule()->ReportWarning(
1394 "load command %u %s has a fileoff (0x%" PRIx64
1395 ") that extends beyond the end of the file (0x%" PRIx64
1396 "), ignoring this section",
1397 cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
1398
1399 seg_cmd.fileoff = 0;
1400 seg_cmd.filesize = 0;
1401 }
1402
1403 if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1404 // We have a load command that says it extends past the end of the file.
1405 // This is likely a corrupt file. We don't have any way to return an error
1406 // condition here (this method was likely invoked from something like
1407 // ObjectFile::GetSectionList()), so we just null out the section contents,
1408 // and dump a message to stdout. The most common case here is core file
1409 // debugging with a truncated file.
1410 const char *lc_segment_name =
1411 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1412 GetModule()->ReportWarning(
1413 "load command %u %s has a fileoff + filesize (0x%" PRIx64
1414 ") that extends beyond the end of the file (0x%" PRIx64
1415 "), the segment will be truncated to match",
1416 cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
1417
1418 // Truncate the length
1419 seg_cmd.filesize = m_length - seg_cmd.fileoff;
1420 }
1421}
1422
1423static uint32_t GetSegmentPermissions(const segment_command_64 &seg_cmd) {
1424 uint32_t result = 0;
1425 if (seg_cmd.initprot & VM_PROT_READ)
1426 result |= ePermissionsReadable;
1427 if (seg_cmd.initprot & VM_PROT_WRITE)
1428 result |= ePermissionsWritable;
1429 if (seg_cmd.initprot & VM_PROT_EXECUTE)
1430 result |= ePermissionsExecutable;
1431 return result;
1432}
1433
1434static lldb::SectionType GetSectionType(uint32_t flags,
1435 ConstString section_name) {
1436
1437 if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1438 return eSectionTypeCode;
1439
1440 uint32_t mach_sect_type = flags & SECTION_TYPE;
1441 static ConstString g_sect_name_objc_data("__objc_data");
1442 static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1443 static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1444 static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
1445 static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
1446 static ConstString g_sect_name_objc_const("__objc_const");
1447 static ConstString g_sect_name_objc_classlist("__objc_classlist");
1448 static ConstString g_sect_name_cfstring("__cfstring");
1449
1450 static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
1451 static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1452 static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1453 static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1454 static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1455 static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
1456 static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
1457 static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1458 static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1459 static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1460 static ConstString g_sect_name_dwarf_debug_str("__debug_str");
1461 static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1462 static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1463 static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1464 static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1465 static ConstString g_sect_name_eh_frame("__eh_frame");
1466 static ConstString g_sect_name_compact_unwind("__unwind_info");
1467 static ConstString g_sect_name_text("__text");
1468 static ConstString g_sect_name_data("__data");
1469 static ConstString g_sect_name_go_symtab("__gosymtab");
1470
1471 if (section_name == g_sect_name_dwarf_debug_abbrev)
1472 return eSectionTypeDWARFDebugAbbrev;
1473 if (section_name == g_sect_name_dwarf_debug_aranges)
1474 return eSectionTypeDWARFDebugAranges;
1475 if (section_name == g_sect_name_dwarf_debug_frame)
1476 return eSectionTypeDWARFDebugFrame;
1477 if (section_name == g_sect_name_dwarf_debug_info)
1478 return eSectionTypeDWARFDebugInfo;
1479 if (section_name == g_sect_name_dwarf_debug_line)
1480 return eSectionTypeDWARFDebugLine;
1481 if (section_name == g_sect_name_dwarf_debug_loc)
1482 return eSectionTypeDWARFDebugLoc;
1483 if (section_name == g_sect_name_dwarf_debug_macinfo)
1484 return eSectionTypeDWARFDebugMacInfo;
1485 if (section_name == g_sect_name_dwarf_debug_pubnames)
1486 return eSectionTypeDWARFDebugPubNames;
1487 if (section_name == g_sect_name_dwarf_debug_pubtypes)
1488 return eSectionTypeDWARFDebugPubTypes;
1489 if (section_name == g_sect_name_dwarf_debug_ranges)
1490 return eSectionTypeDWARFDebugRanges;
1491 if (section_name == g_sect_name_dwarf_debug_str)
1492 return eSectionTypeDWARFDebugStr;
1493 if (section_name == g_sect_name_dwarf_apple_names)
1494 return eSectionTypeDWARFAppleNames;
1495 if (section_name == g_sect_name_dwarf_apple_types)
1496 return eSectionTypeDWARFAppleTypes;
1497 if (section_name == g_sect_name_dwarf_apple_namespaces)
1498 return eSectionTypeDWARFAppleNamespaces;
1499 if (section_name == g_sect_name_dwarf_apple_objc)
1500 return eSectionTypeDWARFAppleObjC;
1501 if (section_name == g_sect_name_objc_selrefs)
1502 return eSectionTypeDataCStringPointers;
1503 if (section_name == g_sect_name_objc_msgrefs)
1504 return eSectionTypeDataObjCMessageRefs;
1505 if (section_name == g_sect_name_eh_frame)
1506 return eSectionTypeEHFrame;
1507 if (section_name == g_sect_name_compact_unwind)
1508 return eSectionTypeCompactUnwind;
1509 if (section_name == g_sect_name_cfstring)
1510 return eSectionTypeDataObjCCFStrings;
1511 if (section_name == g_sect_name_go_symtab)
1512 return eSectionTypeGoSymtab;
1513 if (section_name == g_sect_name_objc_data ||
1514 section_name == g_sect_name_objc_classrefs ||
1515 section_name == g_sect_name_objc_superrefs ||
1516 section_name == g_sect_name_objc_const ||
1517 section_name == g_sect_name_objc_classlist) {
1518 return eSectionTypeDataPointers;
1519 }
1520
1521 switch (mach_sect_type) {
1522 // TODO: categorize sections by other flags for regular sections
1523 case S_REGULAR:
1524 if (section_name == g_sect_name_text)
1525 return eSectionTypeCode;
1526 if (section_name == g_sect_name_data)
1527 return eSectionTypeData;
1528 return eSectionTypeOther;
1529 case S_ZEROFILL:
1530 return eSectionTypeZeroFill;
1531 case S_CSTRING_LITERALS: // section with only literal C strings
1532 return eSectionTypeDataCString;
1533 case S_4BYTE_LITERALS: // section with only 4 byte literals
1534 return eSectionTypeData4;
1535 case S_8BYTE_LITERALS: // section with only 8 byte literals
1536 return eSectionTypeData8;
1537 case S_LITERAL_POINTERS: // section with only pointers to literals
1538 return eSectionTypeDataPointers;
1539 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1540 return eSectionTypeDataPointers;
1541 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1542 return eSectionTypeDataPointers;
1543 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1544 // the reserved2 field
1545 return eSectionTypeCode;
1546 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1547 // initialization
1548 return eSectionTypeDataPointers;
1549 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1550 // termination
1551 return eSectionTypeDataPointers;
1552 case S_COALESCED:
1553 return eSectionTypeOther;
1554 case S_GB_ZEROFILL:
1555 return eSectionTypeZeroFill;
1556 case S_INTERPOSING: // section with only pairs of function pointers for
1557 // interposing
1558 return eSectionTypeCode;
1559 case S_16BYTE_LITERALS: // section with only 16 byte literals
1560 return eSectionTypeData16;
1561 case S_DTRACE_DOF:
1562 return eSectionTypeDebug;
1563 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1564 return eSectionTypeDataPointers;
1565 default:
1566 return eSectionTypeOther;
1567 }
1568}
1569
1570struct ObjectFileMachO::SegmentParsingContext {
1571 const EncryptedFileRanges EncryptedRanges;
1572 lldb_private::SectionList &UnifiedList;
1573 uint32_t NextSegmentIdx = 0;
1574 uint32_t NextSectionIdx = 0;
1575 bool FileAddressesChanged = false;
1576
1577 SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
1578 lldb_private::SectionList &UnifiedList)
1579 : EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
1580};
1581
1582void ObjectFileMachO::ProcessSegmentCommand(const load_command &load_cmd_,
1583 lldb::offset_t offset,
1584 uint32_t cmd_idx,
1585 SegmentParsingContext &context) {
1586 segment_command_64 load_cmd;
1587 memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1588
1589 if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1590 return;
1591
1592 ModuleSP module_sp = GetModule();
1593 const bool is_core = GetType() == eTypeCoreFile;
1594 const bool is_dsym = (m_header.filetype == MH_DSYM);
1595 bool add_section = true;
1596 bool add_to_unified = true;
1597 ConstString const_segname(
1598 load_cmd.segname,
1599 std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname)));
1600
1601 SectionSP unified_section_sp(
1602 context.UnifiedList.FindSectionByName(const_segname));
1603 if (is_dsym && unified_section_sp) {
1604 if (const_segname == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001605 // We need to keep the __LINKEDIT segment private to this object file
1606 // only
Pavel Labathb417eea2018-03-06 13:53:26 +00001607 add_to_unified = false;
1608 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001609 // This is the dSYM file and this section has already been created by the
1610 // object file, no need to create it.
Pavel Labathb417eea2018-03-06 13:53:26 +00001611 add_section = false;
1612 }
1613 }
1614 load_cmd.vmaddr = m_data.GetAddress(&offset);
1615 load_cmd.vmsize = m_data.GetAddress(&offset);
1616 load_cmd.fileoff = m_data.GetAddress(&offset);
1617 load_cmd.filesize = m_data.GetAddress(&offset);
1618 if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1619 return;
1620
1621 SanitizeSegmentCommand(load_cmd, cmd_idx);
1622
1623 const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1624 const bool segment_is_encrypted =
1625 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1626
Adrian Prantl05097242018-04-30 16:49:04 +00001627 // Keep a list of mach segments around in case we need to get at data that
1628 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001629 m_mach_segments.push_back(load_cmd);
1630
Adrian Prantl05097242018-04-30 16:49:04 +00001631 // Use a segment ID of the segment index shifted left by 8 so they never
1632 // conflict with any of the sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001633 SectionSP segment_sp;
1634 if (add_section && (const_segname || is_core)) {
1635 segment_sp.reset(new Section(
1636 module_sp, // Module to which this section belongs
1637 this, // Object file to which this sections belongs
1638 ++context.NextSegmentIdx
1639 << 8, // Section ID is the 1 based segment index
Adrian Prantl05097242018-04-30 16:49:04 +00001640 // shifted right by 8 bits as not to collide with any of the 256
1641 // section IDs that are possible
Pavel Labathb417eea2018-03-06 13:53:26 +00001642 const_segname, // Name of this section
1643 eSectionTypeContainer, // This section is a container of other
1644 // sections.
1645 load_cmd.vmaddr, // File VM address == addresses as they are
1646 // found in the object file
1647 load_cmd.vmsize, // VM size in bytes of this section
1648 load_cmd.fileoff, // Offset to the data for this section in
1649 // the file
1650 load_cmd.filesize, // Size in bytes of this section as found
1651 // in the file
1652 0, // Segments have no alignment information
1653 load_cmd.flags)); // Flags for this section
1654
1655 segment_sp->SetIsEncrypted(segment_is_encrypted);
1656 m_sections_ap->AddSection(segment_sp);
1657 segment_sp->SetPermissions(segment_permissions);
1658 if (add_to_unified)
1659 context.UnifiedList.AddSection(segment_sp);
1660 } else if (unified_section_sp) {
1661 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1662 // Check to see if the module was read from memory?
1663 if (module_sp->GetObjectFile()->GetHeaderAddress().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001664 // We have a module that is in memory and needs to have its file
1665 // address adjusted. We need to do this because when we load a file
1666 // from memory, its addresses will be slid already, yet the addresses
1667 // in the new symbol file will still be unslid. Since everything is
1668 // stored as section offset, this shouldn't cause any problems.
Pavel Labathb417eea2018-03-06 13:53:26 +00001669
Adrian Prantl05097242018-04-30 16:49:04 +00001670 // Make sure we've parsed the symbol table from the ObjectFile before
1671 // we go around changing its Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001672 module_sp->GetObjectFile()->GetSymtab();
Adrian Prantl05097242018-04-30 16:49:04 +00001673 // eh_frame would present the same problems but we parse that on a per-
1674 // function basis as-needed so it's more difficult to remove its use of
1675 // the Sections. Realistically, the environments where this code path
1676 // will be taken will not have eh_frame sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001677
1678 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1679
Adrian Prantl05097242018-04-30 16:49:04 +00001680 // Notify the module that the section addresses have been changed once
1681 // we're done so any file-address caches can be updated.
Pavel Labathb417eea2018-03-06 13:53:26 +00001682 context.FileAddressesChanged = true;
1683 }
1684 }
1685 m_sections_ap->AddSection(unified_section_sp);
1686 }
1687
1688 struct section_64 sect64;
1689 ::memset(&sect64, 0, sizeof(sect64));
Adrian Prantl05097242018-04-30 16:49:04 +00001690 // Push a section into our mach sections for the section at index zero
1691 // (NO_SECT) if we don't have any mach sections yet...
Pavel Labathb417eea2018-03-06 13:53:26 +00001692 if (m_mach_sections.empty())
1693 m_mach_sections.push_back(sect64);
1694 uint32_t segment_sect_idx;
1695 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1696
1697 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1698 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1699 ++segment_sect_idx) {
1700 if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1701 sizeof(sect64.sectname)) == NULL)
1702 break;
1703 if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1704 sizeof(sect64.segname)) == NULL)
1705 break;
1706 sect64.addr = m_data.GetAddress(&offset);
1707 sect64.size = m_data.GetAddress(&offset);
1708
1709 if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
1710 break;
1711
Adrian Prantl05097242018-04-30 16:49:04 +00001712 // Keep a list of mach sections around in case we need to get at data that
1713 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001714 m_mach_sections.push_back(sect64);
1715
1716 if (add_section) {
1717 ConstString section_name(
1718 sect64.sectname,
1719 std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname)));
1720 if (!const_segname) {
Adrian Prantl05097242018-04-30 16:49:04 +00001721 // We have a segment with no name so we need to conjure up segments
1722 // that correspond to the section's segname if there isn't already such
1723 // a section. If there is such a section, we resize the section so that
1724 // it spans all sections. We also mark these sections as fake so
1725 // address matches don't hit if they land in the gaps between the child
1726 // sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001727 const_segname.SetTrimmedCStringWithLength(sect64.segname,
1728 sizeof(sect64.segname));
1729 segment_sp = context.UnifiedList.FindSectionByName(const_segname);
1730 if (segment_sp.get()) {
1731 Section *segment = segment_sp.get();
1732 // Grow the section size as needed.
1733 const lldb::addr_t sect64_min_addr = sect64.addr;
1734 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1735 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1736 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1737 const lldb::addr_t curr_seg_max_addr =
1738 curr_seg_min_addr + curr_seg_byte_size;
1739 if (sect64_min_addr >= curr_seg_min_addr) {
1740 const lldb::addr_t new_seg_byte_size =
1741 sect64_max_addr - curr_seg_min_addr;
1742 // Only grow the section size if needed
1743 if (new_seg_byte_size > curr_seg_byte_size)
1744 segment->SetByteSize(new_seg_byte_size);
1745 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001746 // We need to change the base address of the segment and adjust the
1747 // child section offsets for all existing children.
Pavel Labathb417eea2018-03-06 13:53:26 +00001748 const lldb::addr_t slide_amount =
1749 sect64_min_addr - curr_seg_min_addr;
1750 segment->Slide(slide_amount, false);
1751 segment->GetChildren().Slide(-slide_amount, false);
1752 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1753 }
1754
1755 // Grow the section size as needed.
1756 if (sect64.offset) {
1757 const lldb::addr_t segment_min_file_offset =
1758 segment->GetFileOffset();
1759 const lldb::addr_t segment_max_file_offset =
1760 segment_min_file_offset + segment->GetFileSize();
1761
1762 const lldb::addr_t section_min_file_offset = sect64.offset;
1763 const lldb::addr_t section_max_file_offset =
1764 section_min_file_offset + sect64.size;
1765 const lldb::addr_t new_file_offset =
1766 std::min(section_min_file_offset, segment_min_file_offset);
1767 const lldb::addr_t new_file_size =
1768 std::max(section_max_file_offset, segment_max_file_offset) -
1769 new_file_offset;
1770 segment->SetFileOffset(new_file_offset);
1771 segment->SetFileSize(new_file_size);
1772 }
1773 } else {
1774 // Create a fake section for the section's named segment
1775 segment_sp.reset(new Section(
1776 segment_sp, // Parent section
1777 module_sp, // Module to which this section belongs
1778 this, // Object file to which this section belongs
1779 ++context.NextSegmentIdx
1780 << 8, // Section ID is the 1 based segment index
1781 // shifted right by 8 bits as not to
1782 // collide with any of the 256 section IDs
1783 // that are possible
1784 const_segname, // Name of this section
1785 eSectionTypeContainer, // This section is a container of
1786 // other sections.
1787 sect64.addr, // File VM address == addresses as they are
1788 // found in the object file
1789 sect64.size, // VM size in bytes of this section
1790 sect64.offset, // Offset to the data for this section in
1791 // the file
1792 sect64.offset ? sect64.size : 0, // Size in bytes of
1793 // this section as
1794 // found in the file
1795 sect64.align,
1796 load_cmd.flags)); // Flags for this section
1797 segment_sp->SetIsFake(true);
1798 segment_sp->SetPermissions(segment_permissions);
1799 m_sections_ap->AddSection(segment_sp);
1800 if (add_to_unified)
1801 context.UnifiedList.AddSection(segment_sp);
1802 segment_sp->SetIsEncrypted(segment_is_encrypted);
1803 }
1804 }
1805 assert(segment_sp.get());
1806
1807 lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1808
1809 SectionSP section_sp(new Section(
1810 segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1811 sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1812 sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1813 sect64.flags));
1814 // Set the section to be encrypted to match the segment
1815
1816 bool section_is_encrypted = false;
1817 if (!segment_is_encrypted && load_cmd.filesize != 0)
1818 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1819 sect64.offset) != NULL;
1820
1821 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1822 section_sp->SetPermissions(segment_permissions);
1823 segment_sp->GetChildren().AddSection(section_sp);
1824
1825 if (segment_sp->IsFake()) {
1826 segment_sp.reset();
1827 const_segname.Clear();
1828 }
1829 }
1830 }
1831 if (segment_sp && is_dsym) {
1832 if (first_segment_sectID <= context.NextSectionIdx) {
1833 lldb::user_id_t sect_uid;
1834 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1835 ++sect_uid) {
1836 SectionSP curr_section_sp(
1837 segment_sp->GetChildren().FindSectionByID(sect_uid));
1838 SectionSP next_section_sp;
1839 if (sect_uid + 1 <= context.NextSectionIdx)
1840 next_section_sp =
1841 segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1842
1843 if (curr_section_sp.get()) {
1844 if (curr_section_sp->GetByteSize() == 0) {
1845 if (next_section_sp.get() != NULL)
1846 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1847 curr_section_sp->GetFileAddress());
1848 else
1849 curr_section_sp->SetByteSize(load_cmd.vmsize);
1850 }
1851 }
1852 }
1853 }
1854 }
1855}
1856
1857void ObjectFileMachO::ProcessDysymtabCommand(const load_command &load_cmd,
1858 lldb::offset_t offset) {
1859 m_dysymtab.cmd = load_cmd.cmd;
1860 m_dysymtab.cmdsize = load_cmd.cmdsize;
1861 m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1862 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1863}
1864
1865void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1866 if (m_sections_ap)
1867 return;
1868
1869 m_sections_ap.reset(new SectionList());
1870
1871 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1872 // bool dump_sections = false;
1873 ModuleSP module_sp(GetModule());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001874
Pavel Labathf90054d2018-03-03 22:07:47 +00001875 offset = MachHeaderSizeFromMagic(m_header.magic);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001876
Pavel Labathb417eea2018-03-06 13:53:26 +00001877 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1878 struct load_command load_cmd;
1879 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001880 const lldb::offset_t load_cmd_offset = offset;
1881 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
1882 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001883
Pavel Labathb417eea2018-03-06 13:53:26 +00001884 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1885 ProcessSegmentCommand(load_cmd, offset, i, context);
1886 else if (load_cmd.cmd == LC_DYSYMTAB)
1887 ProcessDysymtabCommand(load_cmd, offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001888
Pavel Labathf90054d2018-03-03 22:07:47 +00001889 offset = load_cmd_offset + load_cmd.cmdsize;
1890 }
1891
Pavel Labathb417eea2018-03-06 13:53:26 +00001892 if (context.FileAddressesChanged && module_sp)
Pavel Labathf90054d2018-03-03 22:07:47 +00001893 module_sp->SectionFileAddressesChanged();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001894}
1895
1896class MachSymtabSectionInfo {
1897public:
1898 MachSymtabSectionInfo(SectionList *section_list)
1899 : m_section_list(section_list), m_section_infos() {
Adrian Prantl05097242018-04-30 16:49:04 +00001900 // Get the number of sections down to a depth of 1 to include all segments
1901 // and their sections, but no other sections that may be added for debug
1902 // map or
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 m_section_infos.resize(section_list->GetNumSections(1));
1904 }
1905
1906 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1907 if (n_sect == 0)
1908 return SectionSP();
1909 if (n_sect < m_section_infos.size()) {
1910 if (!m_section_infos[n_sect].section_sp) {
1911 SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1912 m_section_infos[n_sect].section_sp = section_sp;
1913 if (section_sp) {
1914 m_section_infos[n_sect].vm_range.SetBaseAddress(
1915 section_sp->GetFileAddress());
1916 m_section_infos[n_sect].vm_range.SetByteSize(
1917 section_sp->GetByteSize());
1918 } else {
1919 Host::SystemLog(Host::eSystemLogError,
1920 "error: unable to find section for section %u\n",
1921 n_sect);
1922 }
1923 }
1924 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1925 // Symbol is in section.
1926 return m_section_infos[n_sect].section_sp;
1927 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1928 m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1929 file_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001930 // Symbol is in section with zero size, but has the same start address
1931 // as the section. This can happen with linker symbols (symbols that
1932 // start with the letter 'l' or 'L'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001933 return m_section_infos[n_sect].section_sp;
1934 }
1935 }
1936 return m_section_list->FindSectionContainingFileAddress(file_addr);
1937 }
1938
1939protected:
1940 struct SectionInfo {
1941 SectionInfo() : vm_range(), section_sp() {}
1942
1943 VMRange vm_range;
1944 SectionSP section_sp;
1945 };
1946 SectionList *m_section_list;
1947 std::vector<SectionInfo> m_section_infos;
1948};
1949
1950struct TrieEntry {
1951 TrieEntry()
1952 : name(), address(LLDB_INVALID_ADDRESS), flags(0), other(0),
1953 import_name() {}
1954
1955 void Clear() {
1956 name.Clear();
1957 address = LLDB_INVALID_ADDRESS;
1958 flags = 0;
1959 other = 0;
1960 import_name.Clear();
1961 }
1962
1963 void Dump() const {
1964 printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
1965 static_cast<unsigned long long>(address),
1966 static_cast<unsigned long long>(flags),
1967 static_cast<unsigned long long>(other), name.GetCString());
1968 if (import_name)
1969 printf(" -> \"%s\"\n", import_name.GetCString());
1970 else
1971 printf("\n");
1972 }
1973 ConstString name;
1974 uint64_t address;
1975 uint64_t flags;
1976 uint64_t other;
1977 ConstString import_name;
1978};
1979
1980struct TrieEntryWithOffset {
1981 lldb::offset_t nodeOffset;
1982 TrieEntry entry;
1983
1984 TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
1985
1986 void Dump(uint32_t idx) const {
1987 printf("[%3u] 0x%16.16llx: ", idx,
1988 static_cast<unsigned long long>(nodeOffset));
1989 entry.Dump();
1990 }
1991
1992 bool operator<(const TrieEntryWithOffset &other) const {
1993 return (nodeOffset < other.nodeOffset);
1994 }
1995};
1996
1997static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
1998 const bool is_arm,
1999 std::vector<llvm::StringRef> &nameSlices,
2000 std::set<lldb::addr_t> &resolver_addresses,
2001 std::vector<TrieEntryWithOffset> &output) {
2002 if (!data.ValidOffset(offset))
Greg Clayton8f265f72015-10-28 20:49:34 +00002003 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004
2005 const uint64_t terminalSize = data.GetULEB128(&offset);
2006 lldb::offset_t children_offset = offset + terminalSize;
2007 if (terminalSize != 0) {
2008 TrieEntryWithOffset e(offset);
2009 e.entry.flags = data.GetULEB128(&offset);
2010 const char *import_name = NULL;
2011 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2012 e.entry.address = 0;
2013 e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2014 import_name = data.GetCStr(&offset);
2015 } else {
2016 e.entry.address = data.GetULEB128(&offset);
2017 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2018 e.entry.other = data.GetULEB128(&offset);
2019 uint64_t resolver_addr = e.entry.other;
2020 if (is_arm)
2021 resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2022 resolver_addresses.insert(resolver_addr);
2023 } else
2024 e.entry.other = 0;
2025 }
2026 // Only add symbols that are reexport symbols with a valid import name
2027 if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name &&
2028 import_name[0]) {
2029 std::string name;
2030 if (!nameSlices.empty()) {
2031 for (auto name_slice : nameSlices)
2032 name.append(name_slice.data(), name_slice.size());
2033 }
2034 if (name.size() > 1) {
2035 // Skip the leading '_'
2036 e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2037 }
2038 if (import_name) {
2039 // Skip the leading '_'
2040 e.entry.import_name.SetCString(import_name + 1);
2041 }
2042 output.push_back(e);
2043 }
2044 }
2045
2046 const uint8_t childrenCount = data.GetU8(&children_offset);
2047 for (uint8_t i = 0; i < childrenCount; ++i) {
2048 const char *cstr = data.GetCStr(&children_offset);
2049 if (cstr)
2050 nameSlices.push_back(llvm::StringRef(cstr));
2051 else
2052 return false; // Corrupt data
2053 lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2054 if (childNodeOffset) {
2055 if (!ParseTrieEntries(data, childNodeOffset, is_arm, nameSlices,
2056 resolver_addresses, output)) {
2057 return false;
2058 }
2059 }
2060 nameSlices.pop_back();
2061 }
2062 return true;
Greg Clayton9191db42013-10-21 18:40:51 +00002063}
2064
Jason Molenda649a6072015-11-10 05:21:54 +00002065// Read the UUID out of a dyld_shared_cache file on-disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
2067 const ByteOrder byte_order,
2068 const uint32_t addr_byte_size) {
2069 UUID dsc_uuid;
Pavel Labath50251fc2017-12-21 10:54:30 +00002070 DataBufferSP DscData = MapFileData(
2071 dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002072 if (!DscData)
2073 return dsc_uuid;
2074 DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
Jason Molenda649a6072015-11-10 05:21:54 +00002075
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002076 char version_str[7];
2077 lldb::offset_t offset = 0;
2078 memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
2079 version_str[6] = '\0';
2080 if (strcmp(version_str, "dyld_v") == 0) {
2081 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
2082 uint8_t uuid_bytes[sizeof(uuid_t)];
2083 memcpy(uuid_bytes, dsc_header_data.GetData(&offset, sizeof(uuid_t)),
2084 sizeof(uuid_t));
2085 dsc_uuid.SetBytes(uuid_bytes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002086 }
Jason Molendafd443e92018-02-07 01:28:29 +00002087 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2088 if (log && dsc_uuid.IsValid()) {
2089 log->Printf("Shared cache %s has UUID %s", dyld_shared_cache.GetPath().c_str(),
2090 dsc_uuid.GetAsString().c_str());
2091 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002092 return dsc_uuid;
Jason Molenda649a6072015-11-10 05:21:54 +00002093}
2094
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095size_t ObjectFileMachO::ParseSymtab() {
Pavel Labathf9d16472017-05-15 13:02:37 +00002096 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2097 Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098 m_file.GetFilename().AsCString(""));
2099 ModuleSP module_sp(GetModule());
2100 if (!module_sp)
2101 return 0;
2102
2103 struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2104 struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2105 struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2106 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2107 FunctionStarts function_starts;
2108 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2109 uint32_t i;
2110 FileSpecList dylib_files;
2111 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2112 static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2113 static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2114 static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2115
2116 for (i = 0; i < m_header.ncmds; ++i) {
2117 const lldb::offset_t cmd_offset = offset;
2118 // Read in the load command and load command size
2119 struct load_command lc;
2120 if (m_data.GetU32(&offset, &lc, 2) == NULL)
2121 break;
2122 // Watch for the symbol table load command
2123 switch (lc.cmd) {
2124 case LC_SYMTAB:
2125 symtab_load_command.cmd = lc.cmd;
2126 symtab_load_command.cmdsize = lc.cmdsize;
2127 // Read in the rest of the symtab load command
2128 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2129 0) // fill in symoff, nsyms, stroff, strsize fields
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002130 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002131 if (symtab_load_command.symoff == 0) {
2132 if (log)
2133 module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2134 return 0;
2135 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002136
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 if (symtab_load_command.stroff == 0) {
2138 if (log)
2139 module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2140 return 0;
2141 }
Greg Clayton77ccca72011-12-30 00:32:24 +00002142
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 if (symtab_load_command.nsyms == 0) {
2144 if (log)
2145 module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 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.strsize == 0) {
2150 if (log)
2151 module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2152 return 0;
2153 }
2154 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002155
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156 case LC_DYLD_INFO:
2157 case LC_DYLD_INFO_ONLY:
2158 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2159 dyld_info.cmd = lc.cmd;
2160 dyld_info.cmdsize = lc.cmdsize;
2161 } else {
2162 memset(&dyld_info, 0, sizeof(dyld_info));
2163 }
2164 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002165
Kate Stoneb9c1b512016-09-06 20:57:50 +00002166 case LC_LOAD_DYLIB:
2167 case LC_LOAD_WEAK_DYLIB:
2168 case LC_REEXPORT_DYLIB:
2169 case LC_LOADFVMLIB:
2170 case LC_LOAD_UPWARD_DYLIB: {
2171 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2172 const char *path = m_data.PeekCStr(name_offset);
2173 if (path) {
2174 FileSpec file_spec(path, false);
2175 // Strip the path if there is @rpath, @executable, etc so we just use
2176 // the basename
2177 if (path[0] == '@')
2178 file_spec.GetDirectory().Clear();
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002179
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 if (lc.cmd == LC_REEXPORT_DYLIB) {
2181 m_reexported_dylibs.AppendIfUnique(file_spec);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002182 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183
2184 dylib_files.Append(file_spec);
2185 }
2186 } break;
2187
2188 case LC_FUNCTION_STARTS:
2189 function_starts_load_command.cmd = lc.cmd;
2190 function_starts_load_command.cmdsize = lc.cmdsize;
2191 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2192 NULL) // fill in symoff, nsyms, stroff, strsize fields
2193 memset(&function_starts_load_command, 0,
2194 sizeof(function_starts_load_command));
2195 break;
2196
2197 default:
2198 break;
2199 }
2200 offset = cmd_offset + lc.cmdsize;
2201 }
2202
2203 if (symtab_load_command.cmd) {
2204 Symtab *symtab = m_symtab_ap.get();
2205 SectionList *section_list = GetSectionList();
2206 if (section_list == NULL)
2207 return 0;
2208
2209 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2210 const ByteOrder byte_order = m_data.GetByteOrder();
2211 bool bit_width_32 = addr_byte_size == 4;
2212 const size_t nlist_byte_size =
2213 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2214
2215 DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size);
2216 DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size);
2217 DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size);
2218 DataExtractor indirect_symbol_index_data(NULL, 0, byte_order,
2219 addr_byte_size);
2220 DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size);
2221
2222 const addr_t nlist_data_byte_size =
2223 symtab_load_command.nsyms * nlist_byte_size;
2224 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2225 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2226
2227 ProcessSP process_sp(m_process_wp.lock());
2228 Process *process = process_sp.get();
2229
2230 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2231
2232 if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2233 Target &target = process->GetTarget();
2234
2235 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2236
2237 SectionSP linkedit_section_sp(
2238 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2239 // Reading mach file from memory in a process or core file...
2240
2241 if (linkedit_section_sp) {
2242 addr_t linkedit_load_addr =
2243 linkedit_section_sp->GetLoadBaseAddress(&target);
2244 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2245 // We might be trying to access the symbol table before the
Adrian Prantl05097242018-04-30 16:49:04 +00002246 // __LINKEDIT's load address has been set in the target. We can't
2247 // fail to read the symbol table, so calculate the right address
2248 // manually
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2250 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2251 }
2252
2253 const addr_t linkedit_file_offset =
2254 linkedit_section_sp->GetFileOffset();
2255 const addr_t symoff_addr = linkedit_load_addr +
2256 symtab_load_command.symoff -
2257 linkedit_file_offset;
2258 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2259 linkedit_file_offset;
2260
2261 bool data_was_read = false;
2262
2263#if defined(__APPLE__) && \
2264 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2265 if (m_header.flags & 0x80000000u &&
2266 process->GetAddressByteSize() == sizeof(void *)) {
2267 // This mach-o memory file is in the dyld shared cache. If this
2268 // program is not remote and this is iOS, then this process will
Adrian Prantl05097242018-04-30 16:49:04 +00002269 // share the same shared cache as the process we are debugging and we
2270 // can read the entire __LINKEDIT from the address space in this
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271 // process. This is a needed optimization that is used for local iOS
2272 // debugging only since all shared libraries in the shared cache do
2273 // not have corresponding files that exist in the file system of the
2274 // device. They have been combined into a single file. This means we
2275 // always have to load these files from memory. All of the symbol and
2276 // string tables from all of the __LINKEDIT sections from the shared
2277 // libraries in the shared cache have been merged into a single large
2278 // symbol and string table. Reading all of this symbol and string
Adrian Prantl05097242018-04-30 16:49:04 +00002279 // table data across can slow down debug launch times, so we optimize
2280 // this by reading the memory for the __LINKEDIT section from this
2281 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282
Jason Molenda07580ff2018-05-04 00:59:37 +00002283 UUID lldb_shared_cache;
2284 addr_t lldb_shared_cache_addr;
2285 GetLLDBSharedCacheUUID (lldb_shared_cache_addr, lldb_shared_cache);
2286 UUID process_shared_cache;
2287 addr_t process_shared_cache_addr;
2288 GetProcessSharedCacheUUID(process, process_shared_cache_addr, process_shared_cache);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002289 bool use_lldb_cache = true;
2290 if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
Jason Molenda07580ff2018-05-04 00:59:37 +00002291 (lldb_shared_cache != process_shared_cache
2292 || process_shared_cache_addr != lldb_shared_cache_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293 use_lldb_cache = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 }
2295
2296 PlatformSP platform_sp(target.GetPlatform());
2297 if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2298 data_was_read = true;
2299 nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2300 eByteOrderLittle);
2301 strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2302 eByteOrderLittle);
2303 if (function_starts_load_command.cmd) {
2304 const addr_t func_start_addr =
2305 linkedit_load_addr + function_starts_load_command.dataoff -
2306 linkedit_file_offset;
2307 function_starts_data.SetData(
2308 (void *)func_start_addr,
2309 function_starts_load_command.datasize, eByteOrderLittle);
2310 }
2311 }
2312 }
2313#endif
2314
2315 if (!data_was_read) {
2316 // Always load dyld - the dynamic linker - from memory if we didn't
Adrian Prantl05097242018-04-30 16:49:04 +00002317 // find a binary anywhere else. lldb will not register
2318 // dylib/framework/bundle loads/unloads if we don't have the dyld
2319 // symbols, we force dyld to load from memory despite the user's
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320 // target.memory-module-load-level setting.
2321 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2322 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2323 DataBufferSP nlist_data_sp(
2324 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2325 if (nlist_data_sp)
2326 nlist_data.SetData(nlist_data_sp, 0,
2327 nlist_data_sp->GetByteSize());
2328 // Load strings individually from memory when loading from memory
Adrian Prantl05097242018-04-30 16:49:04 +00002329 // since shared cache string tables contain strings for all symbols
2330 // from all shared cached libraries DataBufferSP strtab_data_sp
2331 // (ReadMemory (process_sp, strtab_addr,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002332 // strtab_data_byte_size));
2333 // if (strtab_data_sp)
2334 // strtab_data.SetData (strtab_data_sp, 0,
2335 // strtab_data_sp->GetByteSize());
2336 if (m_dysymtab.nindirectsyms != 0) {
2337 const addr_t indirect_syms_addr = linkedit_load_addr +
2338 m_dysymtab.indirectsymoff -
2339 linkedit_file_offset;
2340 DataBufferSP indirect_syms_data_sp(
2341 ReadMemory(process_sp, indirect_syms_addr,
2342 m_dysymtab.nindirectsyms * 4));
2343 if (indirect_syms_data_sp)
2344 indirect_symbol_index_data.SetData(
2345 indirect_syms_data_sp, 0,
2346 indirect_syms_data_sp->GetByteSize());
2347 }
2348 } else if (memory_module_load_level >=
2349 eMemoryModuleLoadLevelPartial) {
2350 if (function_starts_load_command.cmd) {
2351 const addr_t func_start_addr =
2352 linkedit_load_addr + function_starts_load_command.dataoff -
2353 linkedit_file_offset;
2354 DataBufferSP func_start_data_sp(
2355 ReadMemory(process_sp, func_start_addr,
2356 function_starts_load_command.datasize));
2357 if (func_start_data_sp)
2358 function_starts_data.SetData(func_start_data_sp, 0,
2359 func_start_data_sp->GetByteSize());
2360 }
2361 }
2362 }
2363 }
2364 } else {
2365 nlist_data.SetData(m_data, symtab_load_command.symoff,
2366 nlist_data_byte_size);
2367 strtab_data.SetData(m_data, symtab_load_command.stroff,
2368 strtab_data_byte_size);
2369
2370 if (dyld_info.export_size > 0) {
2371 dyld_trie_data.SetData(m_data, dyld_info.export_off,
2372 dyld_info.export_size);
2373 }
2374
2375 if (m_dysymtab.nindirectsyms != 0) {
2376 indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2377 m_dysymtab.nindirectsyms * 4);
2378 }
2379 if (function_starts_load_command.cmd) {
2380 function_starts_data.SetData(m_data,
2381 function_starts_load_command.dataoff,
2382 function_starts_load_command.datasize);
2383 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002384 }
2385
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386 if (nlist_data.GetByteSize() == 0 &&
2387 memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2388 if (log)
2389 module_sp->LogMessage(log, "failed to read nlist data");
2390 return 0;
2391 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002392
Kate Stoneb9c1b512016-09-06 20:57:50 +00002393 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2394 if (!have_strtab_data) {
2395 if (process) {
2396 if (strtab_addr == LLDB_INVALID_ADDRESS) {
2397 if (log)
2398 module_sp->LogMessage(log, "failed to locate the strtab in memory");
2399 return 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002400 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401 } else {
2402 if (log)
2403 module_sp->LogMessage(log, "failed to read strtab data");
2404 return 0;
2405 }
2406 }
Greg Clayton9191db42013-10-21 18:40:51 +00002407
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2409 const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2410 const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2411 const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2412 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2413 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2414 SectionSP text_section_sp(
2415 section_list->FindSectionByName(g_segment_name_TEXT));
2416 SectionSP data_section_sp(
2417 section_list->FindSectionByName(g_segment_name_DATA));
2418 SectionSP data_dirty_section_sp(
2419 section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2420 SectionSP data_const_section_sp(
2421 section_list->FindSectionByName(g_segment_name_DATA_CONST));
2422 SectionSP objc_section_sp(
2423 section_list->FindSectionByName(g_segment_name_OBJC));
2424 SectionSP eh_frame_section_sp;
2425 if (text_section_sp.get())
2426 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2427 g_section_name_eh_frame);
2428 else
2429 eh_frame_section_sp =
2430 section_list->FindSectionByName(g_section_name_eh_frame);
Greg Clayton77ccca72011-12-30 00:32:24 +00002431
Kate Stoneb9c1b512016-09-06 20:57:50 +00002432 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
Greg Clayton86eac942013-08-13 21:32:34 +00002433
Kate Stoneb9c1b512016-09-06 20:57:50 +00002434 // lldb works best if it knows the start address of all functions in a
Adrian Prantl05097242018-04-30 16:49:04 +00002435 // module. Linker symbols or debug info are normally the best source of
2436 // information for start addr / size but they may be stripped in a released
2437 // binary. Two additional sources of information exist in Mach-O binaries:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2439 // function's start address in the
2440 // binary, relative to the text section.
2441 // eh_frame - the eh_frame FDEs have the start addr & size of
2442 // each function
2443 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2444 // all modern binaries.
2445 // Binaries built to run on older releases may need to use eh_frame
2446 // information.
Greg Clayton4c82d422012-05-18 23:20:01 +00002447
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448 if (text_section_sp && function_starts_data.GetByteSize()) {
2449 FunctionStarts::Entry function_start_entry;
2450 function_start_entry.data = false;
2451 lldb::offset_t function_start_offset = 0;
2452 function_start_entry.addr = text_section_sp->GetFileAddress();
2453 uint64_t delta;
2454 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2455 0) {
2456 // Now append the current entry
2457 function_start_entry.addr += delta;
2458 function_starts.Append(function_start_entry);
2459 }
2460 } else {
2461 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
Adrian Prantl05097242018-04-30 16:49:04 +00002462 // load command claiming an eh_frame but it doesn't actually have the
2463 // eh_frame content. And if we have a dSYM, we don't need to do any of
2464 // this fill-in-the-missing-symbols works anyway - the debug info should
2465 // give us all the functions in the module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002466 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2467 m_type != eTypeDebugInfo) {
2468 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
Pavel Labath3f2a0812017-06-28 09:09:19 +00002469 DWARFCallFrameInfo::EH);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002470 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2471 eh_frame.GetFunctionAddressAndSizeVector(functions);
2472 addr_t text_base_addr = text_section_sp->GetFileAddress();
2473 size_t count = functions.GetSize();
2474 for (size_t i = 0; i < count; ++i) {
2475 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2476 functions.GetEntryAtIndex(i);
2477 if (func) {
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002478 FunctionStarts::Entry function_start_entry;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002479 function_start_entry.addr = func->base - text_base_addr;
2480 function_starts.Append(function_start_entry);
2481 }
Jason Molendad63d3c72013-04-16 00:18:44 +00002482 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002483 }
2484 }
2485
2486 const size_t function_starts_count = function_starts.GetSize();
2487
2488 // For user process binaries (executables, dylibs, frameworks, bundles), if
Adrian Prantl05097242018-04-30 16:49:04 +00002489 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2490 // going to assume the binary has been stripped. Don't allow assembly
2491 // language instruction emulation because we don't know proper function
2492 // start boundaries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002493 //
2494 // For all other types of binaries (kernels, stand-alone bare board
Adrian Prantl05097242018-04-30 16:49:04 +00002495 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2496 // sections - we should not make any assumptions about them based on that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002497 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2498 m_allow_assembly_emulation_unwind_plans = false;
2499 Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2500 LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2501
2502 if (unwind_or_symbol_log)
2503 module_sp->LogMessage(
2504 unwind_or_symbol_log,
2505 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2506 }
2507
2508 const user_id_t TEXT_eh_frame_sectID =
2509 eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2510 : static_cast<user_id_t>(NO_SECT);
2511
2512 lldb::offset_t nlist_data_offset = 0;
2513
2514 uint32_t N_SO_index = UINT32_MAX;
2515
2516 MachSymtabSectionInfo section_info(section_list);
2517 std::vector<uint32_t> N_FUN_indexes;
2518 std::vector<uint32_t> N_NSYM_indexes;
2519 std::vector<uint32_t> N_INCL_indexes;
2520 std::vector<uint32_t> N_BRAC_indexes;
2521 std::vector<uint32_t> N_COMM_indexes;
2522 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2523 typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2524 typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2525 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2526 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2527 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00002528 // Any symbols that get merged into another will get an entry in this map
2529 // so we know
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2531 uint32_t nlist_idx = 0;
2532 Symbol *symbol_ptr = NULL;
2533
2534 uint32_t sym_idx = 0;
2535 Symbol *sym = NULL;
2536 size_t num_syms = 0;
2537 std::string memory_symbol_name;
2538 uint32_t unmapped_local_symbols_found = 0;
2539
2540 std::vector<TrieEntryWithOffset> trie_entries;
2541 std::set<lldb::addr_t> resolver_addresses;
2542
2543 if (dyld_trie_data.GetByteSize() > 0) {
2544 std::vector<llvm::StringRef> nameSlices;
2545 ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2546 resolver_addresses, trie_entries);
2547
2548 ConstString text_segment_name("__TEXT");
2549 SectionSP text_segment_sp =
2550 GetSectionList()->FindSectionByName(text_segment_name);
2551 if (text_segment_sp) {
2552 const lldb::addr_t text_segment_file_addr =
2553 text_segment_sp->GetFileAddress();
2554 if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2555 for (auto &e : trie_entries)
2556 e.entry.address += text_segment_file_addr;
2557 }
2558 }
2559 }
2560
2561 typedef std::set<ConstString> IndirectSymbols;
2562 IndirectSymbols indirect_symbol_names;
2563
2564#if defined(__APPLE__) && \
2565 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2566
2567 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
Adrian Prantl05097242018-04-30 16:49:04 +00002568 // optimized by moving LOCAL symbols out of the memory mapped portion of
2569 // the DSC. The symbol information has all been retained, but it isn't
2570 // available in the normal nlist data. However, there *are* duplicate
2571 // entries of *some*
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572 // LOCAL symbols in the normal nlist data. To handle this situation
2573 // correctly, we must first attempt
2574 // to parse any DSC unmapped symbol information. If we find any, we set a
Adrian Prantl05097242018-04-30 16:49:04 +00002575 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002576
2577 if (m_header.flags & 0x80000000u) {
Adrian Prantl05097242018-04-30 16:49:04 +00002578 // Before we can start mapping the DSC, we need to make certain the
2579 // target process is actually using the cache we can find.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002580
2581 // Next we need to determine the correct path for the dyld shared cache.
2582
2583 ArchSpec header_arch;
2584 GetArchitecture(header_arch);
2585 char dsc_path[PATH_MAX];
2586 char dsc_path_development[PATH_MAX];
2587
2588 snprintf(
2589 dsc_path, sizeof(dsc_path), "%s%s%s",
2590 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2591 */
2592 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2593 header_arch.GetArchitectureName());
2594
2595 snprintf(
2596 dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2597 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2598 */
2599 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
Ilia K4f730dc2016-09-12 05:25:33 +00002600 header_arch.GetArchitectureName(), ".development");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002601
2602 FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2603 FileSpec dsc_development_filespec(dsc_path_development, false);
2604 FileSpec dsc_filespec;
2605
2606 UUID dsc_uuid;
2607 UUID process_shared_cache_uuid;
Jason Molenda07580ff2018-05-04 00:59:37 +00002608 addr_t process_shared_cache_base_addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002609
2610 if (process) {
Jason Molenda07580ff2018-05-04 00:59:37 +00002611 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, process_shared_cache_uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002612 }
2613
Adrian Prantl05097242018-04-30 16:49:04 +00002614 // First see if we can find an exact match for the inferior process
2615 // shared cache UUID in the development or non-development shared caches
2616 // on disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617 if (process_shared_cache_uuid.IsValid()) {
2618 if (dsc_development_filespec.Exists()) {
2619 UUID dsc_development_uuid = GetSharedCacheUUID(
2620 dsc_development_filespec, byte_order, addr_byte_size);
2621 if (dsc_development_uuid.IsValid() &&
2622 dsc_development_uuid == process_shared_cache_uuid) {
2623 dsc_filespec = dsc_development_filespec;
2624 dsc_uuid = dsc_development_uuid;
2625 }
2626 }
2627 if (!dsc_uuid.IsValid() && dsc_nondevelopment_filespec.Exists()) {
2628 UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2629 dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2630 if (dsc_nondevelopment_uuid.IsValid() &&
2631 dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2632 dsc_filespec = dsc_nondevelopment_filespec;
2633 dsc_uuid = dsc_nondevelopment_uuid;
2634 }
2635 }
2636 }
2637
2638 // Failing a UUID match, prefer the development dyld_shared cache if both
2639 // are present.
2640 if (!dsc_filespec.Exists()) {
2641 if (dsc_development_filespec.Exists()) {
2642 dsc_filespec = dsc_development_filespec;
2643 } else {
2644 dsc_filespec = dsc_nondevelopment_filespec;
2645 }
2646 }
2647
2648 /* The dyld_cache_header has a pointer to the
2649 dyld_cache_local_symbols_info structure (localSymbolsOffset).
2650 The dyld_cache_local_symbols_info structure gives us three things:
2651 1. The start and count of the nlist records in the dyld_shared_cache
2652 file
2653 2. The start and size of the strings for these nlist records
2654 3. The start and count of dyld_cache_local_symbols_entry entries
2655
2656 There is one dyld_cache_local_symbols_entry per dylib/framework in the
2657 dyld shared cache.
2658 The "dylibOffset" field is the Mach-O header of this dylib/framework in
2659 the dyld shared cache.
2660 The dyld_cache_local_symbols_entry also lists the start of this
2661 dylib/framework's nlist records
2662 and the count of how many nlist records there are for this
2663 dylib/framework.
2664 */
2665
2666 // Process the dyld shared cache header to find the unmapped symbols
2667
Pavel Labath50251fc2017-12-21 10:54:30 +00002668 DataBufferSP dsc_data_sp = MapFileData(
2669 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002670 if (!dsc_uuid.IsValid()) {
2671 dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2672 }
2673 if (dsc_data_sp) {
2674 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2675
2676 bool uuid_match = true;
2677 if (dsc_uuid.IsValid() && process) {
2678 if (process_shared_cache_uuid.IsValid() &&
2679 dsc_uuid != process_shared_cache_uuid) {
2680 // The on-disk dyld_shared_cache file is not the same as the one in
Adrian Prantl05097242018-04-30 16:49:04 +00002681 // this process' memory, don't use it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682 uuid_match = false;
2683 ModuleSP module_sp(GetModule());
2684 if (module_sp)
2685 module_sp->ReportWarning("process shared cache does not match "
2686 "on-disk dyld_shared_cache file, some "
2687 "symbol names will be missing.");
2688 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002689 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00002690
Kate Stoneb9c1b512016-09-06 20:57:50 +00002691 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002692
Kate Stoneb9c1b512016-09-06 20:57:50 +00002693 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
Jason Molenda955dcf22016-05-04 03:09:40 +00002694
Kate Stoneb9c1b512016-09-06 20:57:50 +00002695 // If the mappingOffset points to a location inside the header, we've
2696 // opened an old dyld shared cache, and should not proceed further.
2697 if (uuid_match &&
2698 mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
Jason Molenda955dcf22016-05-04 03:09:40 +00002699
Pavel Labath50251fc2017-12-21 10:54:30 +00002700 DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2701 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2702 mappingOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002703
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2705 byte_order, addr_byte_size);
2706 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002707
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708 // The File addresses (from the in-memory Mach-O load commands) for
Adrian Prantl05097242018-04-30 16:49:04 +00002709 // the shared libraries in the shared library cache need to be
2710 // adjusted by an offset to match up with the dylibOffset identifying
2711 // field in the dyld_cache_local_symbol_entry's. This offset is
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 // recorded in mapping_offset_value.
2713 const uint64_t mapping_offset_value =
2714 dsc_mapping_info_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002715
Kate Stoneb9c1b512016-09-06 20:57:50 +00002716 offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2717 localSymbolsOffset);
2718 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2719 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002720
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 if (localSymbolsOffset && localSymbolsSize) {
2722 // Map the local symbols
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002723 DataBufferSP dsc_local_symbols_data_sp =
Pavel Labath50251fc2017-12-21 10:54:30 +00002724 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002725
2726 if (dsc_local_symbols_data_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2728 byte_order, addr_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002729
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002731
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2733 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2734 UndefinedNameToDescMap undefined_name_to_desc;
2735 SymbolIndexToName reexport_shlib_needs_fixup;
Jim Inghamea3ac272014-01-10 22:55:37 +00002736
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737 // Read the local_symbols_infos struct in one shot
2738 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2739 dsc_local_symbols_data.GetU32(&offset,
2740 &local_symbols_info.nlistOffset, 6);
Jim Inghamea3ac272014-01-10 22:55:37 +00002741
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742 SectionSP text_section_sp(
2743 section_list->FindSectionByName(GetSegmentNameTEXT()));
Greg Claytonb65c6292015-02-20 22:20:05 +00002744
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 uint32_t header_file_offset =
2746 (text_section_sp->GetFileAddress() - mapping_offset_value);
Jason Molendaa5609c82012-06-21 01:51:02 +00002747
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 offset = local_symbols_info.entriesOffset;
2749 for (uint32_t entry_index = 0;
2750 entry_index < local_symbols_info.entriesCount;
2751 entry_index++) {
2752 struct lldb_copy_dyld_cache_local_symbols_entry
2753 local_symbols_entry;
2754 local_symbols_entry.dylibOffset =
2755 dsc_local_symbols_data.GetU32(&offset);
2756 local_symbols_entry.nlistStartIndex =
2757 dsc_local_symbols_data.GetU32(&offset);
2758 local_symbols_entry.nlistCount =
2759 dsc_local_symbols_data.GetU32(&offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002760
Kate Stoneb9c1b512016-09-06 20:57:50 +00002761 if (header_file_offset == local_symbols_entry.dylibOffset) {
2762 unmapped_local_symbols_found = local_symbols_entry.nlistCount;
Jason Molendaa5609c82012-06-21 01:51:02 +00002763
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 // The normal nlist code cannot correctly size the Symbols
2765 // array, we need to allocate it here.
2766 sym = symtab->Resize(
2767 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2768 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2769 num_syms = symtab->GetNumSymbols();
Jason Molendaa5609c82012-06-21 01:51:02 +00002770
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771 nlist_data_offset =
2772 local_symbols_info.nlistOffset +
2773 (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2774 uint32_t string_table_offset =
2775 local_symbols_info.stringsOffset;
Jason Molendaa5609c82012-06-21 01:51:02 +00002776
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 for (uint32_t nlist_index = 0;
2778 nlist_index < local_symbols_entry.nlistCount;
2779 nlist_index++) {
2780 /////////////////////////////
Jason Molenda649a6072015-11-10 05:21:54 +00002781 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 struct nlist_64 nlist;
2783 if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(
2784 nlist_data_offset, nlist_byte_size))
2785 break;
Eugene Zelenko8157a882015-10-23 16:56:07 +00002786
Kate Stoneb9c1b512016-09-06 20:57:50 +00002787 nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(
2788 &nlist_data_offset);
2789 nlist.n_type = dsc_local_symbols_data.GetU8_unchecked(
2790 &nlist_data_offset);
2791 nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked(
2792 &nlist_data_offset);
2793 nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked(
2794 &nlist_data_offset);
2795 nlist.n_value =
2796 dsc_local_symbols_data.GetAddress_unchecked(
2797 &nlist_data_offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002798
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 SymbolType type = eSymbolTypeInvalid;
2800 const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2801 string_table_offset + nlist.n_strx);
Jason Molendaf8130862012-06-22 03:28:35 +00002802
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002804 // No symbol should be NULL, even the symbols with no
Adrian Prantl05097242018-04-30 16:49:04 +00002805 // string values should have an offset zero which
2806 // points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 Host::SystemLog(
2808 Host::eSystemLogError,
2809 "error: DSC unmapped local symbol[%u] has invalid "
2810 "string table offset 0x%x in %s, ignoring symbol\n",
2811 entry_index, nlist.n_strx,
2812 module_sp->GetFileSpec().GetPath().c_str());
Greg Claytonfd814c52013-08-13 01:42:25 +00002813 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002814 }
2815 if (symbol_name[0] == '\0')
Greg Claytonfd814c52013-08-13 01:42:25 +00002816 symbol_name = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002817
Kate Stoneb9c1b512016-09-06 20:57:50 +00002818 const char *symbol_name_non_abi_mangled = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002819
Kate Stoneb9c1b512016-09-06 20:57:50 +00002820 SectionSP symbol_section;
2821 uint32_t symbol_byte_size = 0;
2822 bool add_nlist = true;
2823 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2824 bool demangled_is_synthesized = false;
2825 bool is_gsym = false;
2826 bool set_value = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00002827
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 assert(sym_idx < num_syms);
Jason Molenda4e7511e2013-03-06 23:19:17 +00002829
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 sym[sym_idx].SetDebug(is_debug);
Greg Clayton29e08cb2012-03-14 01:53:24 +00002831
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832 if (is_debug) {
2833 switch (nlist.n_type) {
2834 case N_GSYM:
2835 // global symbol: name,,NO_SECT,type,0
2836 // Sometimes the N_GSYM value contains the address.
2837
2838 // FIXME: In the .o files, we have a GSYM and a debug
2839 // symbol for all the ObjC data. They
2840 // have the same address, but we want to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +00002841 // we always find only the real symbol, 'cause we
2842 // don't currently correctly attribute the
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 // GSYM one to the ObjCClass/Ivar/MetaClass
Adrian Prantl05097242018-04-30 16:49:04 +00002844 // symbol type. This is a temporary hack to make
2845 // sure the ObjectiveC symbols get treated correctly.
2846 // To do this right, we should coalesce all the GSYM
2847 // & global symbols that have the same address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848
2849 is_gsym = true;
2850 sym[sym_idx].SetExternal(true);
2851
2852 if (symbol_name && symbol_name[0] == '_' &&
2853 symbol_name[1] == 'O') {
Greg Clayton1e28adf2015-02-25 17:25:02 +00002854 llvm::StringRef symbol_name_ref(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 if (symbol_name_ref.startswith(
2856 g_objc_v2_prefix_class)) {
2857 symbol_name_non_abi_mangled = symbol_name + 1;
2858 symbol_name =
2859 symbol_name + g_objc_v2_prefix_class.size();
2860 type = eSymbolTypeObjCClass;
2861 demangled_is_synthesized = true;
2862
2863 } else if (symbol_name_ref.startswith(
2864 g_objc_v2_prefix_metaclass)) {
2865 symbol_name_non_abi_mangled = symbol_name + 1;
2866 symbol_name = symbol_name +
2867 g_objc_v2_prefix_metaclass.size();
2868 type = eSymbolTypeObjCMetaClass;
2869 demangled_is_synthesized = true;
2870 } else if (symbol_name_ref.startswith(
2871 g_objc_v2_prefix_ivar)) {
2872 symbol_name_non_abi_mangled = symbol_name + 1;
2873 symbol_name =
2874 symbol_name + g_objc_v2_prefix_ivar.size();
2875 type = eSymbolTypeObjCIVar;
2876 demangled_is_synthesized = true;
Greg Clayton1e28adf2015-02-25 17:25:02 +00002877 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002879 if (nlist.n_value != 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 symbol_section = section_info.GetSection(
2881 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002882 type = eSymbolTypeData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002883 }
2884 break;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002885
Kate Stoneb9c1b512016-09-06 20:57:50 +00002886 case N_FNAME:
2887 // procedure name (f77 kludge): name,,NO_SECT,0,0
2888 type = eSymbolTypeCompiler;
2889 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002890
Kate Stoneb9c1b512016-09-06 20:57:50 +00002891 case N_FUN:
2892 // procedure: name,,n_sect,linenumber,address
2893 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002894 type = eSymbolTypeCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 symbol_section = section_info.GetSection(
2896 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002897
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898 N_FUN_addr_to_sym_idx.insert(
2899 std::make_pair(nlist.n_value, sym_idx));
2900 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00002901 // symbol table in lieu of using nlist_idx in case
2902 // we ever start trimming entries out
Greg Claytonfd814c52013-08-13 01:42:25 +00002903 N_FUN_indexes.push_back(sym_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002904 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002905 type = eSymbolTypeCompiler;
2906
Kate Stoneb9c1b512016-09-06 20:57:50 +00002907 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00002908 // Copy the size of the function into the
2909 // original
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 // STAB entry so we don't have
2911 // to hunt for it later
2912 symtab->SymbolAtIndex(N_FUN_indexes.back())
2913 ->SetByteSize(nlist.n_value);
2914 N_FUN_indexes.pop_back();
2915 // We don't really need the end function STAB as
Adrian Prantl05097242018-04-30 16:49:04 +00002916 // it contains the size which we already placed
2917 // with the original symbol, so don't add it if
2918 // we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 add_nlist = false;
Greg Claytondacc4a92013-05-14 22:19:37 +00002920 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 }
2922 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002923
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 case N_STSYM:
2925 // static symbol: name,,n_sect,type,address
2926 N_STSYM_addr_to_sym_idx.insert(
2927 std::make_pair(nlist.n_value, sym_idx));
2928 symbol_section = section_info.GetSection(
2929 nlist.n_sect, nlist.n_value);
2930 if (symbol_name && symbol_name[0]) {
2931 type = ObjectFile::GetSymbolTypeFromName(
2932 symbol_name + 1, eSymbolTypeData);
2933 }
2934 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002935
Kate Stoneb9c1b512016-09-06 20:57:50 +00002936 case N_LCSYM:
2937 // .lcomm symbol: name,,n_sect,type,address
2938 symbol_section = section_info.GetSection(
2939 nlist.n_sect, nlist.n_value);
2940 type = eSymbolTypeCommonBlock;
2941 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002942
Kate Stoneb9c1b512016-09-06 20:57:50 +00002943 case N_BNSYM:
2944 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00002945 // table in lieu of using nlist_idx in case we ever
2946 // start trimming entries out Skip these if we want
2947 // minimal symbol tables
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 add_nlist = false;
2949 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002950
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 case N_ENSYM:
2952 // Set the size of the N_BNSYM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002953 // index of this N_ENSYM so that we can always skip
2954 // the entire symbol if we need to navigate more
2955 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 // Skip these if we want minimal symbol tables
2957 add_nlist = false;
2958 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002959
Kate Stoneb9c1b512016-09-06 20:57:50 +00002960 case N_OPT:
2961 // emitted with gcc2_compiled and in gcc source
2962 type = eSymbolTypeCompiler;
2963 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002964
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965 case N_RSYM:
2966 // register sym: name,,NO_SECT,type,register
2967 type = eSymbolTypeVariable;
2968 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002969
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 case N_SLINE:
2971 // src line: 0,,n_sect,linenumber,address
2972 symbol_section = section_info.GetSection(
2973 nlist.n_sect, nlist.n_value);
2974 type = eSymbolTypeLineEntry;
2975 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002976
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977 case N_SSYM:
2978 // structure elt: name,,NO_SECT,type,struct_offset
2979 type = eSymbolTypeVariableType;
2980 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002981
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 case N_SO:
2983 // source file name
2984 type = eSymbolTypeSourceFile;
2985 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002986 add_nlist = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 if (N_SO_index != UINT32_MAX) {
2988 // Set the size of the N_SO to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002989 // index of this N_SO so that we can always skip
2990 // the entire N_SO if we need to navigate more
2991 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
2993 symbol_ptr->SetByteSize(sym_idx);
2994 symbol_ptr->SetSizeIsSibling(true);
Greg Claytonfd814c52013-08-13 01:42:25 +00002995 }
2996 N_NSYM_indexes.clear();
2997 N_INCL_indexes.clear();
2998 N_BRAC_indexes.clear();
2999 N_COMM_indexes.clear();
3000 N_FUN_indexes.clear();
3001 N_SO_index = UINT32_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002 } else {
3003 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00003004 // symbol table in lieu of using nlist_idx in case
3005 // we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003006 const bool N_SO_has_full_path =
3007 symbol_name[0] == '/';
3008 if (N_SO_has_full_path) {
3009 if ((N_SO_index == sym_idx - 1) &&
3010 ((sym_idx - 1) < num_syms)) {
3011 // We have two consecutive N_SO entries where
Adrian Prantl05097242018-04-30 16:49:04 +00003012 // the first contains a directory and the
3013 // second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003014 sym[sym_idx - 1].GetMangled().SetValue(
3015 ConstString(symbol_name), false);
3016 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3017 add_nlist = false;
3018 } else {
3019 // This is the first entry in a N_SO that
3020 // contains a directory or
3021 // a full path to the source file
Greg Claytonfd814c52013-08-13 01:42:25 +00003022 N_SO_index = sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003023 }
3024 } else if ((N_SO_index == sym_idx - 1) &&
3025 ((sym_idx - 1) < num_syms)) {
3026 // This is usually the second N_SO entry that
Adrian Prantl05097242018-04-30 16:49:04 +00003027 // contains just the filename, so here we combine
3028 // it with the first one if we are minimizing the
3029 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003030 const char *so_path =
3031 sym[sym_idx - 1]
3032 .GetMangled()
3033 .GetDemangledName(
3034 lldb::eLanguageTypeUnknown)
3035 .AsCString();
3036 if (so_path && so_path[0]) {
3037 std::string full_so_path(so_path);
3038 const size_t double_slash_pos =
3039 full_so_path.find("//");
3040 if (double_slash_pos != std::string::npos) {
3041 // The linker has been generating bad N_SO
3042 // entries with doubled up paths
Adrian Prantl05097242018-04-30 16:49:04 +00003043 // in the format "%s%s" where the first
3044 // string in the DW_AT_comp_dir, and the
3045 // second is the directory for the source
3046 // file so you end up with a path that looks
3047 // like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 FileSpec so_dir(so_path, false);
3049 if (!so_dir.Exists()) {
3050 so_dir.SetFile(
3051 &full_so_path[double_slash_pos + 1],
3052 false);
3053 if (so_dir.Exists()) {
3054 // Trim off the incorrect path
3055 full_so_path.erase(0,
3056 double_slash_pos + 1);
3057 }
3058 }
3059 }
3060 if (*full_so_path.rbegin() != '/')
3061 full_so_path += '/';
3062 full_so_path += symbol_name;
3063 sym[sym_idx - 1].GetMangled().SetValue(
3064 ConstString(full_so_path.c_str()), false);
3065 add_nlist = false;
3066 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3067 }
3068 } else {
3069 // This could be a relative path to a N_SO
3070 N_SO_index = sym_idx;
Greg Claytonfd814c52013-08-13 01:42:25 +00003071 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003072 }
3073 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003074
Kate Stoneb9c1b512016-09-06 20:57:50 +00003075 case N_OSO:
3076 // object file name: name,,0,0,st_mtime
3077 type = eSymbolTypeObjectFile;
3078 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003079
Kate Stoneb9c1b512016-09-06 20:57:50 +00003080 case N_LSYM:
3081 // local sym: name,,NO_SECT,type,offset
3082 type = eSymbolTypeLocal;
3083 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003084
Kate Stoneb9c1b512016-09-06 20:57:50 +00003085 //----------------------------------------------------------------------
3086 // INCL scopes
3087 //----------------------------------------------------------------------
3088 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00003089 // include file beginning: name,,NO_SECT,0,sum We use
3090 // the current number of symbols in the symbol table
3091 // in lieu of using nlist_idx in case we ever start
3092 // trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 N_INCL_indexes.push_back(sym_idx);
3094 type = eSymbolTypeScopeBegin;
3095 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003096
Kate Stoneb9c1b512016-09-06 20:57:50 +00003097 case N_EINCL:
3098 // include file end: name,,NO_SECT,0,0
3099 // Set the size of the N_BINCL to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003100 // index of this N_EINCL so that we can always skip
3101 // the entire symbol if we need to navigate more
3102 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103 if (!N_INCL_indexes.empty()) {
3104 symbol_ptr =
3105 symtab->SymbolAtIndex(N_INCL_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003106 symbol_ptr->SetByteSize(sym_idx + 1);
3107 symbol_ptr->SetSizeIsSibling(true);
3108 N_INCL_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003109 }
3110 type = eSymbolTypeScopeEnd;
3111 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003112
Kate Stoneb9c1b512016-09-06 20:57:50 +00003113 case N_SOL:
3114 // #included file name: name,,n_sect,0,address
3115 type = eSymbolTypeHeaderFile;
Greg Claytonfd814c52013-08-13 01:42:25 +00003116
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 // We currently don't use the header files on darwin
3118 add_nlist = false;
3119 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003120
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121 case N_PARAMS:
3122 // compiler parameters: name,,NO_SECT,0,0
3123 type = eSymbolTypeCompiler;
3124 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003125
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126 case N_VERSION:
3127 // compiler version: name,,NO_SECT,0,0
3128 type = eSymbolTypeCompiler;
3129 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003130
Kate Stoneb9c1b512016-09-06 20:57:50 +00003131 case N_OLEVEL:
3132 // compiler -O level: name,,NO_SECT,0,0
3133 type = eSymbolTypeCompiler;
3134 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003135
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136 case N_PSYM:
3137 // parameter: name,,NO_SECT,type,offset
3138 type = eSymbolTypeVariable;
3139 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003140
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141 case N_ENTRY:
3142 // alternate entry: name,,n_sect,linenumber,address
3143 symbol_section = section_info.GetSection(
3144 nlist.n_sect, nlist.n_value);
3145 type = eSymbolTypeLineEntry;
3146 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003147
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 //----------------------------------------------------------------------
3149 // Left and Right Braces
3150 //----------------------------------------------------------------------
3151 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00003152 // left bracket: 0,,NO_SECT,nesting level,address We
3153 // use the current number of symbols in the symbol
3154 // table in lieu of using nlist_idx in case we ever
3155 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156 symbol_section = section_info.GetSection(
3157 nlist.n_sect, nlist.n_value);
3158 N_BRAC_indexes.push_back(sym_idx);
3159 type = eSymbolTypeScopeBegin;
3160 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003161
Kate Stoneb9c1b512016-09-06 20:57:50 +00003162 case N_RBRAC:
3163 // right bracket: 0,,NO_SECT,nesting level,address
3164 // Set the size of the N_LBRAC to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003165 // index of this N_RBRAC so that we can always skip
3166 // the entire symbol if we need to navigate more
3167 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003168 symbol_section = section_info.GetSection(
3169 nlist.n_sect, nlist.n_value);
3170 if (!N_BRAC_indexes.empty()) {
3171 symbol_ptr =
3172 symtab->SymbolAtIndex(N_BRAC_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003173 symbol_ptr->SetByteSize(sym_idx + 1);
3174 symbol_ptr->SetSizeIsSibling(true);
3175 N_BRAC_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003176 }
3177 type = eSymbolTypeScopeEnd;
3178 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003179
Kate Stoneb9c1b512016-09-06 20:57:50 +00003180 case N_EXCL:
3181 // deleted include file: name,,NO_SECT,0,sum
3182 type = eSymbolTypeHeaderFile;
3183 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003184
Kate Stoneb9c1b512016-09-06 20:57:50 +00003185 //----------------------------------------------------------------------
3186 // COMM scopes
3187 //----------------------------------------------------------------------
3188 case N_BCOMM:
3189 // begin common: name,,NO_SECT,0,0
3190 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00003191 // table in lieu of using nlist_idx in case we ever
3192 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003193 type = eSymbolTypeScopeBegin;
3194 N_COMM_indexes.push_back(sym_idx);
3195 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003196
Kate Stoneb9c1b512016-09-06 20:57:50 +00003197 case N_ECOML:
3198 // end common (local name): 0,,n_sect,0,address
3199 symbol_section = section_info.GetSection(
3200 nlist.n_sect, nlist.n_value);
3201 // Fall through
Greg Claytonfd814c52013-08-13 01:42:25 +00003202
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 case N_ECOMM:
3204 // end common: name,,n_sect,0,0
3205 // Set the size of the N_BCOMM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003206 // index of this N_ECOMM/N_ECOML so that we can
3207 // always skip the entire symbol if we need to
3208 // navigate more quickly at the source level when
3209 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003210 if (!N_COMM_indexes.empty()) {
3211 symbol_ptr =
3212 symtab->SymbolAtIndex(N_COMM_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003213 symbol_ptr->SetByteSize(sym_idx + 1);
3214 symbol_ptr->SetSizeIsSibling(true);
3215 N_COMM_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003216 }
3217 type = eSymbolTypeScopeEnd;
3218 break;
3219
3220 case N_LENG:
3221 // second stab entry with length information
3222 type = eSymbolTypeAdditional;
3223 break;
3224
3225 default:
3226 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003227 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228 } else {
3229 // uint8_t n_pext = N_PEXT & nlist.n_type;
3230 uint8_t n_type = N_TYPE & nlist.n_type;
3231 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
Greg Claytonfd814c52013-08-13 01:42:25 +00003232
Kate Stoneb9c1b512016-09-06 20:57:50 +00003233 switch (n_type) {
3234 case N_INDR: {
3235 const char *reexport_name_cstr =
3236 strtab_data.PeekCStr(nlist.n_value);
3237 if (reexport_name_cstr && reexport_name_cstr[0]) {
3238 type = eSymbolTypeReExported;
3239 ConstString reexport_name(
3240 reexport_name_cstr +
3241 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3242 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3243 set_value = false;
3244 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3245 indirect_symbol_names.insert(
3246 ConstString(symbol_name +
3247 ((symbol_name[0] == '_') ? 1 : 0)));
3248 } else
3249 type = eSymbolTypeUndefined;
3250 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003251
Kate Stoneb9c1b512016-09-06 20:57:50 +00003252 case N_UNDF:
3253 if (symbol_name && symbol_name[0]) {
3254 ConstString undefined_name(
3255 symbol_name +
3256 ((symbol_name[0] == '_') ? 1 : 0));
3257 undefined_name_to_desc[undefined_name] =
3258 nlist.n_desc;
3259 }
3260 // Fall through
3261 case N_PBUD:
3262 type = eSymbolTypeUndefined;
3263 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003264
Kate Stoneb9c1b512016-09-06 20:57:50 +00003265 case N_ABS:
3266 type = eSymbolTypeAbsolute;
3267 break;
Greg Clayton60038be2015-02-14 00:51:13 +00003268
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269 case N_SECT: {
3270 symbol_section = section_info.GetSection(
3271 nlist.n_sect, nlist.n_value);
Jason Molenda62e06812016-02-16 04:14:33 +00003272
Kate Stoneb9c1b512016-09-06 20:57:50 +00003273 if (symbol_section == NULL) {
3274 // TODO: warn about this?
3275 add_nlist = false;
3276 break;
3277 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003278
Kate Stoneb9c1b512016-09-06 20:57:50 +00003279 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3280 type = eSymbolTypeException;
3281 } else {
3282 uint32_t section_type =
3283 symbol_section->Get() & SECTION_TYPE;
Greg Claytonfd814c52013-08-13 01:42:25 +00003284
Kate Stoneb9c1b512016-09-06 20:57:50 +00003285 switch (section_type) {
3286 case S_CSTRING_LITERALS:
3287 type = eSymbolTypeData;
3288 break; // section with only literal C strings
3289 case S_4BYTE_LITERALS:
3290 type = eSymbolTypeData;
3291 break; // section with only 4 byte literals
3292 case S_8BYTE_LITERALS:
3293 type = eSymbolTypeData;
3294 break; // section with only 8 byte literals
3295 case S_LITERAL_POINTERS:
3296 type = eSymbolTypeTrampoline;
3297 break; // section with only pointers to literals
3298 case S_NON_LAZY_SYMBOL_POINTERS:
3299 type = eSymbolTypeTrampoline;
3300 break; // section with only non-lazy symbol
3301 // pointers
3302 case S_LAZY_SYMBOL_POINTERS:
3303 type = eSymbolTypeTrampoline;
3304 break; // section with only lazy symbol pointers
3305 case S_SYMBOL_STUBS:
3306 type = eSymbolTypeTrampoline;
3307 break; // section with only symbol stubs, byte
3308 // size of stub in the reserved2 field
3309 case S_MOD_INIT_FUNC_POINTERS:
3310 type = eSymbolTypeCode;
3311 break; // section with only function pointers for
3312 // initialization
3313 case S_MOD_TERM_FUNC_POINTERS:
3314 type = eSymbolTypeCode;
3315 break; // section with only function pointers for
3316 // termination
3317 case S_INTERPOSING:
3318 type = eSymbolTypeTrampoline;
3319 break; // section with only pairs of function
3320 // pointers for interposing
3321 case S_16BYTE_LITERALS:
3322 type = eSymbolTypeData;
3323 break; // section with only 16 byte literals
3324 case S_DTRACE_DOF:
3325 type = eSymbolTypeInstrumentation;
3326 break;
3327 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3328 type = eSymbolTypeTrampoline;
3329 break;
3330 default:
3331 switch (symbol_section->GetType()) {
3332 case lldb::eSectionTypeCode:
3333 type = eSymbolTypeCode;
Greg Claytonfd814c52013-08-13 01:42:25 +00003334 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003335 case eSectionTypeData:
3336 case eSectionTypeDataCString: // Inlined C string
3337 // data
3338 case eSectionTypeDataCStringPointers: // Pointers
3339 // to C
3340 // string
3341 // data
3342 case eSectionTypeDataSymbolAddress: // Address of
3343 // a symbol in
3344 // the symbol
3345 // table
3346 case eSectionTypeData4:
3347 case eSectionTypeData8:
3348 case eSectionTypeData16:
3349 type = eSymbolTypeData;
3350 break;
3351 default:
3352 break;
3353 }
3354 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003355 }
3356
Kate Stoneb9c1b512016-09-06 20:57:50 +00003357 if (type == eSymbolTypeInvalid) {
3358 const char *symbol_sect_name =
3359 symbol_section->GetName().AsCString();
3360 if (symbol_section->IsDescendant(
3361 text_section_sp.get())) {
3362 if (symbol_section->IsClear(
3363 S_ATTR_PURE_INSTRUCTIONS |
3364 S_ATTR_SELF_MODIFYING_CODE |
3365 S_ATTR_SOME_INSTRUCTIONS))
3366 type = eSymbolTypeData;
3367 else
3368 type = eSymbolTypeCode;
3369 } else if (symbol_section->IsDescendant(
3370 data_section_sp.get()) ||
3371 symbol_section->IsDescendant(
3372 data_dirty_section_sp.get()) ||
3373 symbol_section->IsDescendant(
3374 data_const_section_sp.get())) {
3375 if (symbol_sect_name &&
3376 ::strstr(symbol_sect_name, "__objc") ==
3377 symbol_sect_name) {
3378 type = eSymbolTypeRuntime;
Greg Claytonfd814c52013-08-13 01:42:25 +00003379
Kate Stoneb9c1b512016-09-06 20:57:50 +00003380 if (symbol_name) {
3381 llvm::StringRef symbol_name_ref(
3382 symbol_name);
3383 if (symbol_name_ref.startswith("_OBJC_")) {
3384 static const llvm::StringRef
3385 g_objc_v2_prefix_class(
3386 "_OBJC_CLASS_$_");
3387 static const llvm::StringRef
3388 g_objc_v2_prefix_metaclass(
3389 "_OBJC_METACLASS_$_");
3390 static const llvm::StringRef
3391 g_objc_v2_prefix_ivar(
3392 "_OBJC_IVAR_$_");
3393 if (symbol_name_ref.startswith(
3394 g_objc_v2_prefix_class)) {
3395 symbol_name_non_abi_mangled =
3396 symbol_name + 1;
3397 symbol_name =
3398 symbol_name +
3399 g_objc_v2_prefix_class.size();
3400 type = eSymbolTypeObjCClass;
3401 demangled_is_synthesized = true;
3402 } else if (
3403 symbol_name_ref.startswith(
3404 g_objc_v2_prefix_metaclass)) {
3405 symbol_name_non_abi_mangled =
3406 symbol_name + 1;
3407 symbol_name =
3408 symbol_name +
3409 g_objc_v2_prefix_metaclass.size();
3410 type = eSymbolTypeObjCMetaClass;
3411 demangled_is_synthesized = true;
3412 } else if (symbol_name_ref.startswith(
3413 g_objc_v2_prefix_ivar)) {
3414 symbol_name_non_abi_mangled =
3415 symbol_name + 1;
3416 symbol_name =
3417 symbol_name +
3418 g_objc_v2_prefix_ivar.size();
3419 type = eSymbolTypeObjCIVar;
3420 demangled_is_synthesized = true;
3421 }
Greg Clayton38f9cc42014-06-16 22:53:16 +00003422 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003423 }
3424 } else if (symbol_sect_name &&
3425 ::strstr(symbol_sect_name,
3426 "__gcc_except_tab") ==
3427 symbol_sect_name) {
3428 type = eSymbolTypeException;
3429 } else {
3430 type = eSymbolTypeData;
Greg Claytonfd814c52013-08-13 01:42:25 +00003431 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003432 } else if (symbol_sect_name &&
3433 ::strstr(symbol_sect_name,
3434 "__IMPORT") ==
3435 symbol_sect_name) {
3436 type = eSymbolTypeTrampoline;
3437 } else if (symbol_section->IsDescendant(
3438 objc_section_sp.get())) {
3439 type = eSymbolTypeRuntime;
3440 if (symbol_name && symbol_name[0] == '.') {
3441 llvm::StringRef symbol_name_ref(symbol_name);
3442 static const llvm::StringRef
3443 g_objc_v1_prefix_class(
3444 ".objc_class_name_");
3445 if (symbol_name_ref.startswith(
3446 g_objc_v1_prefix_class)) {
3447 symbol_name_non_abi_mangled = symbol_name;
3448 symbol_name = symbol_name +
3449 g_objc_v1_prefix_class.size();
3450 type = eSymbolTypeObjCClass;
3451 demangled_is_synthesized = true;
3452 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003453 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003454 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003455 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003456 }
3457 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003458 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003459 }
Greg Claytondacc4a92013-05-14 22:19:37 +00003460
Kate Stoneb9c1b512016-09-06 20:57:50 +00003461 if (add_nlist) {
3462 uint64_t symbol_value = nlist.n_value;
3463 if (symbol_name_non_abi_mangled) {
3464 sym[sym_idx].GetMangled().SetMangledName(
3465 ConstString(symbol_name_non_abi_mangled));
3466 sym[sym_idx].GetMangled().SetDemangledName(
3467 ConstString(symbol_name));
3468 } else {
3469 bool symbol_name_is_mangled = false;
Greg Claytonfd814c52013-08-13 01:42:25 +00003470
Kate Stoneb9c1b512016-09-06 20:57:50 +00003471 if (symbol_name && symbol_name[0] == '_') {
Greg Claytonfd814c52013-08-13 01:42:25 +00003472 symbol_name_is_mangled = symbol_name[1] == '_';
Kate Stoneb9c1b512016-09-06 20:57:50 +00003473 symbol_name++; // Skip the leading underscore
3474 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003475
Kate Stoneb9c1b512016-09-06 20:57:50 +00003476 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003477 ConstString const_symbol_name(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003478 sym[sym_idx].GetMangled().SetValue(
3479 const_symbol_name, symbol_name_is_mangled);
3480 if (is_gsym && is_debug) {
3481 const char *gsym_name =
3482 sym[sym_idx]
3483 .GetMangled()
3484 .GetName(lldb::eLanguageTypeUnknown,
3485 Mangled::ePreferMangled)
3486 .GetCString();
3487 if (gsym_name)
3488 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3489 }
3490 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003491 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003492 if (symbol_section) {
3493 const addr_t section_file_addr =
3494 symbol_section->GetFileAddress();
3495 if (symbol_byte_size == 0 &&
3496 function_starts_count > 0) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003497 addr_t symbol_lookup_file_addr = nlist.n_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003498 // Do an exact address match for non-ARM addresses,
Adrian Prantl05097242018-04-30 16:49:04 +00003499 // else get the closest since the symbol might be a
3500 // thumb symbol which has an address with bit zero
3501 // set
Kate Stoneb9c1b512016-09-06 20:57:50 +00003502 FunctionStarts::Entry *func_start_entry =
3503 function_starts.FindEntry(
3504 symbol_lookup_file_addr, !is_arm);
3505 if (is_arm && func_start_entry) {
3506 // Verify that the function start address is the
Adrian Prantl05097242018-04-30 16:49:04 +00003507 // symbol address (ARM) or the symbol address + 1
3508 // (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003509 if (func_start_entry->addr !=
3510 symbol_lookup_file_addr &&
3511 func_start_entry->addr !=
3512 (symbol_lookup_file_addr + 1)) {
3513 // Not the right entry, NULL it out...
3514 func_start_entry = NULL;
3515 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003516 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003517 if (func_start_entry) {
3518 func_start_entry->data = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00003519
Kate Stoneb9c1b512016-09-06 20:57:50 +00003520 addr_t symbol_file_addr = func_start_entry->addr;
3521 uint32_t symbol_flags = 0;
3522 if (is_arm) {
3523 if (symbol_file_addr & 1)
3524 symbol_flags =
3525 MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3526 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3527 }
3528
3529 const FunctionStarts::Entry
3530 *next_func_start_entry =
3531 function_starts.FindNextEntry(
3532 func_start_entry);
3533 const addr_t section_end_file_addr =
3534 section_file_addr +
3535 symbol_section->GetByteSize();
3536 if (next_func_start_entry) {
3537 addr_t next_symbol_file_addr =
3538 next_func_start_entry->addr;
3539 // Be sure the clear the Thumb address bit when
Adrian Prantl05097242018-04-30 16:49:04 +00003540 // we calculate the size from the current and
3541 // next address
Greg Claytonfd814c52013-08-13 01:42:25 +00003542 if (is_arm)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003543 next_symbol_file_addr &=
3544 THUMB_ADDRESS_BIT_MASK;
3545 symbol_byte_size = std::min<lldb::addr_t>(
3546 next_symbol_file_addr - symbol_file_addr,
3547 section_end_file_addr - symbol_file_addr);
3548 } else {
3549 symbol_byte_size =
3550 section_end_file_addr - symbol_file_addr;
3551 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003552 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003553 }
3554 symbol_value -= section_file_addr;
Greg Claytonfd814c52013-08-13 01:42:25 +00003555 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003556
Kate Stoneb9c1b512016-09-06 20:57:50 +00003557 if (is_debug == false) {
3558 if (type == eSymbolTypeCode) {
3559 // See if we can find a N_FUN entry for any code
Adrian Prantl05097242018-04-30 16:49:04 +00003560 // symbols. If we do find a match, and the name
3561 // matches, then we can merge the two into just the
3562 // function symbol to avoid duplicate entries in
3563 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003564 std::pair<ValueToSymbolIndexMap::const_iterator,
3565 ValueToSymbolIndexMap::const_iterator>
3566 range;
3567 range = N_FUN_addr_to_sym_idx.equal_range(
3568 nlist.n_value);
3569 if (range.first != range.second) {
3570 bool found_it = false;
3571 for (ValueToSymbolIndexMap::const_iterator pos =
3572 range.first;
3573 pos != range.second; ++pos) {
3574 if (sym[sym_idx].GetMangled().GetName(
3575 lldb::eLanguageTypeUnknown,
3576 Mangled::ePreferMangled) ==
3577 sym[pos->second].GetMangled().GetName(
3578 lldb::eLanguageTypeUnknown,
3579 Mangled::ePreferMangled)) {
3580 m_nlist_idx_to_sym_idx[nlist_idx] =
3581 pos->second;
3582 // We just need the flags from the linker
3583 // symbol, so put these flags
3584 // into the N_FUN flags to avoid duplicate
3585 // symbols in the symbol table
3586 sym[pos->second].SetExternal(
3587 sym[sym_idx].IsExternal());
3588 sym[pos->second].SetFlags(nlist.n_type << 16 |
3589 nlist.n_desc);
3590 if (resolver_addresses.find(nlist.n_value) !=
3591 resolver_addresses.end())
3592 sym[pos->second].SetType(
3593 eSymbolTypeResolver);
3594 sym[sym_idx].Clear();
3595 found_it = true;
3596 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003597 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003598 }
3599 if (found_it)
3600 continue;
3601 } else {
3602 if (resolver_addresses.find(nlist.n_value) !=
3603 resolver_addresses.end())
3604 type = eSymbolTypeResolver;
Greg Claytonfd814c52013-08-13 01:42:25 +00003605 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003606 } else if (type == eSymbolTypeData ||
3607 type == eSymbolTypeObjCClass ||
3608 type == eSymbolTypeObjCMetaClass ||
3609 type == eSymbolTypeObjCIVar) {
3610 // See if we can find a N_STSYM entry for any data
Adrian Prantl05097242018-04-30 16:49:04 +00003611 // symbols. If we do find a match, and the name
3612 // matches, then we can merge the two into just the
3613 // Static symbol to avoid duplicate entries in the
3614 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003615 std::pair<ValueToSymbolIndexMap::const_iterator,
3616 ValueToSymbolIndexMap::const_iterator>
3617 range;
3618 range = N_STSYM_addr_to_sym_idx.equal_range(
3619 nlist.n_value);
3620 if (range.first != range.second) {
3621 bool found_it = false;
3622 for (ValueToSymbolIndexMap::const_iterator pos =
3623 range.first;
3624 pos != range.second; ++pos) {
3625 if (sym[sym_idx].GetMangled().GetName(
3626 lldb::eLanguageTypeUnknown,
3627 Mangled::ePreferMangled) ==
3628 sym[pos->second].GetMangled().GetName(
3629 lldb::eLanguageTypeUnknown,
3630 Mangled::ePreferMangled)) {
3631 m_nlist_idx_to_sym_idx[nlist_idx] =
3632 pos->second;
3633 // We just need the flags from the linker
3634 // symbol, so put these flags
3635 // into the N_STSYM flags to avoid duplicate
3636 // symbols in the symbol table
3637 sym[pos->second].SetExternal(
3638 sym[sym_idx].IsExternal());
3639 sym[pos->second].SetFlags(nlist.n_type << 16 |
3640 nlist.n_desc);
3641 sym[sym_idx].Clear();
3642 found_it = true;
3643 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003645 }
3646 if (found_it)
3647 continue;
3648 } else {
3649 const char *gsym_name =
3650 sym[sym_idx]
3651 .GetMangled()
3652 .GetName(lldb::eLanguageTypeUnknown,
3653 Mangled::ePreferMangled)
3654 .GetCString();
3655 if (gsym_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00003656 // Combine N_GSYM stab entries with the non
3657 // stab symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00003658 ConstNameToSymbolIndexMap::const_iterator pos =
3659 N_GSYM_name_to_sym_idx.find(gsym_name);
3660 if (pos != N_GSYM_name_to_sym_idx.end()) {
3661 const uint32_t GSYM_sym_idx = pos->second;
3662 m_nlist_idx_to_sym_idx[nlist_idx] =
3663 GSYM_sym_idx;
3664 // Copy the address, because often the N_GSYM
3665 // address has an invalid address of zero
3666 // when the global is a common symbol
3667 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3668 symbol_section);
3669 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3670 symbol_value);
3671 // We just need the flags from the linker
3672 // symbol, so put these flags
3673 // into the N_GSYM flags to avoid duplicate
3674 // symbols in the symbol table
3675 sym[GSYM_sym_idx].SetFlags(
3676 nlist.n_type << 16 | nlist.n_desc);
3677 sym[sym_idx].Clear();
3678 continue;
3679 }
3680 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003681 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003682 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003683 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003684
Kate Stoneb9c1b512016-09-06 20:57:50 +00003685 sym[sym_idx].SetID(nlist_idx);
3686 sym[sym_idx].SetType(type);
3687 if (set_value) {
3688 sym[sym_idx].GetAddressRef().SetSection(
3689 symbol_section);
3690 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
Greg Clayton29e08cb2012-03-14 01:53:24 +00003691 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003692 sym[sym_idx].SetFlags(nlist.n_type << 16 |
3693 nlist.n_desc);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003694
Kate Stoneb9c1b512016-09-06 20:57:50 +00003695 if (symbol_byte_size > 0)
3696 sym[sym_idx].SetByteSize(symbol_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003697
Kate Stoneb9c1b512016-09-06 20:57:50 +00003698 if (demangled_is_synthesized)
3699 sym[sym_idx].SetDemangledNameIsSynthesized(true);
Greg Clayton60038be2015-02-14 00:51:13 +00003700 ++sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003701 } else {
3702 sym[sym_idx].Clear();
3703 }
Greg Clayton9191db42013-10-21 18:40:51 +00003704 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003705 /////////////////////////////
3706 }
3707 break; // No more entries to consider
Greg Clayton9191db42013-10-21 18:40:51 +00003708 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003709 }
3710
3711 for (const auto &pos : reexport_shlib_needs_fixup) {
3712 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3713 if (undef_pos != undefined_name_to_desc.end()) {
3714 const uint8_t dylib_ordinal =
3715 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3716 if (dylib_ordinal > 0 &&
3717 dylib_ordinal < dylib_files.GetSize())
3718 sym[pos.first].SetReExportedSymbolSharedLibrary(
3719 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3720 }
3721 }
Greg Clayton9191db42013-10-21 18:40:51 +00003722 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723 }
Greg Clayton9191db42013-10-21 18:40:51 +00003724 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003725 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003727
3728 // Must reset this in case it was mutated above!
3729 nlist_data_offset = 0;
3730#endif
3731
3732 if (nlist_data.GetByteSize() > 0) {
3733
3734 // If the sym array was not created while parsing the DSC unmapped
3735 // symbols, create it now.
3736 if (sym == NULL) {
3737 sym = symtab->Resize(symtab_load_command.nsyms +
3738 m_dysymtab.nindirectsyms);
3739 num_syms = symtab->GetNumSymbols();
3740 }
3741
3742 if (unmapped_local_symbols_found) {
3743 assert(m_dysymtab.ilocalsym == 0);
3744 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3745 nlist_idx = m_dysymtab.nlocalsym;
3746 } else {
3747 nlist_idx = 0;
3748 }
3749
3750 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3751 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3752 UndefinedNameToDescMap undefined_name_to_desc;
3753 SymbolIndexToName reexport_shlib_needs_fixup;
3754 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
3755 struct nlist_64 nlist;
3756 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset,
3757 nlist_byte_size))
3758 break;
3759
3760 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
3761 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
3762 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
3763 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
3764 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
3765
3766 SymbolType type = eSymbolTypeInvalid;
3767 const char *symbol_name = NULL;
3768
3769 if (have_strtab_data) {
3770 symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3771
3772 if (symbol_name == NULL) {
Adrian Prantl05097242018-04-30 16:49:04 +00003773 // No symbol should be NULL, even the symbols with no string values
3774 // should have an offset zero which points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00003775 Host::SystemLog(Host::eSystemLogError,
3776 "error: symbol[%u] has invalid string table offset "
3777 "0x%x in %s, ignoring symbol\n",
3778 nlist_idx, nlist.n_strx,
3779 module_sp->GetFileSpec().GetPath().c_str());
3780 continue;
3781 }
3782 if (symbol_name[0] == '\0')
3783 symbol_name = NULL;
3784 } else {
3785 const addr_t str_addr = strtab_addr + nlist.n_strx;
Zachary Turner97206d52017-05-12 04:51:55 +00003786 Status str_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003787 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3788 str_error))
3789 symbol_name = memory_symbol_name.c_str();
3790 }
3791 const char *symbol_name_non_abi_mangled = NULL;
3792
3793 SectionSP symbol_section;
3794 lldb::addr_t symbol_byte_size = 0;
3795 bool add_nlist = true;
3796 bool is_gsym = false;
3797 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3798 bool demangled_is_synthesized = false;
3799 bool set_value = true;
3800 assert(sym_idx < num_syms);
3801
3802 sym[sym_idx].SetDebug(is_debug);
3803
3804 if (is_debug) {
3805 switch (nlist.n_type) {
3806 case N_GSYM:
3807 // global symbol: name,,NO_SECT,type,0
3808 // Sometimes the N_GSYM value contains the address.
3809
3810 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3811 // the ObjC data. They
3812 // have the same address, but we want to ensure that we always find
Adrian Prantl05097242018-04-30 16:49:04 +00003813 // only the real symbol, 'cause we don't currently correctly
3814 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3815 // type. This is a temporary hack to make sure the ObjectiveC
3816 // symbols get treated correctly. To do this right, we should
3817 // coalesce all the GSYM & global symbols that have the same
3818 // address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003819 is_gsym = true;
3820 sym[sym_idx].SetExternal(true);
3821
3822 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3823 llvm::StringRef symbol_name_ref(symbol_name);
3824 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3825 symbol_name_non_abi_mangled = symbol_name + 1;
3826 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3827 type = eSymbolTypeObjCClass;
3828 demangled_is_synthesized = true;
3829
3830 } else if (symbol_name_ref.startswith(
3831 g_objc_v2_prefix_metaclass)) {
3832 symbol_name_non_abi_mangled = symbol_name + 1;
3833 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3834 type = eSymbolTypeObjCMetaClass;
3835 demangled_is_synthesized = true;
3836 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3837 symbol_name_non_abi_mangled = symbol_name + 1;
3838 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3839 type = eSymbolTypeObjCIVar;
3840 demangled_is_synthesized = true;
3841 }
3842 } else {
3843 if (nlist.n_value != 0)
3844 symbol_section =
3845 section_info.GetSection(nlist.n_sect, nlist.n_value);
3846 type = eSymbolTypeData;
3847 }
3848 break;
3849
3850 case N_FNAME:
3851 // procedure name (f77 kludge): name,,NO_SECT,0,0
3852 type = eSymbolTypeCompiler;
3853 break;
3854
3855 case N_FUN:
3856 // procedure: name,,n_sect,linenumber,address
3857 if (symbol_name) {
3858 type = eSymbolTypeCode;
3859 symbol_section =
3860 section_info.GetSection(nlist.n_sect, nlist.n_value);
3861
3862 N_FUN_addr_to_sym_idx.insert(
3863 std::make_pair(nlist.n_value, sym_idx));
3864 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003865 // lieu of using nlist_idx in case we ever start trimming entries
3866 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003867 N_FUN_indexes.push_back(sym_idx);
3868 } else {
3869 type = eSymbolTypeCompiler;
3870
3871 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003872 // Copy the size of the function into the original STAB entry
3873 // so we don't have to hunt for it later
Kate Stoneb9c1b512016-09-06 20:57:50 +00003874 symtab->SymbolAtIndex(N_FUN_indexes.back())
3875 ->SetByteSize(nlist.n_value);
3876 N_FUN_indexes.pop_back();
Adrian Prantl05097242018-04-30 16:49:04 +00003877 // We don't really need the end function STAB as it contains
3878 // the size which we already placed with the original symbol,
3879 // so don't add it if we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003880 add_nlist = false;
3881 }
3882 }
3883 break;
3884
3885 case N_STSYM:
3886 // static symbol: name,,n_sect,type,address
3887 N_STSYM_addr_to_sym_idx.insert(
3888 std::make_pair(nlist.n_value, sym_idx));
3889 symbol_section =
3890 section_info.GetSection(nlist.n_sect, nlist.n_value);
3891 if (symbol_name && symbol_name[0]) {
3892 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3893 eSymbolTypeData);
3894 }
3895 break;
3896
3897 case N_LCSYM:
3898 // .lcomm symbol: name,,n_sect,type,address
3899 symbol_section =
3900 section_info.GetSection(nlist.n_sect, nlist.n_value);
3901 type = eSymbolTypeCommonBlock;
3902 break;
3903
3904 case N_BNSYM:
3905 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00003906 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003907 // Skip these if we want minimal symbol tables
3908 add_nlist = false;
3909 break;
3910
3911 case N_ENSYM:
3912 // Set the size of the N_BNSYM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003913 // N_ENSYM so that we can always skip the entire symbol if we need
3914 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003915 // Skip these if we want minimal symbol tables
3916 add_nlist = false;
3917 break;
3918
3919 case N_OPT:
3920 // emitted with gcc2_compiled and in gcc source
3921 type = eSymbolTypeCompiler;
3922 break;
3923
3924 case N_RSYM:
3925 // register sym: name,,NO_SECT,type,register
3926 type = eSymbolTypeVariable;
3927 break;
3928
3929 case N_SLINE:
3930 // src line: 0,,n_sect,linenumber,address
3931 symbol_section =
3932 section_info.GetSection(nlist.n_sect, nlist.n_value);
3933 type = eSymbolTypeLineEntry;
3934 break;
3935
3936 case N_SSYM:
3937 // structure elt: name,,NO_SECT,type,struct_offset
3938 type = eSymbolTypeVariableType;
3939 break;
3940
3941 case N_SO:
3942 // source file name
3943 type = eSymbolTypeSourceFile;
3944 if (symbol_name == NULL) {
3945 add_nlist = false;
3946 if (N_SO_index != UINT32_MAX) {
3947 // Set the size of the N_SO to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003948 // N_SO so that we can always skip the entire N_SO if we need
3949 // to navigate more quickly at the source level when parsing
3950 // STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003951 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3952 symbol_ptr->SetByteSize(sym_idx);
3953 symbol_ptr->SetSizeIsSibling(true);
3954 }
3955 N_NSYM_indexes.clear();
3956 N_INCL_indexes.clear();
3957 N_BRAC_indexes.clear();
3958 N_COMM_indexes.clear();
3959 N_FUN_indexes.clear();
3960 N_SO_index = UINT32_MAX;
3961 } else {
3962 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003963 // lieu of using nlist_idx in case we ever start trimming entries
3964 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003965 const bool N_SO_has_full_path = symbol_name[0] == '/';
3966 if (N_SO_has_full_path) {
3967 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3968 // We have two consecutive N_SO entries where the first
Adrian Prantl05097242018-04-30 16:49:04 +00003969 // contains a directory and the second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970 sym[sym_idx - 1].GetMangled().SetValue(
3971 ConstString(symbol_name), false);
3972 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3973 add_nlist = false;
3974 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003975 // This is the first entry in a N_SO that contains a
3976 // directory or a full path to the source file
Kate Stoneb9c1b512016-09-06 20:57:50 +00003977 N_SO_index = sym_idx;
3978 }
3979 } else if ((N_SO_index == sym_idx - 1) &&
3980 ((sym_idx - 1) < num_syms)) {
3981 // This is usually the second N_SO entry that contains just the
Adrian Prantl05097242018-04-30 16:49:04 +00003982 // filename, so here we combine it with the first one if we are
3983 // minimizing the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003984 const char *so_path =
3985 sym[sym_idx - 1]
3986 .GetMangled()
3987 .GetDemangledName(lldb::eLanguageTypeUnknown)
3988 .AsCString();
3989 if (so_path && so_path[0]) {
3990 std::string full_so_path(so_path);
3991 const size_t double_slash_pos = full_so_path.find("//");
3992 if (double_slash_pos != std::string::npos) {
3993 // The linker has been generating bad N_SO entries with
Adrian Prantl05097242018-04-30 16:49:04 +00003994 // doubled up paths in the format "%s%s" where the first
3995 // string in the DW_AT_comp_dir, and the second is the
3996 // directory for the source file so you end up with a path
3997 // that looks like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00003998 FileSpec so_dir(so_path, false);
3999 if (!so_dir.Exists()) {
4000 so_dir.SetFile(&full_so_path[double_slash_pos + 1],
4001 false);
4002 if (so_dir.Exists()) {
4003 // Trim off the incorrect path
4004 full_so_path.erase(0, double_slash_pos + 1);
4005 }
4006 }
4007 }
4008 if (*full_so_path.rbegin() != '/')
4009 full_so_path += '/';
4010 full_so_path += symbol_name;
4011 sym[sym_idx - 1].GetMangled().SetValue(
4012 ConstString(full_so_path.c_str()), false);
4013 add_nlist = false;
4014 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4015 }
4016 } else {
4017 // This could be a relative path to a N_SO
4018 N_SO_index = sym_idx;
4019 }
4020 }
4021 break;
4022
4023 case N_OSO:
4024 // object file name: name,,0,0,st_mtime
4025 type = eSymbolTypeObjectFile;
4026 break;
4027
4028 case N_LSYM:
4029 // local sym: name,,NO_SECT,type,offset
4030 type = eSymbolTypeLocal;
4031 break;
4032
4033 //----------------------------------------------------------------------
4034 // INCL scopes
4035 //----------------------------------------------------------------------
4036 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00004037 // include file beginning: name,,NO_SECT,0,sum We use the current
4038 // number of symbols in the symbol table in lieu of using nlist_idx
4039 // in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004040 N_INCL_indexes.push_back(sym_idx);
4041 type = eSymbolTypeScopeBegin;
4042 break;
4043
4044 case N_EINCL:
4045 // include file end: name,,NO_SECT,0,0
4046 // Set the size of the N_BINCL to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004047 // N_EINCL so that we can always skip the entire symbol if we need
4048 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049 if (!N_INCL_indexes.empty()) {
4050 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
4051 symbol_ptr->SetByteSize(sym_idx + 1);
4052 symbol_ptr->SetSizeIsSibling(true);
4053 N_INCL_indexes.pop_back();
4054 }
4055 type = eSymbolTypeScopeEnd;
4056 break;
4057
4058 case N_SOL:
4059 // #included file name: name,,n_sect,0,address
4060 type = eSymbolTypeHeaderFile;
4061
4062 // We currently don't use the header files on darwin
4063 add_nlist = false;
4064 break;
4065
4066 case N_PARAMS:
4067 // compiler parameters: name,,NO_SECT,0,0
4068 type = eSymbolTypeCompiler;
4069 break;
4070
4071 case N_VERSION:
4072 // compiler version: name,,NO_SECT,0,0
4073 type = eSymbolTypeCompiler;
4074 break;
4075
4076 case N_OLEVEL:
4077 // compiler -O level: name,,NO_SECT,0,0
4078 type = eSymbolTypeCompiler;
4079 break;
4080
4081 case N_PSYM:
4082 // parameter: name,,NO_SECT,type,offset
4083 type = eSymbolTypeVariable;
4084 break;
4085
4086 case N_ENTRY:
4087 // alternate entry: name,,n_sect,linenumber,address
4088 symbol_section =
4089 section_info.GetSection(nlist.n_sect, nlist.n_value);
4090 type = eSymbolTypeLineEntry;
4091 break;
4092
4093 //----------------------------------------------------------------------
4094 // Left and Right Braces
4095 //----------------------------------------------------------------------
4096 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004097 // left bracket: 0,,NO_SECT,nesting level,address We use the
4098 // current number of symbols in the symbol table in lieu of using
4099 // nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004100 symbol_section =
4101 section_info.GetSection(nlist.n_sect, nlist.n_value);
4102 N_BRAC_indexes.push_back(sym_idx);
4103 type = eSymbolTypeScopeBegin;
4104 break;
4105
4106 case N_RBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004107 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4108 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4109 // can always skip the entire symbol if we need to navigate more
4110 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004111 symbol_section =
4112 section_info.GetSection(nlist.n_sect, nlist.n_value);
4113 if (!N_BRAC_indexes.empty()) {
4114 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4115 symbol_ptr->SetByteSize(sym_idx + 1);
4116 symbol_ptr->SetSizeIsSibling(true);
4117 N_BRAC_indexes.pop_back();
4118 }
4119 type = eSymbolTypeScopeEnd;
4120 break;
4121
4122 case N_EXCL:
4123 // deleted include file: name,,NO_SECT,0,sum
4124 type = eSymbolTypeHeaderFile;
4125 break;
4126
4127 //----------------------------------------------------------------------
4128 // COMM scopes
4129 //----------------------------------------------------------------------
4130 case N_BCOMM:
4131 // begin common: name,,NO_SECT,0,0
4132 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00004133 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004134 type = eSymbolTypeScopeBegin;
4135 N_COMM_indexes.push_back(sym_idx);
4136 break;
4137
4138 case N_ECOML:
4139 // end common (local name): 0,,n_sect,0,address
4140 symbol_section =
4141 section_info.GetSection(nlist.n_sect, nlist.n_value);
4142 LLVM_FALLTHROUGH;
4143
4144 case N_ECOMM:
4145 // end common: name,,n_sect,0,0
4146 // Set the size of the N_BCOMM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004147 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4148 // we need to navigate more quickly at the source level when
4149 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004150 if (!N_COMM_indexes.empty()) {
4151 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4152 symbol_ptr->SetByteSize(sym_idx + 1);
4153 symbol_ptr->SetSizeIsSibling(true);
4154 N_COMM_indexes.pop_back();
4155 }
4156 type = eSymbolTypeScopeEnd;
4157 break;
4158
4159 case N_LENG:
4160 // second stab entry with length information
4161 type = eSymbolTypeAdditional;
4162 break;
4163
4164 default:
4165 break;
4166 }
4167 } else {
4168 // uint8_t n_pext = N_PEXT & nlist.n_type;
4169 uint8_t n_type = N_TYPE & nlist.n_type;
4170 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4171
4172 switch (n_type) {
4173 case N_INDR: {
4174 const char *reexport_name_cstr =
4175 strtab_data.PeekCStr(nlist.n_value);
4176 if (reexport_name_cstr && reexport_name_cstr[0]) {
4177 type = eSymbolTypeReExported;
4178 ConstString reexport_name(
4179 reexport_name_cstr +
4180 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4181 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4182 set_value = false;
4183 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4184 indirect_symbol_names.insert(
4185 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4186 } else
4187 type = eSymbolTypeUndefined;
4188 } break;
4189
4190 case N_UNDF:
4191 if (symbol_name && symbol_name[0]) {
4192 ConstString undefined_name(symbol_name +
4193 ((symbol_name[0] == '_') ? 1 : 0));
4194 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4195 }
4196 LLVM_FALLTHROUGH;
4197
4198 case N_PBUD:
4199 type = eSymbolTypeUndefined;
4200 break;
4201
4202 case N_ABS:
4203 type = eSymbolTypeAbsolute;
4204 break;
4205
4206 case N_SECT: {
4207 symbol_section =
4208 section_info.GetSection(nlist.n_sect, nlist.n_value);
4209
4210 if (!symbol_section) {
4211 // TODO: warn about this?
4212 add_nlist = false;
4213 break;
4214 }
4215
4216 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4217 type = eSymbolTypeException;
4218 } else {
4219 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4220
4221 switch (section_type) {
4222 case S_CSTRING_LITERALS:
4223 type = eSymbolTypeData;
4224 break; // section with only literal C strings
4225 case S_4BYTE_LITERALS:
4226 type = eSymbolTypeData;
4227 break; // section with only 4 byte literals
4228 case S_8BYTE_LITERALS:
4229 type = eSymbolTypeData;
4230 break; // section with only 8 byte literals
4231 case S_LITERAL_POINTERS:
4232 type = eSymbolTypeTrampoline;
4233 break; // section with only pointers to literals
4234 case S_NON_LAZY_SYMBOL_POINTERS:
4235 type = eSymbolTypeTrampoline;
4236 break; // section with only non-lazy symbol pointers
4237 case S_LAZY_SYMBOL_POINTERS:
4238 type = eSymbolTypeTrampoline;
4239 break; // section with only lazy symbol pointers
4240 case S_SYMBOL_STUBS:
4241 type = eSymbolTypeTrampoline;
4242 break; // section with only symbol stubs, byte size of stub in
4243 // the reserved2 field
4244 case S_MOD_INIT_FUNC_POINTERS:
4245 type = eSymbolTypeCode;
4246 break; // section with only function pointers for initialization
4247 case S_MOD_TERM_FUNC_POINTERS:
4248 type = eSymbolTypeCode;
4249 break; // section with only function pointers for termination
4250 case S_INTERPOSING:
4251 type = eSymbolTypeTrampoline;
4252 break; // section with only pairs of function pointers for
4253 // interposing
4254 case S_16BYTE_LITERALS:
4255 type = eSymbolTypeData;
4256 break; // section with only 16 byte literals
4257 case S_DTRACE_DOF:
4258 type = eSymbolTypeInstrumentation;
4259 break;
4260 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4261 type = eSymbolTypeTrampoline;
4262 break;
4263 default:
4264 switch (symbol_section->GetType()) {
4265 case lldb::eSectionTypeCode:
4266 type = eSymbolTypeCode;
4267 break;
4268 case eSectionTypeData:
4269 case eSectionTypeDataCString: // Inlined C string data
4270 case eSectionTypeDataCStringPointers: // Pointers to C string
4271 // data
4272 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4273 // the symbol table
4274 case eSectionTypeData4:
4275 case eSectionTypeData8:
4276 case eSectionTypeData16:
4277 type = eSymbolTypeData;
4278 break;
4279 default:
4280 break;
4281 }
4282 break;
4283 }
4284
4285 if (type == eSymbolTypeInvalid) {
4286 const char *symbol_sect_name =
4287 symbol_section->GetName().AsCString();
4288 if (symbol_section->IsDescendant(text_section_sp.get())) {
4289 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4290 S_ATTR_SELF_MODIFYING_CODE |
4291 S_ATTR_SOME_INSTRUCTIONS))
4292 type = eSymbolTypeData;
4293 else
4294 type = eSymbolTypeCode;
4295 } else if (symbol_section->IsDescendant(
4296 data_section_sp.get()) ||
4297 symbol_section->IsDescendant(
4298 data_dirty_section_sp.get()) ||
4299 symbol_section->IsDescendant(
4300 data_const_section_sp.get())) {
4301 if (symbol_sect_name &&
4302 ::strstr(symbol_sect_name, "__objc") ==
4303 symbol_sect_name) {
4304 type = eSymbolTypeRuntime;
4305
4306 if (symbol_name) {
4307 llvm::StringRef symbol_name_ref(symbol_name);
4308 if (symbol_name_ref.startswith("_OBJC_")) {
4309 static const llvm::StringRef g_objc_v2_prefix_class(
4310 "_OBJC_CLASS_$_");
4311 static const llvm::StringRef g_objc_v2_prefix_metaclass(
4312 "_OBJC_METACLASS_$_");
4313 static const llvm::StringRef g_objc_v2_prefix_ivar(
4314 "_OBJC_IVAR_$_");
4315 if (symbol_name_ref.startswith(
4316 g_objc_v2_prefix_class)) {
4317 symbol_name_non_abi_mangled = symbol_name + 1;
4318 symbol_name =
4319 symbol_name + g_objc_v2_prefix_class.size();
4320 type = eSymbolTypeObjCClass;
4321 demangled_is_synthesized = true;
4322 } else if (symbol_name_ref.startswith(
4323 g_objc_v2_prefix_metaclass)) {
4324 symbol_name_non_abi_mangled = symbol_name + 1;
4325 symbol_name =
4326 symbol_name + g_objc_v2_prefix_metaclass.size();
4327 type = eSymbolTypeObjCMetaClass;
4328 demangled_is_synthesized = true;
4329 } else if (symbol_name_ref.startswith(
4330 g_objc_v2_prefix_ivar)) {
4331 symbol_name_non_abi_mangled = symbol_name + 1;
4332 symbol_name =
4333 symbol_name + g_objc_v2_prefix_ivar.size();
4334 type = eSymbolTypeObjCIVar;
4335 demangled_is_synthesized = true;
4336 }
4337 }
4338 }
4339 } else if (symbol_sect_name &&
4340 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4341 symbol_sect_name) {
4342 type = eSymbolTypeException;
4343 } else {
4344 type = eSymbolTypeData;
4345 }
4346 } else if (symbol_sect_name &&
4347 ::strstr(symbol_sect_name, "__IMPORT") ==
4348 symbol_sect_name) {
4349 type = eSymbolTypeTrampoline;
4350 } else if (symbol_section->IsDescendant(
4351 objc_section_sp.get())) {
4352 type = eSymbolTypeRuntime;
4353 if (symbol_name && symbol_name[0] == '.') {
4354 llvm::StringRef symbol_name_ref(symbol_name);
4355 static const llvm::StringRef g_objc_v1_prefix_class(
4356 ".objc_class_name_");
4357 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4358 symbol_name_non_abi_mangled = symbol_name;
4359 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4360 type = eSymbolTypeObjCClass;
4361 demangled_is_synthesized = true;
4362 }
4363 }
4364 }
4365 }
4366 }
4367 } break;
4368 }
4369 }
4370
4371 if (add_nlist) {
4372 uint64_t symbol_value = nlist.n_value;
4373
4374 if (symbol_name_non_abi_mangled) {
4375 sym[sym_idx].GetMangled().SetMangledName(
4376 ConstString(symbol_name_non_abi_mangled));
4377 sym[sym_idx].GetMangled().SetDemangledName(
4378 ConstString(symbol_name));
4379 } else {
4380 bool symbol_name_is_mangled = false;
4381
4382 if (symbol_name && symbol_name[0] == '_') {
4383 symbol_name_is_mangled = symbol_name[1] == '_';
4384 symbol_name++; // Skip the leading underscore
4385 }
4386
4387 if (symbol_name) {
4388 ConstString const_symbol_name(symbol_name);
4389 sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4390 symbol_name_is_mangled);
4391 }
4392 }
4393
4394 if (is_gsym) {
4395 const char *gsym_name = sym[sym_idx]
4396 .GetMangled()
4397 .GetName(lldb::eLanguageTypeUnknown,
4398 Mangled::ePreferMangled)
4399 .GetCString();
4400 if (gsym_name)
4401 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4402 }
4403
4404 if (symbol_section) {
4405 const addr_t section_file_addr = symbol_section->GetFileAddress();
4406 if (symbol_byte_size == 0 && function_starts_count > 0) {
4407 addr_t symbol_lookup_file_addr = nlist.n_value;
4408 // Do an exact address match for non-ARM addresses, else get the
Adrian Prantl05097242018-04-30 16:49:04 +00004409 // closest since the symbol might be a thumb symbol which has an
4410 // address with bit zero set
Kate Stoneb9c1b512016-09-06 20:57:50 +00004411 FunctionStarts::Entry *func_start_entry =
4412 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4413 if (is_arm && func_start_entry) {
4414 // Verify that the function start address is the symbol address
Adrian Prantl05097242018-04-30 16:49:04 +00004415 // (ARM) or the symbol address + 1 (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004416 if (func_start_entry->addr != symbol_lookup_file_addr &&
4417 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4418 // Not the right entry, NULL it out...
4419 func_start_entry = NULL;
4420 }
4421 }
4422 if (func_start_entry) {
4423 func_start_entry->data = true;
4424
4425 addr_t symbol_file_addr = func_start_entry->addr;
4426 if (is_arm)
4427 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4428
4429 const FunctionStarts::Entry *next_func_start_entry =
4430 function_starts.FindNextEntry(func_start_entry);
4431 const addr_t section_end_file_addr =
4432 section_file_addr + symbol_section->GetByteSize();
4433 if (next_func_start_entry) {
4434 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4435 // Be sure the clear the Thumb address bit when we calculate
Adrian Prantl05097242018-04-30 16:49:04 +00004436 // the size from the current and next address
Kate Stoneb9c1b512016-09-06 20:57:50 +00004437 if (is_arm)
4438 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4439 symbol_byte_size = std::min<lldb::addr_t>(
4440 next_symbol_file_addr - symbol_file_addr,
4441 section_end_file_addr - symbol_file_addr);
4442 } else {
4443 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4444 }
4445 }
4446 }
4447 symbol_value -= section_file_addr;
4448 }
4449
4450 if (is_debug == false) {
4451 if (type == eSymbolTypeCode) {
Adrian Prantl05097242018-04-30 16:49:04 +00004452 // See if we can find a N_FUN entry for any code symbols. If we
4453 // do find a match, and the name matches, then we can merge the
4454 // two into just the function symbol to avoid duplicate entries
4455 // in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004456 std::pair<ValueToSymbolIndexMap::const_iterator,
4457 ValueToSymbolIndexMap::const_iterator>
4458 range;
4459 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4460 if (range.first != range.second) {
4461 bool found_it = false;
4462 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4463 pos != range.second; ++pos) {
4464 if (sym[sym_idx].GetMangled().GetName(
4465 lldb::eLanguageTypeUnknown,
4466 Mangled::ePreferMangled) ==
4467 sym[pos->second].GetMangled().GetName(
4468 lldb::eLanguageTypeUnknown,
4469 Mangled::ePreferMangled)) {
4470 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4471 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004472 // these flags into the N_FUN flags to avoid duplicate
4473 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4475 sym[pos->second].SetFlags(nlist.n_type << 16 |
4476 nlist.n_desc);
4477 if (resolver_addresses.find(nlist.n_value) !=
4478 resolver_addresses.end())
4479 sym[pos->second].SetType(eSymbolTypeResolver);
4480 sym[sym_idx].Clear();
4481 found_it = true;
4482 break;
4483 }
4484 }
4485 if (found_it)
4486 continue;
4487 } else {
4488 if (resolver_addresses.find(nlist.n_value) !=
4489 resolver_addresses.end())
4490 type = eSymbolTypeResolver;
4491 }
4492 } else if (type == eSymbolTypeData ||
4493 type == eSymbolTypeObjCClass ||
4494 type == eSymbolTypeObjCMetaClass ||
4495 type == eSymbolTypeObjCIVar) {
Adrian Prantl05097242018-04-30 16:49:04 +00004496 // See if we can find a N_STSYM entry for any data symbols. If we
4497 // do find a match, and the name matches, then we can merge the
4498 // two into just the Static symbol to avoid duplicate entries in
4499 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004500 std::pair<ValueToSymbolIndexMap::const_iterator,
4501 ValueToSymbolIndexMap::const_iterator>
4502 range;
4503 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4504 if (range.first != range.second) {
4505 bool found_it = false;
4506 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4507 pos != range.second; ++pos) {
4508 if (sym[sym_idx].GetMangled().GetName(
4509 lldb::eLanguageTypeUnknown,
4510 Mangled::ePreferMangled) ==
4511 sym[pos->second].GetMangled().GetName(
4512 lldb::eLanguageTypeUnknown,
4513 Mangled::ePreferMangled)) {
4514 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4515 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004516 // these flags into the N_STSYM flags to avoid duplicate
4517 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004518 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4519 sym[pos->second].SetFlags(nlist.n_type << 16 |
4520 nlist.n_desc);
4521 sym[sym_idx].Clear();
4522 found_it = true;
4523 break;
4524 }
4525 }
4526 if (found_it)
4527 continue;
4528 } else {
4529 // Combine N_GSYM stab entries with the non stab symbol
4530 const char *gsym_name = sym[sym_idx]
4531 .GetMangled()
4532 .GetName(lldb::eLanguageTypeUnknown,
4533 Mangled::ePreferMangled)
4534 .GetCString();
4535 if (gsym_name) {
4536 ConstNameToSymbolIndexMap::const_iterator pos =
4537 N_GSYM_name_to_sym_idx.find(gsym_name);
4538 if (pos != N_GSYM_name_to_sym_idx.end()) {
4539 const uint32_t GSYM_sym_idx = pos->second;
4540 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00004541 // Copy the address, because often the N_GSYM address has
4542 // an invalid address of zero when the global is a common
4543 // symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00004544 sym[GSYM_sym_idx].GetAddressRef().SetSection(
4545 symbol_section);
4546 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4547 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004548 // these flags into the N_GSYM flags to avoid duplicate
4549 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004550 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
4551 nlist.n_desc);
4552 sym[sym_idx].Clear();
4553 continue;
4554 }
4555 }
4556 }
4557 }
4558 }
4559
4560 sym[sym_idx].SetID(nlist_idx);
4561 sym[sym_idx].SetType(type);
4562 if (set_value) {
4563 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4564 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4565 }
4566 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4567
4568 if (symbol_byte_size > 0)
4569 sym[sym_idx].SetByteSize(symbol_byte_size);
4570
4571 if (demangled_is_synthesized)
4572 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4573
4574 ++sym_idx;
4575 } else {
4576 sym[sym_idx].Clear();
4577 }
4578 }
4579
4580 for (const auto &pos : reexport_shlib_needs_fixup) {
4581 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4582 if (undef_pos != undefined_name_to_desc.end()) {
4583 const uint8_t dylib_ordinal =
4584 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4585 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4586 sym[pos.first].SetReExportedSymbolSharedLibrary(
4587 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4588 }
4589 }
4590 }
4591
4592 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4593
4594 if (function_starts_count > 0) {
4595 uint32_t num_synthetic_function_symbols = 0;
4596 for (i = 0; i < function_starts_count; ++i) {
4597 if (function_starts.GetEntryRef(i).data == false)
4598 ++num_synthetic_function_symbols;
4599 }
4600
4601 if (num_synthetic_function_symbols > 0) {
4602 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4603 num_syms = sym_idx + num_synthetic_function_symbols;
4604 sym = symtab->Resize(num_syms);
4605 }
4606 for (i = 0; i < function_starts_count; ++i) {
4607 const FunctionStarts::Entry *func_start_entry =
4608 function_starts.GetEntryAtIndex(i);
4609 if (func_start_entry->data == false) {
4610 addr_t symbol_file_addr = func_start_entry->addr;
4611 uint32_t symbol_flags = 0;
4612 if (is_arm) {
4613 if (symbol_file_addr & 1)
4614 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4615 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4616 }
4617 Address symbol_addr;
4618 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4619 SectionSP symbol_section(symbol_addr.GetSection());
4620 uint32_t symbol_byte_size = 0;
4621 if (symbol_section) {
4622 const addr_t section_file_addr =
4623 symbol_section->GetFileAddress();
4624 const FunctionStarts::Entry *next_func_start_entry =
4625 function_starts.FindNextEntry(func_start_entry);
4626 const addr_t section_end_file_addr =
4627 section_file_addr + symbol_section->GetByteSize();
4628 if (next_func_start_entry) {
4629 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4630 if (is_arm)
4631 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4632 symbol_byte_size = std::min<lldb::addr_t>(
4633 next_symbol_file_addr - symbol_file_addr,
4634 section_end_file_addr - symbol_file_addr);
4635 } else {
4636 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4637 }
4638 sym[sym_idx].SetID(synthetic_sym_id++);
4639 sym[sym_idx].GetMangled().SetDemangledName(
4640 GetNextSyntheticSymbolName());
4641 sym[sym_idx].SetType(eSymbolTypeCode);
4642 sym[sym_idx].SetIsSynthetic(true);
4643 sym[sym_idx].GetAddressRef() = symbol_addr;
4644 if (symbol_flags)
4645 sym[sym_idx].SetFlags(symbol_flags);
4646 if (symbol_byte_size)
4647 sym[sym_idx].SetByteSize(symbol_byte_size);
4648 ++sym_idx;
4649 }
4650 }
4651 }
4652 }
4653 }
4654 }
4655
Adrian Prantl05097242018-04-30 16:49:04 +00004656 // Trim our symbols down to just what we ended up with after removing any
4657 // symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004658 if (sym_idx < num_syms) {
4659 num_syms = sym_idx;
4660 sym = symtab->Resize(num_syms);
4661 }
4662
4663 // Now synthesize indirect symbols
4664 if (m_dysymtab.nindirectsyms != 0) {
4665 if (indirect_symbol_index_data.GetByteSize()) {
4666 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4667 m_nlist_idx_to_sym_idx.end();
4668
4669 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4670 ++sect_idx) {
4671 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4672 S_SYMBOL_STUBS) {
4673 uint32_t symbol_stub_byte_size =
4674 m_mach_sections[sect_idx].reserved2;
4675 if (symbol_stub_byte_size == 0)
4676 continue;
4677
4678 const uint32_t num_symbol_stubs =
4679 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4680
4681 if (num_symbol_stubs == 0)
4682 continue;
4683
4684 const uint32_t symbol_stub_index_offset =
4685 m_mach_sections[sect_idx].reserved1;
4686 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs;
4687 ++stub_idx) {
4688 const uint32_t symbol_stub_index =
4689 symbol_stub_index_offset + stub_idx;
4690 const lldb::addr_t symbol_stub_addr =
4691 m_mach_sections[sect_idx].addr +
4692 (stub_idx * symbol_stub_byte_size);
4693 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4694 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4695 symbol_stub_offset, 4)) {
4696 const uint32_t stub_sym_id =
4697 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4698 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4699 continue;
4700
4701 NListIndexToSymbolIndexMap::const_iterator index_pos =
4702 m_nlist_idx_to_sym_idx.find(stub_sym_id);
4703 Symbol *stub_symbol = NULL;
4704 if (index_pos != end_index_pos) {
Adrian Prantl05097242018-04-30 16:49:04 +00004705 // We have a remapping from the original nlist index to a
4706 // current symbol index, so just look this up by index
Kate Stoneb9c1b512016-09-06 20:57:50 +00004707 stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4708 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004709 // We need to lookup a symbol using the original nlist symbol
4710 // index since this index is coming from the S_SYMBOL_STUBS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004711 stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4712 }
4713
4714 if (stub_symbol) {
4715 Address so_addr(symbol_stub_addr, section_list);
4716
4717 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4718 // Change the external symbol into a trampoline that makes
Adrian Prantl05097242018-04-30 16:49:04 +00004719 // sense These symbols were N_UNDF N_EXT, and are useless
4720 // to us, so we can re-use them so we don't have to make up
4721 // a synthetic symbol for no good reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004722 if (resolver_addresses.find(symbol_stub_addr) ==
4723 resolver_addresses.end())
4724 stub_symbol->SetType(eSymbolTypeTrampoline);
4725 else
4726 stub_symbol->SetType(eSymbolTypeResolver);
4727 stub_symbol->SetExternal(false);
4728 stub_symbol->GetAddressRef() = so_addr;
4729 stub_symbol->SetByteSize(symbol_stub_byte_size);
4730 } else {
4731 // Make a synthetic symbol to describe the trampoline stub
4732 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4733 if (sym_idx >= num_syms) {
4734 sym = symtab->Resize(++num_syms);
4735 stub_symbol = NULL; // this pointer no longer valid
4736 }
4737 sym[sym_idx].SetID(synthetic_sym_id++);
4738 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4739 if (resolver_addresses.find(symbol_stub_addr) ==
4740 resolver_addresses.end())
4741 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4742 else
4743 sym[sym_idx].SetType(eSymbolTypeResolver);
4744 sym[sym_idx].SetIsSynthetic(true);
4745 sym[sym_idx].GetAddressRef() = so_addr;
4746 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4747 ++sym_idx;
4748 }
4749 } else {
4750 if (log)
4751 log->Warning("symbol stub referencing symbol table symbol "
4752 "%u that isn't in our minimal symbol table, "
4753 "fix this!!!",
4754 stub_sym_id);
4755 }
4756 }
4757 }
4758 }
4759 }
4760 }
4761 }
4762
4763 if (!trie_entries.empty()) {
4764 for (const auto &e : trie_entries) {
4765 if (e.entry.import_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00004766 // Only add indirect symbols from the Trie entries if we didn't have
4767 // a N_INDR nlist entry for this already
Kate Stoneb9c1b512016-09-06 20:57:50 +00004768 if (indirect_symbol_names.find(e.entry.name) ==
4769 indirect_symbol_names.end()) {
4770 // Make a synthetic symbol to describe re-exported symbol.
4771 if (sym_idx >= num_syms)
4772 sym = symtab->Resize(++num_syms);
4773 sym[sym_idx].SetID(synthetic_sym_id++);
4774 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4775 sym[sym_idx].SetType(eSymbolTypeReExported);
4776 sym[sym_idx].SetIsSynthetic(true);
4777 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4778 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4779 sym[sym_idx].SetReExportedSymbolSharedLibrary(
4780 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4781 }
4782 ++sym_idx;
4783 }
4784 }
4785 }
4786 }
4787
4788 // StreamFile s(stdout, false);
4789 // s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4790 // symtab->Dump(&s, NULL, eSortOrderNone);
4791 // Set symbol byte sizes correctly since mach-o nlist entries don't have
4792 // sizes
4793 symtab->CalculateSymbolSizes();
4794
4795 // s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4796 // symtab->Dump(&s, NULL, eSortOrderNone);
4797
4798 return symtab->GetNumSymbols();
4799 }
4800 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004801}
4802
Kate Stoneb9c1b512016-09-06 20:57:50 +00004803void ObjectFileMachO::Dump(Stream *s) {
4804 ModuleSP module_sp(GetModule());
4805 if (module_sp) {
4806 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4807 s->Printf("%p: ", static_cast<void *>(this));
4808 s->Indent();
4809 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4810 s->PutCString("ObjectFileMachO64");
4811 else
4812 s->PutCString("ObjectFileMachO32");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004813
Kate Stoneb9c1b512016-09-06 20:57:50 +00004814 ArchSpec header_arch;
4815 GetArchitecture(header_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004816
Kate Stoneb9c1b512016-09-06 20:57:50 +00004817 *s << ", file = '" << m_file
4818 << "', arch = " << header_arch.GetArchitectureName() << "\n";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004819
Kate Stoneb9c1b512016-09-06 20:57:50 +00004820 SectionList *sections = GetSectionList();
4821 if (sections)
4822 sections->Dump(s, NULL, true, UINT32_MAX);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004823
Kate Stoneb9c1b512016-09-06 20:57:50 +00004824 if (m_symtab_ap.get())
4825 m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4826 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004827}
4828
Kate Stoneb9c1b512016-09-06 20:57:50 +00004829bool ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4830 const lldb_private::DataExtractor &data,
4831 lldb::offset_t lc_offset,
4832 lldb_private::UUID &uuid) {
4833 uint32_t i;
4834 struct uuid_command load_cmd;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004835
Kate Stoneb9c1b512016-09-06 20:57:50 +00004836 lldb::offset_t offset = lc_offset;
4837 for (i = 0; i < header.ncmds; ++i) {
4838 const lldb::offset_t cmd_offset = offset;
4839 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4840 break;
4841
4842 if (load_cmd.cmd == LC_UUID) {
4843 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4844
4845 if (uuid_bytes) {
4846 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4847 // We pretend these object files have no UUID to prevent crashing.
4848
4849 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4850 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4851 0xbb, 0x14, 0xf0, 0x0d};
4852
4853 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4854 return false;
4855
4856 uuid.SetBytes(uuid_bytes);
4857 return true;
4858 }
4859 return false;
4860 }
4861 offset = cmd_offset + load_cmd.cmdsize;
4862 }
4863 return false;
4864}
4865
4866bool ObjectFileMachO::GetArchitecture(const llvm::MachO::mach_header &header,
4867 const lldb_private::DataExtractor &data,
4868 lldb::offset_t lc_offset,
4869 ArchSpec &arch) {
4870 arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4871
4872 if (arch.IsValid()) {
4873 llvm::Triple &triple = arch.GetTriple();
4874
4875 // Set OS to an unspecified unknown or a "*" so it can match any OS
4876 triple.setOS(llvm::Triple::UnknownOS);
4877 triple.setOSName(llvm::StringRef());
4878
4879 if (header.filetype == MH_PRELOAD) {
4880 if (header.cputype == CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00004881 // If this is a 32-bit arm binary, and it's a standalone binary, force
4882 // the Vendor to Apple so we don't accidentally pick up the generic
4883 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4884 // frame pointer register; most other armv7 ABIs use a combination of
4885 // r7 and r11.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004886 triple.setVendor(llvm::Triple::Apple);
4887 } else {
4888 // Set vendor to an unspecified unknown or a "*" so it can match any
Adrian Prantl05097242018-04-30 16:49:04 +00004889 // vendor This is required for correct behavior of EFI debugging on
4890 // x86_64
Kate Stoneb9c1b512016-09-06 20:57:50 +00004891 triple.setVendor(llvm::Triple::UnknownVendor);
4892 triple.setVendorName(llvm::StringRef());
4893 }
4894 return true;
4895 } else {
4896 struct load_command load_cmd;
4897
4898 lldb::offset_t offset = lc_offset;
4899 for (uint32_t i = 0; i < header.ncmds; ++i) {
Greg Claytonf4d6de62013-04-24 22:29:28 +00004900 const lldb::offset_t cmd_offset = offset;
4901 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004902 break;
4903
4904 switch (load_cmd.cmd) {
4905 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4906 triple.setOS(llvm::Triple::IOS);
4907 return true;
4908
4909 case llvm::MachO::LC_VERSION_MIN_MACOSX:
4910 triple.setOS(llvm::Triple::MacOSX);
4911 return true;
4912
4913 case llvm::MachO::LC_VERSION_MIN_TVOS:
4914 triple.setOS(llvm::Triple::TvOS);
4915 return true;
4916
4917 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4918 triple.setOS(llvm::Triple::WatchOS);
4919 return true;
4920
4921 default:
4922 break;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004923 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004924
Greg Claytonf4d6de62013-04-24 22:29:28 +00004925 offset = cmd_offset + load_cmd.cmdsize;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004926 }
4927
4928 if (header.filetype != MH_KEXT_BUNDLE) {
4929 // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
4930 // so lets not say our Vendor is Apple, leave it as an unspecified
4931 // unknown
4932 triple.setVendor(llvm::Triple::UnknownVendor);
4933 triple.setVendorName(llvm::StringRef());
4934 }
Greg Claytonf4d6de62013-04-24 22:29:28 +00004935 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004936 }
4937 return arch.IsValid();
Greg Claytonf4d6de62013-04-24 22:29:28 +00004938}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004939
Kate Stoneb9c1b512016-09-06 20:57:50 +00004940bool ObjectFileMachO::GetUUID(lldb_private::UUID *uuid) {
4941 ModuleSP module_sp(GetModule());
4942 if (module_sp) {
4943 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4944 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4945 return GetUUID(m_header, m_data, offset, *uuid);
4946 }
4947 return false;
Greg Clayton7ab7f892014-05-29 21:33:45 +00004948}
4949
Kate Stoneb9c1b512016-09-06 20:57:50 +00004950uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
4951 uint32_t count = 0;
4952 ModuleSP module_sp(GetModule());
4953 if (module_sp) {
4954 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4955 struct load_command load_cmd;
4956 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4957 std::vector<std::string> rpath_paths;
4958 std::vector<std::string> rpath_relative_paths;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00004959 std::vector<std::string> at_exec_relative_paths;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004960 const bool resolve_path = false; // Don't resolve the dependent file paths
Adrian Prantl05097242018-04-30 16:49:04 +00004961 // since they may not reside on this
4962 // system
Kate Stoneb9c1b512016-09-06 20:57:50 +00004963 uint32_t i;
4964 for (i = 0; i < m_header.ncmds; ++i) {
4965 const uint32_t cmd_offset = offset;
4966 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4967 break;
4968
4969 switch (load_cmd.cmd) {
4970 case LC_RPATH:
4971 case LC_LOAD_DYLIB:
4972 case LC_LOAD_WEAK_DYLIB:
4973 case LC_REEXPORT_DYLIB:
4974 case LC_LOAD_DYLINKER:
4975 case LC_LOADFVMLIB:
4976 case LC_LOAD_UPWARD_DYLIB: {
4977 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
4978 const char *path = m_data.PeekCStr(name_offset);
4979 if (path) {
4980 if (load_cmd.cmd == LC_RPATH)
4981 rpath_paths.push_back(path);
4982 else {
4983 if (path[0] == '@') {
4984 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
4985 rpath_relative_paths.push_back(path + strlen("@rpath"));
Jim Ingham1aa0ed42017-03-20 19:21:31 +00004986 else if (strncmp(path, "@executable_path",
4987 strlen("@executable_path")) == 0)
4988 at_exec_relative_paths.push_back(path
4989 + strlen("@executable_path"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00004990 } else {
4991 FileSpec file_spec(path, resolve_path);
4992 if (files.AppendIfUnique(file_spec))
4993 count++;
4994 }
4995 }
4996 }
4997 } break;
4998
4999 default:
5000 break;
5001 }
5002 offset = cmd_offset + load_cmd.cmdsize;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005003 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005004
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005005 FileSpec this_file_spec(m_file);
5006 this_file_spec.ResolvePath();
5007
Kate Stoneb9c1b512016-09-06 20:57:50 +00005008 if (!rpath_paths.empty()) {
5009 // Fixup all LC_RPATH values to be absolute paths
Kate Stoneb9c1b512016-09-06 20:57:50 +00005010 std::string loader_path("@loader_path");
5011 std::string executable_path("@executable_path");
5012 for (auto &rpath : rpath_paths) {
5013 if (rpath.find(loader_path) == 0) {
5014 rpath.erase(0, loader_path.size());
5015 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5016 } else if (rpath.find(executable_path) == 0) {
5017 rpath.erase(0, executable_path.size());
5018 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5019 }
5020 }
5021
5022 for (const auto &rpath_relative_path : rpath_relative_paths) {
5023 for (const auto &rpath : rpath_paths) {
5024 std::string path = rpath;
5025 path += rpath_relative_path;
Adrian Prantl05097242018-04-30 16:49:04 +00005026 // It is OK to resolve this path because we must find a file on disk
5027 // for us to accept it anyway if it is rpath relative.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005028 FileSpec file_spec(path, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005029 if (file_spec.Exists() && files.AppendIfUnique(file_spec)) {
5030 count++;
5031 break;
5032 }
5033 }
5034 }
5035 }
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005036
5037 // We may have @executable_paths but no RPATHS. Figure those out here.
5038 // Only do this if this object file is the executable. We have no way to
5039 // get back to the actual executable otherwise, so we won't get the right
5040 // path.
5041 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5042 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5043 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5044 FileSpec file_spec =
5045 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
Adrian Prantl5ec76fe2018-01-30 18:29:16 +00005046 if (file_spec.Exists() && files.AppendIfUnique(file_spec))
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005047 count++;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005048 }
5049 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005050 }
5051 return count;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005052}
5053
Kate Stoneb9c1b512016-09-06 20:57:50 +00005054lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5055 // If the object file is not an executable it can't hold the entry point.
Adrian Prantl05097242018-04-30 16:49:04 +00005056 // m_entry_point_address is initialized to an invalid address, so we can just
5057 // return that. If m_entry_point_address is valid it means we've found it
5058 // already, so return the cached value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005059
Kate Stoneb9c1b512016-09-06 20:57:50 +00005060 if (!IsExecutable() || m_entry_point_address.IsValid())
Jim Ingham672e6f52011-03-07 23:44:08 +00005061 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00005062
Kate Stoneb9c1b512016-09-06 20:57:50 +00005063 // Otherwise, look for the UnixThread or Thread command. The data for the
Adrian Prantl05097242018-04-30 16:49:04 +00005064 // Thread command is given in /usr/include/mach-o.h, but it is basically:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005065 //
5066 // uint32_t flavor - this is the flavor argument you would pass to
5067 // thread_get_state
5068 // uint32_t count - this is the count of longs in the thread state data
5069 // struct XXX_thread_state state - this is the structure from
5070 // <machine/thread_status.h> corresponding to the flavor.
5071 // <repeat this trio>
5072 //
5073 // So we just keep reading the various register flavors till we find the GPR
5074 // one, then read the PC out of there.
5075 // FIXME: We will need to have a "RegisterContext data provider" class at some
5076 // point that can get all the registers
5077 // out of data in this form & attach them to a given thread. That should
Adrian Prantl05097242018-04-30 16:49:04 +00005078 // underlie the MacOS X User process plugin, and we'll also need it for the
5079 // MacOS X Core File process plugin. When we have that we can also use it
5080 // here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005081 //
5082 // For now we hard-code the offsets and flavors we need:
5083 //
5084 //
Greg Claytonc9660542012-02-05 02:38:54 +00005085
Kate Stoneb9c1b512016-09-06 20:57:50 +00005086 ModuleSP module_sp(GetModule());
5087 if (module_sp) {
5088 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5089 struct load_command load_cmd;
5090 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5091 uint32_t i;
5092 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5093 bool done = false;
5094
5095 for (i = 0; i < m_header.ncmds; ++i) {
5096 const lldb::offset_t cmd_offset = offset;
5097 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5098 break;
5099
5100 switch (load_cmd.cmd) {
5101 case LC_UNIXTHREAD:
5102 case LC_THREAD: {
5103 while (offset < cmd_offset + load_cmd.cmdsize) {
5104 uint32_t flavor = m_data.GetU32(&offset);
5105 uint32_t count = m_data.GetU32(&offset);
5106 if (count == 0) {
5107 // We've gotten off somehow, log and exit;
5108 return m_entry_point_address;
5109 }
5110
5111 switch (m_header.cputype) {
5112 case llvm::MachO::CPU_TYPE_ARM:
5113 if (flavor == 1 ||
5114 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 from
5115 // mach/arm/thread_status.h
Greg Claytonc3776bf2012-02-09 06:16:32 +00005116 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005117 offset += 60; // This is the offset of pc in the GPR thread state
5118 // data structure.
5119 start_address = m_data.GetU32(&offset);
5120 done = true;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005121 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005122 break;
5123 case llvm::MachO::CPU_TYPE_ARM64:
5124 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5125 {
5126 offset += 256; // This is the offset of pc in the GPR thread state
5127 // data structure.
5128 start_address = m_data.GetU64(&offset);
5129 done = true;
5130 }
5131 break;
5132 case llvm::MachO::CPU_TYPE_I386:
5133 if (flavor ==
5134 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5135 {
5136 offset += 40; // This is the offset of eip in the GPR thread state
5137 // data structure.
5138 start_address = m_data.GetU32(&offset);
5139 done = true;
5140 }
5141 break;
5142 case llvm::MachO::CPU_TYPE_X86_64:
5143 if (flavor ==
5144 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5145 {
5146 offset += 16 * 8; // This is the offset of rip in the GPR thread
5147 // state data structure.
5148 start_address = m_data.GetU64(&offset);
5149 done = true;
5150 }
5151 break;
5152 default:
5153 return m_entry_point_address;
5154 }
5155 // Haven't found the GPR flavor yet, skip over the data for this
5156 // flavor:
5157 if (done)
5158 break;
5159 offset += count * 4;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005160 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005161 } break;
5162 case LC_MAIN: {
5163 ConstString text_segment_name("__TEXT");
5164 uint64_t entryoffset = m_data.GetU64(&offset);
5165 SectionSP text_segment_sp =
5166 GetSectionList()->FindSectionByName(text_segment_name);
5167 if (text_segment_sp) {
5168 done = true;
5169 start_address = text_segment_sp->GetFileAddress() + entryoffset;
5170 }
5171 } break;
5172
5173 default:
5174 break;
5175 }
5176 if (done)
5177 break;
5178
5179 // Go to the next load command:
5180 offset = cmd_offset + load_cmd.cmdsize;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005181 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005182
5183 if (start_address != LLDB_INVALID_ADDRESS) {
5184 // We got the start address from the load commands, so now resolve that
Adrian Prantl05097242018-04-30 16:49:04 +00005185 // address in the sections of this ObjectFile:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005186 if (!m_entry_point_address.ResolveAddressUsingFileSections(
5187 start_address, GetSectionList())) {
5188 m_entry_point_address.Clear();
5189 }
5190 } else {
5191 // We couldn't read the UnixThread load command - maybe it wasn't there.
Adrian Prantl05097242018-04-30 16:49:04 +00005192 // As a fallback look for the "start" symbol in the main executable.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005193
5194 ModuleSP module_sp(GetModule());
5195
5196 if (module_sp) {
5197 SymbolContextList contexts;
5198 SymbolContext context;
5199 if (module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5200 eSymbolTypeCode, contexts)) {
5201 if (contexts.GetContextAtIndex(0, context))
5202 m_entry_point_address = context.symbol->GetAddress();
5203 }
5204 }
5205 }
5206 }
5207
5208 return m_entry_point_address;
5209}
5210
5211lldb_private::Address ObjectFileMachO::GetHeaderAddress() {
5212 lldb_private::Address header_addr;
5213 SectionList *section_list = GetSectionList();
5214 if (section_list) {
5215 SectionSP text_segment_sp(
5216 section_list->FindSectionByName(GetSegmentNameTEXT()));
5217 if (text_segment_sp) {
5218 header_addr.SetSection(text_segment_sp);
5219 header_addr.SetOffset(0);
5220 }
5221 }
5222 return header_addr;
5223}
5224
5225uint32_t ObjectFileMachO::GetNumThreadContexts() {
5226 ModuleSP module_sp(GetModule());
5227 if (module_sp) {
5228 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5229 if (!m_thread_context_offsets_valid) {
5230 m_thread_context_offsets_valid = true;
5231 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5232 FileRangeArray::Entry file_range;
5233 thread_command thread_cmd;
5234 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5235 const uint32_t cmd_offset = offset;
5236 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5237 break;
5238
5239 if (thread_cmd.cmd == LC_THREAD) {
5240 file_range.SetRangeBase(offset);
5241 file_range.SetByteSize(thread_cmd.cmdsize - 8);
5242 m_thread_context_offsets.Append(file_range);
5243 }
5244 offset = cmd_offset + thread_cmd.cmdsize;
5245 }
5246 }
5247 }
5248 return m_thread_context_offsets.GetSize();
Greg Claytonc3776bf2012-02-09 06:16:32 +00005249}
5250
Jason Molenda3533cec2017-04-06 01:50:11 +00005251std::string ObjectFileMachO::GetIdentifierString() {
5252 std::string result;
5253 ModuleSP module_sp(GetModule());
5254 if (module_sp) {
5255 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005256
Adrian Prantl05097242018-04-30 16:49:04 +00005257 // First, look over the load commands for an LC_NOTE load command with
5258 // data_owner string "kern ver str" & use that if found.
Jason Molenda3533cec2017-04-06 01:50:11 +00005259 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5260 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5261 const uint32_t cmd_offset = offset;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005262 load_command lc;
5263 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5264 break;
5265 if (lc.cmd == LC_NOTE)
5266 {
5267 char data_owner[17];
5268 m_data.CopyData (offset, 16, data_owner);
5269 data_owner[16] = '\0';
5270 offset += 16;
5271 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5272 uint64_t size = m_data.GetU64_unchecked (&offset);
5273
Adrian Prantl05097242018-04-30 16:49:04 +00005274 // "kern ver str" has a uint32_t version and then a nul terminated
5275 // c-string.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005276 if (strcmp ("kern ver str", data_owner) == 0)
5277 {
5278 offset = fileoff;
5279 uint32_t version;
5280 if (m_data.GetU32 (&offset, &version, 1) != nullptr)
5281 {
5282 if (version == 1)
5283 {
5284 uint32_t strsize = size - sizeof (uint32_t);
5285 char *buf = (char*) malloc (strsize);
5286 if (buf)
5287 {
5288 m_data.CopyData (offset, strsize, buf);
5289 buf[strsize - 1] = '\0';
5290 result = buf;
5291 if (buf)
5292 free (buf);
5293 return result;
5294 }
5295 }
5296 }
5297 }
5298 }
5299 offset = cmd_offset + lc.cmdsize;
5300 }
5301
Adrian Prantl05097242018-04-30 16:49:04 +00005302 // Second, make a pass over the load commands looking for an obsolete
5303 // LC_IDENT load command.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005304 offset = MachHeaderSizeFromMagic(m_header.magic);
5305 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5306 const uint32_t cmd_offset = offset;
Jason Molenda3533cec2017-04-06 01:50:11 +00005307 struct ident_command ident_command;
5308 if (m_data.GetU32(&offset, &ident_command, 2) == NULL)
5309 break;
5310 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005311 char *buf = (char *) malloc (ident_command.cmdsize);
Jason Molenda3533cec2017-04-06 01:50:11 +00005312 if (buf != nullptr
5313 && m_data.CopyData (offset, ident_command.cmdsize, buf) == ident_command.cmdsize) {
5314 buf[ident_command.cmdsize - 1] = '\0';
5315 result = buf;
5316 }
5317 if (buf)
5318 free (buf);
5319 }
5320 offset = cmd_offset + ident_command.cmdsize;
5321 }
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005322
Jason Molenda3533cec2017-04-06 01:50:11 +00005323 }
5324 return result;
5325}
5326
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005327bool ObjectFileMachO::GetCorefileMainBinaryInfo (addr_t &address, UUID &uuid) {
5328 address = LLDB_INVALID_ADDRESS;
5329 uuid.Clear();
5330 ModuleSP module_sp(GetModule());
5331 if (module_sp) {
5332 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5333 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5334 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5335 const uint32_t cmd_offset = offset;
5336 load_command lc;
5337 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5338 break;
5339 if (lc.cmd == LC_NOTE)
5340 {
5341 char data_owner[17];
5342 memset (data_owner, 0, sizeof (data_owner));
5343 m_data.CopyData (offset, 16, data_owner);
5344 offset += 16;
5345 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5346 uint64_t size = m_data.GetU64_unchecked (&offset);
5347
Adrian Prantl05097242018-04-30 16:49:04 +00005348 // "main bin spec" (main binary specification) data payload is
5349 // formatted:
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005350 // uint32_t version [currently 1]
5351 // uint32_t type [0 == unspecified, 1 == kernel, 2 == user process]
5352 // uint64_t address [ UINT64_MAX if address not specified ]
5353 // uuid_t uuid [ all zero's if uuid not specified ]
5354 // uint32_t log2_pagesize [ process page size in log base 2, e.g. 4k pages are 12. 0 for unspecified ]
5355
5356 if (strcmp ("main bin spec", data_owner) == 0 && size >= 32)
5357 {
5358 offset = fileoff;
5359 uint32_t version;
5360 if (m_data.GetU32 (&offset, &version, 1) != nullptr && version == 1)
5361 {
5362 uint32_t type = 0;
5363 uuid_t raw_uuid;
Jason Molenda3f608292017-04-13 02:12:32 +00005364 memset (raw_uuid, 0, sizeof (uuid_t));
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005365
5366 if (m_data.GetU32 (&offset, &type, 1)
5367 && m_data.GetU64 (&offset, &address, 1)
5368 && m_data.CopyData (offset, sizeof (uuid_t), raw_uuid) != 0
5369 && uuid.SetBytes (raw_uuid, sizeof (uuid_t)))
5370 {
5371 return true;
5372 }
5373 }
5374 }
5375 }
5376 offset = cmd_offset + lc.cmdsize;
5377 }
5378 }
5379 return false;
5380}
5381
Greg Claytonc3776bf2012-02-09 06:16:32 +00005382lldb::RegisterContextSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005383ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5384 lldb_private::Thread &thread) {
5385 lldb::RegisterContextSP reg_ctx_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00005386
Kate Stoneb9c1b512016-09-06 20:57:50 +00005387 ModuleSP module_sp(GetModule());
5388 if (module_sp) {
5389 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5390 if (!m_thread_context_offsets_valid)
5391 GetNumThreadContexts();
Greg Claytona1743492012-03-13 23:14:29 +00005392
Kate Stoneb9c1b512016-09-06 20:57:50 +00005393 const FileRangeArray::Entry *thread_context_file_range =
5394 m_thread_context_offsets.GetEntryAtIndex(idx);
5395 if (thread_context_file_range) {
Jason Molenda4e7511e2013-03-06 23:19:17 +00005396
Kate Stoneb9c1b512016-09-06 20:57:50 +00005397 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5398 thread_context_file_range->GetByteSize());
Jim Ingham28eb5712012-10-12 17:34:26 +00005399
Kate Stoneb9c1b512016-09-06 20:57:50 +00005400 switch (m_header.cputype) {
5401 case llvm::MachO::CPU_TYPE_ARM64:
5402 reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data));
5403 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005404
Kate Stoneb9c1b512016-09-06 20:57:50 +00005405 case llvm::MachO::CPU_TYPE_ARM:
5406 reg_ctx_sp.reset(new RegisterContextDarwin_arm_Mach(thread, data));
5407 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005408
Kate Stoneb9c1b512016-09-06 20:57:50 +00005409 case llvm::MachO::CPU_TYPE_I386:
5410 reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data));
5411 break;
5412
5413 case llvm::MachO::CPU_TYPE_X86_64:
5414 reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data));
5415 break;
5416 }
Greg Claytonc3776bf2012-02-09 06:16:32 +00005417 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005418 }
5419 return reg_ctx_sp;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005420}
5421
Kate Stoneb9c1b512016-09-06 20:57:50 +00005422ObjectFile::Type ObjectFileMachO::CalculateType() {
5423 switch (m_header.filetype) {
5424 case MH_OBJECT: // 0x1u
5425 if (GetAddressByteSize() == 4) {
5426 // 32 bit kexts are just object files, but they do have a valid
5427 // UUID load command.
5428 UUID uuid;
5429 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005430 // this checking for the UUID load command is not enough we could
5431 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5432 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005433 if (m_strata == eStrataInvalid)
5434 m_strata = eStrataKernel;
5435 return eTypeSharedLibrary;
5436 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005437 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005438 return eTypeObjectFile;
5439
5440 case MH_EXECUTE:
5441 return eTypeExecutable; // 0x2u
5442 case MH_FVMLIB:
5443 return eTypeSharedLibrary; // 0x3u
5444 case MH_CORE:
5445 return eTypeCoreFile; // 0x4u
5446 case MH_PRELOAD:
5447 return eTypeSharedLibrary; // 0x5u
5448 case MH_DYLIB:
5449 return eTypeSharedLibrary; // 0x6u
5450 case MH_DYLINKER:
5451 return eTypeDynamicLinker; // 0x7u
5452 case MH_BUNDLE:
5453 return eTypeSharedLibrary; // 0x8u
5454 case MH_DYLIB_STUB:
5455 return eTypeStubLibrary; // 0x9u
5456 case MH_DSYM:
5457 return eTypeDebugInfo; // 0xAu
5458 case MH_KEXT_BUNDLE:
5459 return eTypeSharedLibrary; // 0xBu
5460 default:
5461 break;
5462 }
5463 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005464}
5465
Kate Stoneb9c1b512016-09-06 20:57:50 +00005466ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5467 switch (m_header.filetype) {
5468 case MH_OBJECT: // 0x1u
5469 {
5470 // 32 bit kexts are just object files, but they do have a valid
5471 // UUID load command.
5472 UUID uuid;
5473 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005474 // this checking for the UUID load command is not enough we could
5475 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5476 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005477 if (m_type == eTypeInvalid)
5478 m_type = eTypeSharedLibrary;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005479
Kate Stoneb9c1b512016-09-06 20:57:50 +00005480 return eStrataKernel;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005481 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005482 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005483 return eStrataUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005484
5485 case MH_EXECUTE: // 0x2u
5486 // Check for the MH_DYLDLINK bit in the flags
5487 if (m_header.flags & MH_DYLDLINK) {
5488 return eStrataUser;
5489 } else {
5490 SectionList *section_list = GetSectionList();
5491 if (section_list) {
5492 static ConstString g_kld_section_name("__KLD");
5493 if (section_list->FindSectionByName(g_kld_section_name))
5494 return eStrataKernel;
5495 }
5496 }
5497 return eStrataRawImage;
5498
5499 case MH_FVMLIB:
5500 return eStrataUser; // 0x3u
5501 case MH_CORE:
5502 return eStrataUnknown; // 0x4u
5503 case MH_PRELOAD:
5504 return eStrataRawImage; // 0x5u
5505 case MH_DYLIB:
5506 return eStrataUser; // 0x6u
5507 case MH_DYLINKER:
5508 return eStrataUser; // 0x7u
5509 case MH_BUNDLE:
5510 return eStrataUser; // 0x8u
5511 case MH_DYLIB_STUB:
5512 return eStrataUser; // 0x9u
5513 case MH_DSYM:
5514 return eStrataUnknown; // 0xAu
5515 case MH_KEXT_BUNDLE:
5516 return eStrataKernel; // 0xBu
5517 default:
5518 break;
5519 }
5520 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005521}
5522
Kate Stoneb9c1b512016-09-06 20:57:50 +00005523uint32_t ObjectFileMachO::GetVersion(uint32_t *versions,
5524 uint32_t num_versions) {
5525 ModuleSP module_sp(GetModule());
5526 if (module_sp) {
5527 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5528 struct dylib_command load_cmd;
5529 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5530 uint32_t version_cmd = 0;
5531 uint64_t version = 0;
5532 uint32_t i;
5533 for (i = 0; i < m_header.ncmds; ++i) {
5534 const lldb::offset_t cmd_offset = offset;
5535 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5536 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005537
Kate Stoneb9c1b512016-09-06 20:57:50 +00005538 if (load_cmd.cmd == LC_ID_DYLIB) {
5539 if (version_cmd == 0) {
5540 version_cmd = load_cmd.cmd;
5541 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5542 break;
5543 version = load_cmd.dylib.current_version;
Greg Claytonc2ff9312012-02-22 19:41:02 +00005544 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005545 break; // Break for now unless there is another more complete version
5546 // number load command in the future.
5547 }
5548 offset = cmd_offset + load_cmd.cmdsize;
5549 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00005550
Kate Stoneb9c1b512016-09-06 20:57:50 +00005551 if (version_cmd == LC_ID_DYLIB) {
5552 if (versions != NULL && num_versions > 0) {
5553 if (num_versions > 0)
5554 versions[0] = (version & 0xFFFF0000ull) >> 16;
5555 if (num_versions > 1)
5556 versions[1] = (version & 0x0000FF00ull) >> 8;
5557 if (num_versions > 2)
5558 versions[2] = (version & 0x000000FFull);
5559 // Fill in an remaining version numbers with invalid values
5560 for (i = 3; i < num_versions; ++i)
5561 versions[i] = UINT32_MAX;
5562 }
Adrian Prantl05097242018-04-30 16:49:04 +00005563 // The LC_ID_DYLIB load command has a version with 3 version numbers in
5564 // it, so always return 3
Kate Stoneb9c1b512016-09-06 20:57:50 +00005565 return 3;
5566 }
5567 }
5568 return false;
5569}
5570
5571bool ObjectFileMachO::GetArchitecture(ArchSpec &arch) {
5572 ModuleSP module_sp(GetModule());
5573 if (module_sp) {
5574 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5575 return GetArchitecture(m_header, m_data,
5576 MachHeaderSizeFromMagic(m_header.magic), arch);
5577 }
5578 return false;
5579}
5580
Jason Molenda07580ff2018-05-04 00:59:37 +00005581void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process, addr_t &base_addr, UUID &uuid) {
5582 uuid.Clear();
5583 base_addr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005584 if (process && process->GetDynamicLoader()) {
5585 DynamicLoader *dl = process->GetDynamicLoader();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005586 LazyBool using_shared_cache;
5587 LazyBool private_shared_cache;
Jason Molenda07580ff2018-05-04 00:59:37 +00005588 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005589 private_shared_cache);
5590 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005591 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005592 if (log)
Jason Molenda07580ff2018-05-04 00:59:37 +00005593 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 +00005594}
5595
Jason Molenda07580ff2018-05-04 00:59:37 +00005596// From dyld SPI header dyld_process_info.h
5597typedef void *dyld_process_info;
5598struct lldb_copy__dyld_process_cache_info {
5599 uuid_t cacheUUID; // UUID of cache used by process
5600 uint64_t cacheBaseAddress; // load address of dyld shared cache
5601 bool noCache; // process is running without a dyld cache
5602 bool privateCache; // process is using a private copy of its dyld cache
5603};
5604
5605// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with llvm
5606// enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile errors.
5607// So we need to use the actual underlying types of task_t and kern_return_t
5608// below.
5609extern "C" unsigned int /*task_t*/ mach_task_self();
5610
5611void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5612 uuid.Clear();
5613 base_addr = LLDB_INVALID_ADDRESS;
5614
Kate Stoneb9c1b512016-09-06 20:57:50 +00005615#if defined(__APPLE__) && \
5616 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5617 uint8_t *(*dyld_get_all_image_infos)(void);
5618 dyld_get_all_image_infos =
5619 (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5620 if (dyld_get_all_image_infos) {
5621 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5622 if (dyld_all_image_infos_address) {
5623 uint32_t *version = (uint32_t *)
5624 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5625 if (*version >= 13) {
5626 uuid_t *sharedCacheUUID_address = 0;
5627 int wordsize = sizeof(uint8_t *);
5628 if (wordsize == 8) {
5629 sharedCacheUUID_address =
5630 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5631 160); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005632 if (*version >= 15)
5633 base_addr = *(uint64_t *) ((uint8_t *) dyld_all_image_infos_address
5634 + 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +00005635 } else {
5636 sharedCacheUUID_address =
5637 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5638 84); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005639 if (*version >= 15) {
5640 base_addr = 0;
5641 base_addr = *(uint32_t *) ((uint8_t *) dyld_all_image_infos_address
5642 + 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5643 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005645 uuid.SetBytes(sharedCacheUUID_address);
5646 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005647 }
Jason Molendafd443e92018-02-07 01:28:29 +00005648 } else {
5649 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
Jason Molenda07580ff2018-05-04 00:59:37 +00005650 dyld_process_info (*dyld_process_info_create)(unsigned int /* task_t */ task, uint64_t timestamp, unsigned int /*kern_return_t*/ *kernelError);
5651 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5652 void (*dyld_process_info_release)(dyld_process_info info);
5653
5654 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, unsigned int /*kern_return_t*/ *))
5655 dlsym (RTLD_DEFAULT, "_dyld_process_info_create");
5656 dyld_process_info_get_cache = (void (*)(void *, void *))
5657 dlsym (RTLD_DEFAULT, "_dyld_process_info_get_cache");
5658 dyld_process_info_release = (void (*)(void *))
5659 dlsym (RTLD_DEFAULT, "_dyld_process_info_release");
5660
5661 if (dyld_process_info_create && dyld_process_info_get_cache) {
5662 unsigned int /*kern_return_t */ kern_ret;
5663 dyld_process_info process_info = dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5664 if (process_info) {
5665 struct lldb_copy__dyld_process_cache_info sc_info;
5666 memset (&sc_info, 0, sizeof (struct lldb_copy__dyld_process_cache_info));
5667 dyld_process_info_get_cache (process_info, &sc_info);
5668 if (sc_info.cacheBaseAddress != 0) {
5669 base_addr = sc_info.cacheBaseAddress;
5670 uuid.SetBytes (sc_info.cacheUUID);
5671 }
5672 dyld_process_info_release (process_info);
5673 }
Jason Molendafd443e92018-02-07 01:28:29 +00005674 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005675 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005676 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005677 if (log && uuid.IsValid())
Jason Molenda07580ff2018-05-04 00:59:37 +00005678 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 +00005679#endif
Jason Molenda0e0954c2013-04-16 06:24:42 +00005680}
5681
Kate Stoneb9c1b512016-09-06 20:57:50 +00005682uint32_t ObjectFileMachO::GetMinimumOSVersion(uint32_t *versions,
5683 uint32_t num_versions) {
5684 if (m_min_os_versions.empty()) {
5685 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5686 bool success = false;
5687 for (uint32_t i = 0; success == false && i < m_header.ncmds; ++i) {
5688 const lldb::offset_t load_cmd_offset = offset;
5689
5690 version_min_command lc;
5691 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5692 break;
5693 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5694 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5695 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5696 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5697 if (m_data.GetU32(&offset, &lc.version,
5698 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5699 const uint32_t xxxx = lc.version >> 16;
5700 const uint32_t yy = (lc.version >> 8) & 0xffu;
5701 const uint32_t zz = lc.version & 0xffu;
5702 if (xxxx) {
5703 m_min_os_versions.push_back(xxxx);
5704 m_min_os_versions.push_back(yy);
5705 m_min_os_versions.push_back(zz);
5706 }
5707 success = true;
Greg Clayton9b234982013-10-24 22:54:08 +00005708 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005709 }
5710 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005711 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005712
5713 if (success == false) {
5714 // Push an invalid value so we don't keep trying to
5715 m_min_os_versions.push_back(UINT32_MAX);
Greg Clayton9b234982013-10-24 22:54:08 +00005716 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005717 }
5718
5719 if (m_min_os_versions.size() > 1 || m_min_os_versions[0] != UINT32_MAX) {
5720 if (versions != NULL && num_versions > 0) {
5721 for (size_t i = 0; i < num_versions; ++i) {
5722 if (i < m_min_os_versions.size())
5723 versions[i] = m_min_os_versions[i];
5724 else
5725 versions[i] = 0;
5726 }
5727 }
5728 return m_min_os_versions.size();
5729 }
5730 // Call the superclasses version that will empty out the data
5731 return ObjectFile::GetMinimumOSVersion(versions, num_versions);
Greg Clayton9b234982013-10-24 22:54:08 +00005732}
5733
Kate Stoneb9c1b512016-09-06 20:57:50 +00005734uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions,
5735 uint32_t num_versions) {
5736 if (m_sdk_versions.empty()) {
5737 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5738 bool success = false;
5739 for (uint32_t i = 0; success == false && i < m_header.ncmds; ++i) {
5740 const lldb::offset_t load_cmd_offset = offset;
5741
5742 version_min_command lc;
5743 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5744 break;
5745 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5746 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5747 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5748 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5749 if (m_data.GetU32(&offset, &lc.version,
5750 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5751 const uint32_t xxxx = lc.sdk >> 16;
5752 const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5753 const uint32_t zz = lc.sdk & 0xffu;
5754 if (xxxx) {
5755 m_sdk_versions.push_back(xxxx);
5756 m_sdk_versions.push_back(yy);
5757 m_sdk_versions.push_back(zz);
5758 }
5759 success = true;
Greg Clayton9b234982013-10-24 22:54:08 +00005760 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005761 }
5762 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005763 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005764
5765 if (success == false) {
5766 // Push an invalid value so we don't keep trying to
5767 m_sdk_versions.push_back(UINT32_MAX);
Greg Clayton9b234982013-10-24 22:54:08 +00005768 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005769 }
5770
5771 if (m_sdk_versions.size() > 1 || m_sdk_versions[0] != UINT32_MAX) {
5772 if (versions != NULL && num_versions > 0) {
5773 for (size_t i = 0; i < num_versions; ++i) {
5774 if (i < m_sdk_versions.size())
5775 versions[i] = m_sdk_versions[i];
5776 else
5777 versions[i] = 0;
5778 }
5779 }
5780 return m_sdk_versions.size();
5781 }
5782 // Call the superclasses version that will empty out the data
5783 return ObjectFile::GetSDKVersion(versions, num_versions);
Greg Clayton9b234982013-10-24 22:54:08 +00005784}
5785
Kate Stoneb9c1b512016-09-06 20:57:50 +00005786bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5787 return m_header.filetype == llvm::MachO::MH_DYLINKER;
Greg Clayton08928f32015-02-05 02:01:34 +00005788}
5789
Kate Stoneb9c1b512016-09-06 20:57:50 +00005790bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5791 return m_allow_assembly_emulation_unwind_plans;
Jason Molenda955dcf22016-05-04 03:09:40 +00005792}
5793
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005794//------------------------------------------------------------------
5795// PluginInterface protocol
5796//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00005797lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5798 return GetPluginNameStatic();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005799}
5800
Kate Stoneb9c1b512016-09-06 20:57:50 +00005801uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005802
Kate Stoneb9c1b512016-09-06 20:57:50 +00005803Section *ObjectFileMachO::GetMachHeaderSection() {
Adrian Prantl05097242018-04-30 16:49:04 +00005804 // Find the first address of the mach header which is the first non-zero file
5805 // sized section whose file offset is zero. This is the base file address of
5806 // the mach-o file which can be subtracted from the vmaddr of the other
Kate Stoneb9c1b512016-09-06 20:57:50 +00005807 // segments found in memory and added to the load address
5808 ModuleSP module_sp = GetModule();
5809 if (module_sp) {
5810 SectionList *section_list = GetSectionList();
5811 if (section_list) {
5812 lldb::addr_t mach_base_file_addr = LLDB_INVALID_ADDRESS;
5813 const size_t num_sections = section_list->GetSize();
Greg Clayton07347372015-06-08 21:53:11 +00005814
Kate Stoneb9c1b512016-09-06 20:57:50 +00005815 for (size_t sect_idx = 0; sect_idx < num_sections &&
5816 mach_base_file_addr == LLDB_INVALID_ADDRESS;
5817 ++sect_idx) {
5818 Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5819 if (section && section->GetFileSize() > 0 &&
5820 section->GetFileOffset() == 0 &&
5821 section->IsThreadSpecific() == false &&
5822 module_sp.get() == section->GetModule().get()) {
5823 return section;
Greg Clayton07347372015-06-08 21:53:11 +00005824 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005825 }
Greg Clayton07347372015-06-08 21:53:11 +00005826 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005827 }
5828 return nullptr;
Greg Clayton07347372015-06-08 21:53:11 +00005829}
5830
Kate Stoneb9c1b512016-09-06 20:57:50 +00005831lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
5832 lldb::addr_t mach_header_load_address, const Section *mach_header_section,
5833 const Section *section) {
5834 ModuleSP module_sp = GetModule();
5835 if (module_sp && mach_header_section && section &&
5836 mach_header_load_address != LLDB_INVALID_ADDRESS) {
5837 lldb::addr_t mach_header_file_addr = mach_header_section->GetFileAddress();
5838 if (mach_header_file_addr != LLDB_INVALID_ADDRESS) {
5839 if (section && section->GetFileSize() > 0 &&
5840 section->IsThreadSpecific() == false &&
5841 module_sp.get() == section->GetModule().get()) {
5842 // Ignore __LINKEDIT and __DWARF segments
5843 if (section->GetName() == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00005844 // Only map __LINKEDIT if we have an in memory image and this isn't a
5845 // kernel binary like a kext or mach_kernel.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005846 const bool is_memory_image = (bool)m_process_wp.lock();
5847 const Strata strata = GetStrata();
5848 if (is_memory_image == false || strata == eStrataKernel)
5849 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00005850 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005851 return section->GetFileAddress() - mach_header_file_addr +
5852 mach_header_load_address;
5853 }
Greg Clayton07347372015-06-08 21:53:11 +00005854 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005855 }
5856 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00005857}
5858
Kate Stoneb9c1b512016-09-06 20:57:50 +00005859bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
5860 bool value_is_offset) {
5861 ModuleSP module_sp = GetModule();
5862 if (module_sp) {
5863 size_t num_loaded_sections = 0;
5864 SectionList *section_list = GetSectionList();
5865 if (section_list) {
5866 const size_t num_sections = section_list->GetSize();
Greg Clayton7524e092014-02-06 20:10:16 +00005867
Kate Stoneb9c1b512016-09-06 20:57:50 +00005868 if (value_is_offset) {
5869 // "value" is an offset to apply to each top level segment
5870 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +00005871 // Iterate through the object file sections to find all of the
5872 // sections that size on disk (to avoid __PAGEZERO) and load them
Kate Stoneb9c1b512016-09-06 20:57:50 +00005873 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5874 if (section_sp && section_sp->GetFileSize() > 0 &&
5875 section_sp->IsThreadSpecific() == false &&
5876 module_sp.get() == section_sp->GetModule().get()) {
5877 // Ignore __LINKEDIT and __DWARF segments
5878 if (section_sp->GetName() == GetSegmentNameLINKEDIT()) {
5879 // Only map __LINKEDIT if we have an in memory image and this
Adrian Prantl05097242018-04-30 16:49:04 +00005880 // isn't a kernel binary like a kext or mach_kernel.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005881 const bool is_memory_image = (bool)m_process_wp.lock();
5882 const Strata strata = GetStrata();
5883 if (is_memory_image == false || strata == eStrataKernel)
5884 continue;
Greg Clayton7524e092014-02-06 20:10:16 +00005885 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005886 if (target.GetSectionLoadList().SetSectionLoadAddress(
5887 section_sp, section_sp->GetFileAddress() + value))
5888 ++num_loaded_sections;
5889 }
Greg Clayton7524e092014-02-06 20:10:16 +00005890 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005891 } else {
5892 // "value" is the new base address of the mach_header, adjust each
5893 // section accordingly
5894
5895 Section *mach_header_section = GetMachHeaderSection();
5896 if (mach_header_section) {
5897 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5898 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5899
5900 lldb::addr_t section_load_addr =
5901 CalculateSectionLoadAddressForMemoryImage(
5902 value, mach_header_section, section_sp.get());
5903 if (section_load_addr != LLDB_INVALID_ADDRESS) {
5904 if (target.GetSectionLoadList().SetSectionLoadAddress(
5905 section_sp, section_load_addr))
5906 ++num_loaded_sections;
5907 }
5908 }
5909 }
5910 }
Greg Clayton7524e092014-02-06 20:10:16 +00005911 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005912 return num_loaded_sections > 0;
5913 }
5914 return false;
Greg Clayton7524e092014-02-06 20:10:16 +00005915}
5916
Kate Stoneb9c1b512016-09-06 20:57:50 +00005917bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00005918 const FileSpec &outfile, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005919 if (process_sp) {
5920 Target &target = process_sp->GetTarget();
5921 const ArchSpec target_arch = target.GetArchitecture();
5922 const llvm::Triple &target_triple = target_arch.GetTriple();
5923 if (target_triple.getVendor() == llvm::Triple::Apple &&
5924 (target_triple.getOS() == llvm::Triple::MacOSX ||
5925 target_triple.getOS() == llvm::Triple::IOS ||
5926 target_triple.getOS() == llvm::Triple::WatchOS ||
5927 target_triple.getOS() == llvm::Triple::TvOS)) {
5928 bool make_core = false;
5929 switch (target_arch.GetMachine()) {
5930 case llvm::Triple::aarch64:
5931 case llvm::Triple::arm:
5932 case llvm::Triple::thumb:
5933 case llvm::Triple::x86:
5934 case llvm::Triple::x86_64:
5935 make_core = true;
5936 break;
5937 default:
5938 error.SetErrorStringWithFormat("unsupported core architecture: %s",
5939 target_triple.str().c_str());
5940 break;
5941 }
5942
5943 if (make_core) {
5944 std::vector<segment_command_64> segment_load_commands;
5945 // uint32_t range_info_idx = 0;
5946 MemoryRegionInfo range_info;
Zachary Turner97206d52017-05-12 04:51:55 +00005947 Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005948 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
5949 const ByteOrder byte_order = target_arch.GetByteOrder();
5950 if (range_error.Success()) {
5951 while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
5952 const addr_t addr = range_info.GetRange().GetRangeBase();
5953 const addr_t size = range_info.GetRange().GetByteSize();
5954
5955 if (size == 0)
5956 break;
5957
5958 // Calculate correct protections
5959 uint32_t prot = 0;
5960 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
5961 prot |= VM_PROT_READ;
5962 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
5963 prot |= VM_PROT_WRITE;
5964 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
5965 prot |= VM_PROT_EXECUTE;
5966
5967 // printf ("[%3u] [0x%16.16" PRIx64 " -
5968 // 0x%16.16" PRIx64 ") %c%c%c\n",
5969 // range_info_idx,
5970 // addr,
5971 // size,
5972 // (prot & VM_PROT_READ ) ? 'r' :
5973 // '-',
5974 // (prot & VM_PROT_WRITE ) ? 'w' :
5975 // '-',
5976 // (prot & VM_PROT_EXECUTE) ? 'x' :
5977 // '-');
5978
5979 if (prot != 0) {
5980 uint32_t cmd_type = LC_SEGMENT_64;
5981 uint32_t segment_size = sizeof(segment_command_64);
5982 if (addr_byte_size == 4) {
5983 cmd_type = LC_SEGMENT;
5984 segment_size = sizeof(segment_command);
5985 }
5986 segment_command_64 segment = {
5987 cmd_type, // uint32_t cmd;
5988 segment_size, // uint32_t cmdsize;
5989 {0}, // char segname[16];
5990 addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
5991 size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
5992 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
5993 size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
5994 prot, // uint32_t maxprot;
5995 prot, // uint32_t initprot;
5996 0, // uint32_t nsects;
5997 0}; // uint32_t flags;
5998 segment_load_commands.push_back(segment);
5999 } else {
6000 // No protections and a size of 1 used to be returned from old
6001 // debugservers when we asked about a region that was past the
6002 // last memory region and it indicates the end...
6003 if (size == 1)
6004 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006005 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006006
Kate Stoneb9c1b512016-09-06 20:57:50 +00006007 range_error = process_sp->GetMemoryRegionInfo(
6008 range_info.GetRange().GetRangeEnd(), range_info);
6009 if (range_error.Fail())
6010 break;
6011 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006012
Kate Stoneb9c1b512016-09-06 20:57:50 +00006013 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
Greg Claytona2715cf2014-06-13 00:54:12 +00006014
Kate Stoneb9c1b512016-09-06 20:57:50 +00006015 mach_header_64 mach_header;
6016 if (addr_byte_size == 8) {
6017 mach_header.magic = MH_MAGIC_64;
6018 } else {
6019 mach_header.magic = MH_MAGIC;
6020 }
6021 mach_header.cputype = target_arch.GetMachOCPUType();
6022 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6023 mach_header.filetype = MH_CORE;
6024 mach_header.ncmds = segment_load_commands.size();
6025 mach_header.flags = 0;
6026 mach_header.reserved = 0;
6027 ThreadList &thread_list = process_sp->GetThreadList();
6028 const uint32_t num_threads = thread_list.GetSize();
Greg Claytona2715cf2014-06-13 00:54:12 +00006029
Adrian Prantl05097242018-04-30 16:49:04 +00006030 // Make an array of LC_THREAD data items. Each one contains the
6031 // contents of the LC_THREAD load command. The data doesn't contain
6032 // the load command + load command size, we will add the load command
6033 // and load command size as we emit the data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006034 std::vector<StreamString> LC_THREAD_datas(num_threads);
6035 for (auto &LC_THREAD_data : LC_THREAD_datas) {
6036 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6037 LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6038 LC_THREAD_data.SetByteOrder(byte_order);
6039 }
6040 for (uint32_t thread_idx = 0; thread_idx < num_threads;
6041 ++thread_idx) {
6042 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6043 if (thread_sp) {
6044 switch (mach_header.cputype) {
6045 case llvm::MachO::CPU_TYPE_ARM64:
6046 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6047 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6048 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006049
Kate Stoneb9c1b512016-09-06 20:57:50 +00006050 case llvm::MachO::CPU_TYPE_ARM:
6051 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6052 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6053 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006054
Kate Stoneb9c1b512016-09-06 20:57:50 +00006055 case llvm::MachO::CPU_TYPE_I386:
6056 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6057 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6058 break;
Jason Molenda22952582014-11-12 01:11:36 +00006059
Kate Stoneb9c1b512016-09-06 20:57:50 +00006060 case llvm::MachO::CPU_TYPE_X86_64:
6061 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6062 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6063 break;
6064 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006065 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006066 }
6067
6068 // The size of the load command is the size of the segments...
6069 if (addr_byte_size == 8) {
6070 mach_header.sizeofcmds = segment_load_commands.size() *
6071 sizeof(struct segment_command_64);
6072 } else {
6073 mach_header.sizeofcmds =
6074 segment_load_commands.size() * sizeof(struct segment_command);
6075 }
6076
6077 // and the size of all LC_THREAD load command
6078 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6079 ++mach_header.ncmds;
6080 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6081 }
6082
6083 printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x "
6084 "0x%8.8x 0x%8.8x\n",
6085 mach_header.magic, mach_header.cputype, mach_header.cpusubtype,
6086 mach_header.filetype, mach_header.ncmds,
6087 mach_header.sizeofcmds, mach_header.flags,
6088 mach_header.reserved);
6089
6090 // Write the mach header
6091 buffer.PutHex32(mach_header.magic);
6092 buffer.PutHex32(mach_header.cputype);
6093 buffer.PutHex32(mach_header.cpusubtype);
6094 buffer.PutHex32(mach_header.filetype);
6095 buffer.PutHex32(mach_header.ncmds);
6096 buffer.PutHex32(mach_header.sizeofcmds);
6097 buffer.PutHex32(mach_header.flags);
6098 if (addr_byte_size == 8) {
6099 buffer.PutHex32(mach_header.reserved);
6100 }
6101
6102 // Skip the mach header and all load commands and align to the next
6103 // 0x1000 byte boundary
6104 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6105 if (file_offset & 0x00000fff) {
6106 file_offset += 0x00001000ull;
6107 file_offset &= (~0x00001000ull + 1);
6108 }
6109
6110 for (auto &segment : segment_load_commands) {
6111 segment.fileoff = file_offset;
6112 file_offset += segment.filesize;
6113 }
6114
6115 // Write out all of the LC_THREAD load commands
6116 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6117 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6118 buffer.PutHex32(LC_THREAD);
6119 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
Zachary Turnerc1564272016-11-16 21:15:24 +00006120 buffer.Write(LC_THREAD_data.GetString().data(),
6121 LC_THREAD_data_size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006122 }
6123
6124 // Write out all of the segment load commands
6125 for (const auto &segment : segment_load_commands) {
6126 printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6127 ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6128 ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6129 segment.cmd, segment.cmdsize, segment.vmaddr,
6130 segment.vmaddr + segment.vmsize, segment.fileoff,
6131 segment.filesize, segment.maxprot, segment.initprot,
6132 segment.nsects, segment.flags);
6133
6134 buffer.PutHex32(segment.cmd);
6135 buffer.PutHex32(segment.cmdsize);
6136 buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6137 if (addr_byte_size == 8) {
6138 buffer.PutHex64(segment.vmaddr);
6139 buffer.PutHex64(segment.vmsize);
6140 buffer.PutHex64(segment.fileoff);
6141 buffer.PutHex64(segment.filesize);
6142 } else {
6143 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6144 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6145 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6146 buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6147 }
6148 buffer.PutHex32(segment.maxprot);
6149 buffer.PutHex32(segment.initprot);
6150 buffer.PutHex32(segment.nsects);
6151 buffer.PutHex32(segment.flags);
6152 }
6153
6154 File core_file;
6155 std::string core_file_path(outfile.GetPath());
6156 error = core_file.Open(core_file_path.c_str(),
6157 File::eOpenOptionWrite |
6158 File::eOpenOptionTruncate |
6159 File::eOpenOptionCanCreate);
6160 if (error.Success()) {
6161 // Read 1 page at a time
6162 uint8_t bytes[0x1000];
6163 // Write the mach header and load commands out to the core file
6164 size_t bytes_written = buffer.GetString().size();
6165 error = core_file.Write(buffer.GetString().data(), bytes_written);
6166 if (error.Success()) {
6167 // Now write the file data for all memory segments in the process
6168 for (const auto &segment : segment_load_commands) {
6169 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6170 error.SetErrorStringWithFormat(
6171 "unable to seek to offset 0x%" PRIx64 " in '%s'",
6172 segment.fileoff, core_file_path.c_str());
6173 break;
6174 }
6175
6176 printf("Saving %" PRId64
6177 " bytes of data for memory region at 0x%" PRIx64 "\n",
6178 segment.vmsize, segment.vmaddr);
6179 addr_t bytes_left = segment.vmsize;
6180 addr_t addr = segment.vmaddr;
Zachary Turner97206d52017-05-12 04:51:55 +00006181 Status memory_read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006182 while (bytes_left > 0 && error.Success()) {
6183 const size_t bytes_to_read =
6184 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6185 const size_t bytes_read = process_sp->ReadMemory(
6186 addr, bytes, bytes_to_read, memory_read_error);
6187 if (bytes_read == bytes_to_read) {
6188 size_t bytes_written = bytes_read;
6189 error = core_file.Write(bytes, bytes_written);
6190 bytes_left -= bytes_read;
6191 addr += bytes_read;
6192 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00006193 // Some pages within regions are not readable, those should
6194 // be zero filled
Kate Stoneb9c1b512016-09-06 20:57:50 +00006195 memset(bytes, 0, bytes_to_read);
6196 size_t bytes_written = bytes_to_read;
6197 error = core_file.Write(bytes, bytes_written);
6198 bytes_left -= bytes_to_read;
6199 addr += bytes_to_read;
6200 }
6201 }
6202 }
6203 }
6204 }
6205 } else {
6206 error.SetErrorString(
6207 "process doesn't support getting memory region info");
Greg Claytona2715cf2014-06-13 00:54:12 +00006208 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006209 }
6210 return true; // This is the right plug to handle saving core files for
6211 // this process
Greg Claytona2715cf2014-06-13 00:54:12 +00006212 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006213 }
6214 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00006215}