blob: 0aa0fc91e408d4c569e5ad2961046d21790c8afe [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:
Pavel Labatha041d842018-06-01 12:06:45 +00001203 case eSectionTypeDWARFDebugNames:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 case eSectionTypeDWARFDebugPubNames:
1205 case eSectionTypeDWARFDebugPubTypes:
1206 case eSectionTypeDWARFDebugRanges:
1207 case eSectionTypeDWARFDebugStr:
1208 case eSectionTypeDWARFDebugStrOffsets:
Greg Clayton2550ca12018-05-08 17:19:24 +00001209 case eSectionTypeDWARFDebugTypes:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 case eSectionTypeDWARFAppleNames:
1211 case eSectionTypeDWARFAppleTypes:
1212 case eSectionTypeDWARFAppleNamespaces:
1213 case eSectionTypeDWARFAppleObjC:
Jan Kratochvile4777a92018-04-29 19:47:48 +00001214 case eSectionTypeDWARFGNUDebugAltLink:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 return eAddressClassDebug;
1216
1217 case eSectionTypeEHFrame:
1218 case eSectionTypeARMexidx:
1219 case eSectionTypeARMextab:
1220 case eSectionTypeCompactUnwind:
1221 return eAddressClassRuntime;
1222
1223 case eSectionTypeAbsoluteAddress:
1224 case eSectionTypeELFSymbolTable:
1225 case eSectionTypeELFDynamicSymbols:
1226 case eSectionTypeELFRelocationEntries:
1227 case eSectionTypeELFDynamicLinkInfo:
1228 case eSectionTypeOther:
1229 return eAddressClassUnknown;
1230 }
1231 }
1232 }
1233
1234 const SymbolType symbol_type = symbol->GetType();
1235 switch (symbol_type) {
1236 case eSymbolTypeAny:
1237 return eAddressClassUnknown;
1238 case eSymbolTypeAbsolute:
1239 return eAddressClassUnknown;
1240
1241 case eSymbolTypeCode:
1242 case eSymbolTypeTrampoline:
1243 case eSymbolTypeResolver:
1244 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00001245 // For ARM we have a bit in the n_desc field of the symbol that tells
1246 // us ARM/Thumb which is bit 0x0008.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1248 return eAddressClassCodeAlternateISA;
1249 }
1250 return eAddressClassCode;
1251
1252 case eSymbolTypeData:
1253 return eAddressClassData;
1254 case eSymbolTypeRuntime:
1255 return eAddressClassRuntime;
1256 case eSymbolTypeException:
1257 return eAddressClassRuntime;
1258 case eSymbolTypeSourceFile:
1259 return eAddressClassDebug;
1260 case eSymbolTypeHeaderFile:
1261 return eAddressClassDebug;
1262 case eSymbolTypeObjectFile:
1263 return eAddressClassDebug;
1264 case eSymbolTypeCommonBlock:
1265 return eAddressClassDebug;
1266 case eSymbolTypeBlock:
1267 return eAddressClassDebug;
1268 case eSymbolTypeLocal:
1269 return eAddressClassData;
1270 case eSymbolTypeParam:
1271 return eAddressClassData;
1272 case eSymbolTypeVariable:
1273 return eAddressClassData;
1274 case eSymbolTypeVariableType:
1275 return eAddressClassDebug;
1276 case eSymbolTypeLineEntry:
1277 return eAddressClassDebug;
1278 case eSymbolTypeLineHeader:
1279 return eAddressClassDebug;
1280 case eSymbolTypeScopeBegin:
1281 return eAddressClassDebug;
1282 case eSymbolTypeScopeEnd:
1283 return eAddressClassDebug;
1284 case eSymbolTypeAdditional:
1285 return eAddressClassUnknown;
1286 case eSymbolTypeCompiler:
1287 return eAddressClassDebug;
1288 case eSymbolTypeInstrumentation:
1289 return eAddressClassDebug;
1290 case eSymbolTypeUndefined:
1291 return eAddressClassUnknown;
1292 case eSymbolTypeObjCClass:
1293 return eAddressClassRuntime;
1294 case eSymbolTypeObjCMetaClass:
1295 return eAddressClassRuntime;
1296 case eSymbolTypeObjCIVar:
1297 return eAddressClassRuntime;
1298 case eSymbolTypeReExported:
1299 return eAddressClassRuntime;
1300 }
1301 }
1302 }
1303 return eAddressClassUnknown;
1304}
1305
1306Symtab *ObjectFileMachO::GetSymtab() {
1307 ModuleSP module_sp(GetModule());
1308 if (module_sp) {
1309 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1310 if (m_symtab_ap.get() == NULL) {
1311 m_symtab_ap.reset(new Symtab(this));
1312 std::lock_guard<std::recursive_mutex> symtab_guard(
1313 m_symtab_ap->GetMutex());
1314 ParseSymtab();
1315 m_symtab_ap->Finalize();
1316 }
1317 }
1318 return m_symtab_ap.get();
1319}
1320
1321bool ObjectFileMachO::IsStripped() {
1322 if (m_dysymtab.cmd == 0) {
1323 ModuleSP module_sp(GetModule());
1324 if (module_sp) {
1325 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1326 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1327 const lldb::offset_t load_cmd_offset = offset;
1328
1329 load_command lc;
1330 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
1331 break;
1332 if (lc.cmd == LC_DYSYMTAB) {
1333 m_dysymtab.cmd = lc.cmd;
1334 m_dysymtab.cmdsize = lc.cmdsize;
1335 if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1336 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1337 NULL) {
1338 // Clear m_dysymtab if we were unable to read all items from the
1339 // load command
1340 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1341 }
1342 }
1343 offset = load_cmd_offset + lc.cmdsize;
1344 }
1345 }
1346 }
1347 if (m_dysymtab.cmd)
1348 return m_dysymtab.nlocalsym <= 1;
1349 return false;
1350}
1351
Pavel Labathb417eea2018-03-06 13:53:26 +00001352ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
1353 EncryptedFileRanges result;
Pavel Labathf90054d2018-03-03 22:07:47 +00001354 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labathb417eea2018-03-06 13:53:26 +00001355
Pavel Labathf90054d2018-03-03 22:07:47 +00001356 encryption_info_command encryption_cmd;
Pavel Labathb417eea2018-03-06 13:53:26 +00001357 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001358 const lldb::offset_t load_cmd_offset = offset;
1359 if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL)
1360 break;
1361
Adrian Prantl05097242018-04-30 16:49:04 +00001362 // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1363 // 3 fields we care about, so treat them the same.
Pavel Labathf90054d2018-03-03 22:07:47 +00001364 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1365 encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1366 if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1367 if (encryption_cmd.cryptid != 0) {
1368 EncryptedFileRanges::Entry entry;
1369 entry.SetRangeBase(encryption_cmd.cryptoff);
1370 entry.SetByteSize(encryption_cmd.cryptsize);
Pavel Labathb417eea2018-03-06 13:53:26 +00001371 result.Append(entry);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372 }
1373 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001374 }
Pavel Labathf90054d2018-03-03 22:07:47 +00001375 offset = load_cmd_offset + encryption_cmd.cmdsize;
1376 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001377
Pavel Labathb417eea2018-03-06 13:53:26 +00001378 return result;
1379}
1380
1381void ObjectFileMachO::SanitizeSegmentCommand(segment_command_64 &seg_cmd,
1382 uint32_t cmd_idx) {
1383 if (m_length == 0 || seg_cmd.filesize == 0)
1384 return;
1385
1386 if (seg_cmd.fileoff > m_length) {
1387 // We have a load command that says it extends past the end of the file.
1388 // This is likely a corrupt file. We don't have any way to return an error
1389 // condition here (this method was likely invoked from something like
1390 // ObjectFile::GetSectionList()), so we just null out the section contents,
1391 // and dump a message to stdout. The most common case here is core file
1392 // debugging with a truncated file.
1393 const char *lc_segment_name =
1394 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1395 GetModule()->ReportWarning(
1396 "load command %u %s has a fileoff (0x%" PRIx64
1397 ") that extends beyond the end of the file (0x%" PRIx64
1398 "), ignoring this section",
1399 cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
1400
1401 seg_cmd.fileoff = 0;
1402 seg_cmd.filesize = 0;
1403 }
1404
1405 if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1406 // We have a load command that says it extends past the end of the file.
1407 // This is likely a corrupt file. We don't have any way to return an error
1408 // condition here (this method was likely invoked from something like
1409 // ObjectFile::GetSectionList()), so we just null out the section contents,
1410 // and dump a message to stdout. The most common case here is core file
1411 // debugging with a truncated file.
1412 const char *lc_segment_name =
1413 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1414 GetModule()->ReportWarning(
1415 "load command %u %s has a fileoff + filesize (0x%" PRIx64
1416 ") that extends beyond the end of the file (0x%" PRIx64
1417 "), the segment will be truncated to match",
1418 cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
1419
1420 // Truncate the length
1421 seg_cmd.filesize = m_length - seg_cmd.fileoff;
1422 }
1423}
1424
1425static uint32_t GetSegmentPermissions(const segment_command_64 &seg_cmd) {
1426 uint32_t result = 0;
1427 if (seg_cmd.initprot & VM_PROT_READ)
1428 result |= ePermissionsReadable;
1429 if (seg_cmd.initprot & VM_PROT_WRITE)
1430 result |= ePermissionsWritable;
1431 if (seg_cmd.initprot & VM_PROT_EXECUTE)
1432 result |= ePermissionsExecutable;
1433 return result;
1434}
1435
1436static lldb::SectionType GetSectionType(uint32_t flags,
1437 ConstString section_name) {
1438
1439 if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1440 return eSectionTypeCode;
1441
1442 uint32_t mach_sect_type = flags & SECTION_TYPE;
1443 static ConstString g_sect_name_objc_data("__objc_data");
1444 static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1445 static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1446 static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
1447 static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
1448 static ConstString g_sect_name_objc_const("__objc_const");
1449 static ConstString g_sect_name_objc_classlist("__objc_classlist");
1450 static ConstString g_sect_name_cfstring("__cfstring");
1451
1452 static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
1453 static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1454 static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1455 static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1456 static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1457 static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
1458 static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
Pavel Labatha041d842018-06-01 12:06:45 +00001459 static ConstString g_sect_name_dwarf_debug_names("__debug_names");
Pavel Labathb417eea2018-03-06 13:53:26 +00001460 static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1461 static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1462 static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1463 static ConstString g_sect_name_dwarf_debug_str("__debug_str");
Greg Clayton2550ca12018-05-08 17:19:24 +00001464 static ConstString g_sect_name_dwarf_debug_types("__debug_types");
Pavel Labathb417eea2018-03-06 13:53:26 +00001465 static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1466 static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1467 static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1468 static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1469 static ConstString g_sect_name_eh_frame("__eh_frame");
1470 static ConstString g_sect_name_compact_unwind("__unwind_info");
1471 static ConstString g_sect_name_text("__text");
1472 static ConstString g_sect_name_data("__data");
1473 static ConstString g_sect_name_go_symtab("__gosymtab");
1474
1475 if (section_name == g_sect_name_dwarf_debug_abbrev)
1476 return eSectionTypeDWARFDebugAbbrev;
1477 if (section_name == g_sect_name_dwarf_debug_aranges)
1478 return eSectionTypeDWARFDebugAranges;
1479 if (section_name == g_sect_name_dwarf_debug_frame)
1480 return eSectionTypeDWARFDebugFrame;
1481 if (section_name == g_sect_name_dwarf_debug_info)
1482 return eSectionTypeDWARFDebugInfo;
1483 if (section_name == g_sect_name_dwarf_debug_line)
1484 return eSectionTypeDWARFDebugLine;
1485 if (section_name == g_sect_name_dwarf_debug_loc)
1486 return eSectionTypeDWARFDebugLoc;
1487 if (section_name == g_sect_name_dwarf_debug_macinfo)
1488 return eSectionTypeDWARFDebugMacInfo;
Pavel Labatha041d842018-06-01 12:06:45 +00001489 if (section_name == g_sect_name_dwarf_debug_names)
1490 return eSectionTypeDWARFDebugNames;
Pavel Labathb417eea2018-03-06 13:53:26 +00001491 if (section_name == g_sect_name_dwarf_debug_pubnames)
1492 return eSectionTypeDWARFDebugPubNames;
1493 if (section_name == g_sect_name_dwarf_debug_pubtypes)
1494 return eSectionTypeDWARFDebugPubTypes;
1495 if (section_name == g_sect_name_dwarf_debug_ranges)
1496 return eSectionTypeDWARFDebugRanges;
1497 if (section_name == g_sect_name_dwarf_debug_str)
1498 return eSectionTypeDWARFDebugStr;
Greg Clayton2550ca12018-05-08 17:19:24 +00001499 if (section_name == g_sect_name_dwarf_debug_types)
1500 return eSectionTypeDWARFDebugTypes;
Pavel Labathb417eea2018-03-06 13:53:26 +00001501 if (section_name == g_sect_name_dwarf_apple_names)
1502 return eSectionTypeDWARFAppleNames;
1503 if (section_name == g_sect_name_dwarf_apple_types)
1504 return eSectionTypeDWARFAppleTypes;
1505 if (section_name == g_sect_name_dwarf_apple_namespaces)
1506 return eSectionTypeDWARFAppleNamespaces;
1507 if (section_name == g_sect_name_dwarf_apple_objc)
1508 return eSectionTypeDWARFAppleObjC;
1509 if (section_name == g_sect_name_objc_selrefs)
1510 return eSectionTypeDataCStringPointers;
1511 if (section_name == g_sect_name_objc_msgrefs)
1512 return eSectionTypeDataObjCMessageRefs;
1513 if (section_name == g_sect_name_eh_frame)
1514 return eSectionTypeEHFrame;
1515 if (section_name == g_sect_name_compact_unwind)
1516 return eSectionTypeCompactUnwind;
1517 if (section_name == g_sect_name_cfstring)
1518 return eSectionTypeDataObjCCFStrings;
1519 if (section_name == g_sect_name_go_symtab)
1520 return eSectionTypeGoSymtab;
1521 if (section_name == g_sect_name_objc_data ||
1522 section_name == g_sect_name_objc_classrefs ||
1523 section_name == g_sect_name_objc_superrefs ||
1524 section_name == g_sect_name_objc_const ||
1525 section_name == g_sect_name_objc_classlist) {
1526 return eSectionTypeDataPointers;
1527 }
1528
1529 switch (mach_sect_type) {
1530 // TODO: categorize sections by other flags for regular sections
1531 case S_REGULAR:
1532 if (section_name == g_sect_name_text)
1533 return eSectionTypeCode;
1534 if (section_name == g_sect_name_data)
1535 return eSectionTypeData;
1536 return eSectionTypeOther;
1537 case S_ZEROFILL:
1538 return eSectionTypeZeroFill;
1539 case S_CSTRING_LITERALS: // section with only literal C strings
1540 return eSectionTypeDataCString;
1541 case S_4BYTE_LITERALS: // section with only 4 byte literals
1542 return eSectionTypeData4;
1543 case S_8BYTE_LITERALS: // section with only 8 byte literals
1544 return eSectionTypeData8;
1545 case S_LITERAL_POINTERS: // section with only pointers to literals
1546 return eSectionTypeDataPointers;
1547 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1548 return eSectionTypeDataPointers;
1549 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1550 return eSectionTypeDataPointers;
1551 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1552 // the reserved2 field
1553 return eSectionTypeCode;
1554 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1555 // initialization
1556 return eSectionTypeDataPointers;
1557 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1558 // termination
1559 return eSectionTypeDataPointers;
1560 case S_COALESCED:
1561 return eSectionTypeOther;
1562 case S_GB_ZEROFILL:
1563 return eSectionTypeZeroFill;
1564 case S_INTERPOSING: // section with only pairs of function pointers for
1565 // interposing
1566 return eSectionTypeCode;
1567 case S_16BYTE_LITERALS: // section with only 16 byte literals
1568 return eSectionTypeData16;
1569 case S_DTRACE_DOF:
1570 return eSectionTypeDebug;
1571 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1572 return eSectionTypeDataPointers;
1573 default:
1574 return eSectionTypeOther;
1575 }
1576}
1577
1578struct ObjectFileMachO::SegmentParsingContext {
1579 const EncryptedFileRanges EncryptedRanges;
1580 lldb_private::SectionList &UnifiedList;
1581 uint32_t NextSegmentIdx = 0;
1582 uint32_t NextSectionIdx = 0;
1583 bool FileAddressesChanged = false;
1584
1585 SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
1586 lldb_private::SectionList &UnifiedList)
1587 : EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
1588};
1589
1590void ObjectFileMachO::ProcessSegmentCommand(const load_command &load_cmd_,
1591 lldb::offset_t offset,
1592 uint32_t cmd_idx,
1593 SegmentParsingContext &context) {
1594 segment_command_64 load_cmd;
1595 memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1596
1597 if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1598 return;
1599
1600 ModuleSP module_sp = GetModule();
1601 const bool is_core = GetType() == eTypeCoreFile;
1602 const bool is_dsym = (m_header.filetype == MH_DSYM);
1603 bool add_section = true;
1604 bool add_to_unified = true;
1605 ConstString const_segname(
1606 load_cmd.segname,
1607 std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname)));
1608
1609 SectionSP unified_section_sp(
1610 context.UnifiedList.FindSectionByName(const_segname));
1611 if (is_dsym && unified_section_sp) {
1612 if (const_segname == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001613 // We need to keep the __LINKEDIT segment private to this object file
1614 // only
Pavel Labathb417eea2018-03-06 13:53:26 +00001615 add_to_unified = false;
1616 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001617 // This is the dSYM file and this section has already been created by the
1618 // object file, no need to create it.
Pavel Labathb417eea2018-03-06 13:53:26 +00001619 add_section = false;
1620 }
1621 }
1622 load_cmd.vmaddr = m_data.GetAddress(&offset);
1623 load_cmd.vmsize = m_data.GetAddress(&offset);
1624 load_cmd.fileoff = m_data.GetAddress(&offset);
1625 load_cmd.filesize = m_data.GetAddress(&offset);
1626 if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1627 return;
1628
1629 SanitizeSegmentCommand(load_cmd, cmd_idx);
1630
1631 const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1632 const bool segment_is_encrypted =
1633 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1634
Adrian Prantl05097242018-04-30 16:49:04 +00001635 // Keep a list of mach segments around in case we need to get at data that
1636 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001637 m_mach_segments.push_back(load_cmd);
1638
Adrian Prantl05097242018-04-30 16:49:04 +00001639 // Use a segment ID of the segment index shifted left by 8 so they never
1640 // conflict with any of the sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001641 SectionSP segment_sp;
1642 if (add_section && (const_segname || is_core)) {
1643 segment_sp.reset(new Section(
1644 module_sp, // Module to which this section belongs
1645 this, // Object file to which this sections belongs
1646 ++context.NextSegmentIdx
1647 << 8, // Section ID is the 1 based segment index
Adrian Prantl05097242018-04-30 16:49:04 +00001648 // shifted right by 8 bits as not to collide with any of the 256
1649 // section IDs that are possible
Pavel Labathb417eea2018-03-06 13:53:26 +00001650 const_segname, // Name of this section
1651 eSectionTypeContainer, // This section is a container of other
1652 // sections.
1653 load_cmd.vmaddr, // File VM address == addresses as they are
1654 // found in the object file
1655 load_cmd.vmsize, // VM size in bytes of this section
1656 load_cmd.fileoff, // Offset to the data for this section in
1657 // the file
1658 load_cmd.filesize, // Size in bytes of this section as found
1659 // in the file
1660 0, // Segments have no alignment information
1661 load_cmd.flags)); // Flags for this section
1662
1663 segment_sp->SetIsEncrypted(segment_is_encrypted);
1664 m_sections_ap->AddSection(segment_sp);
1665 segment_sp->SetPermissions(segment_permissions);
1666 if (add_to_unified)
1667 context.UnifiedList.AddSection(segment_sp);
1668 } else if (unified_section_sp) {
1669 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1670 // Check to see if the module was read from memory?
1671 if (module_sp->GetObjectFile()->GetHeaderAddress().IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001672 // We have a module that is in memory and needs to have its file
1673 // address adjusted. We need to do this because when we load a file
1674 // from memory, its addresses will be slid already, yet the addresses
1675 // in the new symbol file will still be unslid. Since everything is
1676 // stored as section offset, this shouldn't cause any problems.
Pavel Labathb417eea2018-03-06 13:53:26 +00001677
Adrian Prantl05097242018-04-30 16:49:04 +00001678 // Make sure we've parsed the symbol table from the ObjectFile before
1679 // we go around changing its Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001680 module_sp->GetObjectFile()->GetSymtab();
Adrian Prantl05097242018-04-30 16:49:04 +00001681 // eh_frame would present the same problems but we parse that on a per-
1682 // function basis as-needed so it's more difficult to remove its use of
1683 // the Sections. Realistically, the environments where this code path
1684 // will be taken will not have eh_frame sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001685
1686 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1687
Adrian Prantl05097242018-04-30 16:49:04 +00001688 // Notify the module that the section addresses have been changed once
1689 // we're done so any file-address caches can be updated.
Pavel Labathb417eea2018-03-06 13:53:26 +00001690 context.FileAddressesChanged = true;
1691 }
1692 }
1693 m_sections_ap->AddSection(unified_section_sp);
1694 }
1695
1696 struct section_64 sect64;
1697 ::memset(&sect64, 0, sizeof(sect64));
Adrian Prantl05097242018-04-30 16:49:04 +00001698 // Push a section into our mach sections for the section at index zero
1699 // (NO_SECT) if we don't have any mach sections yet...
Pavel Labathb417eea2018-03-06 13:53:26 +00001700 if (m_mach_sections.empty())
1701 m_mach_sections.push_back(sect64);
1702 uint32_t segment_sect_idx;
1703 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1704
1705 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1706 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1707 ++segment_sect_idx) {
1708 if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1709 sizeof(sect64.sectname)) == NULL)
1710 break;
1711 if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1712 sizeof(sect64.segname)) == NULL)
1713 break;
1714 sect64.addr = m_data.GetAddress(&offset);
1715 sect64.size = m_data.GetAddress(&offset);
1716
1717 if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
1718 break;
1719
Adrian Prantl05097242018-04-30 16:49:04 +00001720 // Keep a list of mach sections around in case we need to get at data that
1721 // isn't stored in the abstracted Sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001722 m_mach_sections.push_back(sect64);
1723
1724 if (add_section) {
1725 ConstString section_name(
1726 sect64.sectname,
1727 std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname)));
1728 if (!const_segname) {
Adrian Prantl05097242018-04-30 16:49:04 +00001729 // We have a segment with no name so we need to conjure up segments
1730 // that correspond to the section's segname if there isn't already such
1731 // a section. If there is such a section, we resize the section so that
1732 // it spans all sections. We also mark these sections as fake so
1733 // address matches don't hit if they land in the gaps between the child
1734 // sections.
Pavel Labathb417eea2018-03-06 13:53:26 +00001735 const_segname.SetTrimmedCStringWithLength(sect64.segname,
1736 sizeof(sect64.segname));
1737 segment_sp = context.UnifiedList.FindSectionByName(const_segname);
1738 if (segment_sp.get()) {
1739 Section *segment = segment_sp.get();
1740 // Grow the section size as needed.
1741 const lldb::addr_t sect64_min_addr = sect64.addr;
1742 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1743 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1744 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1745 const lldb::addr_t curr_seg_max_addr =
1746 curr_seg_min_addr + curr_seg_byte_size;
1747 if (sect64_min_addr >= curr_seg_min_addr) {
1748 const lldb::addr_t new_seg_byte_size =
1749 sect64_max_addr - curr_seg_min_addr;
1750 // Only grow the section size if needed
1751 if (new_seg_byte_size > curr_seg_byte_size)
1752 segment->SetByteSize(new_seg_byte_size);
1753 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001754 // We need to change the base address of the segment and adjust the
1755 // child section offsets for all existing children.
Pavel Labathb417eea2018-03-06 13:53:26 +00001756 const lldb::addr_t slide_amount =
1757 sect64_min_addr - curr_seg_min_addr;
1758 segment->Slide(slide_amount, false);
1759 segment->GetChildren().Slide(-slide_amount, false);
1760 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1761 }
1762
1763 // Grow the section size as needed.
1764 if (sect64.offset) {
1765 const lldb::addr_t segment_min_file_offset =
1766 segment->GetFileOffset();
1767 const lldb::addr_t segment_max_file_offset =
1768 segment_min_file_offset + segment->GetFileSize();
1769
1770 const lldb::addr_t section_min_file_offset = sect64.offset;
1771 const lldb::addr_t section_max_file_offset =
1772 section_min_file_offset + sect64.size;
1773 const lldb::addr_t new_file_offset =
1774 std::min(section_min_file_offset, segment_min_file_offset);
1775 const lldb::addr_t new_file_size =
1776 std::max(section_max_file_offset, segment_max_file_offset) -
1777 new_file_offset;
1778 segment->SetFileOffset(new_file_offset);
1779 segment->SetFileSize(new_file_size);
1780 }
1781 } else {
1782 // Create a fake section for the section's named segment
1783 segment_sp.reset(new Section(
1784 segment_sp, // Parent section
1785 module_sp, // Module to which this section belongs
1786 this, // Object file to which this section belongs
1787 ++context.NextSegmentIdx
1788 << 8, // Section ID is the 1 based segment index
1789 // shifted right by 8 bits as not to
1790 // collide with any of the 256 section IDs
1791 // that are possible
1792 const_segname, // Name of this section
1793 eSectionTypeContainer, // This section is a container of
1794 // other sections.
1795 sect64.addr, // File VM address == addresses as they are
1796 // found in the object file
1797 sect64.size, // VM size in bytes of this section
1798 sect64.offset, // Offset to the data for this section in
1799 // the file
1800 sect64.offset ? sect64.size : 0, // Size in bytes of
1801 // this section as
1802 // found in the file
1803 sect64.align,
1804 load_cmd.flags)); // Flags for this section
1805 segment_sp->SetIsFake(true);
1806 segment_sp->SetPermissions(segment_permissions);
1807 m_sections_ap->AddSection(segment_sp);
1808 if (add_to_unified)
1809 context.UnifiedList.AddSection(segment_sp);
1810 segment_sp->SetIsEncrypted(segment_is_encrypted);
1811 }
1812 }
1813 assert(segment_sp.get());
1814
1815 lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1816
1817 SectionSP section_sp(new Section(
1818 segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1819 sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1820 sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1821 sect64.flags));
1822 // Set the section to be encrypted to match the segment
1823
1824 bool section_is_encrypted = false;
1825 if (!segment_is_encrypted && load_cmd.filesize != 0)
1826 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1827 sect64.offset) != NULL;
1828
1829 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1830 section_sp->SetPermissions(segment_permissions);
1831 segment_sp->GetChildren().AddSection(section_sp);
1832
1833 if (segment_sp->IsFake()) {
1834 segment_sp.reset();
1835 const_segname.Clear();
1836 }
1837 }
1838 }
1839 if (segment_sp && is_dsym) {
1840 if (first_segment_sectID <= context.NextSectionIdx) {
1841 lldb::user_id_t sect_uid;
1842 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1843 ++sect_uid) {
1844 SectionSP curr_section_sp(
1845 segment_sp->GetChildren().FindSectionByID(sect_uid));
1846 SectionSP next_section_sp;
1847 if (sect_uid + 1 <= context.NextSectionIdx)
1848 next_section_sp =
1849 segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1850
1851 if (curr_section_sp.get()) {
1852 if (curr_section_sp->GetByteSize() == 0) {
1853 if (next_section_sp.get() != NULL)
1854 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1855 curr_section_sp->GetFileAddress());
1856 else
1857 curr_section_sp->SetByteSize(load_cmd.vmsize);
1858 }
1859 }
1860 }
1861 }
1862 }
1863}
1864
1865void ObjectFileMachO::ProcessDysymtabCommand(const load_command &load_cmd,
1866 lldb::offset_t offset) {
1867 m_dysymtab.cmd = load_cmd.cmd;
1868 m_dysymtab.cmdsize = load_cmd.cmdsize;
1869 m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1870 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1871}
1872
1873void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1874 if (m_sections_ap)
1875 return;
1876
1877 m_sections_ap.reset(new SectionList());
1878
1879 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1880 // bool dump_sections = false;
1881 ModuleSP module_sp(GetModule());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001882
Pavel Labathf90054d2018-03-03 22:07:47 +00001883 offset = MachHeaderSizeFromMagic(m_header.magic);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001884
Pavel Labathb417eea2018-03-06 13:53:26 +00001885 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1886 struct load_command load_cmd;
1887 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Pavel Labathf90054d2018-03-03 22:07:47 +00001888 const lldb::offset_t load_cmd_offset = offset;
1889 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
1890 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001891
Pavel Labathb417eea2018-03-06 13:53:26 +00001892 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1893 ProcessSegmentCommand(load_cmd, offset, i, context);
1894 else if (load_cmd.cmd == LC_DYSYMTAB)
1895 ProcessDysymtabCommand(load_cmd, offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001896
Pavel Labathf90054d2018-03-03 22:07:47 +00001897 offset = load_cmd_offset + load_cmd.cmdsize;
1898 }
1899
Pavel Labathb417eea2018-03-06 13:53:26 +00001900 if (context.FileAddressesChanged && module_sp)
Pavel Labathf90054d2018-03-03 22:07:47 +00001901 module_sp->SectionFileAddressesChanged();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001902}
1903
1904class MachSymtabSectionInfo {
1905public:
1906 MachSymtabSectionInfo(SectionList *section_list)
1907 : m_section_list(section_list), m_section_infos() {
Adrian Prantl05097242018-04-30 16:49:04 +00001908 // Get the number of sections down to a depth of 1 to include all segments
1909 // and their sections, but no other sections that may be added for debug
1910 // map or
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911 m_section_infos.resize(section_list->GetNumSections(1));
1912 }
1913
1914 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1915 if (n_sect == 0)
1916 return SectionSP();
1917 if (n_sect < m_section_infos.size()) {
1918 if (!m_section_infos[n_sect].section_sp) {
1919 SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1920 m_section_infos[n_sect].section_sp = section_sp;
1921 if (section_sp) {
1922 m_section_infos[n_sect].vm_range.SetBaseAddress(
1923 section_sp->GetFileAddress());
1924 m_section_infos[n_sect].vm_range.SetByteSize(
1925 section_sp->GetByteSize());
1926 } else {
1927 Host::SystemLog(Host::eSystemLogError,
1928 "error: unable to find section for section %u\n",
1929 n_sect);
1930 }
1931 }
1932 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1933 // Symbol is in section.
1934 return m_section_infos[n_sect].section_sp;
1935 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1936 m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1937 file_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00001938 // Symbol is in section with zero size, but has the same start address
1939 // as the section. This can happen with linker symbols (symbols that
1940 // start with the letter 'l' or 'L'.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941 return m_section_infos[n_sect].section_sp;
1942 }
1943 }
1944 return m_section_list->FindSectionContainingFileAddress(file_addr);
1945 }
1946
1947protected:
1948 struct SectionInfo {
1949 SectionInfo() : vm_range(), section_sp() {}
1950
1951 VMRange vm_range;
1952 SectionSP section_sp;
1953 };
1954 SectionList *m_section_list;
1955 std::vector<SectionInfo> m_section_infos;
1956};
1957
1958struct TrieEntry {
1959 TrieEntry()
1960 : name(), address(LLDB_INVALID_ADDRESS), flags(0), other(0),
1961 import_name() {}
1962
1963 void Clear() {
1964 name.Clear();
1965 address = LLDB_INVALID_ADDRESS;
1966 flags = 0;
1967 other = 0;
1968 import_name.Clear();
1969 }
1970
1971 void Dump() const {
1972 printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
1973 static_cast<unsigned long long>(address),
1974 static_cast<unsigned long long>(flags),
1975 static_cast<unsigned long long>(other), name.GetCString());
1976 if (import_name)
1977 printf(" -> \"%s\"\n", import_name.GetCString());
1978 else
1979 printf("\n");
1980 }
1981 ConstString name;
1982 uint64_t address;
1983 uint64_t flags;
1984 uint64_t other;
1985 ConstString import_name;
1986};
1987
1988struct TrieEntryWithOffset {
1989 lldb::offset_t nodeOffset;
1990 TrieEntry entry;
1991
1992 TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
1993
1994 void Dump(uint32_t idx) const {
1995 printf("[%3u] 0x%16.16llx: ", idx,
1996 static_cast<unsigned long long>(nodeOffset));
1997 entry.Dump();
1998 }
1999
2000 bool operator<(const TrieEntryWithOffset &other) const {
2001 return (nodeOffset < other.nodeOffset);
2002 }
2003};
2004
2005static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
2006 const bool is_arm,
2007 std::vector<llvm::StringRef> &nameSlices,
2008 std::set<lldb::addr_t> &resolver_addresses,
2009 std::vector<TrieEntryWithOffset> &output) {
2010 if (!data.ValidOffset(offset))
Greg Clayton8f265f72015-10-28 20:49:34 +00002011 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002012
2013 const uint64_t terminalSize = data.GetULEB128(&offset);
2014 lldb::offset_t children_offset = offset + terminalSize;
2015 if (terminalSize != 0) {
2016 TrieEntryWithOffset e(offset);
2017 e.entry.flags = data.GetULEB128(&offset);
2018 const char *import_name = NULL;
2019 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2020 e.entry.address = 0;
2021 e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2022 import_name = data.GetCStr(&offset);
2023 } else {
2024 e.entry.address = data.GetULEB128(&offset);
2025 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2026 e.entry.other = data.GetULEB128(&offset);
2027 uint64_t resolver_addr = e.entry.other;
2028 if (is_arm)
2029 resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2030 resolver_addresses.insert(resolver_addr);
2031 } else
2032 e.entry.other = 0;
2033 }
2034 // Only add symbols that are reexport symbols with a valid import name
2035 if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name &&
2036 import_name[0]) {
2037 std::string name;
2038 if (!nameSlices.empty()) {
2039 for (auto name_slice : nameSlices)
2040 name.append(name_slice.data(), name_slice.size());
2041 }
2042 if (name.size() > 1) {
2043 // Skip the leading '_'
2044 e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2045 }
2046 if (import_name) {
2047 // Skip the leading '_'
2048 e.entry.import_name.SetCString(import_name + 1);
2049 }
2050 output.push_back(e);
2051 }
2052 }
2053
2054 const uint8_t childrenCount = data.GetU8(&children_offset);
2055 for (uint8_t i = 0; i < childrenCount; ++i) {
2056 const char *cstr = data.GetCStr(&children_offset);
2057 if (cstr)
2058 nameSlices.push_back(llvm::StringRef(cstr));
2059 else
2060 return false; // Corrupt data
2061 lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2062 if (childNodeOffset) {
2063 if (!ParseTrieEntries(data, childNodeOffset, is_arm, nameSlices,
2064 resolver_addresses, output)) {
2065 return false;
2066 }
2067 }
2068 nameSlices.pop_back();
2069 }
2070 return true;
Greg Clayton9191db42013-10-21 18:40:51 +00002071}
2072
Jason Molenda649a6072015-11-10 05:21:54 +00002073// Read the UUID out of a dyld_shared_cache file on-disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
2075 const ByteOrder byte_order,
2076 const uint32_t addr_byte_size) {
2077 UUID dsc_uuid;
Pavel Labath50251fc2017-12-21 10:54:30 +00002078 DataBufferSP DscData = MapFileData(
2079 dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002080 if (!DscData)
2081 return dsc_uuid;
2082 DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
Jason Molenda649a6072015-11-10 05:21:54 +00002083
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002084 char version_str[7];
2085 lldb::offset_t offset = 0;
2086 memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
2087 version_str[6] = '\0';
2088 if (strcmp(version_str, "dyld_v") == 0) {
2089 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
2090 uint8_t uuid_bytes[sizeof(uuid_t)];
2091 memcpy(uuid_bytes, dsc_header_data.GetData(&offset, sizeof(uuid_t)),
2092 sizeof(uuid_t));
2093 dsc_uuid.SetBytes(uuid_bytes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094 }
Jason Molendafd443e92018-02-07 01:28:29 +00002095 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2096 if (log && dsc_uuid.IsValid()) {
2097 log->Printf("Shared cache %s has UUID %s", dyld_shared_cache.GetPath().c_str(),
2098 dsc_uuid.GetAsString().c_str());
2099 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100 return dsc_uuid;
Jason Molenda649a6072015-11-10 05:21:54 +00002101}
2102
Kate Stoneb9c1b512016-09-06 20:57:50 +00002103size_t ObjectFileMachO::ParseSymtab() {
Pavel Labathf9d16472017-05-15 13:02:37 +00002104 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2105 Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 m_file.GetFilename().AsCString(""));
2107 ModuleSP module_sp(GetModule());
2108 if (!module_sp)
2109 return 0;
2110
2111 struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2112 struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2113 struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2114 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2115 FunctionStarts function_starts;
2116 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2117 uint32_t i;
2118 FileSpecList dylib_files;
2119 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2120 static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2121 static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2122 static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2123
2124 for (i = 0; i < m_header.ncmds; ++i) {
2125 const lldb::offset_t cmd_offset = offset;
2126 // Read in the load command and load command size
2127 struct load_command lc;
2128 if (m_data.GetU32(&offset, &lc, 2) == NULL)
2129 break;
2130 // Watch for the symbol table load command
2131 switch (lc.cmd) {
2132 case LC_SYMTAB:
2133 symtab_load_command.cmd = lc.cmd;
2134 symtab_load_command.cmdsize = lc.cmdsize;
2135 // Read in the rest of the symtab load command
2136 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2137 0) // fill in symoff, nsyms, stroff, strsize fields
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002138 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 if (symtab_load_command.symoff == 0) {
2140 if (log)
2141 module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2142 return 0;
2143 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002144
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145 if (symtab_load_command.stroff == 0) {
2146 if (log)
2147 module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2148 return 0;
2149 }
Greg Clayton77ccca72011-12-30 00:32:24 +00002150
Kate Stoneb9c1b512016-09-06 20:57:50 +00002151 if (symtab_load_command.nsyms == 0) {
2152 if (log)
2153 module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
2154 return 0;
2155 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002156
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157 if (symtab_load_command.strsize == 0) {
2158 if (log)
2159 module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2160 return 0;
2161 }
2162 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002163
Kate Stoneb9c1b512016-09-06 20:57:50 +00002164 case LC_DYLD_INFO:
2165 case LC_DYLD_INFO_ONLY:
2166 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2167 dyld_info.cmd = lc.cmd;
2168 dyld_info.cmdsize = lc.cmdsize;
2169 } else {
2170 memset(&dyld_info, 0, sizeof(dyld_info));
2171 }
2172 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002173
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 case LC_LOAD_DYLIB:
2175 case LC_LOAD_WEAK_DYLIB:
2176 case LC_REEXPORT_DYLIB:
2177 case LC_LOADFVMLIB:
2178 case LC_LOAD_UPWARD_DYLIB: {
2179 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2180 const char *path = m_data.PeekCStr(name_offset);
2181 if (path) {
2182 FileSpec file_spec(path, false);
2183 // Strip the path if there is @rpath, @executable, etc so we just use
2184 // the basename
2185 if (path[0] == '@')
2186 file_spec.GetDirectory().Clear();
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002187
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188 if (lc.cmd == LC_REEXPORT_DYLIB) {
2189 m_reexported_dylibs.AppendIfUnique(file_spec);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002190 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002191
2192 dylib_files.Append(file_spec);
2193 }
2194 } break;
2195
2196 case LC_FUNCTION_STARTS:
2197 function_starts_load_command.cmd = lc.cmd;
2198 function_starts_load_command.cmdsize = lc.cmdsize;
2199 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2200 NULL) // fill in symoff, nsyms, stroff, strsize fields
2201 memset(&function_starts_load_command, 0,
2202 sizeof(function_starts_load_command));
2203 break;
2204
2205 default:
2206 break;
2207 }
2208 offset = cmd_offset + lc.cmdsize;
2209 }
2210
2211 if (symtab_load_command.cmd) {
2212 Symtab *symtab = m_symtab_ap.get();
2213 SectionList *section_list = GetSectionList();
2214 if (section_list == NULL)
2215 return 0;
2216
2217 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2218 const ByteOrder byte_order = m_data.GetByteOrder();
2219 bool bit_width_32 = addr_byte_size == 4;
2220 const size_t nlist_byte_size =
2221 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2222
2223 DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size);
2224 DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size);
2225 DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size);
2226 DataExtractor indirect_symbol_index_data(NULL, 0, byte_order,
2227 addr_byte_size);
2228 DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size);
2229
2230 const addr_t nlist_data_byte_size =
2231 symtab_load_command.nsyms * nlist_byte_size;
2232 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2233 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2234
2235 ProcessSP process_sp(m_process_wp.lock());
2236 Process *process = process_sp.get();
2237
2238 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2239
2240 if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2241 Target &target = process->GetTarget();
2242
2243 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2244
2245 SectionSP linkedit_section_sp(
2246 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2247 // Reading mach file from memory in a process or core file...
2248
2249 if (linkedit_section_sp) {
2250 addr_t linkedit_load_addr =
2251 linkedit_section_sp->GetLoadBaseAddress(&target);
2252 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2253 // We might be trying to access the symbol table before the
Adrian Prantl05097242018-04-30 16:49:04 +00002254 // __LINKEDIT's load address has been set in the target. We can't
2255 // fail to read the symbol table, so calculate the right address
2256 // manually
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2258 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2259 }
2260
2261 const addr_t linkedit_file_offset =
2262 linkedit_section_sp->GetFileOffset();
2263 const addr_t symoff_addr = linkedit_load_addr +
2264 symtab_load_command.symoff -
2265 linkedit_file_offset;
2266 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2267 linkedit_file_offset;
2268
2269 bool data_was_read = false;
2270
2271#if defined(__APPLE__) && \
2272 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2273 if (m_header.flags & 0x80000000u &&
2274 process->GetAddressByteSize() == sizeof(void *)) {
2275 // This mach-o memory file is in the dyld shared cache. If this
2276 // program is not remote and this is iOS, then this process will
Adrian Prantl05097242018-04-30 16:49:04 +00002277 // share the same shared cache as the process we are debugging and we
2278 // can read the entire __LINKEDIT from the address space in this
Kate Stoneb9c1b512016-09-06 20:57:50 +00002279 // process. This is a needed optimization that is used for local iOS
2280 // debugging only since all shared libraries in the shared cache do
2281 // not have corresponding files that exist in the file system of the
2282 // device. They have been combined into a single file. This means we
2283 // always have to load these files from memory. All of the symbol and
2284 // string tables from all of the __LINKEDIT sections from the shared
2285 // libraries in the shared cache have been merged into a single large
2286 // symbol and string table. Reading all of this symbol and string
Adrian Prantl05097242018-04-30 16:49:04 +00002287 // table data across can slow down debug launch times, so we optimize
2288 // this by reading the memory for the __LINKEDIT section from this
2289 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290
Jason Molenda07580ff2018-05-04 00:59:37 +00002291 UUID lldb_shared_cache;
2292 addr_t lldb_shared_cache_addr;
2293 GetLLDBSharedCacheUUID (lldb_shared_cache_addr, lldb_shared_cache);
2294 UUID process_shared_cache;
2295 addr_t process_shared_cache_addr;
2296 GetProcessSharedCacheUUID(process, process_shared_cache_addr, process_shared_cache);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297 bool use_lldb_cache = true;
2298 if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
Jason Molenda07580ff2018-05-04 00:59:37 +00002299 (lldb_shared_cache != process_shared_cache
2300 || process_shared_cache_addr != lldb_shared_cache_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301 use_lldb_cache = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302 }
2303
2304 PlatformSP platform_sp(target.GetPlatform());
2305 if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2306 data_was_read = true;
2307 nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2308 eByteOrderLittle);
2309 strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2310 eByteOrderLittle);
2311 if (function_starts_load_command.cmd) {
2312 const addr_t func_start_addr =
2313 linkedit_load_addr + function_starts_load_command.dataoff -
2314 linkedit_file_offset;
2315 function_starts_data.SetData(
2316 (void *)func_start_addr,
2317 function_starts_load_command.datasize, eByteOrderLittle);
2318 }
2319 }
2320 }
2321#endif
2322
2323 if (!data_was_read) {
2324 // Always load dyld - the dynamic linker - from memory if we didn't
Adrian Prantl05097242018-04-30 16:49:04 +00002325 // find a binary anywhere else. lldb will not register
2326 // dylib/framework/bundle loads/unloads if we don't have the dyld
2327 // symbols, we force dyld to load from memory despite the user's
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328 // target.memory-module-load-level setting.
2329 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2330 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2331 DataBufferSP nlist_data_sp(
2332 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2333 if (nlist_data_sp)
2334 nlist_data.SetData(nlist_data_sp, 0,
2335 nlist_data_sp->GetByteSize());
2336 // Load strings individually from memory when loading from memory
Adrian Prantl05097242018-04-30 16:49:04 +00002337 // since shared cache string tables contain strings for all symbols
2338 // from all shared cached libraries DataBufferSP strtab_data_sp
2339 // (ReadMemory (process_sp, strtab_addr,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340 // strtab_data_byte_size));
2341 // if (strtab_data_sp)
2342 // strtab_data.SetData (strtab_data_sp, 0,
2343 // strtab_data_sp->GetByteSize());
2344 if (m_dysymtab.nindirectsyms != 0) {
2345 const addr_t indirect_syms_addr = linkedit_load_addr +
2346 m_dysymtab.indirectsymoff -
2347 linkedit_file_offset;
2348 DataBufferSP indirect_syms_data_sp(
2349 ReadMemory(process_sp, indirect_syms_addr,
2350 m_dysymtab.nindirectsyms * 4));
2351 if (indirect_syms_data_sp)
2352 indirect_symbol_index_data.SetData(
2353 indirect_syms_data_sp, 0,
2354 indirect_syms_data_sp->GetByteSize());
2355 }
2356 } else if (memory_module_load_level >=
2357 eMemoryModuleLoadLevelPartial) {
2358 if (function_starts_load_command.cmd) {
2359 const addr_t func_start_addr =
2360 linkedit_load_addr + function_starts_load_command.dataoff -
2361 linkedit_file_offset;
2362 DataBufferSP func_start_data_sp(
2363 ReadMemory(process_sp, func_start_addr,
2364 function_starts_load_command.datasize));
2365 if (func_start_data_sp)
2366 function_starts_data.SetData(func_start_data_sp, 0,
2367 func_start_data_sp->GetByteSize());
2368 }
2369 }
2370 }
2371 }
2372 } else {
2373 nlist_data.SetData(m_data, symtab_load_command.symoff,
2374 nlist_data_byte_size);
2375 strtab_data.SetData(m_data, symtab_load_command.stroff,
2376 strtab_data_byte_size);
2377
2378 if (dyld_info.export_size > 0) {
2379 dyld_trie_data.SetData(m_data, dyld_info.export_off,
2380 dyld_info.export_size);
2381 }
2382
2383 if (m_dysymtab.nindirectsyms != 0) {
2384 indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2385 m_dysymtab.nindirectsyms * 4);
2386 }
2387 if (function_starts_load_command.cmd) {
2388 function_starts_data.SetData(m_data,
2389 function_starts_load_command.dataoff,
2390 function_starts_load_command.datasize);
2391 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002392 }
2393
Kate Stoneb9c1b512016-09-06 20:57:50 +00002394 if (nlist_data.GetByteSize() == 0 &&
2395 memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2396 if (log)
2397 module_sp->LogMessage(log, "failed to read nlist data");
2398 return 0;
2399 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002400
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2402 if (!have_strtab_data) {
2403 if (process) {
2404 if (strtab_addr == LLDB_INVALID_ADDRESS) {
2405 if (log)
2406 module_sp->LogMessage(log, "failed to locate the strtab in memory");
2407 return 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002408 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002409 } else {
2410 if (log)
2411 module_sp->LogMessage(log, "failed to read strtab data");
2412 return 0;
2413 }
2414 }
Greg Clayton9191db42013-10-21 18:40:51 +00002415
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2417 const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2418 const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2419 const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2420 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2421 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2422 SectionSP text_section_sp(
2423 section_list->FindSectionByName(g_segment_name_TEXT));
2424 SectionSP data_section_sp(
2425 section_list->FindSectionByName(g_segment_name_DATA));
2426 SectionSP data_dirty_section_sp(
2427 section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2428 SectionSP data_const_section_sp(
2429 section_list->FindSectionByName(g_segment_name_DATA_CONST));
2430 SectionSP objc_section_sp(
2431 section_list->FindSectionByName(g_segment_name_OBJC));
2432 SectionSP eh_frame_section_sp;
2433 if (text_section_sp.get())
2434 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2435 g_section_name_eh_frame);
2436 else
2437 eh_frame_section_sp =
2438 section_list->FindSectionByName(g_section_name_eh_frame);
Greg Clayton77ccca72011-12-30 00:32:24 +00002439
Kate Stoneb9c1b512016-09-06 20:57:50 +00002440 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
Greg Clayton86eac942013-08-13 21:32:34 +00002441
Kate Stoneb9c1b512016-09-06 20:57:50 +00002442 // lldb works best if it knows the start address of all functions in a
Adrian Prantl05097242018-04-30 16:49:04 +00002443 // module. Linker symbols or debug info are normally the best source of
2444 // information for start addr / size but they may be stripped in a released
2445 // binary. Two additional sources of information exist in Mach-O binaries:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002446 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2447 // function's start address in the
2448 // binary, relative to the text section.
2449 // eh_frame - the eh_frame FDEs have the start addr & size of
2450 // each function
2451 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2452 // all modern binaries.
2453 // Binaries built to run on older releases may need to use eh_frame
2454 // information.
Greg Clayton4c82d422012-05-18 23:20:01 +00002455
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456 if (text_section_sp && function_starts_data.GetByteSize()) {
2457 FunctionStarts::Entry function_start_entry;
2458 function_start_entry.data = false;
2459 lldb::offset_t function_start_offset = 0;
2460 function_start_entry.addr = text_section_sp->GetFileAddress();
2461 uint64_t delta;
2462 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2463 0) {
2464 // Now append the current entry
2465 function_start_entry.addr += delta;
2466 function_starts.Append(function_start_entry);
2467 }
2468 } else {
2469 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
Adrian Prantl05097242018-04-30 16:49:04 +00002470 // load command claiming an eh_frame but it doesn't actually have the
2471 // eh_frame content. And if we have a dSYM, we don't need to do any of
2472 // this fill-in-the-missing-symbols works anyway - the debug info should
2473 // give us all the functions in the module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2475 m_type != eTypeDebugInfo) {
2476 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
Pavel Labath3f2a0812017-06-28 09:09:19 +00002477 DWARFCallFrameInfo::EH);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2479 eh_frame.GetFunctionAddressAndSizeVector(functions);
2480 addr_t text_base_addr = text_section_sp->GetFileAddress();
2481 size_t count = functions.GetSize();
2482 for (size_t i = 0; i < count; ++i) {
2483 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2484 functions.GetEntryAtIndex(i);
2485 if (func) {
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002486 FunctionStarts::Entry function_start_entry;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002487 function_start_entry.addr = func->base - text_base_addr;
2488 function_starts.Append(function_start_entry);
2489 }
Jason Molendad63d3c72013-04-16 00:18:44 +00002490 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 }
2492 }
2493
2494 const size_t function_starts_count = function_starts.GetSize();
2495
2496 // For user process binaries (executables, dylibs, frameworks, bundles), if
Adrian Prantl05097242018-04-30 16:49:04 +00002497 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2498 // going to assume the binary has been stripped. Don't allow assembly
2499 // language instruction emulation because we don't know proper function
2500 // start boundaries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002501 //
2502 // For all other types of binaries (kernels, stand-alone bare board
Adrian Prantl05097242018-04-30 16:49:04 +00002503 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2504 // sections - we should not make any assumptions about them based on that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2506 m_allow_assembly_emulation_unwind_plans = false;
2507 Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2508 LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2509
2510 if (unwind_or_symbol_log)
2511 module_sp->LogMessage(
2512 unwind_or_symbol_log,
2513 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2514 }
2515
2516 const user_id_t TEXT_eh_frame_sectID =
2517 eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2518 : static_cast<user_id_t>(NO_SECT);
2519
2520 lldb::offset_t nlist_data_offset = 0;
2521
2522 uint32_t N_SO_index = UINT32_MAX;
2523
2524 MachSymtabSectionInfo section_info(section_list);
2525 std::vector<uint32_t> N_FUN_indexes;
2526 std::vector<uint32_t> N_NSYM_indexes;
2527 std::vector<uint32_t> N_INCL_indexes;
2528 std::vector<uint32_t> N_BRAC_indexes;
2529 std::vector<uint32_t> N_COMM_indexes;
2530 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2531 typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2532 typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2533 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2534 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2535 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00002536 // Any symbols that get merged into another will get an entry in this map
2537 // so we know
Kate Stoneb9c1b512016-09-06 20:57:50 +00002538 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2539 uint32_t nlist_idx = 0;
2540 Symbol *symbol_ptr = NULL;
2541
2542 uint32_t sym_idx = 0;
2543 Symbol *sym = NULL;
2544 size_t num_syms = 0;
2545 std::string memory_symbol_name;
2546 uint32_t unmapped_local_symbols_found = 0;
2547
2548 std::vector<TrieEntryWithOffset> trie_entries;
2549 std::set<lldb::addr_t> resolver_addresses;
2550
2551 if (dyld_trie_data.GetByteSize() > 0) {
2552 std::vector<llvm::StringRef> nameSlices;
2553 ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2554 resolver_addresses, trie_entries);
2555
2556 ConstString text_segment_name("__TEXT");
2557 SectionSP text_segment_sp =
2558 GetSectionList()->FindSectionByName(text_segment_name);
2559 if (text_segment_sp) {
2560 const lldb::addr_t text_segment_file_addr =
2561 text_segment_sp->GetFileAddress();
2562 if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2563 for (auto &e : trie_entries)
2564 e.entry.address += text_segment_file_addr;
2565 }
2566 }
2567 }
2568
2569 typedef std::set<ConstString> IndirectSymbols;
2570 IndirectSymbols indirect_symbol_names;
2571
2572#if defined(__APPLE__) && \
2573 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2574
2575 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
Adrian Prantl05097242018-04-30 16:49:04 +00002576 // optimized by moving LOCAL symbols out of the memory mapped portion of
2577 // the DSC. The symbol information has all been retained, but it isn't
2578 // available in the normal nlist data. However, there *are* duplicate
2579 // entries of *some*
Kate Stoneb9c1b512016-09-06 20:57:50 +00002580 // LOCAL symbols in the normal nlist data. To handle this situation
2581 // correctly, we must first attempt
2582 // to parse any DSC unmapped symbol information. If we find any, we set a
Adrian Prantl05097242018-04-30 16:49:04 +00002583 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002584
2585 if (m_header.flags & 0x80000000u) {
Adrian Prantl05097242018-04-30 16:49:04 +00002586 // Before we can start mapping the DSC, we need to make certain the
2587 // target process is actually using the cache we can find.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002588
2589 // Next we need to determine the correct path for the dyld shared cache.
2590
2591 ArchSpec header_arch;
2592 GetArchitecture(header_arch);
2593 char dsc_path[PATH_MAX];
2594 char dsc_path_development[PATH_MAX];
2595
2596 snprintf(
2597 dsc_path, sizeof(dsc_path), "%s%s%s",
2598 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2599 */
2600 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2601 header_arch.GetArchitectureName());
2602
2603 snprintf(
2604 dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2605 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2606 */
2607 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
Ilia K4f730dc2016-09-12 05:25:33 +00002608 header_arch.GetArchitectureName(), ".development");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002609
2610 FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2611 FileSpec dsc_development_filespec(dsc_path_development, false);
2612 FileSpec dsc_filespec;
2613
2614 UUID dsc_uuid;
2615 UUID process_shared_cache_uuid;
Jason Molenda07580ff2018-05-04 00:59:37 +00002616 addr_t process_shared_cache_base_addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617
2618 if (process) {
Jason Molenda07580ff2018-05-04 00:59:37 +00002619 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, process_shared_cache_uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620 }
2621
Adrian Prantl05097242018-04-30 16:49:04 +00002622 // First see if we can find an exact match for the inferior process
2623 // shared cache UUID in the development or non-development shared caches
2624 // on disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002625 if (process_shared_cache_uuid.IsValid()) {
2626 if (dsc_development_filespec.Exists()) {
2627 UUID dsc_development_uuid = GetSharedCacheUUID(
2628 dsc_development_filespec, byte_order, addr_byte_size);
2629 if (dsc_development_uuid.IsValid() &&
2630 dsc_development_uuid == process_shared_cache_uuid) {
2631 dsc_filespec = dsc_development_filespec;
2632 dsc_uuid = dsc_development_uuid;
2633 }
2634 }
2635 if (!dsc_uuid.IsValid() && dsc_nondevelopment_filespec.Exists()) {
2636 UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2637 dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2638 if (dsc_nondevelopment_uuid.IsValid() &&
2639 dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2640 dsc_filespec = dsc_nondevelopment_filespec;
2641 dsc_uuid = dsc_nondevelopment_uuid;
2642 }
2643 }
2644 }
2645
2646 // Failing a UUID match, prefer the development dyld_shared cache if both
2647 // are present.
2648 if (!dsc_filespec.Exists()) {
2649 if (dsc_development_filespec.Exists()) {
2650 dsc_filespec = dsc_development_filespec;
2651 } else {
2652 dsc_filespec = dsc_nondevelopment_filespec;
2653 }
2654 }
2655
2656 /* The dyld_cache_header has a pointer to the
2657 dyld_cache_local_symbols_info structure (localSymbolsOffset).
2658 The dyld_cache_local_symbols_info structure gives us three things:
2659 1. The start and count of the nlist records in the dyld_shared_cache
2660 file
2661 2. The start and size of the strings for these nlist records
2662 3. The start and count of dyld_cache_local_symbols_entry entries
2663
2664 There is one dyld_cache_local_symbols_entry per dylib/framework in the
2665 dyld shared cache.
2666 The "dylibOffset" field is the Mach-O header of this dylib/framework in
2667 the dyld shared cache.
2668 The dyld_cache_local_symbols_entry also lists the start of this
2669 dylib/framework's nlist records
2670 and the count of how many nlist records there are for this
2671 dylib/framework.
2672 */
2673
2674 // Process the dyld shared cache header to find the unmapped symbols
2675
Pavel Labath50251fc2017-12-21 10:54:30 +00002676 DataBufferSP dsc_data_sp = MapFileData(
2677 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 if (!dsc_uuid.IsValid()) {
2679 dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2680 }
2681 if (dsc_data_sp) {
2682 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2683
2684 bool uuid_match = true;
2685 if (dsc_uuid.IsValid() && process) {
2686 if (process_shared_cache_uuid.IsValid() &&
2687 dsc_uuid != process_shared_cache_uuid) {
2688 // The on-disk dyld_shared_cache file is not the same as the one in
Adrian Prantl05097242018-04-30 16:49:04 +00002689 // this process' memory, don't use it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690 uuid_match = false;
2691 ModuleSP module_sp(GetModule());
2692 if (module_sp)
2693 module_sp->ReportWarning("process shared cache does not match "
2694 "on-disk dyld_shared_cache file, some "
2695 "symbol names will be missing.");
2696 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002697 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00002698
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002700
Kate Stoneb9c1b512016-09-06 20:57:50 +00002701 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
Jason Molenda955dcf22016-05-04 03:09:40 +00002702
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703 // If the mappingOffset points to a location inside the header, we've
2704 // opened an old dyld shared cache, and should not proceed further.
2705 if (uuid_match &&
2706 mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
Jason Molenda955dcf22016-05-04 03:09:40 +00002707
Pavel Labath50251fc2017-12-21 10:54:30 +00002708 DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2709 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2710 mappingOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002711
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2713 byte_order, addr_byte_size);
2714 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002715
Kate Stoneb9c1b512016-09-06 20:57:50 +00002716 // The File addresses (from the in-memory Mach-O load commands) for
Adrian Prantl05097242018-04-30 16:49:04 +00002717 // the shared libraries in the shared library cache need to be
2718 // adjusted by an offset to match up with the dylibOffset identifying
2719 // field in the dyld_cache_local_symbol_entry's. This offset is
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720 // recorded in mapping_offset_value.
2721 const uint64_t mapping_offset_value =
2722 dsc_mapping_info_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002723
Kate Stoneb9c1b512016-09-06 20:57:50 +00002724 offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2725 localSymbolsOffset);
2726 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2727 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002728
Kate Stoneb9c1b512016-09-06 20:57:50 +00002729 if (localSymbolsOffset && localSymbolsSize) {
2730 // Map the local symbols
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002731 DataBufferSP dsc_local_symbols_data_sp =
Pavel Labath50251fc2017-12-21 10:54:30 +00002732 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002733
2734 if (dsc_local_symbols_data_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2736 byte_order, addr_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002737
Kate Stoneb9c1b512016-09-06 20:57:50 +00002738 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002739
Kate Stoneb9c1b512016-09-06 20:57:50 +00002740 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2741 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2742 UndefinedNameToDescMap undefined_name_to_desc;
2743 SymbolIndexToName reexport_shlib_needs_fixup;
Jim Inghamea3ac272014-01-10 22:55:37 +00002744
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 // Read the local_symbols_infos struct in one shot
2746 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2747 dsc_local_symbols_data.GetU32(&offset,
2748 &local_symbols_info.nlistOffset, 6);
Jim Inghamea3ac272014-01-10 22:55:37 +00002749
Kate Stoneb9c1b512016-09-06 20:57:50 +00002750 SectionSP text_section_sp(
2751 section_list->FindSectionByName(GetSegmentNameTEXT()));
Greg Claytonb65c6292015-02-20 22:20:05 +00002752
Kate Stoneb9c1b512016-09-06 20:57:50 +00002753 uint32_t header_file_offset =
2754 (text_section_sp->GetFileAddress() - mapping_offset_value);
Jason Molendaa5609c82012-06-21 01:51:02 +00002755
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756 offset = local_symbols_info.entriesOffset;
2757 for (uint32_t entry_index = 0;
2758 entry_index < local_symbols_info.entriesCount;
2759 entry_index++) {
2760 struct lldb_copy_dyld_cache_local_symbols_entry
2761 local_symbols_entry;
2762 local_symbols_entry.dylibOffset =
2763 dsc_local_symbols_data.GetU32(&offset);
2764 local_symbols_entry.nlistStartIndex =
2765 dsc_local_symbols_data.GetU32(&offset);
2766 local_symbols_entry.nlistCount =
2767 dsc_local_symbols_data.GetU32(&offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002768
Kate Stoneb9c1b512016-09-06 20:57:50 +00002769 if (header_file_offset == local_symbols_entry.dylibOffset) {
2770 unmapped_local_symbols_found = local_symbols_entry.nlistCount;
Jason Molendaa5609c82012-06-21 01:51:02 +00002771
Kate Stoneb9c1b512016-09-06 20:57:50 +00002772 // The normal nlist code cannot correctly size the Symbols
2773 // array, we need to allocate it here.
2774 sym = symtab->Resize(
2775 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2776 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2777 num_syms = symtab->GetNumSymbols();
Jason Molendaa5609c82012-06-21 01:51:02 +00002778
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 nlist_data_offset =
2780 local_symbols_info.nlistOffset +
2781 (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2782 uint32_t string_table_offset =
2783 local_symbols_info.stringsOffset;
Jason Molendaa5609c82012-06-21 01:51:02 +00002784
Kate Stoneb9c1b512016-09-06 20:57:50 +00002785 for (uint32_t nlist_index = 0;
2786 nlist_index < local_symbols_entry.nlistCount;
2787 nlist_index++) {
2788 /////////////////////////////
Jason Molenda649a6072015-11-10 05:21:54 +00002789 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 struct nlist_64 nlist;
2791 if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(
2792 nlist_data_offset, nlist_byte_size))
2793 break;
Eugene Zelenko8157a882015-10-23 16:56:07 +00002794
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(
2796 &nlist_data_offset);
2797 nlist.n_type = dsc_local_symbols_data.GetU8_unchecked(
2798 &nlist_data_offset);
2799 nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked(
2800 &nlist_data_offset);
2801 nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked(
2802 &nlist_data_offset);
2803 nlist.n_value =
2804 dsc_local_symbols_data.GetAddress_unchecked(
2805 &nlist_data_offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002806
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 SymbolType type = eSymbolTypeInvalid;
2808 const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2809 string_table_offset + nlist.n_strx);
Jason Molendaf8130862012-06-22 03:28:35 +00002810
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002812 // No symbol should be NULL, even the symbols with no
Adrian Prantl05097242018-04-30 16:49:04 +00002813 // string values should have an offset zero which
2814 // points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 Host::SystemLog(
2816 Host::eSystemLogError,
2817 "error: DSC unmapped local symbol[%u] has invalid "
2818 "string table offset 0x%x in %s, ignoring symbol\n",
2819 entry_index, nlist.n_strx,
2820 module_sp->GetFileSpec().GetPath().c_str());
Greg Claytonfd814c52013-08-13 01:42:25 +00002821 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 }
2823 if (symbol_name[0] == '\0')
Greg Claytonfd814c52013-08-13 01:42:25 +00002824 symbol_name = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002825
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 const char *symbol_name_non_abi_mangled = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002827
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 SectionSP symbol_section;
2829 uint32_t symbol_byte_size = 0;
2830 bool add_nlist = true;
2831 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2832 bool demangled_is_synthesized = false;
2833 bool is_gsym = false;
2834 bool set_value = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00002835
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836 assert(sym_idx < num_syms);
Jason Molenda4e7511e2013-03-06 23:19:17 +00002837
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 sym[sym_idx].SetDebug(is_debug);
Greg Clayton29e08cb2012-03-14 01:53:24 +00002839
Kate Stoneb9c1b512016-09-06 20:57:50 +00002840 if (is_debug) {
2841 switch (nlist.n_type) {
2842 case N_GSYM:
2843 // global symbol: name,,NO_SECT,type,0
2844 // Sometimes the N_GSYM value contains the address.
2845
2846 // FIXME: In the .o files, we have a GSYM and a debug
2847 // symbol for all the ObjC data. They
2848 // have the same address, but we want to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +00002849 // we always find only the real symbol, 'cause we
2850 // don't currently correctly attribute the
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851 // GSYM one to the ObjCClass/Ivar/MetaClass
Adrian Prantl05097242018-04-30 16:49:04 +00002852 // symbol type. This is a temporary hack to make
2853 // sure the ObjectiveC symbols get treated correctly.
2854 // To do this right, we should coalesce all the GSYM
2855 // & global symbols that have the same address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002856
2857 is_gsym = true;
2858 sym[sym_idx].SetExternal(true);
2859
2860 if (symbol_name && symbol_name[0] == '_' &&
2861 symbol_name[1] == 'O') {
Greg Clayton1e28adf2015-02-25 17:25:02 +00002862 llvm::StringRef symbol_name_ref(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863 if (symbol_name_ref.startswith(
2864 g_objc_v2_prefix_class)) {
2865 symbol_name_non_abi_mangled = symbol_name + 1;
2866 symbol_name =
2867 symbol_name + g_objc_v2_prefix_class.size();
2868 type = eSymbolTypeObjCClass;
2869 demangled_is_synthesized = true;
2870
2871 } else if (symbol_name_ref.startswith(
2872 g_objc_v2_prefix_metaclass)) {
2873 symbol_name_non_abi_mangled = symbol_name + 1;
2874 symbol_name = symbol_name +
2875 g_objc_v2_prefix_metaclass.size();
2876 type = eSymbolTypeObjCMetaClass;
2877 demangled_is_synthesized = true;
2878 } else if (symbol_name_ref.startswith(
2879 g_objc_v2_prefix_ivar)) {
2880 symbol_name_non_abi_mangled = symbol_name + 1;
2881 symbol_name =
2882 symbol_name + g_objc_v2_prefix_ivar.size();
2883 type = eSymbolTypeObjCIVar;
2884 demangled_is_synthesized = true;
Greg Clayton1e28adf2015-02-25 17:25:02 +00002885 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002886 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002887 if (nlist.n_value != 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888 symbol_section = section_info.GetSection(
2889 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002890 type = eSymbolTypeData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002891 }
2892 break;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002893
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 case N_FNAME:
2895 // procedure name (f77 kludge): name,,NO_SECT,0,0
2896 type = eSymbolTypeCompiler;
2897 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002898
Kate Stoneb9c1b512016-09-06 20:57:50 +00002899 case N_FUN:
2900 // procedure: name,,n_sect,linenumber,address
2901 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002902 type = eSymbolTypeCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 symbol_section = section_info.GetSection(
2904 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002905
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906 N_FUN_addr_to_sym_idx.insert(
2907 std::make_pair(nlist.n_value, sym_idx));
2908 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00002909 // symbol table in lieu of using nlist_idx in case
2910 // we ever start trimming entries out
Greg Claytonfd814c52013-08-13 01:42:25 +00002911 N_FUN_indexes.push_back(sym_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002913 type = eSymbolTypeCompiler;
2914
Kate Stoneb9c1b512016-09-06 20:57:50 +00002915 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00002916 // Copy the size of the function into the
2917 // original
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 // STAB entry so we don't have
2919 // to hunt for it later
2920 symtab->SymbolAtIndex(N_FUN_indexes.back())
2921 ->SetByteSize(nlist.n_value);
2922 N_FUN_indexes.pop_back();
2923 // We don't really need the end function STAB as
Adrian Prantl05097242018-04-30 16:49:04 +00002924 // it contains the size which we already placed
2925 // with the original symbol, so don't add it if
2926 // we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00002927 add_nlist = false;
Greg Claytondacc4a92013-05-14 22:19:37 +00002928 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002929 }
2930 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002931
Kate Stoneb9c1b512016-09-06 20:57:50 +00002932 case N_STSYM:
2933 // static symbol: name,,n_sect,type,address
2934 N_STSYM_addr_to_sym_idx.insert(
2935 std::make_pair(nlist.n_value, sym_idx));
2936 symbol_section = section_info.GetSection(
2937 nlist.n_sect, nlist.n_value);
2938 if (symbol_name && symbol_name[0]) {
2939 type = ObjectFile::GetSymbolTypeFromName(
2940 symbol_name + 1, eSymbolTypeData);
2941 }
2942 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002943
Kate Stoneb9c1b512016-09-06 20:57:50 +00002944 case N_LCSYM:
2945 // .lcomm symbol: name,,n_sect,type,address
2946 symbol_section = section_info.GetSection(
2947 nlist.n_sect, nlist.n_value);
2948 type = eSymbolTypeCommonBlock;
2949 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002950
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 case N_BNSYM:
2952 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00002953 // table in lieu of using nlist_idx in case we ever
2954 // start trimming entries out Skip these if we want
2955 // minimal symbol tables
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 add_nlist = false;
2957 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002958
Kate Stoneb9c1b512016-09-06 20:57:50 +00002959 case N_ENSYM:
2960 // Set the size of the N_BNSYM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002961 // index of this N_ENSYM so that we can always skip
2962 // the entire symbol if we need to navigate more
2963 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 // Skip these if we want minimal symbol tables
2965 add_nlist = false;
2966 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002967
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968 case N_OPT:
2969 // emitted with gcc2_compiled and in gcc source
2970 type = eSymbolTypeCompiler;
2971 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002972
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 case N_RSYM:
2974 // register sym: name,,NO_SECT,type,register
2975 type = eSymbolTypeVariable;
2976 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002977
Kate Stoneb9c1b512016-09-06 20:57:50 +00002978 case N_SLINE:
2979 // src line: 0,,n_sect,linenumber,address
2980 symbol_section = section_info.GetSection(
2981 nlist.n_sect, nlist.n_value);
2982 type = eSymbolTypeLineEntry;
2983 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002984
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 case N_SSYM:
2986 // structure elt: name,,NO_SECT,type,struct_offset
2987 type = eSymbolTypeVariableType;
2988 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002989
Kate Stoneb9c1b512016-09-06 20:57:50 +00002990 case N_SO:
2991 // source file name
2992 type = eSymbolTypeSourceFile;
2993 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002994 add_nlist = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 if (N_SO_index != UINT32_MAX) {
2996 // Set the size of the N_SO to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002997 // index of this N_SO so that we can always skip
2998 // the entire N_SO if we need to navigate more
2999 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003000 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3001 symbol_ptr->SetByteSize(sym_idx);
3002 symbol_ptr->SetSizeIsSibling(true);
Greg Claytonfd814c52013-08-13 01:42:25 +00003003 }
3004 N_NSYM_indexes.clear();
3005 N_INCL_indexes.clear();
3006 N_BRAC_indexes.clear();
3007 N_COMM_indexes.clear();
3008 N_FUN_indexes.clear();
3009 N_SO_index = UINT32_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 } else {
3011 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00003012 // symbol table in lieu of using nlist_idx in case
3013 // we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003014 const bool N_SO_has_full_path =
3015 symbol_name[0] == '/';
3016 if (N_SO_has_full_path) {
3017 if ((N_SO_index == sym_idx - 1) &&
3018 ((sym_idx - 1) < num_syms)) {
3019 // We have two consecutive N_SO entries where
Adrian Prantl05097242018-04-30 16:49:04 +00003020 // the first contains a directory and the
3021 // second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003022 sym[sym_idx - 1].GetMangled().SetValue(
3023 ConstString(symbol_name), false);
3024 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3025 add_nlist = false;
3026 } else {
3027 // This is the first entry in a N_SO that
3028 // contains a directory or
3029 // a full path to the source file
Greg Claytonfd814c52013-08-13 01:42:25 +00003030 N_SO_index = sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031 }
3032 } else if ((N_SO_index == sym_idx - 1) &&
3033 ((sym_idx - 1) < num_syms)) {
3034 // This is usually the second N_SO entry that
Adrian Prantl05097242018-04-30 16:49:04 +00003035 // contains just the filename, so here we combine
3036 // it with the first one if we are minimizing the
3037 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038 const char *so_path =
3039 sym[sym_idx - 1]
3040 .GetMangled()
3041 .GetDemangledName(
3042 lldb::eLanguageTypeUnknown)
3043 .AsCString();
3044 if (so_path && so_path[0]) {
3045 std::string full_so_path(so_path);
3046 const size_t double_slash_pos =
3047 full_so_path.find("//");
3048 if (double_slash_pos != std::string::npos) {
3049 // The linker has been generating bad N_SO
3050 // entries with doubled up paths
Adrian Prantl05097242018-04-30 16:49:04 +00003051 // in the format "%s%s" where the first
3052 // string in the DW_AT_comp_dir, and the
3053 // second is the directory for the source
3054 // file so you end up with a path that looks
3055 // like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056 FileSpec so_dir(so_path, false);
3057 if (!so_dir.Exists()) {
3058 so_dir.SetFile(
3059 &full_so_path[double_slash_pos + 1],
3060 false);
3061 if (so_dir.Exists()) {
3062 // Trim off the incorrect path
3063 full_so_path.erase(0,
3064 double_slash_pos + 1);
3065 }
3066 }
3067 }
3068 if (*full_so_path.rbegin() != '/')
3069 full_so_path += '/';
3070 full_so_path += symbol_name;
3071 sym[sym_idx - 1].GetMangled().SetValue(
3072 ConstString(full_so_path.c_str()), false);
3073 add_nlist = false;
3074 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3075 }
3076 } else {
3077 // This could be a relative path to a N_SO
3078 N_SO_index = sym_idx;
Greg Claytonfd814c52013-08-13 01:42:25 +00003079 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003080 }
3081 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003082
Kate Stoneb9c1b512016-09-06 20:57:50 +00003083 case N_OSO:
3084 // object file name: name,,0,0,st_mtime
3085 type = eSymbolTypeObjectFile;
3086 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003087
Kate Stoneb9c1b512016-09-06 20:57:50 +00003088 case N_LSYM:
3089 // local sym: name,,NO_SECT,type,offset
3090 type = eSymbolTypeLocal;
3091 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003092
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 //----------------------------------------------------------------------
3094 // INCL scopes
3095 //----------------------------------------------------------------------
3096 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00003097 // include file beginning: name,,NO_SECT,0,sum We use
3098 // the current number of symbols in the symbol table
3099 // in lieu of using nlist_idx in case we ever start
3100 // trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003101 N_INCL_indexes.push_back(sym_idx);
3102 type = eSymbolTypeScopeBegin;
3103 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003104
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105 case N_EINCL:
3106 // include file end: name,,NO_SECT,0,0
3107 // Set the size of the N_BINCL to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003108 // index of this N_EINCL so that we can always skip
3109 // the entire symbol if we need to navigate more
3110 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003111 if (!N_INCL_indexes.empty()) {
3112 symbol_ptr =
3113 symtab->SymbolAtIndex(N_INCL_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003114 symbol_ptr->SetByteSize(sym_idx + 1);
3115 symbol_ptr->SetSizeIsSibling(true);
3116 N_INCL_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 }
3118 type = eSymbolTypeScopeEnd;
3119 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003120
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121 case N_SOL:
3122 // #included file name: name,,n_sect,0,address
3123 type = eSymbolTypeHeaderFile;
Greg Claytonfd814c52013-08-13 01:42:25 +00003124
Kate Stoneb9c1b512016-09-06 20:57:50 +00003125 // We currently don't use the header files on darwin
3126 add_nlist = false;
3127 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003128
Kate Stoneb9c1b512016-09-06 20:57:50 +00003129 case N_PARAMS:
3130 // compiler parameters: name,,NO_SECT,0,0
3131 type = eSymbolTypeCompiler;
3132 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134 case N_VERSION:
3135 // compiler version: name,,NO_SECT,0,0
3136 type = eSymbolTypeCompiler;
3137 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003138
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 case N_OLEVEL:
3140 // compiler -O level: name,,NO_SECT,0,0
3141 type = eSymbolTypeCompiler;
3142 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003143
Kate Stoneb9c1b512016-09-06 20:57:50 +00003144 case N_PSYM:
3145 // parameter: name,,NO_SECT,type,offset
3146 type = eSymbolTypeVariable;
3147 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003148
Kate Stoneb9c1b512016-09-06 20:57:50 +00003149 case N_ENTRY:
3150 // alternate entry: name,,n_sect,linenumber,address
3151 symbol_section = section_info.GetSection(
3152 nlist.n_sect, nlist.n_value);
3153 type = eSymbolTypeLineEntry;
3154 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003155
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156 //----------------------------------------------------------------------
3157 // Left and Right Braces
3158 //----------------------------------------------------------------------
3159 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00003160 // left bracket: 0,,NO_SECT,nesting level,address We
3161 // use the current number of symbols in the symbol
3162 // table in lieu of using nlist_idx in case we ever
3163 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003164 symbol_section = section_info.GetSection(
3165 nlist.n_sect, nlist.n_value);
3166 N_BRAC_indexes.push_back(sym_idx);
3167 type = eSymbolTypeScopeBegin;
3168 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003169
Kate Stoneb9c1b512016-09-06 20:57:50 +00003170 case N_RBRAC:
3171 // right bracket: 0,,NO_SECT,nesting level,address
3172 // Set the size of the N_LBRAC to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003173 // index of this N_RBRAC so that we can always skip
3174 // the entire symbol if we need to navigate more
3175 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003176 symbol_section = section_info.GetSection(
3177 nlist.n_sect, nlist.n_value);
3178 if (!N_BRAC_indexes.empty()) {
3179 symbol_ptr =
3180 symtab->SymbolAtIndex(N_BRAC_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003181 symbol_ptr->SetByteSize(sym_idx + 1);
3182 symbol_ptr->SetSizeIsSibling(true);
3183 N_BRAC_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003184 }
3185 type = eSymbolTypeScopeEnd;
3186 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003187
Kate Stoneb9c1b512016-09-06 20:57:50 +00003188 case N_EXCL:
3189 // deleted include file: name,,NO_SECT,0,sum
3190 type = eSymbolTypeHeaderFile;
3191 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003192
Kate Stoneb9c1b512016-09-06 20:57:50 +00003193 //----------------------------------------------------------------------
3194 // COMM scopes
3195 //----------------------------------------------------------------------
3196 case N_BCOMM:
3197 // begin common: name,,NO_SECT,0,0
3198 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00003199 // table in lieu of using nlist_idx in case we ever
3200 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003201 type = eSymbolTypeScopeBegin;
3202 N_COMM_indexes.push_back(sym_idx);
3203 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003204
Kate Stoneb9c1b512016-09-06 20:57:50 +00003205 case N_ECOML:
3206 // end common (local name): 0,,n_sect,0,address
3207 symbol_section = section_info.GetSection(
3208 nlist.n_sect, nlist.n_value);
3209 // Fall through
Greg Claytonfd814c52013-08-13 01:42:25 +00003210
Kate Stoneb9c1b512016-09-06 20:57:50 +00003211 case N_ECOMM:
3212 // end common: name,,n_sect,0,0
3213 // Set the size of the N_BCOMM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003214 // index of this N_ECOMM/N_ECOML so that we can
3215 // always skip the entire symbol if we need to
3216 // navigate more quickly at the source level when
3217 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003218 if (!N_COMM_indexes.empty()) {
3219 symbol_ptr =
3220 symtab->SymbolAtIndex(N_COMM_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003221 symbol_ptr->SetByteSize(sym_idx + 1);
3222 symbol_ptr->SetSizeIsSibling(true);
3223 N_COMM_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003224 }
3225 type = eSymbolTypeScopeEnd;
3226 break;
3227
3228 case N_LENG:
3229 // second stab entry with length information
3230 type = eSymbolTypeAdditional;
3231 break;
3232
3233 default:
3234 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003235 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003236 } else {
3237 // uint8_t n_pext = N_PEXT & nlist.n_type;
3238 uint8_t n_type = N_TYPE & nlist.n_type;
3239 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
Greg Claytonfd814c52013-08-13 01:42:25 +00003240
Kate Stoneb9c1b512016-09-06 20:57:50 +00003241 switch (n_type) {
3242 case N_INDR: {
3243 const char *reexport_name_cstr =
3244 strtab_data.PeekCStr(nlist.n_value);
3245 if (reexport_name_cstr && reexport_name_cstr[0]) {
3246 type = eSymbolTypeReExported;
3247 ConstString reexport_name(
3248 reexport_name_cstr +
3249 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3250 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3251 set_value = false;
3252 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3253 indirect_symbol_names.insert(
3254 ConstString(symbol_name +
3255 ((symbol_name[0] == '_') ? 1 : 0)));
3256 } else
3257 type = eSymbolTypeUndefined;
3258 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003259
Kate Stoneb9c1b512016-09-06 20:57:50 +00003260 case N_UNDF:
3261 if (symbol_name && symbol_name[0]) {
3262 ConstString undefined_name(
3263 symbol_name +
3264 ((symbol_name[0] == '_') ? 1 : 0));
3265 undefined_name_to_desc[undefined_name] =
3266 nlist.n_desc;
3267 }
3268 // Fall through
3269 case N_PBUD:
3270 type = eSymbolTypeUndefined;
3271 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003272
Kate Stoneb9c1b512016-09-06 20:57:50 +00003273 case N_ABS:
3274 type = eSymbolTypeAbsolute;
3275 break;
Greg Clayton60038be2015-02-14 00:51:13 +00003276
Kate Stoneb9c1b512016-09-06 20:57:50 +00003277 case N_SECT: {
3278 symbol_section = section_info.GetSection(
3279 nlist.n_sect, nlist.n_value);
Jason Molenda62e06812016-02-16 04:14:33 +00003280
Kate Stoneb9c1b512016-09-06 20:57:50 +00003281 if (symbol_section == NULL) {
3282 // TODO: warn about this?
3283 add_nlist = false;
3284 break;
3285 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003286
Kate Stoneb9c1b512016-09-06 20:57:50 +00003287 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3288 type = eSymbolTypeException;
3289 } else {
3290 uint32_t section_type =
3291 symbol_section->Get() & SECTION_TYPE;
Greg Claytonfd814c52013-08-13 01:42:25 +00003292
Kate Stoneb9c1b512016-09-06 20:57:50 +00003293 switch (section_type) {
3294 case S_CSTRING_LITERALS:
3295 type = eSymbolTypeData;
3296 break; // section with only literal C strings
3297 case S_4BYTE_LITERALS:
3298 type = eSymbolTypeData;
3299 break; // section with only 4 byte literals
3300 case S_8BYTE_LITERALS:
3301 type = eSymbolTypeData;
3302 break; // section with only 8 byte literals
3303 case S_LITERAL_POINTERS:
3304 type = eSymbolTypeTrampoline;
3305 break; // section with only pointers to literals
3306 case S_NON_LAZY_SYMBOL_POINTERS:
3307 type = eSymbolTypeTrampoline;
3308 break; // section with only non-lazy symbol
3309 // pointers
3310 case S_LAZY_SYMBOL_POINTERS:
3311 type = eSymbolTypeTrampoline;
3312 break; // section with only lazy symbol pointers
3313 case S_SYMBOL_STUBS:
3314 type = eSymbolTypeTrampoline;
3315 break; // section with only symbol stubs, byte
3316 // size of stub in the reserved2 field
3317 case S_MOD_INIT_FUNC_POINTERS:
3318 type = eSymbolTypeCode;
3319 break; // section with only function pointers for
3320 // initialization
3321 case S_MOD_TERM_FUNC_POINTERS:
3322 type = eSymbolTypeCode;
3323 break; // section with only function pointers for
3324 // termination
3325 case S_INTERPOSING:
3326 type = eSymbolTypeTrampoline;
3327 break; // section with only pairs of function
3328 // pointers for interposing
3329 case S_16BYTE_LITERALS:
3330 type = eSymbolTypeData;
3331 break; // section with only 16 byte literals
3332 case S_DTRACE_DOF:
3333 type = eSymbolTypeInstrumentation;
3334 break;
3335 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3336 type = eSymbolTypeTrampoline;
3337 break;
3338 default:
3339 switch (symbol_section->GetType()) {
3340 case lldb::eSectionTypeCode:
3341 type = eSymbolTypeCode;
Greg Claytonfd814c52013-08-13 01:42:25 +00003342 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003343 case eSectionTypeData:
3344 case eSectionTypeDataCString: // Inlined C string
3345 // data
3346 case eSectionTypeDataCStringPointers: // Pointers
3347 // to C
3348 // string
3349 // data
3350 case eSectionTypeDataSymbolAddress: // Address of
3351 // a symbol in
3352 // the symbol
3353 // table
3354 case eSectionTypeData4:
3355 case eSectionTypeData8:
3356 case eSectionTypeData16:
3357 type = eSymbolTypeData;
3358 break;
3359 default:
3360 break;
3361 }
3362 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003363 }
3364
Kate Stoneb9c1b512016-09-06 20:57:50 +00003365 if (type == eSymbolTypeInvalid) {
3366 const char *symbol_sect_name =
3367 symbol_section->GetName().AsCString();
3368 if (symbol_section->IsDescendant(
3369 text_section_sp.get())) {
3370 if (symbol_section->IsClear(
3371 S_ATTR_PURE_INSTRUCTIONS |
3372 S_ATTR_SELF_MODIFYING_CODE |
3373 S_ATTR_SOME_INSTRUCTIONS))
3374 type = eSymbolTypeData;
3375 else
3376 type = eSymbolTypeCode;
3377 } else if (symbol_section->IsDescendant(
3378 data_section_sp.get()) ||
3379 symbol_section->IsDescendant(
3380 data_dirty_section_sp.get()) ||
3381 symbol_section->IsDescendant(
3382 data_const_section_sp.get())) {
3383 if (symbol_sect_name &&
3384 ::strstr(symbol_sect_name, "__objc") ==
3385 symbol_sect_name) {
3386 type = eSymbolTypeRuntime;
Greg Claytonfd814c52013-08-13 01:42:25 +00003387
Kate Stoneb9c1b512016-09-06 20:57:50 +00003388 if (symbol_name) {
3389 llvm::StringRef symbol_name_ref(
3390 symbol_name);
3391 if (symbol_name_ref.startswith("_OBJC_")) {
3392 static const llvm::StringRef
3393 g_objc_v2_prefix_class(
3394 "_OBJC_CLASS_$_");
3395 static const llvm::StringRef
3396 g_objc_v2_prefix_metaclass(
3397 "_OBJC_METACLASS_$_");
3398 static const llvm::StringRef
3399 g_objc_v2_prefix_ivar(
3400 "_OBJC_IVAR_$_");
3401 if (symbol_name_ref.startswith(
3402 g_objc_v2_prefix_class)) {
3403 symbol_name_non_abi_mangled =
3404 symbol_name + 1;
3405 symbol_name =
3406 symbol_name +
3407 g_objc_v2_prefix_class.size();
3408 type = eSymbolTypeObjCClass;
3409 demangled_is_synthesized = true;
3410 } else if (
3411 symbol_name_ref.startswith(
3412 g_objc_v2_prefix_metaclass)) {
3413 symbol_name_non_abi_mangled =
3414 symbol_name + 1;
3415 symbol_name =
3416 symbol_name +
3417 g_objc_v2_prefix_metaclass.size();
3418 type = eSymbolTypeObjCMetaClass;
3419 demangled_is_synthesized = true;
3420 } else if (symbol_name_ref.startswith(
3421 g_objc_v2_prefix_ivar)) {
3422 symbol_name_non_abi_mangled =
3423 symbol_name + 1;
3424 symbol_name =
3425 symbol_name +
3426 g_objc_v2_prefix_ivar.size();
3427 type = eSymbolTypeObjCIVar;
3428 demangled_is_synthesized = true;
3429 }
Greg Clayton38f9cc42014-06-16 22:53:16 +00003430 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003431 }
3432 } else if (symbol_sect_name &&
3433 ::strstr(symbol_sect_name,
3434 "__gcc_except_tab") ==
3435 symbol_sect_name) {
3436 type = eSymbolTypeException;
3437 } else {
3438 type = eSymbolTypeData;
Greg Claytonfd814c52013-08-13 01:42:25 +00003439 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003440 } else if (symbol_sect_name &&
3441 ::strstr(symbol_sect_name,
3442 "__IMPORT") ==
3443 symbol_sect_name) {
3444 type = eSymbolTypeTrampoline;
3445 } else if (symbol_section->IsDescendant(
3446 objc_section_sp.get())) {
3447 type = eSymbolTypeRuntime;
3448 if (symbol_name && symbol_name[0] == '.') {
3449 llvm::StringRef symbol_name_ref(symbol_name);
3450 static const llvm::StringRef
3451 g_objc_v1_prefix_class(
3452 ".objc_class_name_");
3453 if (symbol_name_ref.startswith(
3454 g_objc_v1_prefix_class)) {
3455 symbol_name_non_abi_mangled = symbol_name;
3456 symbol_name = symbol_name +
3457 g_objc_v1_prefix_class.size();
3458 type = eSymbolTypeObjCClass;
3459 demangled_is_synthesized = true;
3460 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003461 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003462 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003463 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003464 }
3465 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003466 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003467 }
Greg Claytondacc4a92013-05-14 22:19:37 +00003468
Kate Stoneb9c1b512016-09-06 20:57:50 +00003469 if (add_nlist) {
3470 uint64_t symbol_value = nlist.n_value;
3471 if (symbol_name_non_abi_mangled) {
3472 sym[sym_idx].GetMangled().SetMangledName(
3473 ConstString(symbol_name_non_abi_mangled));
3474 sym[sym_idx].GetMangled().SetDemangledName(
3475 ConstString(symbol_name));
3476 } else {
3477 bool symbol_name_is_mangled = false;
Greg Claytonfd814c52013-08-13 01:42:25 +00003478
Kate Stoneb9c1b512016-09-06 20:57:50 +00003479 if (symbol_name && symbol_name[0] == '_') {
Greg Claytonfd814c52013-08-13 01:42:25 +00003480 symbol_name_is_mangled = symbol_name[1] == '_';
Kate Stoneb9c1b512016-09-06 20:57:50 +00003481 symbol_name++; // Skip the leading underscore
3482 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003483
Kate Stoneb9c1b512016-09-06 20:57:50 +00003484 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003485 ConstString const_symbol_name(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003486 sym[sym_idx].GetMangled().SetValue(
3487 const_symbol_name, symbol_name_is_mangled);
3488 if (is_gsym && is_debug) {
3489 const char *gsym_name =
3490 sym[sym_idx]
3491 .GetMangled()
3492 .GetName(lldb::eLanguageTypeUnknown,
3493 Mangled::ePreferMangled)
3494 .GetCString();
3495 if (gsym_name)
3496 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3497 }
3498 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003499 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003500 if (symbol_section) {
3501 const addr_t section_file_addr =
3502 symbol_section->GetFileAddress();
3503 if (symbol_byte_size == 0 &&
3504 function_starts_count > 0) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003505 addr_t symbol_lookup_file_addr = nlist.n_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003506 // Do an exact address match for non-ARM addresses,
Adrian Prantl05097242018-04-30 16:49:04 +00003507 // else get the closest since the symbol might be a
3508 // thumb symbol which has an address with bit zero
3509 // set
Kate Stoneb9c1b512016-09-06 20:57:50 +00003510 FunctionStarts::Entry *func_start_entry =
3511 function_starts.FindEntry(
3512 symbol_lookup_file_addr, !is_arm);
3513 if (is_arm && func_start_entry) {
3514 // Verify that the function start address is the
Adrian Prantl05097242018-04-30 16:49:04 +00003515 // symbol address (ARM) or the symbol address + 1
3516 // (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003517 if (func_start_entry->addr !=
3518 symbol_lookup_file_addr &&
3519 func_start_entry->addr !=
3520 (symbol_lookup_file_addr + 1)) {
3521 // Not the right entry, NULL it out...
3522 func_start_entry = NULL;
3523 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003524 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003525 if (func_start_entry) {
3526 func_start_entry->data = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00003527
Kate Stoneb9c1b512016-09-06 20:57:50 +00003528 addr_t symbol_file_addr = func_start_entry->addr;
3529 uint32_t symbol_flags = 0;
3530 if (is_arm) {
3531 if (symbol_file_addr & 1)
3532 symbol_flags =
3533 MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3534 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3535 }
3536
3537 const FunctionStarts::Entry
3538 *next_func_start_entry =
3539 function_starts.FindNextEntry(
3540 func_start_entry);
3541 const addr_t section_end_file_addr =
3542 section_file_addr +
3543 symbol_section->GetByteSize();
3544 if (next_func_start_entry) {
3545 addr_t next_symbol_file_addr =
3546 next_func_start_entry->addr;
3547 // Be sure the clear the Thumb address bit when
Adrian Prantl05097242018-04-30 16:49:04 +00003548 // we calculate the size from the current and
3549 // next address
Greg Claytonfd814c52013-08-13 01:42:25 +00003550 if (is_arm)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003551 next_symbol_file_addr &=
3552 THUMB_ADDRESS_BIT_MASK;
3553 symbol_byte_size = std::min<lldb::addr_t>(
3554 next_symbol_file_addr - symbol_file_addr,
3555 section_end_file_addr - symbol_file_addr);
3556 } else {
3557 symbol_byte_size =
3558 section_end_file_addr - symbol_file_addr;
3559 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003560 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003561 }
3562 symbol_value -= section_file_addr;
Greg Claytonfd814c52013-08-13 01:42:25 +00003563 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003564
Kate Stoneb9c1b512016-09-06 20:57:50 +00003565 if (is_debug == false) {
3566 if (type == eSymbolTypeCode) {
3567 // See if we can find a N_FUN entry for any code
Adrian Prantl05097242018-04-30 16:49:04 +00003568 // symbols. If we do find a match, and the name
3569 // matches, then we can merge the two into just the
3570 // function symbol to avoid duplicate entries in
3571 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003572 std::pair<ValueToSymbolIndexMap::const_iterator,
3573 ValueToSymbolIndexMap::const_iterator>
3574 range;
3575 range = N_FUN_addr_to_sym_idx.equal_range(
3576 nlist.n_value);
3577 if (range.first != range.second) {
3578 bool found_it = false;
3579 for (ValueToSymbolIndexMap::const_iterator pos =
3580 range.first;
3581 pos != range.second; ++pos) {
3582 if (sym[sym_idx].GetMangled().GetName(
3583 lldb::eLanguageTypeUnknown,
3584 Mangled::ePreferMangled) ==
3585 sym[pos->second].GetMangled().GetName(
3586 lldb::eLanguageTypeUnknown,
3587 Mangled::ePreferMangled)) {
3588 m_nlist_idx_to_sym_idx[nlist_idx] =
3589 pos->second;
3590 // We just need the flags from the linker
3591 // symbol, so put these flags
3592 // into the N_FUN flags to avoid duplicate
3593 // symbols in the symbol table
3594 sym[pos->second].SetExternal(
3595 sym[sym_idx].IsExternal());
3596 sym[pos->second].SetFlags(nlist.n_type << 16 |
3597 nlist.n_desc);
3598 if (resolver_addresses.find(nlist.n_value) !=
3599 resolver_addresses.end())
3600 sym[pos->second].SetType(
3601 eSymbolTypeResolver);
3602 sym[sym_idx].Clear();
3603 found_it = true;
3604 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003605 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003606 }
3607 if (found_it)
3608 continue;
3609 } else {
3610 if (resolver_addresses.find(nlist.n_value) !=
3611 resolver_addresses.end())
3612 type = eSymbolTypeResolver;
Greg Claytonfd814c52013-08-13 01:42:25 +00003613 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003614 } else if (type == eSymbolTypeData ||
3615 type == eSymbolTypeObjCClass ||
3616 type == eSymbolTypeObjCMetaClass ||
3617 type == eSymbolTypeObjCIVar) {
3618 // See if we can find a N_STSYM entry for any data
Adrian Prantl05097242018-04-30 16:49:04 +00003619 // symbols. If we do find a match, and the name
3620 // matches, then we can merge the two into just the
3621 // Static symbol to avoid duplicate entries in the
3622 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003623 std::pair<ValueToSymbolIndexMap::const_iterator,
3624 ValueToSymbolIndexMap::const_iterator>
3625 range;
3626 range = N_STSYM_addr_to_sym_idx.equal_range(
3627 nlist.n_value);
3628 if (range.first != range.second) {
3629 bool found_it = false;
3630 for (ValueToSymbolIndexMap::const_iterator pos =
3631 range.first;
3632 pos != range.second; ++pos) {
3633 if (sym[sym_idx].GetMangled().GetName(
3634 lldb::eLanguageTypeUnknown,
3635 Mangled::ePreferMangled) ==
3636 sym[pos->second].GetMangled().GetName(
3637 lldb::eLanguageTypeUnknown,
3638 Mangled::ePreferMangled)) {
3639 m_nlist_idx_to_sym_idx[nlist_idx] =
3640 pos->second;
3641 // We just need the flags from the linker
3642 // symbol, so put these flags
3643 // into the N_STSYM flags to avoid duplicate
3644 // symbols in the symbol table
3645 sym[pos->second].SetExternal(
3646 sym[sym_idx].IsExternal());
3647 sym[pos->second].SetFlags(nlist.n_type << 16 |
3648 nlist.n_desc);
3649 sym[sym_idx].Clear();
3650 found_it = true;
3651 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003652 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003653 }
3654 if (found_it)
3655 continue;
3656 } else {
3657 const char *gsym_name =
3658 sym[sym_idx]
3659 .GetMangled()
3660 .GetName(lldb::eLanguageTypeUnknown,
3661 Mangled::ePreferMangled)
3662 .GetCString();
3663 if (gsym_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00003664 // Combine N_GSYM stab entries with the non
3665 // stab symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00003666 ConstNameToSymbolIndexMap::const_iterator pos =
3667 N_GSYM_name_to_sym_idx.find(gsym_name);
3668 if (pos != N_GSYM_name_to_sym_idx.end()) {
3669 const uint32_t GSYM_sym_idx = pos->second;
3670 m_nlist_idx_to_sym_idx[nlist_idx] =
3671 GSYM_sym_idx;
3672 // Copy the address, because often the N_GSYM
3673 // address has an invalid address of zero
3674 // when the global is a common symbol
3675 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3676 symbol_section);
3677 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3678 symbol_value);
3679 // We just need the flags from the linker
3680 // symbol, so put these flags
3681 // into the N_GSYM flags to avoid duplicate
3682 // symbols in the symbol table
3683 sym[GSYM_sym_idx].SetFlags(
3684 nlist.n_type << 16 | nlist.n_desc);
3685 sym[sym_idx].Clear();
3686 continue;
3687 }
3688 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003689 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003690 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003691 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003692
Kate Stoneb9c1b512016-09-06 20:57:50 +00003693 sym[sym_idx].SetID(nlist_idx);
3694 sym[sym_idx].SetType(type);
3695 if (set_value) {
3696 sym[sym_idx].GetAddressRef().SetSection(
3697 symbol_section);
3698 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
Greg Clayton29e08cb2012-03-14 01:53:24 +00003699 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003700 sym[sym_idx].SetFlags(nlist.n_type << 16 |
3701 nlist.n_desc);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003702
Kate Stoneb9c1b512016-09-06 20:57:50 +00003703 if (symbol_byte_size > 0)
3704 sym[sym_idx].SetByteSize(symbol_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003705
Kate Stoneb9c1b512016-09-06 20:57:50 +00003706 if (demangled_is_synthesized)
3707 sym[sym_idx].SetDemangledNameIsSynthesized(true);
Greg Clayton60038be2015-02-14 00:51:13 +00003708 ++sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003709 } else {
3710 sym[sym_idx].Clear();
3711 }
Greg Clayton9191db42013-10-21 18:40:51 +00003712 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003713 /////////////////////////////
3714 }
3715 break; // No more entries to consider
Greg Clayton9191db42013-10-21 18:40:51 +00003716 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003717 }
3718
3719 for (const auto &pos : reexport_shlib_needs_fixup) {
3720 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3721 if (undef_pos != undefined_name_to_desc.end()) {
3722 const uint8_t dylib_ordinal =
3723 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3724 if (dylib_ordinal > 0 &&
3725 dylib_ordinal < dylib_files.GetSize())
3726 sym[pos.first].SetReExportedSymbolSharedLibrary(
3727 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3728 }
3729 }
Greg Clayton9191db42013-10-21 18:40:51 +00003730 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731 }
Greg Clayton9191db42013-10-21 18:40:51 +00003732 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003733 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003734 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003735
3736 // Must reset this in case it was mutated above!
3737 nlist_data_offset = 0;
3738#endif
3739
3740 if (nlist_data.GetByteSize() > 0) {
3741
3742 // If the sym array was not created while parsing the DSC unmapped
3743 // symbols, create it now.
3744 if (sym == NULL) {
3745 sym = symtab->Resize(symtab_load_command.nsyms +
3746 m_dysymtab.nindirectsyms);
3747 num_syms = symtab->GetNumSymbols();
3748 }
3749
3750 if (unmapped_local_symbols_found) {
3751 assert(m_dysymtab.ilocalsym == 0);
3752 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3753 nlist_idx = m_dysymtab.nlocalsym;
3754 } else {
3755 nlist_idx = 0;
3756 }
3757
3758 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3759 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3760 UndefinedNameToDescMap undefined_name_to_desc;
3761 SymbolIndexToName reexport_shlib_needs_fixup;
3762 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
3763 struct nlist_64 nlist;
3764 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset,
3765 nlist_byte_size))
3766 break;
3767
3768 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
3769 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
3770 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
3771 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
3772 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
3773
3774 SymbolType type = eSymbolTypeInvalid;
3775 const char *symbol_name = NULL;
3776
3777 if (have_strtab_data) {
3778 symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3779
3780 if (symbol_name == NULL) {
Adrian Prantl05097242018-04-30 16:49:04 +00003781 // No symbol should be NULL, even the symbols with no string values
3782 // should have an offset zero which points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00003783 Host::SystemLog(Host::eSystemLogError,
3784 "error: symbol[%u] has invalid string table offset "
3785 "0x%x in %s, ignoring symbol\n",
3786 nlist_idx, nlist.n_strx,
3787 module_sp->GetFileSpec().GetPath().c_str());
3788 continue;
3789 }
3790 if (symbol_name[0] == '\0')
3791 symbol_name = NULL;
3792 } else {
3793 const addr_t str_addr = strtab_addr + nlist.n_strx;
Zachary Turner97206d52017-05-12 04:51:55 +00003794 Status str_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003795 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3796 str_error))
3797 symbol_name = memory_symbol_name.c_str();
3798 }
3799 const char *symbol_name_non_abi_mangled = NULL;
3800
3801 SectionSP symbol_section;
3802 lldb::addr_t symbol_byte_size = 0;
3803 bool add_nlist = true;
3804 bool is_gsym = false;
3805 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3806 bool demangled_is_synthesized = false;
3807 bool set_value = true;
3808 assert(sym_idx < num_syms);
3809
3810 sym[sym_idx].SetDebug(is_debug);
3811
3812 if (is_debug) {
3813 switch (nlist.n_type) {
3814 case N_GSYM:
3815 // global symbol: name,,NO_SECT,type,0
3816 // Sometimes the N_GSYM value contains the address.
3817
3818 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3819 // the ObjC data. They
3820 // have the same address, but we want to ensure that we always find
Adrian Prantl05097242018-04-30 16:49:04 +00003821 // only the real symbol, 'cause we don't currently correctly
3822 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3823 // type. This is a temporary hack to make sure the ObjectiveC
3824 // symbols get treated correctly. To do this right, we should
3825 // coalesce all the GSYM & global symbols that have the same
3826 // address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003827 is_gsym = true;
3828 sym[sym_idx].SetExternal(true);
3829
3830 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3831 llvm::StringRef symbol_name_ref(symbol_name);
3832 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3833 symbol_name_non_abi_mangled = symbol_name + 1;
3834 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3835 type = eSymbolTypeObjCClass;
3836 demangled_is_synthesized = true;
3837
3838 } else if (symbol_name_ref.startswith(
3839 g_objc_v2_prefix_metaclass)) {
3840 symbol_name_non_abi_mangled = symbol_name + 1;
3841 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3842 type = eSymbolTypeObjCMetaClass;
3843 demangled_is_synthesized = true;
3844 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3845 symbol_name_non_abi_mangled = symbol_name + 1;
3846 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3847 type = eSymbolTypeObjCIVar;
3848 demangled_is_synthesized = true;
3849 }
3850 } else {
3851 if (nlist.n_value != 0)
3852 symbol_section =
3853 section_info.GetSection(nlist.n_sect, nlist.n_value);
3854 type = eSymbolTypeData;
3855 }
3856 break;
3857
3858 case N_FNAME:
3859 // procedure name (f77 kludge): name,,NO_SECT,0,0
3860 type = eSymbolTypeCompiler;
3861 break;
3862
3863 case N_FUN:
3864 // procedure: name,,n_sect,linenumber,address
3865 if (symbol_name) {
3866 type = eSymbolTypeCode;
3867 symbol_section =
3868 section_info.GetSection(nlist.n_sect, nlist.n_value);
3869
3870 N_FUN_addr_to_sym_idx.insert(
3871 std::make_pair(nlist.n_value, sym_idx));
3872 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003873 // lieu of using nlist_idx in case we ever start trimming entries
3874 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003875 N_FUN_indexes.push_back(sym_idx);
3876 } else {
3877 type = eSymbolTypeCompiler;
3878
3879 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003880 // Copy the size of the function into the original STAB entry
3881 // so we don't have to hunt for it later
Kate Stoneb9c1b512016-09-06 20:57:50 +00003882 symtab->SymbolAtIndex(N_FUN_indexes.back())
3883 ->SetByteSize(nlist.n_value);
3884 N_FUN_indexes.pop_back();
Adrian Prantl05097242018-04-30 16:49:04 +00003885 // We don't really need the end function STAB as it contains
3886 // the size which we already placed with the original symbol,
3887 // so don't add it if we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003888 add_nlist = false;
3889 }
3890 }
3891 break;
3892
3893 case N_STSYM:
3894 // static symbol: name,,n_sect,type,address
3895 N_STSYM_addr_to_sym_idx.insert(
3896 std::make_pair(nlist.n_value, sym_idx));
3897 symbol_section =
3898 section_info.GetSection(nlist.n_sect, nlist.n_value);
3899 if (symbol_name && symbol_name[0]) {
3900 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3901 eSymbolTypeData);
3902 }
3903 break;
3904
3905 case N_LCSYM:
3906 // .lcomm symbol: name,,n_sect,type,address
3907 symbol_section =
3908 section_info.GetSection(nlist.n_sect, nlist.n_value);
3909 type = eSymbolTypeCommonBlock;
3910 break;
3911
3912 case N_BNSYM:
3913 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00003914 // of using nlist_idx in case we ever start trimming entries out
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_ENSYM:
3920 // Set the size of the N_BNSYM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003921 // N_ENSYM so that we can always skip the entire symbol if we need
3922 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003923 // Skip these if we want minimal symbol tables
3924 add_nlist = false;
3925 break;
3926
3927 case N_OPT:
3928 // emitted with gcc2_compiled and in gcc source
3929 type = eSymbolTypeCompiler;
3930 break;
3931
3932 case N_RSYM:
3933 // register sym: name,,NO_SECT,type,register
3934 type = eSymbolTypeVariable;
3935 break;
3936
3937 case N_SLINE:
3938 // src line: 0,,n_sect,linenumber,address
3939 symbol_section =
3940 section_info.GetSection(nlist.n_sect, nlist.n_value);
3941 type = eSymbolTypeLineEntry;
3942 break;
3943
3944 case N_SSYM:
3945 // structure elt: name,,NO_SECT,type,struct_offset
3946 type = eSymbolTypeVariableType;
3947 break;
3948
3949 case N_SO:
3950 // source file name
3951 type = eSymbolTypeSourceFile;
3952 if (symbol_name == NULL) {
3953 add_nlist = false;
3954 if (N_SO_index != UINT32_MAX) {
3955 // Set the size of the N_SO to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003956 // N_SO so that we can always skip the entire N_SO if we need
3957 // to navigate more quickly at the source level when parsing
3958 // STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003959 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3960 symbol_ptr->SetByteSize(sym_idx);
3961 symbol_ptr->SetSizeIsSibling(true);
3962 }
3963 N_NSYM_indexes.clear();
3964 N_INCL_indexes.clear();
3965 N_BRAC_indexes.clear();
3966 N_COMM_indexes.clear();
3967 N_FUN_indexes.clear();
3968 N_SO_index = UINT32_MAX;
3969 } else {
3970 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003971 // lieu of using nlist_idx in case we ever start trimming entries
3972 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003973 const bool N_SO_has_full_path = symbol_name[0] == '/';
3974 if (N_SO_has_full_path) {
3975 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3976 // We have two consecutive N_SO entries where the first
Adrian Prantl05097242018-04-30 16:49:04 +00003977 // contains a directory and the second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003978 sym[sym_idx - 1].GetMangled().SetValue(
3979 ConstString(symbol_name), false);
3980 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3981 add_nlist = false;
3982 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003983 // This is the first entry in a N_SO that contains a
3984 // directory or a full path to the source file
Kate Stoneb9c1b512016-09-06 20:57:50 +00003985 N_SO_index = sym_idx;
3986 }
3987 } else if ((N_SO_index == sym_idx - 1) &&
3988 ((sym_idx - 1) < num_syms)) {
3989 // This is usually the second N_SO entry that contains just the
Adrian Prantl05097242018-04-30 16:49:04 +00003990 // filename, so here we combine it with the first one if we are
3991 // minimizing the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992 const char *so_path =
3993 sym[sym_idx - 1]
3994 .GetMangled()
3995 .GetDemangledName(lldb::eLanguageTypeUnknown)
3996 .AsCString();
3997 if (so_path && so_path[0]) {
3998 std::string full_so_path(so_path);
3999 const size_t double_slash_pos = full_so_path.find("//");
4000 if (double_slash_pos != std::string::npos) {
4001 // The linker has been generating bad N_SO entries with
Adrian Prantl05097242018-04-30 16:49:04 +00004002 // doubled up paths in the format "%s%s" where the first
4003 // string in the DW_AT_comp_dir, and the second is the
4004 // directory for the source file so you end up with a path
4005 // that looks like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004006 FileSpec so_dir(so_path, false);
4007 if (!so_dir.Exists()) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00004008 so_dir.SetFile(&full_so_path[double_slash_pos + 1], false,
4009 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004010 if (so_dir.Exists()) {
4011 // Trim off the incorrect path
4012 full_so_path.erase(0, double_slash_pos + 1);
4013 }
4014 }
4015 }
4016 if (*full_so_path.rbegin() != '/')
4017 full_so_path += '/';
4018 full_so_path += symbol_name;
4019 sym[sym_idx - 1].GetMangled().SetValue(
4020 ConstString(full_so_path.c_str()), false);
4021 add_nlist = false;
4022 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4023 }
4024 } else {
4025 // This could be a relative path to a N_SO
4026 N_SO_index = sym_idx;
4027 }
4028 }
4029 break;
4030
4031 case N_OSO:
4032 // object file name: name,,0,0,st_mtime
4033 type = eSymbolTypeObjectFile;
4034 break;
4035
4036 case N_LSYM:
4037 // local sym: name,,NO_SECT,type,offset
4038 type = eSymbolTypeLocal;
4039 break;
4040
4041 //----------------------------------------------------------------------
4042 // INCL scopes
4043 //----------------------------------------------------------------------
4044 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00004045 // include file beginning: name,,NO_SECT,0,sum We use the current
4046 // number of symbols in the symbol table in lieu of using nlist_idx
4047 // in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004048 N_INCL_indexes.push_back(sym_idx);
4049 type = eSymbolTypeScopeBegin;
4050 break;
4051
4052 case N_EINCL:
4053 // include file end: name,,NO_SECT,0,0
4054 // Set the size of the N_BINCL to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004055 // N_EINCL so that we can always skip the entire symbol if we need
4056 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004057 if (!N_INCL_indexes.empty()) {
4058 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
4059 symbol_ptr->SetByteSize(sym_idx + 1);
4060 symbol_ptr->SetSizeIsSibling(true);
4061 N_INCL_indexes.pop_back();
4062 }
4063 type = eSymbolTypeScopeEnd;
4064 break;
4065
4066 case N_SOL:
4067 // #included file name: name,,n_sect,0,address
4068 type = eSymbolTypeHeaderFile;
4069
4070 // We currently don't use the header files on darwin
4071 add_nlist = false;
4072 break;
4073
4074 case N_PARAMS:
4075 // compiler parameters: name,,NO_SECT,0,0
4076 type = eSymbolTypeCompiler;
4077 break;
4078
4079 case N_VERSION:
4080 // compiler version: name,,NO_SECT,0,0
4081 type = eSymbolTypeCompiler;
4082 break;
4083
4084 case N_OLEVEL:
4085 // compiler -O level: name,,NO_SECT,0,0
4086 type = eSymbolTypeCompiler;
4087 break;
4088
4089 case N_PSYM:
4090 // parameter: name,,NO_SECT,type,offset
4091 type = eSymbolTypeVariable;
4092 break;
4093
4094 case N_ENTRY:
4095 // alternate entry: name,,n_sect,linenumber,address
4096 symbol_section =
4097 section_info.GetSection(nlist.n_sect, nlist.n_value);
4098 type = eSymbolTypeLineEntry;
4099 break;
4100
4101 //----------------------------------------------------------------------
4102 // Left and Right Braces
4103 //----------------------------------------------------------------------
4104 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004105 // left bracket: 0,,NO_SECT,nesting level,address We use the
4106 // current number of symbols in the symbol table in lieu of using
4107 // nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004108 symbol_section =
4109 section_info.GetSection(nlist.n_sect, nlist.n_value);
4110 N_BRAC_indexes.push_back(sym_idx);
4111 type = eSymbolTypeScopeBegin;
4112 break;
4113
4114 case N_RBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004115 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4116 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4117 // can always skip the entire symbol if we need to navigate more
4118 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004119 symbol_section =
4120 section_info.GetSection(nlist.n_sect, nlist.n_value);
4121 if (!N_BRAC_indexes.empty()) {
4122 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4123 symbol_ptr->SetByteSize(sym_idx + 1);
4124 symbol_ptr->SetSizeIsSibling(true);
4125 N_BRAC_indexes.pop_back();
4126 }
4127 type = eSymbolTypeScopeEnd;
4128 break;
4129
4130 case N_EXCL:
4131 // deleted include file: name,,NO_SECT,0,sum
4132 type = eSymbolTypeHeaderFile;
4133 break;
4134
4135 //----------------------------------------------------------------------
4136 // COMM scopes
4137 //----------------------------------------------------------------------
4138 case N_BCOMM:
4139 // begin common: name,,NO_SECT,0,0
4140 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00004141 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004142 type = eSymbolTypeScopeBegin;
4143 N_COMM_indexes.push_back(sym_idx);
4144 break;
4145
4146 case N_ECOML:
4147 // end common (local name): 0,,n_sect,0,address
4148 symbol_section =
4149 section_info.GetSection(nlist.n_sect, nlist.n_value);
4150 LLVM_FALLTHROUGH;
4151
4152 case N_ECOMM:
4153 // end common: name,,n_sect,0,0
4154 // Set the size of the N_BCOMM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004155 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4156 // we need to navigate more quickly at the source level when
4157 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004158 if (!N_COMM_indexes.empty()) {
4159 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4160 symbol_ptr->SetByteSize(sym_idx + 1);
4161 symbol_ptr->SetSizeIsSibling(true);
4162 N_COMM_indexes.pop_back();
4163 }
4164 type = eSymbolTypeScopeEnd;
4165 break;
4166
4167 case N_LENG:
4168 // second stab entry with length information
4169 type = eSymbolTypeAdditional;
4170 break;
4171
4172 default:
4173 break;
4174 }
4175 } else {
4176 // uint8_t n_pext = N_PEXT & nlist.n_type;
4177 uint8_t n_type = N_TYPE & nlist.n_type;
4178 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4179
4180 switch (n_type) {
4181 case N_INDR: {
4182 const char *reexport_name_cstr =
4183 strtab_data.PeekCStr(nlist.n_value);
4184 if (reexport_name_cstr && reexport_name_cstr[0]) {
4185 type = eSymbolTypeReExported;
4186 ConstString reexport_name(
4187 reexport_name_cstr +
4188 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4189 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4190 set_value = false;
4191 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4192 indirect_symbol_names.insert(
4193 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4194 } else
4195 type = eSymbolTypeUndefined;
4196 } break;
4197
4198 case N_UNDF:
4199 if (symbol_name && symbol_name[0]) {
4200 ConstString undefined_name(symbol_name +
4201 ((symbol_name[0] == '_') ? 1 : 0));
4202 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4203 }
4204 LLVM_FALLTHROUGH;
4205
4206 case N_PBUD:
4207 type = eSymbolTypeUndefined;
4208 break;
4209
4210 case N_ABS:
4211 type = eSymbolTypeAbsolute;
4212 break;
4213
4214 case N_SECT: {
4215 symbol_section =
4216 section_info.GetSection(nlist.n_sect, nlist.n_value);
4217
4218 if (!symbol_section) {
4219 // TODO: warn about this?
4220 add_nlist = false;
4221 break;
4222 }
4223
4224 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4225 type = eSymbolTypeException;
4226 } else {
4227 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4228
4229 switch (section_type) {
4230 case S_CSTRING_LITERALS:
4231 type = eSymbolTypeData;
4232 break; // section with only literal C strings
4233 case S_4BYTE_LITERALS:
4234 type = eSymbolTypeData;
4235 break; // section with only 4 byte literals
4236 case S_8BYTE_LITERALS:
4237 type = eSymbolTypeData;
4238 break; // section with only 8 byte literals
4239 case S_LITERAL_POINTERS:
4240 type = eSymbolTypeTrampoline;
4241 break; // section with only pointers to literals
4242 case S_NON_LAZY_SYMBOL_POINTERS:
4243 type = eSymbolTypeTrampoline;
4244 break; // section with only non-lazy symbol pointers
4245 case S_LAZY_SYMBOL_POINTERS:
4246 type = eSymbolTypeTrampoline;
4247 break; // section with only lazy symbol pointers
4248 case S_SYMBOL_STUBS:
4249 type = eSymbolTypeTrampoline;
4250 break; // section with only symbol stubs, byte size of stub in
4251 // the reserved2 field
4252 case S_MOD_INIT_FUNC_POINTERS:
4253 type = eSymbolTypeCode;
4254 break; // section with only function pointers for initialization
4255 case S_MOD_TERM_FUNC_POINTERS:
4256 type = eSymbolTypeCode;
4257 break; // section with only function pointers for termination
4258 case S_INTERPOSING:
4259 type = eSymbolTypeTrampoline;
4260 break; // section with only pairs of function pointers for
4261 // interposing
4262 case S_16BYTE_LITERALS:
4263 type = eSymbolTypeData;
4264 break; // section with only 16 byte literals
4265 case S_DTRACE_DOF:
4266 type = eSymbolTypeInstrumentation;
4267 break;
4268 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4269 type = eSymbolTypeTrampoline;
4270 break;
4271 default:
4272 switch (symbol_section->GetType()) {
4273 case lldb::eSectionTypeCode:
4274 type = eSymbolTypeCode;
4275 break;
4276 case eSectionTypeData:
4277 case eSectionTypeDataCString: // Inlined C string data
4278 case eSectionTypeDataCStringPointers: // Pointers to C string
4279 // data
4280 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4281 // the symbol table
4282 case eSectionTypeData4:
4283 case eSectionTypeData8:
4284 case eSectionTypeData16:
4285 type = eSymbolTypeData;
4286 break;
4287 default:
4288 break;
4289 }
4290 break;
4291 }
4292
4293 if (type == eSymbolTypeInvalid) {
4294 const char *symbol_sect_name =
4295 symbol_section->GetName().AsCString();
4296 if (symbol_section->IsDescendant(text_section_sp.get())) {
4297 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4298 S_ATTR_SELF_MODIFYING_CODE |
4299 S_ATTR_SOME_INSTRUCTIONS))
4300 type = eSymbolTypeData;
4301 else
4302 type = eSymbolTypeCode;
4303 } else if (symbol_section->IsDescendant(
4304 data_section_sp.get()) ||
4305 symbol_section->IsDescendant(
4306 data_dirty_section_sp.get()) ||
4307 symbol_section->IsDescendant(
4308 data_const_section_sp.get())) {
4309 if (symbol_sect_name &&
4310 ::strstr(symbol_sect_name, "__objc") ==
4311 symbol_sect_name) {
4312 type = eSymbolTypeRuntime;
4313
4314 if (symbol_name) {
4315 llvm::StringRef symbol_name_ref(symbol_name);
4316 if (symbol_name_ref.startswith("_OBJC_")) {
4317 static const llvm::StringRef g_objc_v2_prefix_class(
4318 "_OBJC_CLASS_$_");
4319 static const llvm::StringRef g_objc_v2_prefix_metaclass(
4320 "_OBJC_METACLASS_$_");
4321 static const llvm::StringRef g_objc_v2_prefix_ivar(
4322 "_OBJC_IVAR_$_");
4323 if (symbol_name_ref.startswith(
4324 g_objc_v2_prefix_class)) {
4325 symbol_name_non_abi_mangled = symbol_name + 1;
4326 symbol_name =
4327 symbol_name + g_objc_v2_prefix_class.size();
4328 type = eSymbolTypeObjCClass;
4329 demangled_is_synthesized = true;
4330 } else if (symbol_name_ref.startswith(
4331 g_objc_v2_prefix_metaclass)) {
4332 symbol_name_non_abi_mangled = symbol_name + 1;
4333 symbol_name =
4334 symbol_name + g_objc_v2_prefix_metaclass.size();
4335 type = eSymbolTypeObjCMetaClass;
4336 demangled_is_synthesized = true;
4337 } else if (symbol_name_ref.startswith(
4338 g_objc_v2_prefix_ivar)) {
4339 symbol_name_non_abi_mangled = symbol_name + 1;
4340 symbol_name =
4341 symbol_name + g_objc_v2_prefix_ivar.size();
4342 type = eSymbolTypeObjCIVar;
4343 demangled_is_synthesized = true;
4344 }
4345 }
4346 }
4347 } else if (symbol_sect_name &&
4348 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4349 symbol_sect_name) {
4350 type = eSymbolTypeException;
4351 } else {
4352 type = eSymbolTypeData;
4353 }
4354 } else if (symbol_sect_name &&
4355 ::strstr(symbol_sect_name, "__IMPORT") ==
4356 symbol_sect_name) {
4357 type = eSymbolTypeTrampoline;
4358 } else if (symbol_section->IsDescendant(
4359 objc_section_sp.get())) {
4360 type = eSymbolTypeRuntime;
4361 if (symbol_name && symbol_name[0] == '.') {
4362 llvm::StringRef symbol_name_ref(symbol_name);
4363 static const llvm::StringRef g_objc_v1_prefix_class(
4364 ".objc_class_name_");
4365 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4366 symbol_name_non_abi_mangled = symbol_name;
4367 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4368 type = eSymbolTypeObjCClass;
4369 demangled_is_synthesized = true;
4370 }
4371 }
4372 }
4373 }
4374 }
4375 } break;
4376 }
4377 }
4378
4379 if (add_nlist) {
4380 uint64_t symbol_value = nlist.n_value;
4381
4382 if (symbol_name_non_abi_mangled) {
4383 sym[sym_idx].GetMangled().SetMangledName(
4384 ConstString(symbol_name_non_abi_mangled));
4385 sym[sym_idx].GetMangled().SetDemangledName(
4386 ConstString(symbol_name));
4387 } else {
4388 bool symbol_name_is_mangled = false;
4389
4390 if (symbol_name && symbol_name[0] == '_') {
4391 symbol_name_is_mangled = symbol_name[1] == '_';
4392 symbol_name++; // Skip the leading underscore
4393 }
4394
4395 if (symbol_name) {
4396 ConstString const_symbol_name(symbol_name);
4397 sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4398 symbol_name_is_mangled);
4399 }
4400 }
4401
4402 if (is_gsym) {
4403 const char *gsym_name = sym[sym_idx]
4404 .GetMangled()
4405 .GetName(lldb::eLanguageTypeUnknown,
4406 Mangled::ePreferMangled)
4407 .GetCString();
4408 if (gsym_name)
4409 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4410 }
4411
4412 if (symbol_section) {
4413 const addr_t section_file_addr = symbol_section->GetFileAddress();
4414 if (symbol_byte_size == 0 && function_starts_count > 0) {
4415 addr_t symbol_lookup_file_addr = nlist.n_value;
4416 // Do an exact address match for non-ARM addresses, else get the
Adrian Prantl05097242018-04-30 16:49:04 +00004417 // closest since the symbol might be a thumb symbol which has an
4418 // address with bit zero set
Kate Stoneb9c1b512016-09-06 20:57:50 +00004419 FunctionStarts::Entry *func_start_entry =
4420 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4421 if (is_arm && func_start_entry) {
4422 // Verify that the function start address is the symbol address
Adrian Prantl05097242018-04-30 16:49:04 +00004423 // (ARM) or the symbol address + 1 (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004424 if (func_start_entry->addr != symbol_lookup_file_addr &&
4425 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4426 // Not the right entry, NULL it out...
4427 func_start_entry = NULL;
4428 }
4429 }
4430 if (func_start_entry) {
4431 func_start_entry->data = true;
4432
4433 addr_t symbol_file_addr = func_start_entry->addr;
4434 if (is_arm)
4435 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4436
4437 const FunctionStarts::Entry *next_func_start_entry =
4438 function_starts.FindNextEntry(func_start_entry);
4439 const addr_t section_end_file_addr =
4440 section_file_addr + symbol_section->GetByteSize();
4441 if (next_func_start_entry) {
4442 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4443 // Be sure the clear the Thumb address bit when we calculate
Adrian Prantl05097242018-04-30 16:49:04 +00004444 // the size from the current and next address
Kate Stoneb9c1b512016-09-06 20:57:50 +00004445 if (is_arm)
4446 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4447 symbol_byte_size = std::min<lldb::addr_t>(
4448 next_symbol_file_addr - symbol_file_addr,
4449 section_end_file_addr - symbol_file_addr);
4450 } else {
4451 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4452 }
4453 }
4454 }
4455 symbol_value -= section_file_addr;
4456 }
4457
4458 if (is_debug == false) {
4459 if (type == eSymbolTypeCode) {
Adrian Prantl05097242018-04-30 16:49:04 +00004460 // See if we can find a N_FUN entry for any code symbols. If we
4461 // do find a match, and the name matches, then we can merge the
4462 // two into just the function symbol to avoid duplicate entries
4463 // in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004464 std::pair<ValueToSymbolIndexMap::const_iterator,
4465 ValueToSymbolIndexMap::const_iterator>
4466 range;
4467 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4468 if (range.first != range.second) {
4469 bool found_it = false;
4470 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4471 pos != range.second; ++pos) {
4472 if (sym[sym_idx].GetMangled().GetName(
4473 lldb::eLanguageTypeUnknown,
4474 Mangled::ePreferMangled) ==
4475 sym[pos->second].GetMangled().GetName(
4476 lldb::eLanguageTypeUnknown,
4477 Mangled::ePreferMangled)) {
4478 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4479 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004480 // these flags into the N_FUN flags to avoid duplicate
4481 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004482 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4483 sym[pos->second].SetFlags(nlist.n_type << 16 |
4484 nlist.n_desc);
4485 if (resolver_addresses.find(nlist.n_value) !=
4486 resolver_addresses.end())
4487 sym[pos->second].SetType(eSymbolTypeResolver);
4488 sym[sym_idx].Clear();
4489 found_it = true;
4490 break;
4491 }
4492 }
4493 if (found_it)
4494 continue;
4495 } else {
4496 if (resolver_addresses.find(nlist.n_value) !=
4497 resolver_addresses.end())
4498 type = eSymbolTypeResolver;
4499 }
4500 } else if (type == eSymbolTypeData ||
4501 type == eSymbolTypeObjCClass ||
4502 type == eSymbolTypeObjCMetaClass ||
4503 type == eSymbolTypeObjCIVar) {
Adrian Prantl05097242018-04-30 16:49:04 +00004504 // See if we can find a N_STSYM entry for any data symbols. If we
4505 // do find a match, and the name matches, then we can merge the
4506 // two into just the Static symbol to avoid duplicate entries in
4507 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004508 std::pair<ValueToSymbolIndexMap::const_iterator,
4509 ValueToSymbolIndexMap::const_iterator>
4510 range;
4511 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4512 if (range.first != range.second) {
4513 bool found_it = false;
4514 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4515 pos != range.second; ++pos) {
4516 if (sym[sym_idx].GetMangled().GetName(
4517 lldb::eLanguageTypeUnknown,
4518 Mangled::ePreferMangled) ==
4519 sym[pos->second].GetMangled().GetName(
4520 lldb::eLanguageTypeUnknown,
4521 Mangled::ePreferMangled)) {
4522 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4523 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004524 // these flags into the N_STSYM flags to avoid duplicate
4525 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004526 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4527 sym[pos->second].SetFlags(nlist.n_type << 16 |
4528 nlist.n_desc);
4529 sym[sym_idx].Clear();
4530 found_it = true;
4531 break;
4532 }
4533 }
4534 if (found_it)
4535 continue;
4536 } else {
4537 // Combine N_GSYM stab entries with the non stab symbol
4538 const char *gsym_name = sym[sym_idx]
4539 .GetMangled()
4540 .GetName(lldb::eLanguageTypeUnknown,
4541 Mangled::ePreferMangled)
4542 .GetCString();
4543 if (gsym_name) {
4544 ConstNameToSymbolIndexMap::const_iterator pos =
4545 N_GSYM_name_to_sym_idx.find(gsym_name);
4546 if (pos != N_GSYM_name_to_sym_idx.end()) {
4547 const uint32_t GSYM_sym_idx = pos->second;
4548 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00004549 // Copy the address, because often the N_GSYM address has
4550 // an invalid address of zero when the global is a common
4551 // symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00004552 sym[GSYM_sym_idx].GetAddressRef().SetSection(
4553 symbol_section);
4554 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4555 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004556 // these flags into the N_GSYM flags to avoid duplicate
4557 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004558 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
4559 nlist.n_desc);
4560 sym[sym_idx].Clear();
4561 continue;
4562 }
4563 }
4564 }
4565 }
4566 }
4567
4568 sym[sym_idx].SetID(nlist_idx);
4569 sym[sym_idx].SetType(type);
4570 if (set_value) {
4571 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4572 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4573 }
4574 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4575
4576 if (symbol_byte_size > 0)
4577 sym[sym_idx].SetByteSize(symbol_byte_size);
4578
4579 if (demangled_is_synthesized)
4580 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4581
4582 ++sym_idx;
4583 } else {
4584 sym[sym_idx].Clear();
4585 }
4586 }
4587
4588 for (const auto &pos : reexport_shlib_needs_fixup) {
4589 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4590 if (undef_pos != undefined_name_to_desc.end()) {
4591 const uint8_t dylib_ordinal =
4592 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4593 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4594 sym[pos.first].SetReExportedSymbolSharedLibrary(
4595 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4596 }
4597 }
4598 }
4599
4600 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4601
4602 if (function_starts_count > 0) {
4603 uint32_t num_synthetic_function_symbols = 0;
4604 for (i = 0; i < function_starts_count; ++i) {
4605 if (function_starts.GetEntryRef(i).data == false)
4606 ++num_synthetic_function_symbols;
4607 }
4608
4609 if (num_synthetic_function_symbols > 0) {
4610 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4611 num_syms = sym_idx + num_synthetic_function_symbols;
4612 sym = symtab->Resize(num_syms);
4613 }
4614 for (i = 0; i < function_starts_count; ++i) {
4615 const FunctionStarts::Entry *func_start_entry =
4616 function_starts.GetEntryAtIndex(i);
4617 if (func_start_entry->data == false) {
4618 addr_t symbol_file_addr = func_start_entry->addr;
4619 uint32_t symbol_flags = 0;
4620 if (is_arm) {
4621 if (symbol_file_addr & 1)
4622 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4623 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4624 }
4625 Address symbol_addr;
4626 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4627 SectionSP symbol_section(symbol_addr.GetSection());
4628 uint32_t symbol_byte_size = 0;
4629 if (symbol_section) {
4630 const addr_t section_file_addr =
4631 symbol_section->GetFileAddress();
4632 const FunctionStarts::Entry *next_func_start_entry =
4633 function_starts.FindNextEntry(func_start_entry);
4634 const addr_t section_end_file_addr =
4635 section_file_addr + symbol_section->GetByteSize();
4636 if (next_func_start_entry) {
4637 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4638 if (is_arm)
4639 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4640 symbol_byte_size = std::min<lldb::addr_t>(
4641 next_symbol_file_addr - symbol_file_addr,
4642 section_end_file_addr - symbol_file_addr);
4643 } else {
4644 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4645 }
4646 sym[sym_idx].SetID(synthetic_sym_id++);
4647 sym[sym_idx].GetMangled().SetDemangledName(
4648 GetNextSyntheticSymbolName());
4649 sym[sym_idx].SetType(eSymbolTypeCode);
4650 sym[sym_idx].SetIsSynthetic(true);
4651 sym[sym_idx].GetAddressRef() = symbol_addr;
4652 if (symbol_flags)
4653 sym[sym_idx].SetFlags(symbol_flags);
4654 if (symbol_byte_size)
4655 sym[sym_idx].SetByteSize(symbol_byte_size);
4656 ++sym_idx;
4657 }
4658 }
4659 }
4660 }
4661 }
4662 }
4663
Adrian Prantl05097242018-04-30 16:49:04 +00004664 // Trim our symbols down to just what we ended up with after removing any
4665 // symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004666 if (sym_idx < num_syms) {
4667 num_syms = sym_idx;
4668 sym = symtab->Resize(num_syms);
4669 }
4670
4671 // Now synthesize indirect symbols
4672 if (m_dysymtab.nindirectsyms != 0) {
4673 if (indirect_symbol_index_data.GetByteSize()) {
4674 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4675 m_nlist_idx_to_sym_idx.end();
4676
4677 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4678 ++sect_idx) {
4679 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4680 S_SYMBOL_STUBS) {
4681 uint32_t symbol_stub_byte_size =
4682 m_mach_sections[sect_idx].reserved2;
4683 if (symbol_stub_byte_size == 0)
4684 continue;
4685
4686 const uint32_t num_symbol_stubs =
4687 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4688
4689 if (num_symbol_stubs == 0)
4690 continue;
4691
4692 const uint32_t symbol_stub_index_offset =
4693 m_mach_sections[sect_idx].reserved1;
4694 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs;
4695 ++stub_idx) {
4696 const uint32_t symbol_stub_index =
4697 symbol_stub_index_offset + stub_idx;
4698 const lldb::addr_t symbol_stub_addr =
4699 m_mach_sections[sect_idx].addr +
4700 (stub_idx * symbol_stub_byte_size);
4701 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4702 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4703 symbol_stub_offset, 4)) {
4704 const uint32_t stub_sym_id =
4705 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4706 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4707 continue;
4708
4709 NListIndexToSymbolIndexMap::const_iterator index_pos =
4710 m_nlist_idx_to_sym_idx.find(stub_sym_id);
4711 Symbol *stub_symbol = NULL;
4712 if (index_pos != end_index_pos) {
Adrian Prantl05097242018-04-30 16:49:04 +00004713 // We have a remapping from the original nlist index to a
4714 // current symbol index, so just look this up by index
Kate Stoneb9c1b512016-09-06 20:57:50 +00004715 stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4716 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004717 // We need to lookup a symbol using the original nlist symbol
4718 // index since this index is coming from the S_SYMBOL_STUBS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004719 stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4720 }
4721
4722 if (stub_symbol) {
4723 Address so_addr(symbol_stub_addr, section_list);
4724
4725 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4726 // Change the external symbol into a trampoline that makes
Adrian Prantl05097242018-04-30 16:49:04 +00004727 // sense These symbols were N_UNDF N_EXT, and are useless
4728 // to us, so we can re-use them so we don't have to make up
4729 // a synthetic symbol for no good reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004730 if (resolver_addresses.find(symbol_stub_addr) ==
4731 resolver_addresses.end())
4732 stub_symbol->SetType(eSymbolTypeTrampoline);
4733 else
4734 stub_symbol->SetType(eSymbolTypeResolver);
4735 stub_symbol->SetExternal(false);
4736 stub_symbol->GetAddressRef() = so_addr;
4737 stub_symbol->SetByteSize(symbol_stub_byte_size);
4738 } else {
4739 // Make a synthetic symbol to describe the trampoline stub
4740 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4741 if (sym_idx >= num_syms) {
4742 sym = symtab->Resize(++num_syms);
4743 stub_symbol = NULL; // this pointer no longer valid
4744 }
4745 sym[sym_idx].SetID(synthetic_sym_id++);
4746 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4747 if (resolver_addresses.find(symbol_stub_addr) ==
4748 resolver_addresses.end())
4749 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4750 else
4751 sym[sym_idx].SetType(eSymbolTypeResolver);
4752 sym[sym_idx].SetIsSynthetic(true);
4753 sym[sym_idx].GetAddressRef() = so_addr;
4754 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4755 ++sym_idx;
4756 }
4757 } else {
4758 if (log)
4759 log->Warning("symbol stub referencing symbol table symbol "
4760 "%u that isn't in our minimal symbol table, "
4761 "fix this!!!",
4762 stub_sym_id);
4763 }
4764 }
4765 }
4766 }
4767 }
4768 }
4769 }
4770
4771 if (!trie_entries.empty()) {
4772 for (const auto &e : trie_entries) {
4773 if (e.entry.import_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00004774 // Only add indirect symbols from the Trie entries if we didn't have
4775 // a N_INDR nlist entry for this already
Kate Stoneb9c1b512016-09-06 20:57:50 +00004776 if (indirect_symbol_names.find(e.entry.name) ==
4777 indirect_symbol_names.end()) {
4778 // Make a synthetic symbol to describe re-exported symbol.
4779 if (sym_idx >= num_syms)
4780 sym = symtab->Resize(++num_syms);
4781 sym[sym_idx].SetID(synthetic_sym_id++);
4782 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4783 sym[sym_idx].SetType(eSymbolTypeReExported);
4784 sym[sym_idx].SetIsSynthetic(true);
4785 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4786 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4787 sym[sym_idx].SetReExportedSymbolSharedLibrary(
4788 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4789 }
4790 ++sym_idx;
4791 }
4792 }
4793 }
4794 }
4795
4796 // StreamFile s(stdout, false);
4797 // s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4798 // symtab->Dump(&s, NULL, eSortOrderNone);
4799 // Set symbol byte sizes correctly since mach-o nlist entries don't have
4800 // sizes
4801 symtab->CalculateSymbolSizes();
4802
4803 // s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4804 // symtab->Dump(&s, NULL, eSortOrderNone);
4805
4806 return symtab->GetNumSymbols();
4807 }
4808 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004809}
4810
Kate Stoneb9c1b512016-09-06 20:57:50 +00004811void ObjectFileMachO::Dump(Stream *s) {
4812 ModuleSP module_sp(GetModule());
4813 if (module_sp) {
4814 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4815 s->Printf("%p: ", static_cast<void *>(this));
4816 s->Indent();
4817 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4818 s->PutCString("ObjectFileMachO64");
4819 else
4820 s->PutCString("ObjectFileMachO32");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004821
Kate Stoneb9c1b512016-09-06 20:57:50 +00004822 ArchSpec header_arch;
4823 GetArchitecture(header_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004824
Kate Stoneb9c1b512016-09-06 20:57:50 +00004825 *s << ", file = '" << m_file
Adrian Prantl9702c962018-05-11 00:41:20 +00004826 << "', triple = " << header_arch.GetTriple().getTriple() << "\n";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004827
Kate Stoneb9c1b512016-09-06 20:57:50 +00004828 SectionList *sections = GetSectionList();
4829 if (sections)
4830 sections->Dump(s, NULL, true, UINT32_MAX);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004831
Kate Stoneb9c1b512016-09-06 20:57:50 +00004832 if (m_symtab_ap.get())
4833 m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4834 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004835}
4836
Kate Stoneb9c1b512016-09-06 20:57:50 +00004837bool ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4838 const lldb_private::DataExtractor &data,
4839 lldb::offset_t lc_offset,
4840 lldb_private::UUID &uuid) {
4841 uint32_t i;
4842 struct uuid_command load_cmd;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004843
Kate Stoneb9c1b512016-09-06 20:57:50 +00004844 lldb::offset_t offset = lc_offset;
4845 for (i = 0; i < header.ncmds; ++i) {
4846 const lldb::offset_t cmd_offset = offset;
4847 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4848 break;
4849
4850 if (load_cmd.cmd == LC_UUID) {
4851 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4852
4853 if (uuid_bytes) {
4854 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4855 // We pretend these object files have no UUID to prevent crashing.
4856
4857 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4858 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4859 0xbb, 0x14, 0xf0, 0x0d};
4860
4861 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4862 return false;
4863
4864 uuid.SetBytes(uuid_bytes);
4865 return true;
4866 }
4867 return false;
4868 }
4869 offset = cmd_offset + load_cmd.cmdsize;
4870 }
4871 return false;
4872}
4873
Adrian Prantl9702c962018-05-11 00:41:20 +00004874static const char *GetOSName(uint32_t cmd) {
4875 switch (cmd) {
4876 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4877 return "ios";
4878 case llvm::MachO::LC_VERSION_MIN_MACOSX:
4879 return "macosx";
4880 case llvm::MachO::LC_VERSION_MIN_TVOS:
4881 return "tvos";
4882 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4883 return "watchos";
4884 default:
4885 llvm_unreachable("unexpected LC_VERSION load command");
4886 }
4887}
4888
Kate Stoneb9c1b512016-09-06 20:57:50 +00004889bool ObjectFileMachO::GetArchitecture(const llvm::MachO::mach_header &header,
4890 const lldb_private::DataExtractor &data,
4891 lldb::offset_t lc_offset,
4892 ArchSpec &arch) {
4893 arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4894
4895 if (arch.IsValid()) {
4896 llvm::Triple &triple = arch.GetTriple();
4897
4898 // Set OS to an unspecified unknown or a "*" so it can match any OS
4899 triple.setOS(llvm::Triple::UnknownOS);
4900 triple.setOSName(llvm::StringRef());
4901
4902 if (header.filetype == MH_PRELOAD) {
4903 if (header.cputype == CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00004904 // If this is a 32-bit arm binary, and it's a standalone binary, force
4905 // the Vendor to Apple so we don't accidentally pick up the generic
4906 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4907 // frame pointer register; most other armv7 ABIs use a combination of
4908 // r7 and r11.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004909 triple.setVendor(llvm::Triple::Apple);
4910 } else {
4911 // Set vendor to an unspecified unknown or a "*" so it can match any
Adrian Prantl05097242018-04-30 16:49:04 +00004912 // vendor This is required for correct behavior of EFI debugging on
4913 // x86_64
Kate Stoneb9c1b512016-09-06 20:57:50 +00004914 triple.setVendor(llvm::Triple::UnknownVendor);
4915 triple.setVendorName(llvm::StringRef());
4916 }
4917 return true;
4918 } else {
4919 struct load_command load_cmd;
4920
4921 lldb::offset_t offset = lc_offset;
4922 for (uint32_t i = 0; i < header.ncmds; ++i) {
Greg Claytonf4d6de62013-04-24 22:29:28 +00004923 const lldb::offset_t cmd_offset = offset;
4924 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004925 break;
4926
Adrian Prantl9702c962018-05-11 00:41:20 +00004927 uint32_t major, minor, patch;
4928 struct version_min_command version_min;
4929
4930 llvm::SmallString<16> os_name;
4931 llvm::raw_svector_ostream os(os_name);
4932
Kate Stoneb9c1b512016-09-06 20:57:50 +00004933 switch (load_cmd.cmd) {
4934 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004935 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004936 case llvm::MachO::LC_VERSION_MIN_TVOS:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004937 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
Adrian Prantl9702c962018-05-11 00:41:20 +00004938 if (load_cmd.cmdsize != sizeof(version_min))
4939 break;
4940 data.ExtractBytes(cmd_offset,
4941 sizeof(version_min), data.GetByteOrder(),
4942 &version_min);
4943 major = version_min.version >> 16;
4944 minor = (version_min.version >> 8) & 0xffu;
4945 patch = version_min.version & 0xffu;
4946 os << GetOSName(load_cmd.cmd) << major << '.' << minor << '.'
4947 << patch;
4948 triple.setOSName(os.str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004949 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004950 default:
4951 break;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004952 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004953
Greg Claytonf4d6de62013-04-24 22:29:28 +00004954 offset = cmd_offset + load_cmd.cmdsize;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004955 }
4956
4957 if (header.filetype != MH_KEXT_BUNDLE) {
4958 // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
4959 // so lets not say our Vendor is Apple, leave it as an unspecified
4960 // unknown
4961 triple.setVendor(llvm::Triple::UnknownVendor);
4962 triple.setVendorName(llvm::StringRef());
4963 }
Greg Claytonf4d6de62013-04-24 22:29:28 +00004964 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004965 }
4966 return arch.IsValid();
Greg Claytonf4d6de62013-04-24 22:29:28 +00004967}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004968
Kate Stoneb9c1b512016-09-06 20:57:50 +00004969bool ObjectFileMachO::GetUUID(lldb_private::UUID *uuid) {
4970 ModuleSP module_sp(GetModule());
4971 if (module_sp) {
4972 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4973 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4974 return GetUUID(m_header, m_data, offset, *uuid);
4975 }
4976 return false;
Greg Clayton7ab7f892014-05-29 21:33:45 +00004977}
4978
Kate Stoneb9c1b512016-09-06 20:57:50 +00004979uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
4980 uint32_t count = 0;
4981 ModuleSP module_sp(GetModule());
4982 if (module_sp) {
4983 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4984 struct load_command load_cmd;
4985 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4986 std::vector<std::string> rpath_paths;
4987 std::vector<std::string> rpath_relative_paths;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00004988 std::vector<std::string> at_exec_relative_paths;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004989 const bool resolve_path = false; // Don't resolve the dependent file paths
Adrian Prantl05097242018-04-30 16:49:04 +00004990 // since they may not reside on this
4991 // system
Kate Stoneb9c1b512016-09-06 20:57:50 +00004992 uint32_t i;
4993 for (i = 0; i < m_header.ncmds; ++i) {
4994 const uint32_t cmd_offset = offset;
4995 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4996 break;
4997
4998 switch (load_cmd.cmd) {
4999 case LC_RPATH:
5000 case LC_LOAD_DYLIB:
5001 case LC_LOAD_WEAK_DYLIB:
5002 case LC_REEXPORT_DYLIB:
5003 case LC_LOAD_DYLINKER:
5004 case LC_LOADFVMLIB:
5005 case LC_LOAD_UPWARD_DYLIB: {
5006 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5007 const char *path = m_data.PeekCStr(name_offset);
5008 if (path) {
5009 if (load_cmd.cmd == LC_RPATH)
5010 rpath_paths.push_back(path);
5011 else {
5012 if (path[0] == '@') {
5013 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5014 rpath_relative_paths.push_back(path + strlen("@rpath"));
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005015 else if (strncmp(path, "@executable_path",
5016 strlen("@executable_path")) == 0)
5017 at_exec_relative_paths.push_back(path
5018 + strlen("@executable_path"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005019 } else {
5020 FileSpec file_spec(path, resolve_path);
5021 if (files.AppendIfUnique(file_spec))
5022 count++;
5023 }
5024 }
5025 }
5026 } break;
5027
5028 default:
5029 break;
5030 }
5031 offset = cmd_offset + load_cmd.cmdsize;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005032 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005034 FileSpec this_file_spec(m_file);
5035 this_file_spec.ResolvePath();
5036
Kate Stoneb9c1b512016-09-06 20:57:50 +00005037 if (!rpath_paths.empty()) {
5038 // Fixup all LC_RPATH values to be absolute paths
Kate Stoneb9c1b512016-09-06 20:57:50 +00005039 std::string loader_path("@loader_path");
5040 std::string executable_path("@executable_path");
5041 for (auto &rpath : rpath_paths) {
5042 if (rpath.find(loader_path) == 0) {
5043 rpath.erase(0, loader_path.size());
5044 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5045 } else if (rpath.find(executable_path) == 0) {
5046 rpath.erase(0, executable_path.size());
5047 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5048 }
5049 }
5050
5051 for (const auto &rpath_relative_path : rpath_relative_paths) {
5052 for (const auto &rpath : rpath_paths) {
5053 std::string path = rpath;
5054 path += rpath_relative_path;
Adrian Prantl05097242018-04-30 16:49:04 +00005055 // It is OK to resolve this path because we must find a file on disk
5056 // for us to accept it anyway if it is rpath relative.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005057 FileSpec file_spec(path, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005058 if (file_spec.Exists() && files.AppendIfUnique(file_spec)) {
5059 count++;
5060 break;
5061 }
5062 }
5063 }
5064 }
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005065
5066 // We may have @executable_paths but no RPATHS. Figure those out here.
5067 // Only do this if this object file is the executable. We have no way to
5068 // get back to the actual executable otherwise, so we won't get the right
5069 // path.
5070 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5071 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5072 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5073 FileSpec file_spec =
5074 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
Adrian Prantl5ec76fe2018-01-30 18:29:16 +00005075 if (file_spec.Exists() && files.AppendIfUnique(file_spec))
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005076 count++;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005077 }
5078 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005079 }
5080 return count;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005081}
5082
Kate Stoneb9c1b512016-09-06 20:57:50 +00005083lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5084 // If the object file is not an executable it can't hold the entry point.
Adrian Prantl05097242018-04-30 16:49:04 +00005085 // m_entry_point_address is initialized to an invalid address, so we can just
5086 // return that. If m_entry_point_address is valid it means we've found it
5087 // already, so return the cached value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005088
Kate Stoneb9c1b512016-09-06 20:57:50 +00005089 if (!IsExecutable() || m_entry_point_address.IsValid())
Jim Ingham672e6f52011-03-07 23:44:08 +00005090 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00005091
Kate Stoneb9c1b512016-09-06 20:57:50 +00005092 // Otherwise, look for the UnixThread or Thread command. The data for the
Adrian Prantl05097242018-04-30 16:49:04 +00005093 // Thread command is given in /usr/include/mach-o.h, but it is basically:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005094 //
5095 // uint32_t flavor - this is the flavor argument you would pass to
5096 // thread_get_state
5097 // uint32_t count - this is the count of longs in the thread state data
5098 // struct XXX_thread_state state - this is the structure from
5099 // <machine/thread_status.h> corresponding to the flavor.
5100 // <repeat this trio>
5101 //
5102 // So we just keep reading the various register flavors till we find the GPR
5103 // one, then read the PC out of there.
5104 // FIXME: We will need to have a "RegisterContext data provider" class at some
5105 // point that can get all the registers
5106 // out of data in this form & attach them to a given thread. That should
Adrian Prantl05097242018-04-30 16:49:04 +00005107 // underlie the MacOS X User process plugin, and we'll also need it for the
5108 // MacOS X Core File process plugin. When we have that we can also use it
5109 // here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005110 //
5111 // For now we hard-code the offsets and flavors we need:
5112 //
5113 //
Greg Claytonc9660542012-02-05 02:38:54 +00005114
Kate Stoneb9c1b512016-09-06 20:57:50 +00005115 ModuleSP module_sp(GetModule());
5116 if (module_sp) {
5117 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5118 struct load_command load_cmd;
5119 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5120 uint32_t i;
5121 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5122 bool done = false;
5123
5124 for (i = 0; i < m_header.ncmds; ++i) {
5125 const lldb::offset_t cmd_offset = offset;
5126 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5127 break;
5128
5129 switch (load_cmd.cmd) {
5130 case LC_UNIXTHREAD:
5131 case LC_THREAD: {
5132 while (offset < cmd_offset + load_cmd.cmdsize) {
5133 uint32_t flavor = m_data.GetU32(&offset);
5134 uint32_t count = m_data.GetU32(&offset);
5135 if (count == 0) {
5136 // We've gotten off somehow, log and exit;
5137 return m_entry_point_address;
5138 }
5139
5140 switch (m_header.cputype) {
5141 case llvm::MachO::CPU_TYPE_ARM:
5142 if (flavor == 1 ||
5143 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 from
5144 // mach/arm/thread_status.h
Greg Claytonc3776bf2012-02-09 06:16:32 +00005145 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005146 offset += 60; // This is the offset of pc in the GPR thread state
5147 // data structure.
5148 start_address = m_data.GetU32(&offset);
5149 done = true;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005151 break;
5152 case llvm::MachO::CPU_TYPE_ARM64:
5153 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5154 {
5155 offset += 256; // This is the offset of pc in the GPR thread state
5156 // data structure.
5157 start_address = m_data.GetU64(&offset);
5158 done = true;
5159 }
5160 break;
5161 case llvm::MachO::CPU_TYPE_I386:
5162 if (flavor ==
5163 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5164 {
5165 offset += 40; // This is the offset of eip in the GPR thread state
5166 // data structure.
5167 start_address = m_data.GetU32(&offset);
5168 done = true;
5169 }
5170 break;
5171 case llvm::MachO::CPU_TYPE_X86_64:
5172 if (flavor ==
5173 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5174 {
5175 offset += 16 * 8; // This is the offset of rip in the GPR thread
5176 // state data structure.
5177 start_address = m_data.GetU64(&offset);
5178 done = true;
5179 }
5180 break;
5181 default:
5182 return m_entry_point_address;
5183 }
5184 // Haven't found the GPR flavor yet, skip over the data for this
5185 // flavor:
5186 if (done)
5187 break;
5188 offset += count * 4;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005189 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005190 } break;
5191 case LC_MAIN: {
5192 ConstString text_segment_name("__TEXT");
5193 uint64_t entryoffset = m_data.GetU64(&offset);
5194 SectionSP text_segment_sp =
5195 GetSectionList()->FindSectionByName(text_segment_name);
5196 if (text_segment_sp) {
5197 done = true;
5198 start_address = text_segment_sp->GetFileAddress() + entryoffset;
5199 }
5200 } break;
5201
5202 default:
5203 break;
5204 }
5205 if (done)
5206 break;
5207
5208 // Go to the next load command:
5209 offset = cmd_offset + load_cmd.cmdsize;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005210 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005211
5212 if (start_address != LLDB_INVALID_ADDRESS) {
5213 // We got the start address from the load commands, so now resolve that
Adrian Prantl05097242018-04-30 16:49:04 +00005214 // address in the sections of this ObjectFile:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005215 if (!m_entry_point_address.ResolveAddressUsingFileSections(
5216 start_address, GetSectionList())) {
5217 m_entry_point_address.Clear();
5218 }
5219 } else {
5220 // We couldn't read the UnixThread load command - maybe it wasn't there.
Adrian Prantl05097242018-04-30 16:49:04 +00005221 // As a fallback look for the "start" symbol in the main executable.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005222
5223 ModuleSP module_sp(GetModule());
5224
5225 if (module_sp) {
5226 SymbolContextList contexts;
5227 SymbolContext context;
5228 if (module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5229 eSymbolTypeCode, contexts)) {
5230 if (contexts.GetContextAtIndex(0, context))
5231 m_entry_point_address = context.symbol->GetAddress();
5232 }
5233 }
5234 }
5235 }
5236
5237 return m_entry_point_address;
5238}
5239
5240lldb_private::Address ObjectFileMachO::GetHeaderAddress() {
5241 lldb_private::Address header_addr;
5242 SectionList *section_list = GetSectionList();
5243 if (section_list) {
5244 SectionSP text_segment_sp(
5245 section_list->FindSectionByName(GetSegmentNameTEXT()));
5246 if (text_segment_sp) {
5247 header_addr.SetSection(text_segment_sp);
5248 header_addr.SetOffset(0);
5249 }
5250 }
5251 return header_addr;
5252}
5253
5254uint32_t ObjectFileMachO::GetNumThreadContexts() {
5255 ModuleSP module_sp(GetModule());
5256 if (module_sp) {
5257 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5258 if (!m_thread_context_offsets_valid) {
5259 m_thread_context_offsets_valid = true;
5260 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5261 FileRangeArray::Entry file_range;
5262 thread_command thread_cmd;
5263 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5264 const uint32_t cmd_offset = offset;
5265 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5266 break;
5267
5268 if (thread_cmd.cmd == LC_THREAD) {
5269 file_range.SetRangeBase(offset);
5270 file_range.SetByteSize(thread_cmd.cmdsize - 8);
5271 m_thread_context_offsets.Append(file_range);
5272 }
5273 offset = cmd_offset + thread_cmd.cmdsize;
5274 }
5275 }
5276 }
5277 return m_thread_context_offsets.GetSize();
Greg Claytonc3776bf2012-02-09 06:16:32 +00005278}
5279
Jason Molenda3533cec2017-04-06 01:50:11 +00005280std::string ObjectFileMachO::GetIdentifierString() {
5281 std::string result;
5282 ModuleSP module_sp(GetModule());
5283 if (module_sp) {
5284 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005285
Adrian Prantl05097242018-04-30 16:49:04 +00005286 // First, look over the load commands for an LC_NOTE load command with
5287 // data_owner string "kern ver str" & use that if found.
Jason Molenda3533cec2017-04-06 01:50:11 +00005288 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5289 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5290 const uint32_t cmd_offset = offset;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005291 load_command lc;
5292 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5293 break;
5294 if (lc.cmd == LC_NOTE)
5295 {
5296 char data_owner[17];
5297 m_data.CopyData (offset, 16, data_owner);
5298 data_owner[16] = '\0';
5299 offset += 16;
5300 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5301 uint64_t size = m_data.GetU64_unchecked (&offset);
5302
Adrian Prantl05097242018-04-30 16:49:04 +00005303 // "kern ver str" has a uint32_t version and then a nul terminated
5304 // c-string.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005305 if (strcmp ("kern ver str", data_owner) == 0)
5306 {
5307 offset = fileoff;
5308 uint32_t version;
5309 if (m_data.GetU32 (&offset, &version, 1) != nullptr)
5310 {
5311 if (version == 1)
5312 {
5313 uint32_t strsize = size - sizeof (uint32_t);
5314 char *buf = (char*) malloc (strsize);
5315 if (buf)
5316 {
5317 m_data.CopyData (offset, strsize, buf);
5318 buf[strsize - 1] = '\0';
5319 result = buf;
5320 if (buf)
5321 free (buf);
5322 return result;
5323 }
5324 }
5325 }
5326 }
5327 }
5328 offset = cmd_offset + lc.cmdsize;
5329 }
5330
Adrian Prantl05097242018-04-30 16:49:04 +00005331 // Second, make a pass over the load commands looking for an obsolete
5332 // LC_IDENT load command.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005333 offset = MachHeaderSizeFromMagic(m_header.magic);
5334 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5335 const uint32_t cmd_offset = offset;
Jason Molenda3533cec2017-04-06 01:50:11 +00005336 struct ident_command ident_command;
5337 if (m_data.GetU32(&offset, &ident_command, 2) == NULL)
5338 break;
5339 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005340 char *buf = (char *) malloc (ident_command.cmdsize);
Jason Molenda3533cec2017-04-06 01:50:11 +00005341 if (buf != nullptr
5342 && m_data.CopyData (offset, ident_command.cmdsize, buf) == ident_command.cmdsize) {
5343 buf[ident_command.cmdsize - 1] = '\0';
5344 result = buf;
5345 }
5346 if (buf)
5347 free (buf);
5348 }
5349 offset = cmd_offset + ident_command.cmdsize;
5350 }
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005351
Jason Molenda3533cec2017-04-06 01:50:11 +00005352 }
5353 return result;
5354}
5355
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005356bool ObjectFileMachO::GetCorefileMainBinaryInfo (addr_t &address, UUID &uuid) {
5357 address = LLDB_INVALID_ADDRESS;
5358 uuid.Clear();
5359 ModuleSP module_sp(GetModule());
5360 if (module_sp) {
5361 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5362 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5363 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5364 const uint32_t cmd_offset = offset;
5365 load_command lc;
5366 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5367 break;
5368 if (lc.cmd == LC_NOTE)
5369 {
5370 char data_owner[17];
5371 memset (data_owner, 0, sizeof (data_owner));
5372 m_data.CopyData (offset, 16, data_owner);
5373 offset += 16;
5374 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5375 uint64_t size = m_data.GetU64_unchecked (&offset);
5376
Adrian Prantl05097242018-04-30 16:49:04 +00005377 // "main bin spec" (main binary specification) data payload is
5378 // formatted:
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005379 // uint32_t version [currently 1]
5380 // uint32_t type [0 == unspecified, 1 == kernel, 2 == user process]
5381 // uint64_t address [ UINT64_MAX if address not specified ]
5382 // uuid_t uuid [ all zero's if uuid not specified ]
5383 // uint32_t log2_pagesize [ process page size in log base 2, e.g. 4k pages are 12. 0 for unspecified ]
5384
5385 if (strcmp ("main bin spec", data_owner) == 0 && size >= 32)
5386 {
5387 offset = fileoff;
5388 uint32_t version;
5389 if (m_data.GetU32 (&offset, &version, 1) != nullptr && version == 1)
5390 {
5391 uint32_t type = 0;
5392 uuid_t raw_uuid;
Jason Molenda3f608292017-04-13 02:12:32 +00005393 memset (raw_uuid, 0, sizeof (uuid_t));
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005394
5395 if (m_data.GetU32 (&offset, &type, 1)
5396 && m_data.GetU64 (&offset, &address, 1)
5397 && m_data.CopyData (offset, sizeof (uuid_t), raw_uuid) != 0
5398 && uuid.SetBytes (raw_uuid, sizeof (uuid_t)))
5399 {
5400 return true;
5401 }
5402 }
5403 }
5404 }
5405 offset = cmd_offset + lc.cmdsize;
5406 }
5407 }
5408 return false;
5409}
5410
Greg Claytonc3776bf2012-02-09 06:16:32 +00005411lldb::RegisterContextSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005412ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5413 lldb_private::Thread &thread) {
5414 lldb::RegisterContextSP reg_ctx_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00005415
Kate Stoneb9c1b512016-09-06 20:57:50 +00005416 ModuleSP module_sp(GetModule());
5417 if (module_sp) {
5418 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5419 if (!m_thread_context_offsets_valid)
5420 GetNumThreadContexts();
Greg Claytona1743492012-03-13 23:14:29 +00005421
Kate Stoneb9c1b512016-09-06 20:57:50 +00005422 const FileRangeArray::Entry *thread_context_file_range =
5423 m_thread_context_offsets.GetEntryAtIndex(idx);
5424 if (thread_context_file_range) {
Jason Molenda4e7511e2013-03-06 23:19:17 +00005425
Kate Stoneb9c1b512016-09-06 20:57:50 +00005426 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5427 thread_context_file_range->GetByteSize());
Jim Ingham28eb5712012-10-12 17:34:26 +00005428
Kate Stoneb9c1b512016-09-06 20:57:50 +00005429 switch (m_header.cputype) {
5430 case llvm::MachO::CPU_TYPE_ARM64:
5431 reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data));
5432 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005433
Kate Stoneb9c1b512016-09-06 20:57:50 +00005434 case llvm::MachO::CPU_TYPE_ARM:
5435 reg_ctx_sp.reset(new RegisterContextDarwin_arm_Mach(thread, data));
5436 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005437
Kate Stoneb9c1b512016-09-06 20:57:50 +00005438 case llvm::MachO::CPU_TYPE_I386:
5439 reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data));
5440 break;
5441
5442 case llvm::MachO::CPU_TYPE_X86_64:
5443 reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data));
5444 break;
5445 }
Greg Claytonc3776bf2012-02-09 06:16:32 +00005446 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005447 }
5448 return reg_ctx_sp;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005449}
5450
Kate Stoneb9c1b512016-09-06 20:57:50 +00005451ObjectFile::Type ObjectFileMachO::CalculateType() {
5452 switch (m_header.filetype) {
5453 case MH_OBJECT: // 0x1u
5454 if (GetAddressByteSize() == 4) {
5455 // 32 bit kexts are just object files, but they do have a valid
5456 // UUID load command.
5457 UUID uuid;
5458 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005459 // this checking for the UUID load command is not enough we could
5460 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5461 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005462 if (m_strata == eStrataInvalid)
5463 m_strata = eStrataKernel;
5464 return eTypeSharedLibrary;
5465 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005466 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005467 return eTypeObjectFile;
5468
5469 case MH_EXECUTE:
5470 return eTypeExecutable; // 0x2u
5471 case MH_FVMLIB:
5472 return eTypeSharedLibrary; // 0x3u
5473 case MH_CORE:
5474 return eTypeCoreFile; // 0x4u
5475 case MH_PRELOAD:
5476 return eTypeSharedLibrary; // 0x5u
5477 case MH_DYLIB:
5478 return eTypeSharedLibrary; // 0x6u
5479 case MH_DYLINKER:
5480 return eTypeDynamicLinker; // 0x7u
5481 case MH_BUNDLE:
5482 return eTypeSharedLibrary; // 0x8u
5483 case MH_DYLIB_STUB:
5484 return eTypeStubLibrary; // 0x9u
5485 case MH_DSYM:
5486 return eTypeDebugInfo; // 0xAu
5487 case MH_KEXT_BUNDLE:
5488 return eTypeSharedLibrary; // 0xBu
5489 default:
5490 break;
5491 }
5492 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005493}
5494
Kate Stoneb9c1b512016-09-06 20:57:50 +00005495ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5496 switch (m_header.filetype) {
5497 case MH_OBJECT: // 0x1u
5498 {
5499 // 32 bit kexts are just object files, but they do have a valid
5500 // UUID load command.
5501 UUID uuid;
5502 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005503 // this checking for the UUID load command is not enough we could
5504 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5505 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005506 if (m_type == eTypeInvalid)
5507 m_type = eTypeSharedLibrary;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005508
Kate Stoneb9c1b512016-09-06 20:57:50 +00005509 return eStrataKernel;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005510 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005511 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005512 return eStrataUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005513
5514 case MH_EXECUTE: // 0x2u
5515 // Check for the MH_DYLDLINK bit in the flags
5516 if (m_header.flags & MH_DYLDLINK) {
5517 return eStrataUser;
5518 } else {
5519 SectionList *section_list = GetSectionList();
5520 if (section_list) {
5521 static ConstString g_kld_section_name("__KLD");
5522 if (section_list->FindSectionByName(g_kld_section_name))
5523 return eStrataKernel;
5524 }
5525 }
5526 return eStrataRawImage;
5527
5528 case MH_FVMLIB:
5529 return eStrataUser; // 0x3u
5530 case MH_CORE:
5531 return eStrataUnknown; // 0x4u
5532 case MH_PRELOAD:
5533 return eStrataRawImage; // 0x5u
5534 case MH_DYLIB:
5535 return eStrataUser; // 0x6u
5536 case MH_DYLINKER:
5537 return eStrataUser; // 0x7u
5538 case MH_BUNDLE:
5539 return eStrataUser; // 0x8u
5540 case MH_DYLIB_STUB:
5541 return eStrataUser; // 0x9u
5542 case MH_DSYM:
5543 return eStrataUnknown; // 0xAu
5544 case MH_KEXT_BUNDLE:
5545 return eStrataKernel; // 0xBu
5546 default:
5547 break;
5548 }
5549 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005550}
5551
Pavel Labath2272c482018-06-18 15:02:23 +00005552llvm::VersionTuple ObjectFileMachO::GetVersion() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005553 ModuleSP module_sp(GetModule());
5554 if (module_sp) {
5555 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5556 struct dylib_command load_cmd;
5557 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5558 uint32_t version_cmd = 0;
5559 uint64_t version = 0;
5560 uint32_t i;
5561 for (i = 0; i < m_header.ncmds; ++i) {
5562 const lldb::offset_t cmd_offset = offset;
5563 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5564 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005565
Kate Stoneb9c1b512016-09-06 20:57:50 +00005566 if (load_cmd.cmd == LC_ID_DYLIB) {
5567 if (version_cmd == 0) {
5568 version_cmd = load_cmd.cmd;
5569 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5570 break;
5571 version = load_cmd.dylib.current_version;
Greg Claytonc2ff9312012-02-22 19:41:02 +00005572 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005573 break; // Break for now unless there is another more complete version
5574 // number load command in the future.
5575 }
5576 offset = cmd_offset + load_cmd.cmdsize;
5577 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00005578
Kate Stoneb9c1b512016-09-06 20:57:50 +00005579 if (version_cmd == LC_ID_DYLIB) {
Pavel Labath2272c482018-06-18 15:02:23 +00005580 unsigned major = (version & 0xFFFF0000ull) >> 16;
5581 unsigned minor = (version & 0x0000FF00ull) >> 8;
5582 unsigned subminor = (version & 0x000000FFull);
5583 return llvm::VersionTuple(major, minor, subminor);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005584 }
5585 }
Pavel Labath2272c482018-06-18 15:02:23 +00005586 return llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005587}
5588
5589bool ObjectFileMachO::GetArchitecture(ArchSpec &arch) {
5590 ModuleSP module_sp(GetModule());
5591 if (module_sp) {
5592 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5593 return GetArchitecture(m_header, m_data,
5594 MachHeaderSizeFromMagic(m_header.magic), arch);
5595 }
5596 return false;
5597}
5598
Jason Molenda07580ff2018-05-04 00:59:37 +00005599void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process, addr_t &base_addr, UUID &uuid) {
5600 uuid.Clear();
5601 base_addr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005602 if (process && process->GetDynamicLoader()) {
5603 DynamicLoader *dl = process->GetDynamicLoader();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005604 LazyBool using_shared_cache;
5605 LazyBool private_shared_cache;
Jason Molenda07580ff2018-05-04 00:59:37 +00005606 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005607 private_shared_cache);
5608 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005609 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005610 if (log)
Jason Molenda07580ff2018-05-04 00:59:37 +00005611 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 +00005612}
5613
Jason Molenda07580ff2018-05-04 00:59:37 +00005614// From dyld SPI header dyld_process_info.h
5615typedef void *dyld_process_info;
5616struct lldb_copy__dyld_process_cache_info {
5617 uuid_t cacheUUID; // UUID of cache used by process
5618 uint64_t cacheBaseAddress; // load address of dyld shared cache
5619 bool noCache; // process is running without a dyld cache
5620 bool privateCache; // process is using a private copy of its dyld cache
5621};
5622
5623// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with llvm
5624// enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile errors.
5625// So we need to use the actual underlying types of task_t and kern_return_t
5626// below.
5627extern "C" unsigned int /*task_t*/ mach_task_self();
5628
5629void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5630 uuid.Clear();
5631 base_addr = LLDB_INVALID_ADDRESS;
5632
Kate Stoneb9c1b512016-09-06 20:57:50 +00005633#if defined(__APPLE__) && \
5634 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5635 uint8_t *(*dyld_get_all_image_infos)(void);
5636 dyld_get_all_image_infos =
5637 (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5638 if (dyld_get_all_image_infos) {
5639 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5640 if (dyld_all_image_infos_address) {
5641 uint32_t *version = (uint32_t *)
5642 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5643 if (*version >= 13) {
5644 uuid_t *sharedCacheUUID_address = 0;
5645 int wordsize = sizeof(uint8_t *);
5646 if (wordsize == 8) {
5647 sharedCacheUUID_address =
5648 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5649 160); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005650 if (*version >= 15)
5651 base_addr = *(uint64_t *) ((uint8_t *) dyld_all_image_infos_address
5652 + 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +00005653 } else {
5654 sharedCacheUUID_address =
5655 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5656 84); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005657 if (*version >= 15) {
5658 base_addr = 0;
5659 base_addr = *(uint32_t *) ((uint8_t *) dyld_all_image_infos_address
5660 + 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5661 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005662 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005663 uuid.SetBytes(sharedCacheUUID_address);
5664 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005665 }
Jason Molendafd443e92018-02-07 01:28:29 +00005666 } else {
5667 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
Jason Molenda07580ff2018-05-04 00:59:37 +00005668 dyld_process_info (*dyld_process_info_create)(unsigned int /* task_t */ task, uint64_t timestamp, unsigned int /*kern_return_t*/ *kernelError);
5669 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5670 void (*dyld_process_info_release)(dyld_process_info info);
5671
5672 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, unsigned int /*kern_return_t*/ *))
5673 dlsym (RTLD_DEFAULT, "_dyld_process_info_create");
5674 dyld_process_info_get_cache = (void (*)(void *, void *))
5675 dlsym (RTLD_DEFAULT, "_dyld_process_info_get_cache");
5676 dyld_process_info_release = (void (*)(void *))
5677 dlsym (RTLD_DEFAULT, "_dyld_process_info_release");
5678
5679 if (dyld_process_info_create && dyld_process_info_get_cache) {
5680 unsigned int /*kern_return_t */ kern_ret;
5681 dyld_process_info process_info = dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5682 if (process_info) {
5683 struct lldb_copy__dyld_process_cache_info sc_info;
5684 memset (&sc_info, 0, sizeof (struct lldb_copy__dyld_process_cache_info));
5685 dyld_process_info_get_cache (process_info, &sc_info);
5686 if (sc_info.cacheBaseAddress != 0) {
5687 base_addr = sc_info.cacheBaseAddress;
5688 uuid.SetBytes (sc_info.cacheUUID);
5689 }
5690 dyld_process_info_release (process_info);
5691 }
Jason Molendafd443e92018-02-07 01:28:29 +00005692 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005693 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005694 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005695 if (log && uuid.IsValid())
Jason Molenda07580ff2018-05-04 00:59:37 +00005696 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 +00005697#endif
Jason Molenda0e0954c2013-04-16 06:24:42 +00005698}
5699
Pavel Labath2272c482018-06-18 15:02:23 +00005700llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5701 if (!m_min_os_version) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005702 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labath2272c482018-06-18 15:02:23 +00005703 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005704 const lldb::offset_t load_cmd_offset = offset;
5705
5706 version_min_command lc;
5707 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5708 break;
5709 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5710 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5711 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5712 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5713 if (m_data.GetU32(&offset, &lc.version,
5714 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5715 const uint32_t xxxx = lc.version >> 16;
5716 const uint32_t yy = (lc.version >> 8) & 0xffu;
5717 const uint32_t zz = lc.version & 0xffu;
5718 if (xxxx) {
Pavel Labath2272c482018-06-18 15:02:23 +00005719 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5720 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005721 }
Greg Clayton9b234982013-10-24 22:54:08 +00005722 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005723 }
5724 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005725 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005726
Pavel Labath2272c482018-06-18 15:02:23 +00005727 if (!m_min_os_version) {
5728 // Set version to an empty value so we don't keep trying to
5729 m_min_os_version = llvm::VersionTuple();
Greg Clayton9b234982013-10-24 22:54:08 +00005730 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005731 }
5732
Pavel Labath2272c482018-06-18 15:02:23 +00005733 return *m_min_os_version;
Greg Clayton9b234982013-10-24 22:54:08 +00005734}
5735
Kate Stoneb9c1b512016-09-06 20:57:50 +00005736uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions,
5737 uint32_t num_versions) {
5738 if (m_sdk_versions.empty()) {
5739 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5740 bool success = false;
5741 for (uint32_t i = 0; success == false && i < m_header.ncmds; ++i) {
5742 const lldb::offset_t load_cmd_offset = offset;
5743
5744 version_min_command lc;
5745 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5746 break;
5747 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5748 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5749 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5750 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5751 if (m_data.GetU32(&offset, &lc.version,
5752 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5753 const uint32_t xxxx = lc.sdk >> 16;
5754 const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5755 const uint32_t zz = lc.sdk & 0xffu;
5756 if (xxxx) {
5757 m_sdk_versions.push_back(xxxx);
5758 m_sdk_versions.push_back(yy);
5759 m_sdk_versions.push_back(zz);
5760 }
5761 success = true;
Greg Clayton9b234982013-10-24 22:54:08 +00005762 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005763 }
5764 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005765 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005766
5767 if (success == false) {
5768 // Push an invalid value so we don't keep trying to
5769 m_sdk_versions.push_back(UINT32_MAX);
Greg Clayton9b234982013-10-24 22:54:08 +00005770 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005771 }
5772
5773 if (m_sdk_versions.size() > 1 || m_sdk_versions[0] != UINT32_MAX) {
5774 if (versions != NULL && num_versions > 0) {
5775 for (size_t i = 0; i < num_versions; ++i) {
5776 if (i < m_sdk_versions.size())
5777 versions[i] = m_sdk_versions[i];
5778 else
5779 versions[i] = 0;
5780 }
5781 }
5782 return m_sdk_versions.size();
5783 }
5784 // Call the superclasses version that will empty out the data
5785 return ObjectFile::GetSDKVersion(versions, num_versions);
Greg Clayton9b234982013-10-24 22:54:08 +00005786}
5787
Kate Stoneb9c1b512016-09-06 20:57:50 +00005788bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5789 return m_header.filetype == llvm::MachO::MH_DYLINKER;
Greg Clayton08928f32015-02-05 02:01:34 +00005790}
5791
Kate Stoneb9c1b512016-09-06 20:57:50 +00005792bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5793 return m_allow_assembly_emulation_unwind_plans;
Jason Molenda955dcf22016-05-04 03:09:40 +00005794}
5795
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005796//------------------------------------------------------------------
5797// PluginInterface protocol
5798//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00005799lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5800 return GetPluginNameStatic();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005801}
5802
Kate Stoneb9c1b512016-09-06 20:57:50 +00005803uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005804
Kate Stoneb9c1b512016-09-06 20:57:50 +00005805Section *ObjectFileMachO::GetMachHeaderSection() {
Adrian Prantl05097242018-04-30 16:49:04 +00005806 // Find the first address of the mach header which is the first non-zero file
5807 // sized section whose file offset is zero. This is the base file address of
5808 // the mach-o file which can be subtracted from the vmaddr of the other
Kate Stoneb9c1b512016-09-06 20:57:50 +00005809 // segments found in memory and added to the load address
5810 ModuleSP module_sp = GetModule();
5811 if (module_sp) {
5812 SectionList *section_list = GetSectionList();
5813 if (section_list) {
5814 lldb::addr_t mach_base_file_addr = LLDB_INVALID_ADDRESS;
5815 const size_t num_sections = section_list->GetSize();
Greg Clayton07347372015-06-08 21:53:11 +00005816
Kate Stoneb9c1b512016-09-06 20:57:50 +00005817 for (size_t sect_idx = 0; sect_idx < num_sections &&
5818 mach_base_file_addr == LLDB_INVALID_ADDRESS;
5819 ++sect_idx) {
5820 Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5821 if (section && section->GetFileSize() > 0 &&
5822 section->GetFileOffset() == 0 &&
5823 section->IsThreadSpecific() == false &&
5824 module_sp.get() == section->GetModule().get()) {
5825 return section;
Greg Clayton07347372015-06-08 21:53:11 +00005826 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005827 }
Greg Clayton07347372015-06-08 21:53:11 +00005828 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005829 }
5830 return nullptr;
Greg Clayton07347372015-06-08 21:53:11 +00005831}
5832
Kate Stoneb9c1b512016-09-06 20:57:50 +00005833lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
5834 lldb::addr_t mach_header_load_address, const Section *mach_header_section,
5835 const Section *section) {
5836 ModuleSP module_sp = GetModule();
5837 if (module_sp && mach_header_section && section &&
5838 mach_header_load_address != LLDB_INVALID_ADDRESS) {
5839 lldb::addr_t mach_header_file_addr = mach_header_section->GetFileAddress();
5840 if (mach_header_file_addr != LLDB_INVALID_ADDRESS) {
5841 if (section && section->GetFileSize() > 0 &&
5842 section->IsThreadSpecific() == false &&
5843 module_sp.get() == section->GetModule().get()) {
5844 // Ignore __LINKEDIT and __DWARF segments
5845 if (section->GetName() == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00005846 // Only map __LINKEDIT if we have an in memory image and this isn't a
5847 // kernel binary like a kext or mach_kernel.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005848 const bool is_memory_image = (bool)m_process_wp.lock();
5849 const Strata strata = GetStrata();
5850 if (is_memory_image == false || strata == eStrataKernel)
5851 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00005852 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005853 return section->GetFileAddress() - mach_header_file_addr +
5854 mach_header_load_address;
5855 }
Greg Clayton07347372015-06-08 21:53:11 +00005856 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005857 }
5858 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00005859}
5860
Kate Stoneb9c1b512016-09-06 20:57:50 +00005861bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
5862 bool value_is_offset) {
5863 ModuleSP module_sp = GetModule();
5864 if (module_sp) {
5865 size_t num_loaded_sections = 0;
5866 SectionList *section_list = GetSectionList();
5867 if (section_list) {
5868 const size_t num_sections = section_list->GetSize();
Greg Clayton7524e092014-02-06 20:10:16 +00005869
Kate Stoneb9c1b512016-09-06 20:57:50 +00005870 if (value_is_offset) {
5871 // "value" is an offset to apply to each top level segment
5872 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +00005873 // Iterate through the object file sections to find all of the
5874 // sections that size on disk (to avoid __PAGEZERO) and load them
Kate Stoneb9c1b512016-09-06 20:57:50 +00005875 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5876 if (section_sp && section_sp->GetFileSize() > 0 &&
5877 section_sp->IsThreadSpecific() == false &&
5878 module_sp.get() == section_sp->GetModule().get()) {
5879 // Ignore __LINKEDIT and __DWARF segments
5880 if (section_sp->GetName() == GetSegmentNameLINKEDIT()) {
5881 // Only map __LINKEDIT if we have an in memory image and this
Adrian Prantl05097242018-04-30 16:49:04 +00005882 // isn't a kernel binary like a kext or mach_kernel.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005883 const bool is_memory_image = (bool)m_process_wp.lock();
5884 const Strata strata = GetStrata();
5885 if (is_memory_image == false || strata == eStrataKernel)
5886 continue;
Greg Clayton7524e092014-02-06 20:10:16 +00005887 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005888 if (target.GetSectionLoadList().SetSectionLoadAddress(
5889 section_sp, section_sp->GetFileAddress() + value))
5890 ++num_loaded_sections;
5891 }
Greg Clayton7524e092014-02-06 20:10:16 +00005892 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005893 } else {
5894 // "value" is the new base address of the mach_header, adjust each
5895 // section accordingly
5896
5897 Section *mach_header_section = GetMachHeaderSection();
5898 if (mach_header_section) {
5899 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5900 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5901
5902 lldb::addr_t section_load_addr =
5903 CalculateSectionLoadAddressForMemoryImage(
5904 value, mach_header_section, section_sp.get());
5905 if (section_load_addr != LLDB_INVALID_ADDRESS) {
5906 if (target.GetSectionLoadList().SetSectionLoadAddress(
5907 section_sp, section_load_addr))
5908 ++num_loaded_sections;
5909 }
5910 }
5911 }
5912 }
Greg Clayton7524e092014-02-06 20:10:16 +00005913 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005914 return num_loaded_sections > 0;
5915 }
5916 return false;
Greg Clayton7524e092014-02-06 20:10:16 +00005917}
5918
Kate Stoneb9c1b512016-09-06 20:57:50 +00005919bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00005920 const FileSpec &outfile, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005921 if (process_sp) {
5922 Target &target = process_sp->GetTarget();
5923 const ArchSpec target_arch = target.GetArchitecture();
5924 const llvm::Triple &target_triple = target_arch.GetTriple();
5925 if (target_triple.getVendor() == llvm::Triple::Apple &&
5926 (target_triple.getOS() == llvm::Triple::MacOSX ||
5927 target_triple.getOS() == llvm::Triple::IOS ||
5928 target_triple.getOS() == llvm::Triple::WatchOS ||
5929 target_triple.getOS() == llvm::Triple::TvOS)) {
5930 bool make_core = false;
5931 switch (target_arch.GetMachine()) {
5932 case llvm::Triple::aarch64:
5933 case llvm::Triple::arm:
5934 case llvm::Triple::thumb:
5935 case llvm::Triple::x86:
5936 case llvm::Triple::x86_64:
5937 make_core = true;
5938 break;
5939 default:
5940 error.SetErrorStringWithFormat("unsupported core architecture: %s",
5941 target_triple.str().c_str());
5942 break;
5943 }
5944
5945 if (make_core) {
5946 std::vector<segment_command_64> segment_load_commands;
5947 // uint32_t range_info_idx = 0;
5948 MemoryRegionInfo range_info;
Zachary Turner97206d52017-05-12 04:51:55 +00005949 Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005950 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
5951 const ByteOrder byte_order = target_arch.GetByteOrder();
5952 if (range_error.Success()) {
5953 while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
5954 const addr_t addr = range_info.GetRange().GetRangeBase();
5955 const addr_t size = range_info.GetRange().GetByteSize();
5956
5957 if (size == 0)
5958 break;
5959
5960 // Calculate correct protections
5961 uint32_t prot = 0;
5962 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
5963 prot |= VM_PROT_READ;
5964 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
5965 prot |= VM_PROT_WRITE;
5966 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
5967 prot |= VM_PROT_EXECUTE;
5968
5969 // printf ("[%3u] [0x%16.16" PRIx64 " -
5970 // 0x%16.16" PRIx64 ") %c%c%c\n",
5971 // range_info_idx,
5972 // addr,
5973 // size,
5974 // (prot & VM_PROT_READ ) ? 'r' :
5975 // '-',
5976 // (prot & VM_PROT_WRITE ) ? 'w' :
5977 // '-',
5978 // (prot & VM_PROT_EXECUTE) ? 'x' :
5979 // '-');
5980
5981 if (prot != 0) {
5982 uint32_t cmd_type = LC_SEGMENT_64;
5983 uint32_t segment_size = sizeof(segment_command_64);
5984 if (addr_byte_size == 4) {
5985 cmd_type = LC_SEGMENT;
5986 segment_size = sizeof(segment_command);
5987 }
5988 segment_command_64 segment = {
5989 cmd_type, // uint32_t cmd;
5990 segment_size, // uint32_t cmdsize;
5991 {0}, // char segname[16];
5992 addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
5993 size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
5994 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
5995 size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
5996 prot, // uint32_t maxprot;
5997 prot, // uint32_t initprot;
5998 0, // uint32_t nsects;
5999 0}; // uint32_t flags;
6000 segment_load_commands.push_back(segment);
6001 } else {
6002 // No protections and a size of 1 used to be returned from old
6003 // debugservers when we asked about a region that was past the
6004 // last memory region and it indicates the end...
6005 if (size == 1)
6006 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006007 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006008
Kate Stoneb9c1b512016-09-06 20:57:50 +00006009 range_error = process_sp->GetMemoryRegionInfo(
6010 range_info.GetRange().GetRangeEnd(), range_info);
6011 if (range_error.Fail())
6012 break;
6013 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006014
Kate Stoneb9c1b512016-09-06 20:57:50 +00006015 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
Greg Claytona2715cf2014-06-13 00:54:12 +00006016
Kate Stoneb9c1b512016-09-06 20:57:50 +00006017 mach_header_64 mach_header;
6018 if (addr_byte_size == 8) {
6019 mach_header.magic = MH_MAGIC_64;
6020 } else {
6021 mach_header.magic = MH_MAGIC;
6022 }
6023 mach_header.cputype = target_arch.GetMachOCPUType();
6024 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6025 mach_header.filetype = MH_CORE;
6026 mach_header.ncmds = segment_load_commands.size();
6027 mach_header.flags = 0;
6028 mach_header.reserved = 0;
6029 ThreadList &thread_list = process_sp->GetThreadList();
6030 const uint32_t num_threads = thread_list.GetSize();
Greg Claytona2715cf2014-06-13 00:54:12 +00006031
Adrian Prantl05097242018-04-30 16:49:04 +00006032 // Make an array of LC_THREAD data items. Each one contains the
6033 // contents of the LC_THREAD load command. The data doesn't contain
6034 // the load command + load command size, we will add the load command
6035 // and load command size as we emit the data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006036 std::vector<StreamString> LC_THREAD_datas(num_threads);
6037 for (auto &LC_THREAD_data : LC_THREAD_datas) {
6038 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6039 LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6040 LC_THREAD_data.SetByteOrder(byte_order);
6041 }
6042 for (uint32_t thread_idx = 0; thread_idx < num_threads;
6043 ++thread_idx) {
6044 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6045 if (thread_sp) {
6046 switch (mach_header.cputype) {
6047 case llvm::MachO::CPU_TYPE_ARM64:
6048 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6049 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6050 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006051
Kate Stoneb9c1b512016-09-06 20:57:50 +00006052 case llvm::MachO::CPU_TYPE_ARM:
6053 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6054 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6055 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006056
Kate Stoneb9c1b512016-09-06 20:57:50 +00006057 case llvm::MachO::CPU_TYPE_I386:
6058 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6059 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6060 break;
Jason Molenda22952582014-11-12 01:11:36 +00006061
Kate Stoneb9c1b512016-09-06 20:57:50 +00006062 case llvm::MachO::CPU_TYPE_X86_64:
6063 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6064 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6065 break;
6066 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006067 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006068 }
6069
6070 // The size of the load command is the size of the segments...
6071 if (addr_byte_size == 8) {
6072 mach_header.sizeofcmds = segment_load_commands.size() *
6073 sizeof(struct segment_command_64);
6074 } else {
6075 mach_header.sizeofcmds =
6076 segment_load_commands.size() * sizeof(struct segment_command);
6077 }
6078
6079 // and the size of all LC_THREAD load command
6080 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6081 ++mach_header.ncmds;
6082 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6083 }
6084
6085 printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x "
6086 "0x%8.8x 0x%8.8x\n",
6087 mach_header.magic, mach_header.cputype, mach_header.cpusubtype,
6088 mach_header.filetype, mach_header.ncmds,
6089 mach_header.sizeofcmds, mach_header.flags,
6090 mach_header.reserved);
6091
6092 // Write the mach header
6093 buffer.PutHex32(mach_header.magic);
6094 buffer.PutHex32(mach_header.cputype);
6095 buffer.PutHex32(mach_header.cpusubtype);
6096 buffer.PutHex32(mach_header.filetype);
6097 buffer.PutHex32(mach_header.ncmds);
6098 buffer.PutHex32(mach_header.sizeofcmds);
6099 buffer.PutHex32(mach_header.flags);
6100 if (addr_byte_size == 8) {
6101 buffer.PutHex32(mach_header.reserved);
6102 }
6103
6104 // Skip the mach header and all load commands and align to the next
6105 // 0x1000 byte boundary
6106 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6107 if (file_offset & 0x00000fff) {
6108 file_offset += 0x00001000ull;
6109 file_offset &= (~0x00001000ull + 1);
6110 }
6111
6112 for (auto &segment : segment_load_commands) {
6113 segment.fileoff = file_offset;
6114 file_offset += segment.filesize;
6115 }
6116
6117 // Write out all of the LC_THREAD load commands
6118 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6119 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6120 buffer.PutHex32(LC_THREAD);
6121 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
Zachary Turnerc1564272016-11-16 21:15:24 +00006122 buffer.Write(LC_THREAD_data.GetString().data(),
6123 LC_THREAD_data_size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006124 }
6125
6126 // Write out all of the segment load commands
6127 for (const auto &segment : segment_load_commands) {
6128 printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6129 ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6130 ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6131 segment.cmd, segment.cmdsize, segment.vmaddr,
6132 segment.vmaddr + segment.vmsize, segment.fileoff,
6133 segment.filesize, segment.maxprot, segment.initprot,
6134 segment.nsects, segment.flags);
6135
6136 buffer.PutHex32(segment.cmd);
6137 buffer.PutHex32(segment.cmdsize);
6138 buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6139 if (addr_byte_size == 8) {
6140 buffer.PutHex64(segment.vmaddr);
6141 buffer.PutHex64(segment.vmsize);
6142 buffer.PutHex64(segment.fileoff);
6143 buffer.PutHex64(segment.filesize);
6144 } else {
6145 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6146 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6147 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6148 buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6149 }
6150 buffer.PutHex32(segment.maxprot);
6151 buffer.PutHex32(segment.initprot);
6152 buffer.PutHex32(segment.nsects);
6153 buffer.PutHex32(segment.flags);
6154 }
6155
6156 File core_file;
6157 std::string core_file_path(outfile.GetPath());
6158 error = core_file.Open(core_file_path.c_str(),
6159 File::eOpenOptionWrite |
6160 File::eOpenOptionTruncate |
6161 File::eOpenOptionCanCreate);
6162 if (error.Success()) {
6163 // Read 1 page at a time
6164 uint8_t bytes[0x1000];
6165 // Write the mach header and load commands out to the core file
6166 size_t bytes_written = buffer.GetString().size();
6167 error = core_file.Write(buffer.GetString().data(), bytes_written);
6168 if (error.Success()) {
6169 // Now write the file data for all memory segments in the process
6170 for (const auto &segment : segment_load_commands) {
6171 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6172 error.SetErrorStringWithFormat(
6173 "unable to seek to offset 0x%" PRIx64 " in '%s'",
6174 segment.fileoff, core_file_path.c_str());
6175 break;
6176 }
6177
6178 printf("Saving %" PRId64
6179 " bytes of data for memory region at 0x%" PRIx64 "\n",
6180 segment.vmsize, segment.vmaddr);
6181 addr_t bytes_left = segment.vmsize;
6182 addr_t addr = segment.vmaddr;
Zachary Turner97206d52017-05-12 04:51:55 +00006183 Status memory_read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006184 while (bytes_left > 0 && error.Success()) {
6185 const size_t bytes_to_read =
6186 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6187 const size_t bytes_read = process_sp->ReadMemory(
6188 addr, bytes, bytes_to_read, memory_read_error);
6189 if (bytes_read == bytes_to_read) {
6190 size_t bytes_written = bytes_read;
6191 error = core_file.Write(bytes, bytes_written);
6192 bytes_left -= bytes_read;
6193 addr += bytes_read;
6194 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00006195 // Some pages within regions are not readable, those should
6196 // be zero filled
Kate Stoneb9c1b512016-09-06 20:57:50 +00006197 memset(bytes, 0, bytes_to_read);
6198 size_t bytes_written = bytes_to_read;
6199 error = core_file.Write(bytes, bytes_written);
6200 bytes_left -= bytes_to_read;
6201 addr += bytes_to_read;
6202 }
6203 }
6204 }
6205 }
6206 }
6207 } else {
6208 error.SetErrorString(
6209 "process doesn't support getting memory region info");
Greg Claytona2715cf2014-06-13 00:54:12 +00006210 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006211 }
6212 return true; // This is the right plug to handle saving core files for
6213 // this process
Greg Claytona2715cf2014-06-13 00:54:12 +00006214 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006215 }
6216 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00006217}