blob: 653613a8255deccdfd12cbabc5651b2e9524aba0 [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"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Core/Section.h"
27#include "lldb/Core/StreamFile.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000028#include "lldb/Host/Host.h"
Jason Molenda5635f772013-03-21 03:36:01 +000029#include "lldb/Symbol/DWARFCallFrameInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Symbol/ObjectFile.h"
Jason Molenda13becd42016-07-29 00:18:39 +000031#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000032#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton26b47e22012-04-18 05:19:20 +000033#include "lldb/Target/Platform.h"
Greg Claytonc9660542012-02-05 02:38:54 +000034#include "lldb/Target/Process.h"
Greg Clayton7524e092014-02-06 20:10:16 +000035#include "lldb/Target/SectionLoadList.h"
Greg Clayton26b47e22012-04-18 05:19:20 +000036#include "lldb/Target/Target.h"
Greg Claytona2715cf2014-06-13 00:54:12 +000037#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadList.h"
Pavel Labath5f19b902017-11-13 16:16:33 +000039#include "lldb/Utility/ArchSpec.h"
Pavel Labath50251fc2017-12-21 10:54:30 +000040#include "lldb/Utility/DataBuffer.h"
Zachary Turner5713a052017-03-22 18:40:07 +000041#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000042#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000043#include "lldb/Utility/RegisterValue.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
Pavel Labath77044732018-09-12 12:26:05 +000049#include "lldb/Host/SafeMachO.h"
Jim Ingham46d005d2014-04-02 22:53:21 +000050
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:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001164 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165
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)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001171 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001173 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174
1175 case eSectionTypeContainer:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001176 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177
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:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001190 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191
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:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001215 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216
1217 case eSectionTypeEHFrame:
1218 case eSectionTypeARMexidx:
1219 case eSectionTypeARMextab:
1220 case eSectionTypeCompactUnwind:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001221 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222
1223 case eSectionTypeAbsoluteAddress:
1224 case eSectionTypeELFSymbolTable:
1225 case eSectionTypeELFDynamicSymbols:
1226 case eSectionTypeELFRelocationEntries:
1227 case eSectionTypeELFDynamicLinkInfo:
1228 case eSectionTypeOther:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001229 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 }
1231 }
1232 }
1233
1234 const SymbolType symbol_type = symbol->GetType();
1235 switch (symbol_type) {
1236 case eSymbolTypeAny:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001237 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 case eSymbolTypeAbsolute:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001239 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240
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)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001248 return AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001250 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251
1252 case eSymbolTypeData:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001253 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 case eSymbolTypeRuntime:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001255 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 case eSymbolTypeException:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001257 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 case eSymbolTypeSourceFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001259 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260 case eSymbolTypeHeaderFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001261 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 case eSymbolTypeObjectFile:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001263 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264 case eSymbolTypeCommonBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001265 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 case eSymbolTypeBlock:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001267 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 case eSymbolTypeLocal:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001269 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 case eSymbolTypeParam:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001271 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 case eSymbolTypeVariable:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001273 return AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 case eSymbolTypeVariableType:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001275 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276 case eSymbolTypeLineEntry:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001277 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 case eSymbolTypeLineHeader:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001279 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280 case eSymbolTypeScopeBegin:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001281 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 case eSymbolTypeScopeEnd:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001283 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 case eSymbolTypeAdditional:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001285 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 case eSymbolTypeCompiler:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001287 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 case eSymbolTypeInstrumentation:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001289 return AddressClass::eDebug;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 case eSymbolTypeUndefined:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001291 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292 case eSymbolTypeObjCClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001293 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 case eSymbolTypeObjCMetaClass:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001295 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 case eSymbolTypeObjCIVar:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001297 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 case eSymbolTypeReExported:
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001299 return AddressClass::eRuntime;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 }
1301 }
1302 }
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00001303 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304}
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);
Pavel Labath2f93fd12018-06-26 15:12:20 +00002090 dsc_uuid = UUID::fromOptionalData(
2091 dsc_header_data.GetData(&offset, sizeof(uuid_t)), sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002092 }
Jason Molendafd443e92018-02-07 01:28:29 +00002093 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2094 if (log && dsc_uuid.IsValid()) {
2095 log->Printf("Shared cache %s has UUID %s", dyld_shared_cache.GetPath().c_str(),
2096 dsc_uuid.GetAsString().c_str());
2097 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098 return dsc_uuid;
Jason Molenda649a6072015-11-10 05:21:54 +00002099}
2100
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101size_t ObjectFileMachO::ParseSymtab() {
Pavel Labathf9d16472017-05-15 13:02:37 +00002102 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2103 Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104 m_file.GetFilename().AsCString(""));
2105 ModuleSP module_sp(GetModule());
2106 if (!module_sp)
2107 return 0;
2108
2109 struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2110 struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2111 struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2112 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2113 FunctionStarts function_starts;
2114 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2115 uint32_t i;
2116 FileSpecList dylib_files;
2117 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2118 static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2119 static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2120 static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2121
2122 for (i = 0; i < m_header.ncmds; ++i) {
2123 const lldb::offset_t cmd_offset = offset;
2124 // Read in the load command and load command size
2125 struct load_command lc;
2126 if (m_data.GetU32(&offset, &lc, 2) == NULL)
2127 break;
2128 // Watch for the symbol table load command
2129 switch (lc.cmd) {
2130 case LC_SYMTAB:
2131 symtab_load_command.cmd = lc.cmd;
2132 symtab_load_command.cmdsize = lc.cmdsize;
2133 // Read in the rest of the symtab load command
2134 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2135 0) // fill in symoff, nsyms, stroff, strsize fields
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002136 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002137 if (symtab_load_command.symoff == 0) {
2138 if (log)
2139 module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2140 return 0;
2141 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002142
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 if (symtab_load_command.stroff == 0) {
2144 if (log)
2145 module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2146 return 0;
2147 }
Greg Clayton77ccca72011-12-30 00:32:24 +00002148
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149 if (symtab_load_command.nsyms == 0) {
2150 if (log)
2151 module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
2152 return 0;
2153 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002154
Kate Stoneb9c1b512016-09-06 20:57:50 +00002155 if (symtab_load_command.strsize == 0) {
2156 if (log)
2157 module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2158 return 0;
2159 }
2160 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002161
Kate Stoneb9c1b512016-09-06 20:57:50 +00002162 case LC_DYLD_INFO:
2163 case LC_DYLD_INFO_ONLY:
2164 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2165 dyld_info.cmd = lc.cmd;
2166 dyld_info.cmdsize = lc.cmdsize;
2167 } else {
2168 memset(&dyld_info, 0, sizeof(dyld_info));
2169 }
2170 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00002171
Kate Stoneb9c1b512016-09-06 20:57:50 +00002172 case LC_LOAD_DYLIB:
2173 case LC_LOAD_WEAK_DYLIB:
2174 case LC_REEXPORT_DYLIB:
2175 case LC_LOADFVMLIB:
2176 case LC_LOAD_UPWARD_DYLIB: {
2177 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2178 const char *path = m_data.PeekCStr(name_offset);
2179 if (path) {
2180 FileSpec file_spec(path, false);
2181 // Strip the path if there is @rpath, @executable, etc so we just use
2182 // the basename
2183 if (path[0] == '@')
2184 file_spec.GetDirectory().Clear();
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002185
Kate Stoneb9c1b512016-09-06 20:57:50 +00002186 if (lc.cmd == LC_REEXPORT_DYLIB) {
2187 m_reexported_dylibs.AppendIfUnique(file_spec);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002188 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189
2190 dylib_files.Append(file_spec);
2191 }
2192 } break;
2193
2194 case LC_FUNCTION_STARTS:
2195 function_starts_load_command.cmd = lc.cmd;
2196 function_starts_load_command.cmdsize = lc.cmdsize;
2197 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2198 NULL) // fill in symoff, nsyms, stroff, strsize fields
2199 memset(&function_starts_load_command, 0,
2200 sizeof(function_starts_load_command));
2201 break;
2202
2203 default:
2204 break;
2205 }
2206 offset = cmd_offset + lc.cmdsize;
2207 }
2208
2209 if (symtab_load_command.cmd) {
2210 Symtab *symtab = m_symtab_ap.get();
2211 SectionList *section_list = GetSectionList();
2212 if (section_list == NULL)
2213 return 0;
2214
2215 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2216 const ByteOrder byte_order = m_data.GetByteOrder();
2217 bool bit_width_32 = addr_byte_size == 4;
2218 const size_t nlist_byte_size =
2219 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2220
2221 DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size);
2222 DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size);
2223 DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size);
2224 DataExtractor indirect_symbol_index_data(NULL, 0, byte_order,
2225 addr_byte_size);
2226 DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size);
2227
2228 const addr_t nlist_data_byte_size =
2229 symtab_load_command.nsyms * nlist_byte_size;
2230 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2231 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2232
2233 ProcessSP process_sp(m_process_wp.lock());
2234 Process *process = process_sp.get();
2235
2236 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2237
2238 if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2239 Target &target = process->GetTarget();
2240
2241 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2242
2243 SectionSP linkedit_section_sp(
2244 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2245 // Reading mach file from memory in a process or core file...
2246
2247 if (linkedit_section_sp) {
2248 addr_t linkedit_load_addr =
2249 linkedit_section_sp->GetLoadBaseAddress(&target);
2250 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2251 // We might be trying to access the symbol table before the
Adrian Prantl05097242018-04-30 16:49:04 +00002252 // __LINKEDIT's load address has been set in the target. We can't
2253 // fail to read the symbol table, so calculate the right address
2254 // manually
Kate Stoneb9c1b512016-09-06 20:57:50 +00002255 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2256 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2257 }
2258
2259 const addr_t linkedit_file_offset =
2260 linkedit_section_sp->GetFileOffset();
2261 const addr_t symoff_addr = linkedit_load_addr +
2262 symtab_load_command.symoff -
2263 linkedit_file_offset;
2264 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2265 linkedit_file_offset;
2266
2267 bool data_was_read = false;
2268
2269#if defined(__APPLE__) && \
2270 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2271 if (m_header.flags & 0x80000000u &&
2272 process->GetAddressByteSize() == sizeof(void *)) {
2273 // This mach-o memory file is in the dyld shared cache. If this
2274 // program is not remote and this is iOS, then this process will
Adrian Prantl05097242018-04-30 16:49:04 +00002275 // share the same shared cache as the process we are debugging and we
2276 // can read the entire __LINKEDIT from the address space in this
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277 // process. This is a needed optimization that is used for local iOS
2278 // debugging only since all shared libraries in the shared cache do
2279 // not have corresponding files that exist in the file system of the
2280 // device. They have been combined into a single file. This means we
2281 // always have to load these files from memory. All of the symbol and
2282 // string tables from all of the __LINKEDIT sections from the shared
2283 // libraries in the shared cache have been merged into a single large
2284 // symbol and string table. Reading all of this symbol and string
Adrian Prantl05097242018-04-30 16:49:04 +00002285 // table data across can slow down debug launch times, so we optimize
2286 // this by reading the memory for the __LINKEDIT section from this
2287 // process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288
Jason Molenda07580ff2018-05-04 00:59:37 +00002289 UUID lldb_shared_cache;
2290 addr_t lldb_shared_cache_addr;
2291 GetLLDBSharedCacheUUID (lldb_shared_cache_addr, lldb_shared_cache);
2292 UUID process_shared_cache;
2293 addr_t process_shared_cache_addr;
2294 GetProcessSharedCacheUUID(process, process_shared_cache_addr, process_shared_cache);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295 bool use_lldb_cache = true;
2296 if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
Jason Molenda07580ff2018-05-04 00:59:37 +00002297 (lldb_shared_cache != process_shared_cache
2298 || process_shared_cache_addr != lldb_shared_cache_addr)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299 use_lldb_cache = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002300 }
2301
2302 PlatformSP platform_sp(target.GetPlatform());
2303 if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2304 data_was_read = true;
2305 nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2306 eByteOrderLittle);
2307 strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2308 eByteOrderLittle);
2309 if (function_starts_load_command.cmd) {
2310 const addr_t func_start_addr =
2311 linkedit_load_addr + function_starts_load_command.dataoff -
2312 linkedit_file_offset;
2313 function_starts_data.SetData(
2314 (void *)func_start_addr,
2315 function_starts_load_command.datasize, eByteOrderLittle);
2316 }
2317 }
2318 }
2319#endif
2320
2321 if (!data_was_read) {
2322 // Always load dyld - the dynamic linker - from memory if we didn't
Adrian Prantl05097242018-04-30 16:49:04 +00002323 // find a binary anywhere else. lldb will not register
2324 // dylib/framework/bundle loads/unloads if we don't have the dyld
2325 // symbols, we force dyld to load from memory despite the user's
Kate Stoneb9c1b512016-09-06 20:57:50 +00002326 // target.memory-module-load-level setting.
2327 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2328 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2329 DataBufferSP nlist_data_sp(
2330 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2331 if (nlist_data_sp)
2332 nlist_data.SetData(nlist_data_sp, 0,
2333 nlist_data_sp->GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002334 if (m_dysymtab.nindirectsyms != 0) {
2335 const addr_t indirect_syms_addr = linkedit_load_addr +
2336 m_dysymtab.indirectsymoff -
2337 linkedit_file_offset;
2338 DataBufferSP indirect_syms_data_sp(
2339 ReadMemory(process_sp, indirect_syms_addr,
2340 m_dysymtab.nindirectsyms * 4));
2341 if (indirect_syms_data_sp)
2342 indirect_symbol_index_data.SetData(
2343 indirect_syms_data_sp, 0,
2344 indirect_syms_data_sp->GetByteSize());
Jason Molendab0d33e92018-09-06 00:55:27 +00002345 // If this binary is outside the shared cache,
2346 // cache the string table.
2347 // Binaries in the shared cache all share a giant string table, and
2348 // we can't share the string tables across multiple ObjectFileMachO's,
2349 // so we'd end up re-reading this mega-strtab for every binary
2350 // in the shared cache - it would be a big perf problem.
2351 // For binaries outside the shared cache, it's faster to read the
2352 // entire strtab at once instead of piece-by-piece as we process
2353 // the nlist records.
2354 if ((m_header.flags & 0x80000000u) == 0) {
2355 DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr,
2356 strtab_data_byte_size));
2357 if (strtab_data_sp) {
2358 strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
2359 }
2360 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361 }
Jim Ingham8a5d7a22018-08-15 23:10:32 +00002362 }
2363 if (memory_module_load_level >=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002364 eMemoryModuleLoadLevelPartial) {
2365 if (function_starts_load_command.cmd) {
2366 const addr_t func_start_addr =
2367 linkedit_load_addr + function_starts_load_command.dataoff -
2368 linkedit_file_offset;
2369 DataBufferSP func_start_data_sp(
2370 ReadMemory(process_sp, func_start_addr,
2371 function_starts_load_command.datasize));
2372 if (func_start_data_sp)
2373 function_starts_data.SetData(func_start_data_sp, 0,
2374 func_start_data_sp->GetByteSize());
2375 }
2376 }
2377 }
2378 }
2379 } else {
2380 nlist_data.SetData(m_data, symtab_load_command.symoff,
2381 nlist_data_byte_size);
2382 strtab_data.SetData(m_data, symtab_load_command.stroff,
2383 strtab_data_byte_size);
2384
2385 if (dyld_info.export_size > 0) {
2386 dyld_trie_data.SetData(m_data, dyld_info.export_off,
2387 dyld_info.export_size);
2388 }
2389
2390 if (m_dysymtab.nindirectsyms != 0) {
2391 indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2392 m_dysymtab.nindirectsyms * 4);
2393 }
2394 if (function_starts_load_command.cmd) {
2395 function_starts_data.SetData(m_data,
2396 function_starts_load_command.dataoff,
2397 function_starts_load_command.datasize);
2398 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002399 }
2400
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401 if (nlist_data.GetByteSize() == 0 &&
2402 memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2403 if (log)
2404 module_sp->LogMessage(log, "failed to read nlist data");
2405 return 0;
2406 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002407
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2409 if (!have_strtab_data) {
2410 if (process) {
2411 if (strtab_addr == LLDB_INVALID_ADDRESS) {
2412 if (log)
2413 module_sp->LogMessage(log, "failed to locate the strtab in memory");
2414 return 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002415 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416 } else {
2417 if (log)
2418 module_sp->LogMessage(log, "failed to read strtab data");
2419 return 0;
2420 }
2421 }
Greg Clayton9191db42013-10-21 18:40:51 +00002422
Kate Stoneb9c1b512016-09-06 20:57:50 +00002423 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2424 const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2425 const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2426 const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2427 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2428 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2429 SectionSP text_section_sp(
2430 section_list->FindSectionByName(g_segment_name_TEXT));
2431 SectionSP data_section_sp(
2432 section_list->FindSectionByName(g_segment_name_DATA));
2433 SectionSP data_dirty_section_sp(
2434 section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2435 SectionSP data_const_section_sp(
2436 section_list->FindSectionByName(g_segment_name_DATA_CONST));
2437 SectionSP objc_section_sp(
2438 section_list->FindSectionByName(g_segment_name_OBJC));
2439 SectionSP eh_frame_section_sp;
2440 if (text_section_sp.get())
2441 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2442 g_section_name_eh_frame);
2443 else
2444 eh_frame_section_sp =
2445 section_list->FindSectionByName(g_section_name_eh_frame);
Greg Clayton77ccca72011-12-30 00:32:24 +00002446
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
Greg Clayton86eac942013-08-13 21:32:34 +00002448
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449 // lldb works best if it knows the start address of all functions in a
Adrian Prantl05097242018-04-30 16:49:04 +00002450 // module. Linker symbols or debug info are normally the best source of
2451 // information for start addr / size but they may be stripped in a released
2452 // binary. Two additional sources of information exist in Mach-O binaries:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2454 // function's start address in the
2455 // binary, relative to the text section.
2456 // eh_frame - the eh_frame FDEs have the start addr & size of
2457 // each function
2458 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2459 // all modern binaries.
2460 // Binaries built to run on older releases may need to use eh_frame
2461 // information.
Greg Clayton4c82d422012-05-18 23:20:01 +00002462
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463 if (text_section_sp && function_starts_data.GetByteSize()) {
2464 FunctionStarts::Entry function_start_entry;
2465 function_start_entry.data = false;
2466 lldb::offset_t function_start_offset = 0;
2467 function_start_entry.addr = text_section_sp->GetFileAddress();
2468 uint64_t delta;
2469 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2470 0) {
2471 // Now append the current entry
2472 function_start_entry.addr += delta;
2473 function_starts.Append(function_start_entry);
2474 }
2475 } else {
2476 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
Adrian Prantl05097242018-04-30 16:49:04 +00002477 // load command claiming an eh_frame but it doesn't actually have the
2478 // eh_frame content. And if we have a dSYM, we don't need to do any of
2479 // this fill-in-the-missing-symbols works anyway - the debug info should
2480 // give us all the functions in the module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002481 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2482 m_type != eTypeDebugInfo) {
2483 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
Pavel Labath3f2a0812017-06-28 09:09:19 +00002484 DWARFCallFrameInfo::EH);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002485 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2486 eh_frame.GetFunctionAddressAndSizeVector(functions);
2487 addr_t text_base_addr = text_section_sp->GetFileAddress();
2488 size_t count = functions.GetSize();
2489 for (size_t i = 0; i < count; ++i) {
2490 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2491 functions.GetEntryAtIndex(i);
2492 if (func) {
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002493 FunctionStarts::Entry function_start_entry;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002494 function_start_entry.addr = func->base - text_base_addr;
2495 function_starts.Append(function_start_entry);
2496 }
Jason Molendad63d3c72013-04-16 00:18:44 +00002497 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 }
2499 }
2500
2501 const size_t function_starts_count = function_starts.GetSize();
2502
2503 // For user process binaries (executables, dylibs, frameworks, bundles), if
Adrian Prantl05097242018-04-30 16:49:04 +00002504 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2505 // going to assume the binary has been stripped. Don't allow assembly
2506 // language instruction emulation because we don't know proper function
2507 // start boundaries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002508 //
2509 // For all other types of binaries (kernels, stand-alone bare board
Adrian Prantl05097242018-04-30 16:49:04 +00002510 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2511 // sections - we should not make any assumptions about them based on that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002512 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2513 m_allow_assembly_emulation_unwind_plans = false;
2514 Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2515 LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2516
2517 if (unwind_or_symbol_log)
2518 module_sp->LogMessage(
2519 unwind_or_symbol_log,
2520 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2521 }
2522
2523 const user_id_t TEXT_eh_frame_sectID =
2524 eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2525 : static_cast<user_id_t>(NO_SECT);
2526
2527 lldb::offset_t nlist_data_offset = 0;
2528
2529 uint32_t N_SO_index = UINT32_MAX;
2530
2531 MachSymtabSectionInfo section_info(section_list);
2532 std::vector<uint32_t> N_FUN_indexes;
2533 std::vector<uint32_t> N_NSYM_indexes;
2534 std::vector<uint32_t> N_INCL_indexes;
2535 std::vector<uint32_t> N_BRAC_indexes;
2536 std::vector<uint32_t> N_COMM_indexes;
2537 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2538 typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2539 typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2540 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2541 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2542 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00002543 // Any symbols that get merged into another will get an entry in this map
2544 // so we know
Kate Stoneb9c1b512016-09-06 20:57:50 +00002545 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2546 uint32_t nlist_idx = 0;
2547 Symbol *symbol_ptr = NULL;
2548
2549 uint32_t sym_idx = 0;
2550 Symbol *sym = NULL;
2551 size_t num_syms = 0;
2552 std::string memory_symbol_name;
2553 uint32_t unmapped_local_symbols_found = 0;
2554
2555 std::vector<TrieEntryWithOffset> trie_entries;
2556 std::set<lldb::addr_t> resolver_addresses;
2557
2558 if (dyld_trie_data.GetByteSize() > 0) {
2559 std::vector<llvm::StringRef> nameSlices;
2560 ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2561 resolver_addresses, trie_entries);
2562
2563 ConstString text_segment_name("__TEXT");
2564 SectionSP text_segment_sp =
2565 GetSectionList()->FindSectionByName(text_segment_name);
2566 if (text_segment_sp) {
2567 const lldb::addr_t text_segment_file_addr =
2568 text_segment_sp->GetFileAddress();
2569 if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2570 for (auto &e : trie_entries)
2571 e.entry.address += text_segment_file_addr;
2572 }
2573 }
2574 }
2575
2576 typedef std::set<ConstString> IndirectSymbols;
2577 IndirectSymbols indirect_symbol_names;
2578
2579#if defined(__APPLE__) && \
2580 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2581
2582 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
Adrian Prantl05097242018-04-30 16:49:04 +00002583 // optimized by moving LOCAL symbols out of the memory mapped portion of
2584 // the DSC. The symbol information has all been retained, but it isn't
2585 // available in the normal nlist data. However, there *are* duplicate
2586 // entries of *some*
Kate Stoneb9c1b512016-09-06 20:57:50 +00002587 // LOCAL symbols in the normal nlist data. To handle this situation
2588 // correctly, we must first attempt
2589 // to parse any DSC unmapped symbol information. If we find any, we set a
Adrian Prantl05097242018-04-30 16:49:04 +00002590 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002591
2592 if (m_header.flags & 0x80000000u) {
Adrian Prantl05097242018-04-30 16:49:04 +00002593 // Before we can start mapping the DSC, we need to make certain the
2594 // target process is actually using the cache we can find.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002595
2596 // Next we need to determine the correct path for the dyld shared cache.
2597
2598 ArchSpec header_arch;
2599 GetArchitecture(header_arch);
2600 char dsc_path[PATH_MAX];
2601 char dsc_path_development[PATH_MAX];
2602
2603 snprintf(
2604 dsc_path, sizeof(dsc_path), "%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 */
2608 header_arch.GetArchitectureName());
2609
2610 snprintf(
2611 dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2612 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2613 */
2614 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
Ilia K4f730dc2016-09-12 05:25:33 +00002615 header_arch.GetArchitectureName(), ".development");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002616
2617 FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2618 FileSpec dsc_development_filespec(dsc_path_development, false);
2619 FileSpec dsc_filespec;
2620
2621 UUID dsc_uuid;
2622 UUID process_shared_cache_uuid;
Jason Molenda07580ff2018-05-04 00:59:37 +00002623 addr_t process_shared_cache_base_addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002624
2625 if (process) {
Jason Molenda07580ff2018-05-04 00:59:37 +00002626 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, process_shared_cache_uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002627 }
2628
Adrian Prantl05097242018-04-30 16:49:04 +00002629 // First see if we can find an exact match for the inferior process
2630 // shared cache UUID in the development or non-development shared caches
2631 // on disk.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002632 if (process_shared_cache_uuid.IsValid()) {
2633 if (dsc_development_filespec.Exists()) {
2634 UUID dsc_development_uuid = GetSharedCacheUUID(
2635 dsc_development_filespec, byte_order, addr_byte_size);
2636 if (dsc_development_uuid.IsValid() &&
2637 dsc_development_uuid == process_shared_cache_uuid) {
2638 dsc_filespec = dsc_development_filespec;
2639 dsc_uuid = dsc_development_uuid;
2640 }
2641 }
2642 if (!dsc_uuid.IsValid() && dsc_nondevelopment_filespec.Exists()) {
2643 UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2644 dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2645 if (dsc_nondevelopment_uuid.IsValid() &&
2646 dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2647 dsc_filespec = dsc_nondevelopment_filespec;
2648 dsc_uuid = dsc_nondevelopment_uuid;
2649 }
2650 }
2651 }
2652
2653 // Failing a UUID match, prefer the development dyld_shared cache if both
2654 // are present.
2655 if (!dsc_filespec.Exists()) {
2656 if (dsc_development_filespec.Exists()) {
2657 dsc_filespec = dsc_development_filespec;
2658 } else {
2659 dsc_filespec = dsc_nondevelopment_filespec;
2660 }
2661 }
2662
2663 /* The dyld_cache_header has a pointer to the
2664 dyld_cache_local_symbols_info structure (localSymbolsOffset).
2665 The dyld_cache_local_symbols_info structure gives us three things:
2666 1. The start and count of the nlist records in the dyld_shared_cache
2667 file
2668 2. The start and size of the strings for these nlist records
2669 3. The start and count of dyld_cache_local_symbols_entry entries
2670
2671 There is one dyld_cache_local_symbols_entry per dylib/framework in the
2672 dyld shared cache.
2673 The "dylibOffset" field is the Mach-O header of this dylib/framework in
2674 the dyld shared cache.
2675 The dyld_cache_local_symbols_entry also lists the start of this
2676 dylib/framework's nlist records
2677 and the count of how many nlist records there are for this
2678 dylib/framework.
2679 */
2680
2681 // Process the dyld shared cache header to find the unmapped symbols
2682
Pavel Labath50251fc2017-12-21 10:54:30 +00002683 DataBufferSP dsc_data_sp = MapFileData(
2684 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685 if (!dsc_uuid.IsValid()) {
2686 dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2687 }
2688 if (dsc_data_sp) {
2689 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2690
2691 bool uuid_match = true;
2692 if (dsc_uuid.IsValid() && process) {
2693 if (process_shared_cache_uuid.IsValid() &&
2694 dsc_uuid != process_shared_cache_uuid) {
2695 // The on-disk dyld_shared_cache file is not the same as the one in
Adrian Prantl05097242018-04-30 16:49:04 +00002696 // this process' memory, don't use it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697 uuid_match = false;
2698 ModuleSP module_sp(GetModule());
2699 if (module_sp)
2700 module_sp->ReportWarning("process shared cache does not match "
2701 "on-disk dyld_shared_cache file, some "
2702 "symbol names will be missing.");
2703 }
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002704 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00002705
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002707
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
Jason Molenda955dcf22016-05-04 03:09:40 +00002709
Kate Stoneb9c1b512016-09-06 20:57:50 +00002710 // If the mappingOffset points to a location inside the header, we've
2711 // opened an old dyld shared cache, and should not proceed further.
2712 if (uuid_match &&
2713 mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
Jason Molenda955dcf22016-05-04 03:09:40 +00002714
Pavel Labath50251fc2017-12-21 10:54:30 +00002715 DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2716 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2717 mappingOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002718
Kate Stoneb9c1b512016-09-06 20:57:50 +00002719 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2720 byte_order, addr_byte_size);
2721 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002722
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723 // The File addresses (from the in-memory Mach-O load commands) for
Adrian Prantl05097242018-04-30 16:49:04 +00002724 // the shared libraries in the shared library cache need to be
2725 // adjusted by an offset to match up with the dylibOffset identifying
2726 // field in the dyld_cache_local_symbol_entry's. This offset is
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727 // recorded in mapping_offset_value.
2728 const uint64_t mapping_offset_value =
2729 dsc_mapping_info_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002730
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731 offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2732 localSymbolsOffset);
2733 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2734 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002735
Kate Stoneb9c1b512016-09-06 20:57:50 +00002736 if (localSymbolsOffset && localSymbolsSize) {
2737 // Map the local symbols
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002738 DataBufferSP dsc_local_symbols_data_sp =
Pavel Labath50251fc2017-12-21 10:54:30 +00002739 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +00002740
2741 if (dsc_local_symbols_data_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2743 byte_order, addr_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002744
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 offset = 0;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002746
Kate Stoneb9c1b512016-09-06 20:57:50 +00002747 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2748 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2749 UndefinedNameToDescMap undefined_name_to_desc;
2750 SymbolIndexToName reexport_shlib_needs_fixup;
Jim Inghamea3ac272014-01-10 22:55:37 +00002751
Kate Stoneb9c1b512016-09-06 20:57:50 +00002752 // Read the local_symbols_infos struct in one shot
2753 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2754 dsc_local_symbols_data.GetU32(&offset,
2755 &local_symbols_info.nlistOffset, 6);
Jim Inghamea3ac272014-01-10 22:55:37 +00002756
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 SectionSP text_section_sp(
2758 section_list->FindSectionByName(GetSegmentNameTEXT()));
Greg Claytonb65c6292015-02-20 22:20:05 +00002759
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 uint32_t header_file_offset =
2761 (text_section_sp->GetFileAddress() - mapping_offset_value);
Jason Molendaa5609c82012-06-21 01:51:02 +00002762
Kate Stoneb9c1b512016-09-06 20:57:50 +00002763 offset = local_symbols_info.entriesOffset;
2764 for (uint32_t entry_index = 0;
2765 entry_index < local_symbols_info.entriesCount;
2766 entry_index++) {
2767 struct lldb_copy_dyld_cache_local_symbols_entry
2768 local_symbols_entry;
2769 local_symbols_entry.dylibOffset =
2770 dsc_local_symbols_data.GetU32(&offset);
2771 local_symbols_entry.nlistStartIndex =
2772 dsc_local_symbols_data.GetU32(&offset);
2773 local_symbols_entry.nlistCount =
2774 dsc_local_symbols_data.GetU32(&offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002775
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 if (header_file_offset == local_symbols_entry.dylibOffset) {
2777 unmapped_local_symbols_found = local_symbols_entry.nlistCount;
Jason Molendaa5609c82012-06-21 01:51:02 +00002778
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 // The normal nlist code cannot correctly size the Symbols
2780 // array, we need to allocate it here.
2781 sym = symtab->Resize(
2782 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2783 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2784 num_syms = symtab->GetNumSymbols();
Jason Molendaa5609c82012-06-21 01:51:02 +00002785
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 nlist_data_offset =
2787 local_symbols_info.nlistOffset +
2788 (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2789 uint32_t string_table_offset =
2790 local_symbols_info.stringsOffset;
Jason Molendaa5609c82012-06-21 01:51:02 +00002791
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 for (uint32_t nlist_index = 0;
2793 nlist_index < local_symbols_entry.nlistCount;
2794 nlist_index++) {
2795 /////////////////////////////
Jason Molenda649a6072015-11-10 05:21:54 +00002796 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002797 struct nlist_64 nlist;
2798 if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(
2799 nlist_data_offset, nlist_byte_size))
2800 break;
Eugene Zelenko8157a882015-10-23 16:56:07 +00002801
Kate Stoneb9c1b512016-09-06 20:57:50 +00002802 nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(
2803 &nlist_data_offset);
2804 nlist.n_type = dsc_local_symbols_data.GetU8_unchecked(
2805 &nlist_data_offset);
2806 nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked(
2807 &nlist_data_offset);
2808 nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked(
2809 &nlist_data_offset);
2810 nlist.n_value =
2811 dsc_local_symbols_data.GetAddress_unchecked(
2812 &nlist_data_offset);
Jason Molendaa5609c82012-06-21 01:51:02 +00002813
Kate Stoneb9c1b512016-09-06 20:57:50 +00002814 SymbolType type = eSymbolTypeInvalid;
2815 const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2816 string_table_offset + nlist.n_strx);
Jason Molendaf8130862012-06-22 03:28:35 +00002817
Kate Stoneb9c1b512016-09-06 20:57:50 +00002818 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002819 // No symbol should be NULL, even the symbols with no
Adrian Prantl05097242018-04-30 16:49:04 +00002820 // string values should have an offset zero which
2821 // points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 Host::SystemLog(
2823 Host::eSystemLogError,
2824 "error: DSC unmapped local symbol[%u] has invalid "
2825 "string table offset 0x%x in %s, ignoring symbol\n",
2826 entry_index, nlist.n_strx,
2827 module_sp->GetFileSpec().GetPath().c_str());
Greg Claytonfd814c52013-08-13 01:42:25 +00002828 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002829 }
2830 if (symbol_name[0] == '\0')
Greg Claytonfd814c52013-08-13 01:42:25 +00002831 symbol_name = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002832
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 const char *symbol_name_non_abi_mangled = NULL;
Greg Claytonfd814c52013-08-13 01:42:25 +00002834
Kate Stoneb9c1b512016-09-06 20:57:50 +00002835 SectionSP symbol_section;
2836 uint32_t symbol_byte_size = 0;
2837 bool add_nlist = true;
2838 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2839 bool demangled_is_synthesized = false;
2840 bool is_gsym = false;
2841 bool set_value = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00002842
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 assert(sym_idx < num_syms);
Jason Molenda4e7511e2013-03-06 23:19:17 +00002844
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 sym[sym_idx].SetDebug(is_debug);
Greg Clayton29e08cb2012-03-14 01:53:24 +00002846
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847 if (is_debug) {
2848 switch (nlist.n_type) {
2849 case N_GSYM:
2850 // global symbol: name,,NO_SECT,type,0
2851 // Sometimes the N_GSYM value contains the address.
2852
2853 // FIXME: In the .o files, we have a GSYM and a debug
2854 // symbol for all the ObjC data. They
2855 // have the same address, but we want to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +00002856 // we always find only the real symbol, 'cause we
2857 // don't currently correctly attribute the
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858 // GSYM one to the ObjCClass/Ivar/MetaClass
Adrian Prantl05097242018-04-30 16:49:04 +00002859 // symbol type. This is a temporary hack to make
2860 // sure the ObjectiveC symbols get treated correctly.
2861 // To do this right, we should coalesce all the GSYM
2862 // & global symbols that have the same address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863
2864 is_gsym = true;
2865 sym[sym_idx].SetExternal(true);
2866
2867 if (symbol_name && symbol_name[0] == '_' &&
2868 symbol_name[1] == 'O') {
Greg Clayton1e28adf2015-02-25 17:25:02 +00002869 llvm::StringRef symbol_name_ref(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002870 if (symbol_name_ref.startswith(
2871 g_objc_v2_prefix_class)) {
2872 symbol_name_non_abi_mangled = symbol_name + 1;
2873 symbol_name =
2874 symbol_name + g_objc_v2_prefix_class.size();
2875 type = eSymbolTypeObjCClass;
2876 demangled_is_synthesized = true;
2877
2878 } else if (symbol_name_ref.startswith(
2879 g_objc_v2_prefix_metaclass)) {
2880 symbol_name_non_abi_mangled = symbol_name + 1;
2881 symbol_name = symbol_name +
2882 g_objc_v2_prefix_metaclass.size();
2883 type = eSymbolTypeObjCMetaClass;
2884 demangled_is_synthesized = true;
2885 } else if (symbol_name_ref.startswith(
2886 g_objc_v2_prefix_ivar)) {
2887 symbol_name_non_abi_mangled = symbol_name + 1;
2888 symbol_name =
2889 symbol_name + g_objc_v2_prefix_ivar.size();
2890 type = eSymbolTypeObjCIVar;
2891 demangled_is_synthesized = true;
Greg Clayton1e28adf2015-02-25 17:25:02 +00002892 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002894 if (nlist.n_value != 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 symbol_section = section_info.GetSection(
2896 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002897 type = eSymbolTypeData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898 }
2899 break;
Greg Claytonf3bb3e42012-03-09 04:26:05 +00002900
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 case N_FNAME:
2902 // procedure name (f77 kludge): name,,NO_SECT,0,0
2903 type = eSymbolTypeCompiler;
2904 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002905
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906 case N_FUN:
2907 // procedure: name,,n_sect,linenumber,address
2908 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00002909 type = eSymbolTypeCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 symbol_section = section_info.GetSection(
2911 nlist.n_sect, nlist.n_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00002912
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 N_FUN_addr_to_sym_idx.insert(
2914 std::make_pair(nlist.n_value, sym_idx));
2915 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00002916 // symbol table in lieu of using nlist_idx in case
2917 // we ever start trimming entries out
Greg Claytonfd814c52013-08-13 01:42:25 +00002918 N_FUN_indexes.push_back(sym_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 } else {
Greg Claytonfd814c52013-08-13 01:42:25 +00002920 type = eSymbolTypeCompiler;
2921
Kate Stoneb9c1b512016-09-06 20:57:50 +00002922 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00002923 // Copy the size of the function into the
2924 // original
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 // STAB entry so we don't have
2926 // to hunt for it later
2927 symtab->SymbolAtIndex(N_FUN_indexes.back())
2928 ->SetByteSize(nlist.n_value);
2929 N_FUN_indexes.pop_back();
2930 // We don't really need the end function STAB as
Adrian Prantl05097242018-04-30 16:49:04 +00002931 // it contains the size which we already placed
2932 // with the original symbol, so don't add it if
2933 // we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00002934 add_nlist = false;
Greg Claytondacc4a92013-05-14 22:19:37 +00002935 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002936 }
2937 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002938
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 case N_STSYM:
2940 // static symbol: name,,n_sect,type,address
2941 N_STSYM_addr_to_sym_idx.insert(
2942 std::make_pair(nlist.n_value, sym_idx));
2943 symbol_section = section_info.GetSection(
2944 nlist.n_sect, nlist.n_value);
2945 if (symbol_name && symbol_name[0]) {
2946 type = ObjectFile::GetSymbolTypeFromName(
2947 symbol_name + 1, eSymbolTypeData);
2948 }
2949 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002950
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 case N_LCSYM:
2952 // .lcomm symbol: name,,n_sect,type,address
2953 symbol_section = section_info.GetSection(
2954 nlist.n_sect, nlist.n_value);
2955 type = eSymbolTypeCommonBlock;
2956 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002957
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 case N_BNSYM:
2959 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00002960 // table in lieu of using nlist_idx in case we ever
2961 // start trimming entries out Skip these if we want
2962 // minimal symbol tables
Kate Stoneb9c1b512016-09-06 20:57:50 +00002963 add_nlist = false;
2964 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002965
Kate Stoneb9c1b512016-09-06 20:57:50 +00002966 case N_ENSYM:
2967 // Set the size of the N_BNSYM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00002968 // index of this N_ENSYM so that we can always skip
2969 // the entire symbol if we need to navigate more
2970 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00002971 // Skip these if we want minimal symbol tables
2972 add_nlist = false;
2973 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002974
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 case N_OPT:
2976 // emitted with gcc2_compiled and in gcc source
2977 type = eSymbolTypeCompiler;
2978 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002979
Kate Stoneb9c1b512016-09-06 20:57:50 +00002980 case N_RSYM:
2981 // register sym: name,,NO_SECT,type,register
2982 type = eSymbolTypeVariable;
2983 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002984
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 case N_SLINE:
2986 // src line: 0,,n_sect,linenumber,address
2987 symbol_section = section_info.GetSection(
2988 nlist.n_sect, nlist.n_value);
2989 type = eSymbolTypeLineEntry;
2990 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002991
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 case N_SSYM:
2993 // structure elt: name,,NO_SECT,type,struct_offset
2994 type = eSymbolTypeVariableType;
2995 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00002996
Kate Stoneb9c1b512016-09-06 20:57:50 +00002997 case N_SO:
2998 // source file name
2999 type = eSymbolTypeSourceFile;
3000 if (symbol_name == NULL) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003001 add_nlist = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002 if (N_SO_index != UINT32_MAX) {
3003 // Set the size of the N_SO to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003004 // index of this N_SO so that we can always skip
3005 // the entire N_SO if we need to navigate more
3006 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003007 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3008 symbol_ptr->SetByteSize(sym_idx);
3009 symbol_ptr->SetSizeIsSibling(true);
Greg Claytonfd814c52013-08-13 01:42:25 +00003010 }
3011 N_NSYM_indexes.clear();
3012 N_INCL_indexes.clear();
3013 N_BRAC_indexes.clear();
3014 N_COMM_indexes.clear();
3015 N_FUN_indexes.clear();
3016 N_SO_index = UINT32_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003017 } else {
3018 // We use the current number of symbols in the
Adrian Prantl05097242018-04-30 16:49:04 +00003019 // symbol table in lieu of using nlist_idx in case
3020 // we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003021 const bool N_SO_has_full_path =
3022 symbol_name[0] == '/';
3023 if (N_SO_has_full_path) {
3024 if ((N_SO_index == sym_idx - 1) &&
3025 ((sym_idx - 1) < num_syms)) {
3026 // We have two consecutive N_SO entries where
Adrian Prantl05097242018-04-30 16:49:04 +00003027 // the first contains a directory and the
3028 // second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003029 sym[sym_idx - 1].GetMangled().SetValue(
3030 ConstString(symbol_name), false);
3031 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3032 add_nlist = false;
3033 } else {
3034 // This is the first entry in a N_SO that
3035 // contains a directory or
3036 // a full path to the source file
Greg Claytonfd814c52013-08-13 01:42:25 +00003037 N_SO_index = sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038 }
3039 } else if ((N_SO_index == sym_idx - 1) &&
3040 ((sym_idx - 1) < num_syms)) {
3041 // This is usually the second N_SO entry that
Adrian Prantl05097242018-04-30 16:49:04 +00003042 // contains just the filename, so here we combine
3043 // it with the first one if we are minimizing the
3044 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003045 const char *so_path =
3046 sym[sym_idx - 1]
3047 .GetMangled()
3048 .GetDemangledName(
3049 lldb::eLanguageTypeUnknown)
3050 .AsCString();
3051 if (so_path && so_path[0]) {
3052 std::string full_so_path(so_path);
3053 const size_t double_slash_pos =
3054 full_so_path.find("//");
3055 if (double_slash_pos != std::string::npos) {
3056 // The linker has been generating bad N_SO
3057 // entries with doubled up paths
Adrian Prantl05097242018-04-30 16:49:04 +00003058 // in the format "%s%s" where the first
3059 // string in the DW_AT_comp_dir, and the
3060 // second is the directory for the source
3061 // file so you end up with a path that looks
3062 // like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00003063 FileSpec so_dir(so_path, false);
3064 if (!so_dir.Exists()) {
3065 so_dir.SetFile(
3066 &full_so_path[double_slash_pos + 1],
3067 false);
3068 if (so_dir.Exists()) {
3069 // Trim off the incorrect path
3070 full_so_path.erase(0,
3071 double_slash_pos + 1);
3072 }
3073 }
3074 }
3075 if (*full_so_path.rbegin() != '/')
3076 full_so_path += '/';
3077 full_so_path += symbol_name;
3078 sym[sym_idx - 1].GetMangled().SetValue(
3079 ConstString(full_so_path.c_str()), false);
3080 add_nlist = false;
3081 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3082 }
3083 } else {
3084 // This could be a relative path to a N_SO
3085 N_SO_index = sym_idx;
Greg Claytonfd814c52013-08-13 01:42:25 +00003086 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003087 }
3088 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003089
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090 case N_OSO:
3091 // object file name: name,,0,0,st_mtime
3092 type = eSymbolTypeObjectFile;
3093 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003094
Kate Stoneb9c1b512016-09-06 20:57:50 +00003095 case N_LSYM:
3096 // local sym: name,,NO_SECT,type,offset
3097 type = eSymbolTypeLocal;
3098 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003099
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100 //----------------------------------------------------------------------
3101 // INCL scopes
3102 //----------------------------------------------------------------------
3103 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00003104 // include file beginning: name,,NO_SECT,0,sum We use
3105 // the current number of symbols in the symbol table
3106 // in lieu of using nlist_idx in case we ever start
3107 // trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108 N_INCL_indexes.push_back(sym_idx);
3109 type = eSymbolTypeScopeBegin;
3110 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003111
Kate Stoneb9c1b512016-09-06 20:57:50 +00003112 case N_EINCL:
3113 // include file end: name,,NO_SECT,0,0
3114 // Set the size of the N_BINCL to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003115 // index of this N_EINCL so that we can always skip
3116 // the entire symbol if we need to navigate more
3117 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003118 if (!N_INCL_indexes.empty()) {
3119 symbol_ptr =
3120 symtab->SymbolAtIndex(N_INCL_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003121 symbol_ptr->SetByteSize(sym_idx + 1);
3122 symbol_ptr->SetSizeIsSibling(true);
3123 N_INCL_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 }
3125 type = eSymbolTypeScopeEnd;
3126 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003127
Kate Stoneb9c1b512016-09-06 20:57:50 +00003128 case N_SOL:
3129 // #included file name: name,,n_sect,0,address
3130 type = eSymbolTypeHeaderFile;
Greg Claytonfd814c52013-08-13 01:42:25 +00003131
Kate Stoneb9c1b512016-09-06 20:57:50 +00003132 // We currently don't use the header files on darwin
3133 add_nlist = false;
3134 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003135
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136 case N_PARAMS:
3137 // compiler parameters: name,,NO_SECT,0,0
3138 type = eSymbolTypeCompiler;
3139 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003140
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141 case N_VERSION:
3142 // compiler version: name,,NO_SECT,0,0
3143 type = eSymbolTypeCompiler;
3144 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003145
Kate Stoneb9c1b512016-09-06 20:57:50 +00003146 case N_OLEVEL:
3147 // compiler -O level: name,,NO_SECT,0,0
3148 type = eSymbolTypeCompiler;
3149 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003150
Kate Stoneb9c1b512016-09-06 20:57:50 +00003151 case N_PSYM:
3152 // parameter: name,,NO_SECT,type,offset
3153 type = eSymbolTypeVariable;
3154 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003155
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156 case N_ENTRY:
3157 // alternate entry: name,,n_sect,linenumber,address
3158 symbol_section = section_info.GetSection(
3159 nlist.n_sect, nlist.n_value);
3160 type = eSymbolTypeLineEntry;
3161 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003162
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163 //----------------------------------------------------------------------
3164 // Left and Right Braces
3165 //----------------------------------------------------------------------
3166 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00003167 // left bracket: 0,,NO_SECT,nesting level,address We
3168 // use the current number of symbols in the symbol
3169 // table in lieu of using nlist_idx in case we ever
3170 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003171 symbol_section = section_info.GetSection(
3172 nlist.n_sect, nlist.n_value);
3173 N_BRAC_indexes.push_back(sym_idx);
3174 type = eSymbolTypeScopeBegin;
3175 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003176
Kate Stoneb9c1b512016-09-06 20:57:50 +00003177 case N_RBRAC:
3178 // right bracket: 0,,NO_SECT,nesting level,address
3179 // Set the size of the N_LBRAC to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003180 // index of this N_RBRAC so that we can always skip
3181 // the entire symbol if we need to navigate more
3182 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003183 symbol_section = section_info.GetSection(
3184 nlist.n_sect, nlist.n_value);
3185 if (!N_BRAC_indexes.empty()) {
3186 symbol_ptr =
3187 symtab->SymbolAtIndex(N_BRAC_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003188 symbol_ptr->SetByteSize(sym_idx + 1);
3189 symbol_ptr->SetSizeIsSibling(true);
3190 N_BRAC_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191 }
3192 type = eSymbolTypeScopeEnd;
3193 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003194
Kate Stoneb9c1b512016-09-06 20:57:50 +00003195 case N_EXCL:
3196 // deleted include file: name,,NO_SECT,0,sum
3197 type = eSymbolTypeHeaderFile;
3198 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003199
Kate Stoneb9c1b512016-09-06 20:57:50 +00003200 //----------------------------------------------------------------------
3201 // COMM scopes
3202 //----------------------------------------------------------------------
3203 case N_BCOMM:
3204 // begin common: name,,NO_SECT,0,0
3205 // We use the current number of symbols in the symbol
Adrian Prantl05097242018-04-30 16:49:04 +00003206 // table in lieu of using nlist_idx in case we ever
3207 // start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003208 type = eSymbolTypeScopeBegin;
3209 N_COMM_indexes.push_back(sym_idx);
3210 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003211
Kate Stoneb9c1b512016-09-06 20:57:50 +00003212 case N_ECOML:
3213 // end common (local name): 0,,n_sect,0,address
3214 symbol_section = section_info.GetSection(
3215 nlist.n_sect, nlist.n_value);
3216 // Fall through
Greg Claytonfd814c52013-08-13 01:42:25 +00003217
Kate Stoneb9c1b512016-09-06 20:57:50 +00003218 case N_ECOMM:
3219 // end common: name,,n_sect,0,0
3220 // Set the size of the N_BCOMM to the terminating
Adrian Prantl05097242018-04-30 16:49:04 +00003221 // index of this N_ECOMM/N_ECOML so that we can
3222 // always skip the entire symbol if we need to
3223 // navigate more quickly at the source level when
3224 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225 if (!N_COMM_indexes.empty()) {
3226 symbol_ptr =
3227 symtab->SymbolAtIndex(N_COMM_indexes.back());
Greg Claytonfd814c52013-08-13 01:42:25 +00003228 symbol_ptr->SetByteSize(sym_idx + 1);
3229 symbol_ptr->SetSizeIsSibling(true);
3230 N_COMM_indexes.pop_back();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003231 }
3232 type = eSymbolTypeScopeEnd;
3233 break;
3234
3235 case N_LENG:
3236 // second stab entry with length information
3237 type = eSymbolTypeAdditional;
3238 break;
3239
3240 default:
3241 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003242 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 } else {
3244 // uint8_t n_pext = N_PEXT & nlist.n_type;
3245 uint8_t n_type = N_TYPE & nlist.n_type;
3246 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
Greg Claytonfd814c52013-08-13 01:42:25 +00003247
Kate Stoneb9c1b512016-09-06 20:57:50 +00003248 switch (n_type) {
3249 case N_INDR: {
3250 const char *reexport_name_cstr =
3251 strtab_data.PeekCStr(nlist.n_value);
3252 if (reexport_name_cstr && reexport_name_cstr[0]) {
3253 type = eSymbolTypeReExported;
3254 ConstString reexport_name(
3255 reexport_name_cstr +
3256 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3257 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3258 set_value = false;
3259 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3260 indirect_symbol_names.insert(
3261 ConstString(symbol_name +
3262 ((symbol_name[0] == '_') ? 1 : 0)));
3263 } else
3264 type = eSymbolTypeUndefined;
3265 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003266
Kate Stoneb9c1b512016-09-06 20:57:50 +00003267 case N_UNDF:
3268 if (symbol_name && symbol_name[0]) {
3269 ConstString undefined_name(
3270 symbol_name +
3271 ((symbol_name[0] == '_') ? 1 : 0));
3272 undefined_name_to_desc[undefined_name] =
3273 nlist.n_desc;
3274 }
3275 // Fall through
3276 case N_PBUD:
3277 type = eSymbolTypeUndefined;
3278 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003279
Kate Stoneb9c1b512016-09-06 20:57:50 +00003280 case N_ABS:
3281 type = eSymbolTypeAbsolute;
3282 break;
Greg Clayton60038be2015-02-14 00:51:13 +00003283
Kate Stoneb9c1b512016-09-06 20:57:50 +00003284 case N_SECT: {
3285 symbol_section = section_info.GetSection(
3286 nlist.n_sect, nlist.n_value);
Jason Molenda62e06812016-02-16 04:14:33 +00003287
Kate Stoneb9c1b512016-09-06 20:57:50 +00003288 if (symbol_section == NULL) {
3289 // TODO: warn about this?
3290 add_nlist = false;
3291 break;
3292 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003293
Kate Stoneb9c1b512016-09-06 20:57:50 +00003294 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3295 type = eSymbolTypeException;
3296 } else {
3297 uint32_t section_type =
3298 symbol_section->Get() & SECTION_TYPE;
Greg Claytonfd814c52013-08-13 01:42:25 +00003299
Kate Stoneb9c1b512016-09-06 20:57:50 +00003300 switch (section_type) {
3301 case S_CSTRING_LITERALS:
3302 type = eSymbolTypeData;
3303 break; // section with only literal C strings
3304 case S_4BYTE_LITERALS:
3305 type = eSymbolTypeData;
3306 break; // section with only 4 byte literals
3307 case S_8BYTE_LITERALS:
3308 type = eSymbolTypeData;
3309 break; // section with only 8 byte literals
3310 case S_LITERAL_POINTERS:
3311 type = eSymbolTypeTrampoline;
3312 break; // section with only pointers to literals
3313 case S_NON_LAZY_SYMBOL_POINTERS:
3314 type = eSymbolTypeTrampoline;
3315 break; // section with only non-lazy symbol
3316 // pointers
3317 case S_LAZY_SYMBOL_POINTERS:
3318 type = eSymbolTypeTrampoline;
3319 break; // section with only lazy symbol pointers
3320 case S_SYMBOL_STUBS:
3321 type = eSymbolTypeTrampoline;
3322 break; // section with only symbol stubs, byte
3323 // size of stub in the reserved2 field
3324 case S_MOD_INIT_FUNC_POINTERS:
3325 type = eSymbolTypeCode;
3326 break; // section with only function pointers for
3327 // initialization
3328 case S_MOD_TERM_FUNC_POINTERS:
3329 type = eSymbolTypeCode;
3330 break; // section with only function pointers for
3331 // termination
3332 case S_INTERPOSING:
3333 type = eSymbolTypeTrampoline;
3334 break; // section with only pairs of function
3335 // pointers for interposing
3336 case S_16BYTE_LITERALS:
3337 type = eSymbolTypeData;
3338 break; // section with only 16 byte literals
3339 case S_DTRACE_DOF:
3340 type = eSymbolTypeInstrumentation;
3341 break;
3342 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3343 type = eSymbolTypeTrampoline;
3344 break;
3345 default:
3346 switch (symbol_section->GetType()) {
3347 case lldb::eSectionTypeCode:
3348 type = eSymbolTypeCode;
Greg Claytonfd814c52013-08-13 01:42:25 +00003349 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003350 case eSectionTypeData:
3351 case eSectionTypeDataCString: // Inlined C string
3352 // data
3353 case eSectionTypeDataCStringPointers: // Pointers
3354 // to C
3355 // string
3356 // data
3357 case eSectionTypeDataSymbolAddress: // Address of
3358 // a symbol in
3359 // the symbol
3360 // table
3361 case eSectionTypeData4:
3362 case eSectionTypeData8:
3363 case eSectionTypeData16:
3364 type = eSymbolTypeData;
3365 break;
3366 default:
3367 break;
3368 }
3369 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003370 }
3371
Kate Stoneb9c1b512016-09-06 20:57:50 +00003372 if (type == eSymbolTypeInvalid) {
3373 const char *symbol_sect_name =
3374 symbol_section->GetName().AsCString();
3375 if (symbol_section->IsDescendant(
3376 text_section_sp.get())) {
3377 if (symbol_section->IsClear(
3378 S_ATTR_PURE_INSTRUCTIONS |
3379 S_ATTR_SELF_MODIFYING_CODE |
3380 S_ATTR_SOME_INSTRUCTIONS))
3381 type = eSymbolTypeData;
3382 else
3383 type = eSymbolTypeCode;
3384 } else if (symbol_section->IsDescendant(
3385 data_section_sp.get()) ||
3386 symbol_section->IsDescendant(
3387 data_dirty_section_sp.get()) ||
3388 symbol_section->IsDescendant(
3389 data_const_section_sp.get())) {
3390 if (symbol_sect_name &&
3391 ::strstr(symbol_sect_name, "__objc") ==
3392 symbol_sect_name) {
3393 type = eSymbolTypeRuntime;
Greg Claytonfd814c52013-08-13 01:42:25 +00003394
Kate Stoneb9c1b512016-09-06 20:57:50 +00003395 if (symbol_name) {
3396 llvm::StringRef symbol_name_ref(
3397 symbol_name);
3398 if (symbol_name_ref.startswith("_OBJC_")) {
3399 static const llvm::StringRef
3400 g_objc_v2_prefix_class(
3401 "_OBJC_CLASS_$_");
3402 static const llvm::StringRef
3403 g_objc_v2_prefix_metaclass(
3404 "_OBJC_METACLASS_$_");
3405 static const llvm::StringRef
3406 g_objc_v2_prefix_ivar(
3407 "_OBJC_IVAR_$_");
3408 if (symbol_name_ref.startswith(
3409 g_objc_v2_prefix_class)) {
3410 symbol_name_non_abi_mangled =
3411 symbol_name + 1;
3412 symbol_name =
3413 symbol_name +
3414 g_objc_v2_prefix_class.size();
3415 type = eSymbolTypeObjCClass;
3416 demangled_is_synthesized = true;
3417 } else if (
3418 symbol_name_ref.startswith(
3419 g_objc_v2_prefix_metaclass)) {
3420 symbol_name_non_abi_mangled =
3421 symbol_name + 1;
3422 symbol_name =
3423 symbol_name +
3424 g_objc_v2_prefix_metaclass.size();
3425 type = eSymbolTypeObjCMetaClass;
3426 demangled_is_synthesized = true;
3427 } else if (symbol_name_ref.startswith(
3428 g_objc_v2_prefix_ivar)) {
3429 symbol_name_non_abi_mangled =
3430 symbol_name + 1;
3431 symbol_name =
3432 symbol_name +
3433 g_objc_v2_prefix_ivar.size();
3434 type = eSymbolTypeObjCIVar;
3435 demangled_is_synthesized = true;
3436 }
Greg Clayton38f9cc42014-06-16 22:53:16 +00003437 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003438 }
3439 } else if (symbol_sect_name &&
3440 ::strstr(symbol_sect_name,
3441 "__gcc_except_tab") ==
3442 symbol_sect_name) {
3443 type = eSymbolTypeException;
3444 } else {
3445 type = eSymbolTypeData;
Greg Claytonfd814c52013-08-13 01:42:25 +00003446 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003447 } else if (symbol_sect_name &&
3448 ::strstr(symbol_sect_name,
3449 "__IMPORT") ==
3450 symbol_sect_name) {
3451 type = eSymbolTypeTrampoline;
3452 } else if (symbol_section->IsDescendant(
3453 objc_section_sp.get())) {
3454 type = eSymbolTypeRuntime;
3455 if (symbol_name && symbol_name[0] == '.') {
3456 llvm::StringRef symbol_name_ref(symbol_name);
3457 static const llvm::StringRef
3458 g_objc_v1_prefix_class(
3459 ".objc_class_name_");
3460 if (symbol_name_ref.startswith(
3461 g_objc_v1_prefix_class)) {
3462 symbol_name_non_abi_mangled = symbol_name;
3463 symbol_name = symbol_name +
3464 g_objc_v1_prefix_class.size();
3465 type = eSymbolTypeObjCClass;
3466 demangled_is_synthesized = true;
3467 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003468 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003469 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003470 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003471 }
3472 } break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003473 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003474 }
Greg Claytondacc4a92013-05-14 22:19:37 +00003475
Kate Stoneb9c1b512016-09-06 20:57:50 +00003476 if (add_nlist) {
3477 uint64_t symbol_value = nlist.n_value;
3478 if (symbol_name_non_abi_mangled) {
3479 sym[sym_idx].GetMangled().SetMangledName(
3480 ConstString(symbol_name_non_abi_mangled));
3481 sym[sym_idx].GetMangled().SetDemangledName(
3482 ConstString(symbol_name));
3483 } else {
3484 bool symbol_name_is_mangled = false;
Greg Claytonfd814c52013-08-13 01:42:25 +00003485
Kate Stoneb9c1b512016-09-06 20:57:50 +00003486 if (symbol_name && symbol_name[0] == '_') {
Greg Claytonfd814c52013-08-13 01:42:25 +00003487 symbol_name_is_mangled = symbol_name[1] == '_';
Kate Stoneb9c1b512016-09-06 20:57:50 +00003488 symbol_name++; // Skip the leading underscore
3489 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003490
Kate Stoneb9c1b512016-09-06 20:57:50 +00003491 if (symbol_name) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003492 ConstString const_symbol_name(symbol_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003493 sym[sym_idx].GetMangled().SetValue(
3494 const_symbol_name, symbol_name_is_mangled);
3495 if (is_gsym && is_debug) {
3496 const char *gsym_name =
3497 sym[sym_idx]
3498 .GetMangled()
3499 .GetName(lldb::eLanguageTypeUnknown,
3500 Mangled::ePreferMangled)
3501 .GetCString();
3502 if (gsym_name)
3503 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3504 }
3505 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003506 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003507 if (symbol_section) {
3508 const addr_t section_file_addr =
3509 symbol_section->GetFileAddress();
3510 if (symbol_byte_size == 0 &&
3511 function_starts_count > 0) {
Greg Claytonfd814c52013-08-13 01:42:25 +00003512 addr_t symbol_lookup_file_addr = nlist.n_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003513 // Do an exact address match for non-ARM addresses,
Adrian Prantl05097242018-04-30 16:49:04 +00003514 // else get the closest since the symbol might be a
3515 // thumb symbol which has an address with bit zero
3516 // set
Kate Stoneb9c1b512016-09-06 20:57:50 +00003517 FunctionStarts::Entry *func_start_entry =
3518 function_starts.FindEntry(
3519 symbol_lookup_file_addr, !is_arm);
3520 if (is_arm && func_start_entry) {
3521 // Verify that the function start address is the
Adrian Prantl05097242018-04-30 16:49:04 +00003522 // symbol address (ARM) or the symbol address + 1
3523 // (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003524 if (func_start_entry->addr !=
3525 symbol_lookup_file_addr &&
3526 func_start_entry->addr !=
3527 (symbol_lookup_file_addr + 1)) {
3528 // Not the right entry, NULL it out...
3529 func_start_entry = NULL;
3530 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003531 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003532 if (func_start_entry) {
3533 func_start_entry->data = true;
Greg Claytonfd814c52013-08-13 01:42:25 +00003534
Kate Stoneb9c1b512016-09-06 20:57:50 +00003535 addr_t symbol_file_addr = func_start_entry->addr;
3536 uint32_t symbol_flags = 0;
3537 if (is_arm) {
3538 if (symbol_file_addr & 1)
3539 symbol_flags =
3540 MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3541 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3542 }
3543
3544 const FunctionStarts::Entry
3545 *next_func_start_entry =
3546 function_starts.FindNextEntry(
3547 func_start_entry);
3548 const addr_t section_end_file_addr =
3549 section_file_addr +
3550 symbol_section->GetByteSize();
3551 if (next_func_start_entry) {
3552 addr_t next_symbol_file_addr =
3553 next_func_start_entry->addr;
3554 // Be sure the clear the Thumb address bit when
Adrian Prantl05097242018-04-30 16:49:04 +00003555 // we calculate the size from the current and
3556 // next address
Greg Claytonfd814c52013-08-13 01:42:25 +00003557 if (is_arm)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003558 next_symbol_file_addr &=
3559 THUMB_ADDRESS_BIT_MASK;
3560 symbol_byte_size = std::min<lldb::addr_t>(
3561 next_symbol_file_addr - symbol_file_addr,
3562 section_end_file_addr - symbol_file_addr);
3563 } else {
3564 symbol_byte_size =
3565 section_end_file_addr - symbol_file_addr;
3566 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003567 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003568 }
3569 symbol_value -= section_file_addr;
Greg Claytonfd814c52013-08-13 01:42:25 +00003570 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003571
Kate Stoneb9c1b512016-09-06 20:57:50 +00003572 if (is_debug == false) {
3573 if (type == eSymbolTypeCode) {
3574 // See if we can find a N_FUN entry for any code
Adrian Prantl05097242018-04-30 16:49:04 +00003575 // symbols. If we do find a match, and the name
3576 // matches, then we can merge the two into just the
3577 // function symbol to avoid duplicate entries in
3578 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003579 std::pair<ValueToSymbolIndexMap::const_iterator,
3580 ValueToSymbolIndexMap::const_iterator>
3581 range;
3582 range = N_FUN_addr_to_sym_idx.equal_range(
3583 nlist.n_value);
3584 if (range.first != range.second) {
3585 bool found_it = false;
3586 for (ValueToSymbolIndexMap::const_iterator pos =
3587 range.first;
3588 pos != range.second; ++pos) {
3589 if (sym[sym_idx].GetMangled().GetName(
3590 lldb::eLanguageTypeUnknown,
3591 Mangled::ePreferMangled) ==
3592 sym[pos->second].GetMangled().GetName(
3593 lldb::eLanguageTypeUnknown,
3594 Mangled::ePreferMangled)) {
3595 m_nlist_idx_to_sym_idx[nlist_idx] =
3596 pos->second;
3597 // We just need the flags from the linker
3598 // symbol, so put these flags
3599 // into the N_FUN flags to avoid duplicate
3600 // symbols in the symbol table
3601 sym[pos->second].SetExternal(
3602 sym[sym_idx].IsExternal());
3603 sym[pos->second].SetFlags(nlist.n_type << 16 |
3604 nlist.n_desc);
3605 if (resolver_addresses.find(nlist.n_value) !=
3606 resolver_addresses.end())
3607 sym[pos->second].SetType(
3608 eSymbolTypeResolver);
3609 sym[sym_idx].Clear();
3610 found_it = true;
3611 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003612 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003613 }
3614 if (found_it)
3615 continue;
3616 } else {
3617 if (resolver_addresses.find(nlist.n_value) !=
3618 resolver_addresses.end())
3619 type = eSymbolTypeResolver;
Greg Claytonfd814c52013-08-13 01:42:25 +00003620 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003621 } else if (type == eSymbolTypeData ||
3622 type == eSymbolTypeObjCClass ||
3623 type == eSymbolTypeObjCMetaClass ||
3624 type == eSymbolTypeObjCIVar) {
3625 // See if we can find a N_STSYM entry for any data
Adrian Prantl05097242018-04-30 16:49:04 +00003626 // symbols. If we do find a match, and the name
3627 // matches, then we can merge the two into just the
3628 // Static symbol to avoid duplicate entries in the
3629 // symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003630 std::pair<ValueToSymbolIndexMap::const_iterator,
3631 ValueToSymbolIndexMap::const_iterator>
3632 range;
3633 range = N_STSYM_addr_to_sym_idx.equal_range(
3634 nlist.n_value);
3635 if (range.first != range.second) {
3636 bool found_it = false;
3637 for (ValueToSymbolIndexMap::const_iterator pos =
3638 range.first;
3639 pos != range.second; ++pos) {
3640 if (sym[sym_idx].GetMangled().GetName(
3641 lldb::eLanguageTypeUnknown,
3642 Mangled::ePreferMangled) ==
3643 sym[pos->second].GetMangled().GetName(
3644 lldb::eLanguageTypeUnknown,
3645 Mangled::ePreferMangled)) {
3646 m_nlist_idx_to_sym_idx[nlist_idx] =
3647 pos->second;
3648 // We just need the flags from the linker
3649 // symbol, so put these flags
3650 // into the N_STSYM flags to avoid duplicate
3651 // symbols in the symbol table
3652 sym[pos->second].SetExternal(
3653 sym[sym_idx].IsExternal());
3654 sym[pos->second].SetFlags(nlist.n_type << 16 |
3655 nlist.n_desc);
3656 sym[sym_idx].Clear();
3657 found_it = true;
3658 break;
Greg Claytonfd814c52013-08-13 01:42:25 +00003659 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003660 }
3661 if (found_it)
3662 continue;
3663 } else {
3664 const char *gsym_name =
3665 sym[sym_idx]
3666 .GetMangled()
3667 .GetName(lldb::eLanguageTypeUnknown,
3668 Mangled::ePreferMangled)
3669 .GetCString();
3670 if (gsym_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00003671 // Combine N_GSYM stab entries with the non
3672 // stab symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00003673 ConstNameToSymbolIndexMap::const_iterator pos =
3674 N_GSYM_name_to_sym_idx.find(gsym_name);
3675 if (pos != N_GSYM_name_to_sym_idx.end()) {
3676 const uint32_t GSYM_sym_idx = pos->second;
3677 m_nlist_idx_to_sym_idx[nlist_idx] =
3678 GSYM_sym_idx;
3679 // Copy the address, because often the N_GSYM
3680 // address has an invalid address of zero
3681 // when the global is a common symbol
3682 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3683 symbol_section);
3684 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3685 symbol_value);
3686 // We just need the flags from the linker
3687 // symbol, so put these flags
3688 // into the N_GSYM flags to avoid duplicate
3689 // symbols in the symbol table
3690 sym[GSYM_sym_idx].SetFlags(
3691 nlist.n_type << 16 | nlist.n_desc);
3692 sym[sym_idx].Clear();
3693 continue;
3694 }
3695 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003696 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003697 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003698 }
Greg Claytonfd814c52013-08-13 01:42:25 +00003699
Kate Stoneb9c1b512016-09-06 20:57:50 +00003700 sym[sym_idx].SetID(nlist_idx);
3701 sym[sym_idx].SetType(type);
3702 if (set_value) {
3703 sym[sym_idx].GetAddressRef().SetSection(
3704 symbol_section);
3705 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
Greg Clayton29e08cb2012-03-14 01:53:24 +00003706 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003707 sym[sym_idx].SetFlags(nlist.n_type << 16 |
3708 nlist.n_desc);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003709
Kate Stoneb9c1b512016-09-06 20:57:50 +00003710 if (symbol_byte_size > 0)
3711 sym[sym_idx].SetByteSize(symbol_byte_size);
Greg Claytonf3bb3e42012-03-09 04:26:05 +00003712
Kate Stoneb9c1b512016-09-06 20:57:50 +00003713 if (demangled_is_synthesized)
3714 sym[sym_idx].SetDemangledNameIsSynthesized(true);
Greg Clayton60038be2015-02-14 00:51:13 +00003715 ++sym_idx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003716 } else {
3717 sym[sym_idx].Clear();
3718 }
Greg Clayton9191db42013-10-21 18:40:51 +00003719 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003720 /////////////////////////////
3721 }
3722 break; // No more entries to consider
Greg Clayton9191db42013-10-21 18:40:51 +00003723 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003724 }
3725
3726 for (const auto &pos : reexport_shlib_needs_fixup) {
3727 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3728 if (undef_pos != undefined_name_to_desc.end()) {
3729 const uint8_t dylib_ordinal =
3730 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3731 if (dylib_ordinal > 0 &&
3732 dylib_ordinal < dylib_files.GetSize())
3733 sym[pos.first].SetReExportedSymbolSharedLibrary(
3734 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3735 }
3736 }
Greg Clayton9191db42013-10-21 18:40:51 +00003737 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003738 }
Greg Clayton9191db42013-10-21 18:40:51 +00003739 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003740 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003741 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003742
3743 // Must reset this in case it was mutated above!
3744 nlist_data_offset = 0;
3745#endif
3746
3747 if (nlist_data.GetByteSize() > 0) {
3748
3749 // If the sym array was not created while parsing the DSC unmapped
3750 // symbols, create it now.
3751 if (sym == NULL) {
3752 sym = symtab->Resize(symtab_load_command.nsyms +
3753 m_dysymtab.nindirectsyms);
3754 num_syms = symtab->GetNumSymbols();
3755 }
3756
3757 if (unmapped_local_symbols_found) {
3758 assert(m_dysymtab.ilocalsym == 0);
3759 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3760 nlist_idx = m_dysymtab.nlocalsym;
3761 } else {
3762 nlist_idx = 0;
3763 }
3764
3765 typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3766 typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3767 UndefinedNameToDescMap undefined_name_to_desc;
3768 SymbolIndexToName reexport_shlib_needs_fixup;
3769 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
3770 struct nlist_64 nlist;
3771 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset,
3772 nlist_byte_size))
3773 break;
3774
3775 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
3776 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
3777 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
3778 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
3779 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
3780
3781 SymbolType type = eSymbolTypeInvalid;
3782 const char *symbol_name = NULL;
3783
3784 if (have_strtab_data) {
3785 symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3786
3787 if (symbol_name == NULL) {
Adrian Prantl05097242018-04-30 16:49:04 +00003788 // No symbol should be NULL, even the symbols with no string values
3789 // should have an offset zero which points to an empty C-string
Kate Stoneb9c1b512016-09-06 20:57:50 +00003790 Host::SystemLog(Host::eSystemLogError,
3791 "error: symbol[%u] has invalid string table offset "
3792 "0x%x in %s, ignoring symbol\n",
3793 nlist_idx, nlist.n_strx,
3794 module_sp->GetFileSpec().GetPath().c_str());
3795 continue;
3796 }
3797 if (symbol_name[0] == '\0')
3798 symbol_name = NULL;
3799 } else {
3800 const addr_t str_addr = strtab_addr + nlist.n_strx;
Zachary Turner97206d52017-05-12 04:51:55 +00003801 Status str_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3803 str_error))
3804 symbol_name = memory_symbol_name.c_str();
3805 }
3806 const char *symbol_name_non_abi_mangled = NULL;
3807
3808 SectionSP symbol_section;
3809 lldb::addr_t symbol_byte_size = 0;
3810 bool add_nlist = true;
3811 bool is_gsym = false;
3812 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3813 bool demangled_is_synthesized = false;
3814 bool set_value = true;
3815 assert(sym_idx < num_syms);
3816
3817 sym[sym_idx].SetDebug(is_debug);
3818
3819 if (is_debug) {
3820 switch (nlist.n_type) {
3821 case N_GSYM:
3822 // global symbol: name,,NO_SECT,type,0
3823 // Sometimes the N_GSYM value contains the address.
3824
3825 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3826 // the ObjC data. They
3827 // have the same address, but we want to ensure that we always find
Adrian Prantl05097242018-04-30 16:49:04 +00003828 // only the real symbol, 'cause we don't currently correctly
3829 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3830 // type. This is a temporary hack to make sure the ObjectiveC
3831 // symbols get treated correctly. To do this right, we should
3832 // coalesce all the GSYM & global symbols that have the same
3833 // address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003834 is_gsym = true;
3835 sym[sym_idx].SetExternal(true);
3836
3837 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3838 llvm::StringRef symbol_name_ref(symbol_name);
3839 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3840 symbol_name_non_abi_mangled = symbol_name + 1;
3841 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3842 type = eSymbolTypeObjCClass;
3843 demangled_is_synthesized = true;
3844
3845 } else if (symbol_name_ref.startswith(
3846 g_objc_v2_prefix_metaclass)) {
3847 symbol_name_non_abi_mangled = symbol_name + 1;
3848 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3849 type = eSymbolTypeObjCMetaClass;
3850 demangled_is_synthesized = true;
3851 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3852 symbol_name_non_abi_mangled = symbol_name + 1;
3853 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3854 type = eSymbolTypeObjCIVar;
3855 demangled_is_synthesized = true;
3856 }
3857 } else {
3858 if (nlist.n_value != 0)
3859 symbol_section =
3860 section_info.GetSection(nlist.n_sect, nlist.n_value);
3861 type = eSymbolTypeData;
3862 }
3863 break;
3864
3865 case N_FNAME:
3866 // procedure name (f77 kludge): name,,NO_SECT,0,0
3867 type = eSymbolTypeCompiler;
3868 break;
3869
3870 case N_FUN:
3871 // procedure: name,,n_sect,linenumber,address
3872 if (symbol_name) {
3873 type = eSymbolTypeCode;
3874 symbol_section =
3875 section_info.GetSection(nlist.n_sect, nlist.n_value);
3876
3877 N_FUN_addr_to_sym_idx.insert(
3878 std::make_pair(nlist.n_value, sym_idx));
3879 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003880 // lieu of using nlist_idx in case we ever start trimming entries
3881 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003882 N_FUN_indexes.push_back(sym_idx);
3883 } else {
3884 type = eSymbolTypeCompiler;
3885
3886 if (!N_FUN_indexes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003887 // Copy the size of the function into the original STAB entry
3888 // so we don't have to hunt for it later
Kate Stoneb9c1b512016-09-06 20:57:50 +00003889 symtab->SymbolAtIndex(N_FUN_indexes.back())
3890 ->SetByteSize(nlist.n_value);
3891 N_FUN_indexes.pop_back();
Adrian Prantl05097242018-04-30 16:49:04 +00003892 // We don't really need the end function STAB as it contains
3893 // the size which we already placed with the original symbol,
3894 // so don't add it if we want a minimal symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895 add_nlist = false;
3896 }
3897 }
3898 break;
3899
3900 case N_STSYM:
3901 // static symbol: name,,n_sect,type,address
3902 N_STSYM_addr_to_sym_idx.insert(
3903 std::make_pair(nlist.n_value, sym_idx));
3904 symbol_section =
3905 section_info.GetSection(nlist.n_sect, nlist.n_value);
3906 if (symbol_name && symbol_name[0]) {
3907 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3908 eSymbolTypeData);
3909 }
3910 break;
3911
3912 case N_LCSYM:
3913 // .lcomm symbol: name,,n_sect,type,address
3914 symbol_section =
3915 section_info.GetSection(nlist.n_sect, nlist.n_value);
3916 type = eSymbolTypeCommonBlock;
3917 break;
3918
3919 case N_BNSYM:
3920 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00003921 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003922 // Skip these if we want minimal symbol tables
3923 add_nlist = false;
3924 break;
3925
3926 case N_ENSYM:
3927 // Set the size of the N_BNSYM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003928 // N_ENSYM so that we can always skip the entire symbol if we need
3929 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003930 // Skip these if we want minimal symbol tables
3931 add_nlist = false;
3932 break;
3933
3934 case N_OPT:
3935 // emitted with gcc2_compiled and in gcc source
3936 type = eSymbolTypeCompiler;
3937 break;
3938
3939 case N_RSYM:
3940 // register sym: name,,NO_SECT,type,register
3941 type = eSymbolTypeVariable;
3942 break;
3943
3944 case N_SLINE:
3945 // src line: 0,,n_sect,linenumber,address
3946 symbol_section =
3947 section_info.GetSection(nlist.n_sect, nlist.n_value);
3948 type = eSymbolTypeLineEntry;
3949 break;
3950
3951 case N_SSYM:
3952 // structure elt: name,,NO_SECT,type,struct_offset
3953 type = eSymbolTypeVariableType;
3954 break;
3955
3956 case N_SO:
3957 // source file name
3958 type = eSymbolTypeSourceFile;
3959 if (symbol_name == NULL) {
3960 add_nlist = false;
3961 if (N_SO_index != UINT32_MAX) {
3962 // Set the size of the N_SO to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00003963 // N_SO so that we can always skip the entire N_SO if we need
3964 // to navigate more quickly at the source level when parsing
3965 // STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00003966 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3967 symbol_ptr->SetByteSize(sym_idx);
3968 symbol_ptr->SetSizeIsSibling(true);
3969 }
3970 N_NSYM_indexes.clear();
3971 N_INCL_indexes.clear();
3972 N_BRAC_indexes.clear();
3973 N_COMM_indexes.clear();
3974 N_FUN_indexes.clear();
3975 N_SO_index = UINT32_MAX;
3976 } else {
3977 // We use the current number of symbols in the symbol table in
Adrian Prantl05097242018-04-30 16:49:04 +00003978 // lieu of using nlist_idx in case we ever start trimming entries
3979 // out
Kate Stoneb9c1b512016-09-06 20:57:50 +00003980 const bool N_SO_has_full_path = symbol_name[0] == '/';
3981 if (N_SO_has_full_path) {
3982 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3983 // We have two consecutive N_SO entries where the first
Adrian Prantl05097242018-04-30 16:49:04 +00003984 // contains a directory and the second contains a full path.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003985 sym[sym_idx - 1].GetMangled().SetValue(
3986 ConstString(symbol_name), false);
3987 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3988 add_nlist = false;
3989 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003990 // This is the first entry in a N_SO that contains a
3991 // directory or a full path to the source file
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992 N_SO_index = sym_idx;
3993 }
3994 } else if ((N_SO_index == sym_idx - 1) &&
3995 ((sym_idx - 1) < num_syms)) {
3996 // This is usually the second N_SO entry that contains just the
Adrian Prantl05097242018-04-30 16:49:04 +00003997 // filename, so here we combine it with the first one if we are
3998 // minimizing the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00003999 const char *so_path =
4000 sym[sym_idx - 1]
4001 .GetMangled()
4002 .GetDemangledName(lldb::eLanguageTypeUnknown)
4003 .AsCString();
4004 if (so_path && so_path[0]) {
4005 std::string full_so_path(so_path);
4006 const size_t double_slash_pos = full_so_path.find("//");
4007 if (double_slash_pos != std::string::npos) {
4008 // The linker has been generating bad N_SO entries with
Adrian Prantl05097242018-04-30 16:49:04 +00004009 // doubled up paths in the format "%s%s" where the first
4010 // string in the DW_AT_comp_dir, and the second is the
4011 // directory for the source file so you end up with a path
4012 // that looks like "/tmp/src//tmp/src/"
Kate Stoneb9c1b512016-09-06 20:57:50 +00004013 FileSpec so_dir(so_path, false);
4014 if (!so_dir.Exists()) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00004015 so_dir.SetFile(&full_so_path[double_slash_pos + 1], false,
4016 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004017 if (so_dir.Exists()) {
4018 // Trim off the incorrect path
4019 full_so_path.erase(0, double_slash_pos + 1);
4020 }
4021 }
4022 }
4023 if (*full_so_path.rbegin() != '/')
4024 full_so_path += '/';
4025 full_so_path += symbol_name;
4026 sym[sym_idx - 1].GetMangled().SetValue(
4027 ConstString(full_so_path.c_str()), false);
4028 add_nlist = false;
4029 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4030 }
4031 } else {
4032 // This could be a relative path to a N_SO
4033 N_SO_index = sym_idx;
4034 }
4035 }
4036 break;
4037
4038 case N_OSO:
4039 // object file name: name,,0,0,st_mtime
4040 type = eSymbolTypeObjectFile;
4041 break;
4042
4043 case N_LSYM:
4044 // local sym: name,,NO_SECT,type,offset
4045 type = eSymbolTypeLocal;
4046 break;
4047
4048 //----------------------------------------------------------------------
4049 // INCL scopes
4050 //----------------------------------------------------------------------
4051 case N_BINCL:
Adrian Prantl05097242018-04-30 16:49:04 +00004052 // include file beginning: name,,NO_SECT,0,sum We use the current
4053 // number of symbols in the symbol table in lieu of using nlist_idx
4054 // in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004055 N_INCL_indexes.push_back(sym_idx);
4056 type = eSymbolTypeScopeBegin;
4057 break;
4058
4059 case N_EINCL:
4060 // include file end: name,,NO_SECT,0,0
4061 // Set the size of the N_BINCL to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004062 // N_EINCL so that we can always skip the entire symbol if we need
4063 // to navigate more quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004064 if (!N_INCL_indexes.empty()) {
4065 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
4066 symbol_ptr->SetByteSize(sym_idx + 1);
4067 symbol_ptr->SetSizeIsSibling(true);
4068 N_INCL_indexes.pop_back();
4069 }
4070 type = eSymbolTypeScopeEnd;
4071 break;
4072
4073 case N_SOL:
4074 // #included file name: name,,n_sect,0,address
4075 type = eSymbolTypeHeaderFile;
4076
4077 // We currently don't use the header files on darwin
4078 add_nlist = false;
4079 break;
4080
4081 case N_PARAMS:
4082 // compiler parameters: name,,NO_SECT,0,0
4083 type = eSymbolTypeCompiler;
4084 break;
4085
4086 case N_VERSION:
4087 // compiler version: name,,NO_SECT,0,0
4088 type = eSymbolTypeCompiler;
4089 break;
4090
4091 case N_OLEVEL:
4092 // compiler -O level: name,,NO_SECT,0,0
4093 type = eSymbolTypeCompiler;
4094 break;
4095
4096 case N_PSYM:
4097 // parameter: name,,NO_SECT,type,offset
4098 type = eSymbolTypeVariable;
4099 break;
4100
4101 case N_ENTRY:
4102 // alternate entry: name,,n_sect,linenumber,address
4103 symbol_section =
4104 section_info.GetSection(nlist.n_sect, nlist.n_value);
4105 type = eSymbolTypeLineEntry;
4106 break;
4107
4108 //----------------------------------------------------------------------
4109 // Left and Right Braces
4110 //----------------------------------------------------------------------
4111 case N_LBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004112 // left bracket: 0,,NO_SECT,nesting level,address We use the
4113 // current number of symbols in the symbol table in lieu of using
4114 // nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004115 symbol_section =
4116 section_info.GetSection(nlist.n_sect, nlist.n_value);
4117 N_BRAC_indexes.push_back(sym_idx);
4118 type = eSymbolTypeScopeBegin;
4119 break;
4120
4121 case N_RBRAC:
Adrian Prantl05097242018-04-30 16:49:04 +00004122 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4123 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4124 // can always skip the entire symbol if we need to navigate more
4125 // quickly at the source level when parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004126 symbol_section =
4127 section_info.GetSection(nlist.n_sect, nlist.n_value);
4128 if (!N_BRAC_indexes.empty()) {
4129 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4130 symbol_ptr->SetByteSize(sym_idx + 1);
4131 symbol_ptr->SetSizeIsSibling(true);
4132 N_BRAC_indexes.pop_back();
4133 }
4134 type = eSymbolTypeScopeEnd;
4135 break;
4136
4137 case N_EXCL:
4138 // deleted include file: name,,NO_SECT,0,sum
4139 type = eSymbolTypeHeaderFile;
4140 break;
4141
4142 //----------------------------------------------------------------------
4143 // COMM scopes
4144 //----------------------------------------------------------------------
4145 case N_BCOMM:
4146 // begin common: name,,NO_SECT,0,0
4147 // We use the current number of symbols in the symbol table in lieu
Adrian Prantl05097242018-04-30 16:49:04 +00004148 // of using nlist_idx in case we ever start trimming entries out
Kate Stoneb9c1b512016-09-06 20:57:50 +00004149 type = eSymbolTypeScopeBegin;
4150 N_COMM_indexes.push_back(sym_idx);
4151 break;
4152
4153 case N_ECOML:
4154 // end common (local name): 0,,n_sect,0,address
4155 symbol_section =
4156 section_info.GetSection(nlist.n_sect, nlist.n_value);
4157 LLVM_FALLTHROUGH;
4158
4159 case N_ECOMM:
4160 // end common: name,,n_sect,0,0
4161 // Set the size of the N_BCOMM to the terminating index of this
Adrian Prantl05097242018-04-30 16:49:04 +00004162 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4163 // we need to navigate more quickly at the source level when
4164 // parsing STABS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004165 if (!N_COMM_indexes.empty()) {
4166 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4167 symbol_ptr->SetByteSize(sym_idx + 1);
4168 symbol_ptr->SetSizeIsSibling(true);
4169 N_COMM_indexes.pop_back();
4170 }
4171 type = eSymbolTypeScopeEnd;
4172 break;
4173
4174 case N_LENG:
4175 // second stab entry with length information
4176 type = eSymbolTypeAdditional;
4177 break;
4178
4179 default:
4180 break;
4181 }
4182 } else {
4183 // uint8_t n_pext = N_PEXT & nlist.n_type;
4184 uint8_t n_type = N_TYPE & nlist.n_type;
4185 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4186
4187 switch (n_type) {
4188 case N_INDR: {
4189 const char *reexport_name_cstr =
4190 strtab_data.PeekCStr(nlist.n_value);
4191 if (reexport_name_cstr && reexport_name_cstr[0]) {
4192 type = eSymbolTypeReExported;
4193 ConstString reexport_name(
4194 reexport_name_cstr +
4195 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4196 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4197 set_value = false;
4198 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4199 indirect_symbol_names.insert(
4200 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4201 } else
4202 type = eSymbolTypeUndefined;
4203 } break;
4204
4205 case N_UNDF:
4206 if (symbol_name && symbol_name[0]) {
4207 ConstString undefined_name(symbol_name +
4208 ((symbol_name[0] == '_') ? 1 : 0));
4209 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4210 }
4211 LLVM_FALLTHROUGH;
4212
4213 case N_PBUD:
4214 type = eSymbolTypeUndefined;
4215 break;
4216
4217 case N_ABS:
4218 type = eSymbolTypeAbsolute;
4219 break;
4220
4221 case N_SECT: {
4222 symbol_section =
4223 section_info.GetSection(nlist.n_sect, nlist.n_value);
4224
4225 if (!symbol_section) {
4226 // TODO: warn about this?
4227 add_nlist = false;
4228 break;
4229 }
4230
4231 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4232 type = eSymbolTypeException;
4233 } else {
4234 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4235
4236 switch (section_type) {
4237 case S_CSTRING_LITERALS:
4238 type = eSymbolTypeData;
4239 break; // section with only literal C strings
4240 case S_4BYTE_LITERALS:
4241 type = eSymbolTypeData;
4242 break; // section with only 4 byte literals
4243 case S_8BYTE_LITERALS:
4244 type = eSymbolTypeData;
4245 break; // section with only 8 byte literals
4246 case S_LITERAL_POINTERS:
4247 type = eSymbolTypeTrampoline;
4248 break; // section with only pointers to literals
4249 case S_NON_LAZY_SYMBOL_POINTERS:
4250 type = eSymbolTypeTrampoline;
4251 break; // section with only non-lazy symbol pointers
4252 case S_LAZY_SYMBOL_POINTERS:
4253 type = eSymbolTypeTrampoline;
4254 break; // section with only lazy symbol pointers
4255 case S_SYMBOL_STUBS:
4256 type = eSymbolTypeTrampoline;
4257 break; // section with only symbol stubs, byte size of stub in
4258 // the reserved2 field
4259 case S_MOD_INIT_FUNC_POINTERS:
4260 type = eSymbolTypeCode;
4261 break; // section with only function pointers for initialization
4262 case S_MOD_TERM_FUNC_POINTERS:
4263 type = eSymbolTypeCode;
4264 break; // section with only function pointers for termination
4265 case S_INTERPOSING:
4266 type = eSymbolTypeTrampoline;
4267 break; // section with only pairs of function pointers for
4268 // interposing
4269 case S_16BYTE_LITERALS:
4270 type = eSymbolTypeData;
4271 break; // section with only 16 byte literals
4272 case S_DTRACE_DOF:
4273 type = eSymbolTypeInstrumentation;
4274 break;
4275 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4276 type = eSymbolTypeTrampoline;
4277 break;
4278 default:
4279 switch (symbol_section->GetType()) {
4280 case lldb::eSectionTypeCode:
4281 type = eSymbolTypeCode;
4282 break;
4283 case eSectionTypeData:
4284 case eSectionTypeDataCString: // Inlined C string data
4285 case eSectionTypeDataCStringPointers: // Pointers to C string
4286 // data
4287 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4288 // the symbol table
4289 case eSectionTypeData4:
4290 case eSectionTypeData8:
4291 case eSectionTypeData16:
4292 type = eSymbolTypeData;
4293 break;
4294 default:
4295 break;
4296 }
4297 break;
4298 }
4299
4300 if (type == eSymbolTypeInvalid) {
4301 const char *symbol_sect_name =
4302 symbol_section->GetName().AsCString();
4303 if (symbol_section->IsDescendant(text_section_sp.get())) {
4304 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4305 S_ATTR_SELF_MODIFYING_CODE |
4306 S_ATTR_SOME_INSTRUCTIONS))
4307 type = eSymbolTypeData;
4308 else
4309 type = eSymbolTypeCode;
4310 } else if (symbol_section->IsDescendant(
4311 data_section_sp.get()) ||
4312 symbol_section->IsDescendant(
4313 data_dirty_section_sp.get()) ||
4314 symbol_section->IsDescendant(
4315 data_const_section_sp.get())) {
4316 if (symbol_sect_name &&
4317 ::strstr(symbol_sect_name, "__objc") ==
4318 symbol_sect_name) {
4319 type = eSymbolTypeRuntime;
4320
4321 if (symbol_name) {
4322 llvm::StringRef symbol_name_ref(symbol_name);
4323 if (symbol_name_ref.startswith("_OBJC_")) {
4324 static const llvm::StringRef g_objc_v2_prefix_class(
4325 "_OBJC_CLASS_$_");
4326 static const llvm::StringRef g_objc_v2_prefix_metaclass(
4327 "_OBJC_METACLASS_$_");
4328 static const llvm::StringRef g_objc_v2_prefix_ivar(
4329 "_OBJC_IVAR_$_");
4330 if (symbol_name_ref.startswith(
4331 g_objc_v2_prefix_class)) {
4332 symbol_name_non_abi_mangled = symbol_name + 1;
4333 symbol_name =
4334 symbol_name + g_objc_v2_prefix_class.size();
4335 type = eSymbolTypeObjCClass;
4336 demangled_is_synthesized = true;
4337 } else if (symbol_name_ref.startswith(
4338 g_objc_v2_prefix_metaclass)) {
4339 symbol_name_non_abi_mangled = symbol_name + 1;
4340 symbol_name =
4341 symbol_name + g_objc_v2_prefix_metaclass.size();
4342 type = eSymbolTypeObjCMetaClass;
4343 demangled_is_synthesized = true;
4344 } else if (symbol_name_ref.startswith(
4345 g_objc_v2_prefix_ivar)) {
4346 symbol_name_non_abi_mangled = symbol_name + 1;
4347 symbol_name =
4348 symbol_name + g_objc_v2_prefix_ivar.size();
4349 type = eSymbolTypeObjCIVar;
4350 demangled_is_synthesized = true;
4351 }
4352 }
4353 }
4354 } else if (symbol_sect_name &&
4355 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4356 symbol_sect_name) {
4357 type = eSymbolTypeException;
4358 } else {
4359 type = eSymbolTypeData;
4360 }
4361 } else if (symbol_sect_name &&
4362 ::strstr(symbol_sect_name, "__IMPORT") ==
4363 symbol_sect_name) {
4364 type = eSymbolTypeTrampoline;
4365 } else if (symbol_section->IsDescendant(
4366 objc_section_sp.get())) {
4367 type = eSymbolTypeRuntime;
4368 if (symbol_name && symbol_name[0] == '.') {
4369 llvm::StringRef symbol_name_ref(symbol_name);
4370 static const llvm::StringRef g_objc_v1_prefix_class(
4371 ".objc_class_name_");
4372 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4373 symbol_name_non_abi_mangled = symbol_name;
4374 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4375 type = eSymbolTypeObjCClass;
4376 demangled_is_synthesized = true;
4377 }
4378 }
4379 }
4380 }
4381 }
4382 } break;
4383 }
4384 }
4385
4386 if (add_nlist) {
4387 uint64_t symbol_value = nlist.n_value;
4388
4389 if (symbol_name_non_abi_mangled) {
4390 sym[sym_idx].GetMangled().SetMangledName(
4391 ConstString(symbol_name_non_abi_mangled));
4392 sym[sym_idx].GetMangled().SetDemangledName(
4393 ConstString(symbol_name));
4394 } else {
4395 bool symbol_name_is_mangled = false;
4396
4397 if (symbol_name && symbol_name[0] == '_') {
4398 symbol_name_is_mangled = symbol_name[1] == '_';
4399 symbol_name++; // Skip the leading underscore
4400 }
4401
4402 if (symbol_name) {
4403 ConstString const_symbol_name(symbol_name);
4404 sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4405 symbol_name_is_mangled);
4406 }
4407 }
4408
4409 if (is_gsym) {
4410 const char *gsym_name = sym[sym_idx]
4411 .GetMangled()
4412 .GetName(lldb::eLanguageTypeUnknown,
4413 Mangled::ePreferMangled)
4414 .GetCString();
4415 if (gsym_name)
4416 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4417 }
4418
4419 if (symbol_section) {
4420 const addr_t section_file_addr = symbol_section->GetFileAddress();
4421 if (symbol_byte_size == 0 && function_starts_count > 0) {
4422 addr_t symbol_lookup_file_addr = nlist.n_value;
4423 // Do an exact address match for non-ARM addresses, else get the
Adrian Prantl05097242018-04-30 16:49:04 +00004424 // closest since the symbol might be a thumb symbol which has an
4425 // address with bit zero set
Kate Stoneb9c1b512016-09-06 20:57:50 +00004426 FunctionStarts::Entry *func_start_entry =
4427 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4428 if (is_arm && func_start_entry) {
4429 // Verify that the function start address is the symbol address
Adrian Prantl05097242018-04-30 16:49:04 +00004430 // (ARM) or the symbol address + 1 (thumb)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004431 if (func_start_entry->addr != symbol_lookup_file_addr &&
4432 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4433 // Not the right entry, NULL it out...
4434 func_start_entry = NULL;
4435 }
4436 }
4437 if (func_start_entry) {
4438 func_start_entry->data = true;
4439
4440 addr_t symbol_file_addr = func_start_entry->addr;
4441 if (is_arm)
4442 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4443
4444 const FunctionStarts::Entry *next_func_start_entry =
4445 function_starts.FindNextEntry(func_start_entry);
4446 const addr_t section_end_file_addr =
4447 section_file_addr + symbol_section->GetByteSize();
4448 if (next_func_start_entry) {
4449 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4450 // Be sure the clear the Thumb address bit when we calculate
Adrian Prantl05097242018-04-30 16:49:04 +00004451 // the size from the current and next address
Kate Stoneb9c1b512016-09-06 20:57:50 +00004452 if (is_arm)
4453 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4454 symbol_byte_size = std::min<lldb::addr_t>(
4455 next_symbol_file_addr - symbol_file_addr,
4456 section_end_file_addr - symbol_file_addr);
4457 } else {
4458 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4459 }
4460 }
4461 }
4462 symbol_value -= section_file_addr;
4463 }
4464
4465 if (is_debug == false) {
4466 if (type == eSymbolTypeCode) {
Adrian Prantl05097242018-04-30 16:49:04 +00004467 // See if we can find a N_FUN entry for any code symbols. If we
4468 // do find a match, and the name matches, then we can merge the
4469 // two into just the function symbol to avoid duplicate entries
4470 // in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004471 std::pair<ValueToSymbolIndexMap::const_iterator,
4472 ValueToSymbolIndexMap::const_iterator>
4473 range;
4474 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4475 if (range.first != range.second) {
4476 bool found_it = false;
4477 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4478 pos != range.second; ++pos) {
4479 if (sym[sym_idx].GetMangled().GetName(
4480 lldb::eLanguageTypeUnknown,
4481 Mangled::ePreferMangled) ==
4482 sym[pos->second].GetMangled().GetName(
4483 lldb::eLanguageTypeUnknown,
4484 Mangled::ePreferMangled)) {
4485 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4486 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004487 // these flags into the N_FUN flags to avoid duplicate
4488 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004489 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4490 sym[pos->second].SetFlags(nlist.n_type << 16 |
4491 nlist.n_desc);
4492 if (resolver_addresses.find(nlist.n_value) !=
4493 resolver_addresses.end())
4494 sym[pos->second].SetType(eSymbolTypeResolver);
4495 sym[sym_idx].Clear();
4496 found_it = true;
4497 break;
4498 }
4499 }
4500 if (found_it)
4501 continue;
4502 } else {
4503 if (resolver_addresses.find(nlist.n_value) !=
4504 resolver_addresses.end())
4505 type = eSymbolTypeResolver;
4506 }
4507 } else if (type == eSymbolTypeData ||
4508 type == eSymbolTypeObjCClass ||
4509 type == eSymbolTypeObjCMetaClass ||
4510 type == eSymbolTypeObjCIVar) {
Adrian Prantl05097242018-04-30 16:49:04 +00004511 // See if we can find a N_STSYM entry for any data symbols. If we
4512 // do find a match, and the name matches, then we can merge the
4513 // two into just the Static symbol to avoid duplicate entries in
4514 // the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004515 std::pair<ValueToSymbolIndexMap::const_iterator,
4516 ValueToSymbolIndexMap::const_iterator>
4517 range;
4518 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4519 if (range.first != range.second) {
4520 bool found_it = false;
4521 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4522 pos != range.second; ++pos) {
4523 if (sym[sym_idx].GetMangled().GetName(
4524 lldb::eLanguageTypeUnknown,
4525 Mangled::ePreferMangled) ==
4526 sym[pos->second].GetMangled().GetName(
4527 lldb::eLanguageTypeUnknown,
4528 Mangled::ePreferMangled)) {
4529 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4530 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004531 // these flags into the N_STSYM flags to avoid duplicate
4532 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004533 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4534 sym[pos->second].SetFlags(nlist.n_type << 16 |
4535 nlist.n_desc);
4536 sym[sym_idx].Clear();
4537 found_it = true;
4538 break;
4539 }
4540 }
4541 if (found_it)
4542 continue;
4543 } else {
4544 // Combine N_GSYM stab entries with the non stab symbol
4545 const char *gsym_name = sym[sym_idx]
4546 .GetMangled()
4547 .GetName(lldb::eLanguageTypeUnknown,
4548 Mangled::ePreferMangled)
4549 .GetCString();
4550 if (gsym_name) {
4551 ConstNameToSymbolIndexMap::const_iterator pos =
4552 N_GSYM_name_to_sym_idx.find(gsym_name);
4553 if (pos != N_GSYM_name_to_sym_idx.end()) {
4554 const uint32_t GSYM_sym_idx = pos->second;
4555 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
Adrian Prantl05097242018-04-30 16:49:04 +00004556 // Copy the address, because often the N_GSYM address has
4557 // an invalid address of zero when the global is a common
4558 // symbol
Kate Stoneb9c1b512016-09-06 20:57:50 +00004559 sym[GSYM_sym_idx].GetAddressRef().SetSection(
4560 symbol_section);
4561 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4562 // We just need the flags from the linker symbol, so put
Adrian Prantl05097242018-04-30 16:49:04 +00004563 // these flags into the N_GSYM flags to avoid duplicate
4564 // symbols in the symbol table
Kate Stoneb9c1b512016-09-06 20:57:50 +00004565 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
4566 nlist.n_desc);
4567 sym[sym_idx].Clear();
4568 continue;
4569 }
4570 }
4571 }
4572 }
4573 }
4574
4575 sym[sym_idx].SetID(nlist_idx);
4576 sym[sym_idx].SetType(type);
4577 if (set_value) {
4578 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4579 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4580 }
4581 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4582
4583 if (symbol_byte_size > 0)
4584 sym[sym_idx].SetByteSize(symbol_byte_size);
4585
4586 if (demangled_is_synthesized)
4587 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4588
4589 ++sym_idx;
4590 } else {
4591 sym[sym_idx].Clear();
4592 }
4593 }
4594
4595 for (const auto &pos : reexport_shlib_needs_fixup) {
4596 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4597 if (undef_pos != undefined_name_to_desc.end()) {
4598 const uint8_t dylib_ordinal =
4599 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4600 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4601 sym[pos.first].SetReExportedSymbolSharedLibrary(
4602 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4603 }
4604 }
4605 }
4606
4607 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4608
4609 if (function_starts_count > 0) {
4610 uint32_t num_synthetic_function_symbols = 0;
4611 for (i = 0; i < function_starts_count; ++i) {
4612 if (function_starts.GetEntryRef(i).data == false)
4613 ++num_synthetic_function_symbols;
4614 }
4615
4616 if (num_synthetic_function_symbols > 0) {
4617 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4618 num_syms = sym_idx + num_synthetic_function_symbols;
4619 sym = symtab->Resize(num_syms);
4620 }
4621 for (i = 0; i < function_starts_count; ++i) {
4622 const FunctionStarts::Entry *func_start_entry =
4623 function_starts.GetEntryAtIndex(i);
4624 if (func_start_entry->data == false) {
4625 addr_t symbol_file_addr = func_start_entry->addr;
4626 uint32_t symbol_flags = 0;
4627 if (is_arm) {
4628 if (symbol_file_addr & 1)
4629 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4630 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4631 }
4632 Address symbol_addr;
4633 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4634 SectionSP symbol_section(symbol_addr.GetSection());
4635 uint32_t symbol_byte_size = 0;
4636 if (symbol_section) {
4637 const addr_t section_file_addr =
4638 symbol_section->GetFileAddress();
4639 const FunctionStarts::Entry *next_func_start_entry =
4640 function_starts.FindNextEntry(func_start_entry);
4641 const addr_t section_end_file_addr =
4642 section_file_addr + symbol_section->GetByteSize();
4643 if (next_func_start_entry) {
4644 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4645 if (is_arm)
4646 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4647 symbol_byte_size = std::min<lldb::addr_t>(
4648 next_symbol_file_addr - symbol_file_addr,
4649 section_end_file_addr - symbol_file_addr);
4650 } else {
4651 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4652 }
4653 sym[sym_idx].SetID(synthetic_sym_id++);
4654 sym[sym_idx].GetMangled().SetDemangledName(
4655 GetNextSyntheticSymbolName());
4656 sym[sym_idx].SetType(eSymbolTypeCode);
4657 sym[sym_idx].SetIsSynthetic(true);
4658 sym[sym_idx].GetAddressRef() = symbol_addr;
4659 if (symbol_flags)
4660 sym[sym_idx].SetFlags(symbol_flags);
4661 if (symbol_byte_size)
4662 sym[sym_idx].SetByteSize(symbol_byte_size);
4663 ++sym_idx;
4664 }
4665 }
4666 }
4667 }
4668 }
4669 }
4670
Adrian Prantl05097242018-04-30 16:49:04 +00004671 // Trim our symbols down to just what we ended up with after removing any
4672 // symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004673 if (sym_idx < num_syms) {
4674 num_syms = sym_idx;
4675 sym = symtab->Resize(num_syms);
4676 }
4677
4678 // Now synthesize indirect symbols
4679 if (m_dysymtab.nindirectsyms != 0) {
4680 if (indirect_symbol_index_data.GetByteSize()) {
4681 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4682 m_nlist_idx_to_sym_idx.end();
4683
4684 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4685 ++sect_idx) {
4686 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4687 S_SYMBOL_STUBS) {
4688 uint32_t symbol_stub_byte_size =
4689 m_mach_sections[sect_idx].reserved2;
4690 if (symbol_stub_byte_size == 0)
4691 continue;
4692
4693 const uint32_t num_symbol_stubs =
4694 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4695
4696 if (num_symbol_stubs == 0)
4697 continue;
4698
4699 const uint32_t symbol_stub_index_offset =
4700 m_mach_sections[sect_idx].reserved1;
4701 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs;
4702 ++stub_idx) {
4703 const uint32_t symbol_stub_index =
4704 symbol_stub_index_offset + stub_idx;
4705 const lldb::addr_t symbol_stub_addr =
4706 m_mach_sections[sect_idx].addr +
4707 (stub_idx * symbol_stub_byte_size);
4708 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4709 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4710 symbol_stub_offset, 4)) {
4711 const uint32_t stub_sym_id =
4712 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4713 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4714 continue;
4715
4716 NListIndexToSymbolIndexMap::const_iterator index_pos =
4717 m_nlist_idx_to_sym_idx.find(stub_sym_id);
4718 Symbol *stub_symbol = NULL;
4719 if (index_pos != end_index_pos) {
Adrian Prantl05097242018-04-30 16:49:04 +00004720 // We have a remapping from the original nlist index to a
4721 // current symbol index, so just look this up by index
Kate Stoneb9c1b512016-09-06 20:57:50 +00004722 stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4723 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004724 // We need to lookup a symbol using the original nlist symbol
4725 // index since this index is coming from the S_SYMBOL_STUBS
Kate Stoneb9c1b512016-09-06 20:57:50 +00004726 stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4727 }
4728
4729 if (stub_symbol) {
4730 Address so_addr(symbol_stub_addr, section_list);
4731
4732 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4733 // Change the external symbol into a trampoline that makes
Adrian Prantl05097242018-04-30 16:49:04 +00004734 // sense These symbols were N_UNDF N_EXT, and are useless
4735 // to us, so we can re-use them so we don't have to make up
4736 // a synthetic symbol for no good reason.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004737 if (resolver_addresses.find(symbol_stub_addr) ==
4738 resolver_addresses.end())
4739 stub_symbol->SetType(eSymbolTypeTrampoline);
4740 else
4741 stub_symbol->SetType(eSymbolTypeResolver);
4742 stub_symbol->SetExternal(false);
4743 stub_symbol->GetAddressRef() = so_addr;
4744 stub_symbol->SetByteSize(symbol_stub_byte_size);
4745 } else {
4746 // Make a synthetic symbol to describe the trampoline stub
4747 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4748 if (sym_idx >= num_syms) {
4749 sym = symtab->Resize(++num_syms);
4750 stub_symbol = NULL; // this pointer no longer valid
4751 }
4752 sym[sym_idx].SetID(synthetic_sym_id++);
4753 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4754 if (resolver_addresses.find(symbol_stub_addr) ==
4755 resolver_addresses.end())
4756 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4757 else
4758 sym[sym_idx].SetType(eSymbolTypeResolver);
4759 sym[sym_idx].SetIsSynthetic(true);
4760 sym[sym_idx].GetAddressRef() = so_addr;
4761 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4762 ++sym_idx;
4763 }
4764 } else {
4765 if (log)
4766 log->Warning("symbol stub referencing symbol table symbol "
4767 "%u that isn't in our minimal symbol table, "
4768 "fix this!!!",
4769 stub_sym_id);
4770 }
4771 }
4772 }
4773 }
4774 }
4775 }
4776 }
4777
4778 if (!trie_entries.empty()) {
4779 for (const auto &e : trie_entries) {
4780 if (e.entry.import_name) {
Adrian Prantl05097242018-04-30 16:49:04 +00004781 // Only add indirect symbols from the Trie entries if we didn't have
4782 // a N_INDR nlist entry for this already
Kate Stoneb9c1b512016-09-06 20:57:50 +00004783 if (indirect_symbol_names.find(e.entry.name) ==
4784 indirect_symbol_names.end()) {
4785 // Make a synthetic symbol to describe re-exported symbol.
4786 if (sym_idx >= num_syms)
4787 sym = symtab->Resize(++num_syms);
4788 sym[sym_idx].SetID(synthetic_sym_id++);
4789 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4790 sym[sym_idx].SetType(eSymbolTypeReExported);
4791 sym[sym_idx].SetIsSynthetic(true);
4792 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4793 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4794 sym[sym_idx].SetReExportedSymbolSharedLibrary(
4795 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4796 }
4797 ++sym_idx;
4798 }
4799 }
4800 }
4801 }
4802
4803 // StreamFile s(stdout, false);
4804 // s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4805 // symtab->Dump(&s, NULL, eSortOrderNone);
4806 // Set symbol byte sizes correctly since mach-o nlist entries don't have
4807 // sizes
4808 symtab->CalculateSymbolSizes();
4809
4810 // s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4811 // symtab->Dump(&s, NULL, eSortOrderNone);
4812
4813 return symtab->GetNumSymbols();
4814 }
4815 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004816}
4817
Kate Stoneb9c1b512016-09-06 20:57:50 +00004818void ObjectFileMachO::Dump(Stream *s) {
4819 ModuleSP module_sp(GetModule());
4820 if (module_sp) {
4821 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4822 s->Printf("%p: ", static_cast<void *>(this));
4823 s->Indent();
4824 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4825 s->PutCString("ObjectFileMachO64");
4826 else
4827 s->PutCString("ObjectFileMachO32");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004828
Kate Stoneb9c1b512016-09-06 20:57:50 +00004829 ArchSpec header_arch;
4830 GetArchitecture(header_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004831
Kate Stoneb9c1b512016-09-06 20:57:50 +00004832 *s << ", file = '" << m_file
Adrian Prantl9702c962018-05-11 00:41:20 +00004833 << "', triple = " << header_arch.GetTriple().getTriple() << "\n";
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004834
Kate Stoneb9c1b512016-09-06 20:57:50 +00004835 SectionList *sections = GetSectionList();
4836 if (sections)
4837 sections->Dump(s, NULL, true, UINT32_MAX);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004838
Kate Stoneb9c1b512016-09-06 20:57:50 +00004839 if (m_symtab_ap.get())
4840 m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4841 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004842}
4843
Kate Stoneb9c1b512016-09-06 20:57:50 +00004844bool ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4845 const lldb_private::DataExtractor &data,
4846 lldb::offset_t lc_offset,
4847 lldb_private::UUID &uuid) {
4848 uint32_t i;
4849 struct uuid_command load_cmd;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004850
Kate Stoneb9c1b512016-09-06 20:57:50 +00004851 lldb::offset_t offset = lc_offset;
4852 for (i = 0; i < header.ncmds; ++i) {
4853 const lldb::offset_t cmd_offset = offset;
4854 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4855 break;
4856
4857 if (load_cmd.cmd == LC_UUID) {
4858 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4859
4860 if (uuid_bytes) {
4861 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4862 // We pretend these object files have no UUID to prevent crashing.
4863
4864 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4865 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4866 0xbb, 0x14, 0xf0, 0x0d};
4867
4868 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4869 return false;
4870
Pavel Labath2f93fd12018-06-26 15:12:20 +00004871 uuid = UUID::fromOptionalData(uuid_bytes, 16);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004872 return true;
4873 }
4874 return false;
4875 }
4876 offset = cmd_offset + load_cmd.cmdsize;
4877 }
4878 return false;
4879}
4880
Adrian Prantl9702c962018-05-11 00:41:20 +00004881static const char *GetOSName(uint32_t cmd) {
4882 switch (cmd) {
4883 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4884 return "ios";
4885 case llvm::MachO::LC_VERSION_MIN_MACOSX:
4886 return "macosx";
4887 case llvm::MachO::LC_VERSION_MIN_TVOS:
4888 return "tvos";
4889 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4890 return "watchos";
4891 default:
4892 llvm_unreachable("unexpected LC_VERSION load command");
4893 }
4894}
4895
Kate Stoneb9c1b512016-09-06 20:57:50 +00004896bool ObjectFileMachO::GetArchitecture(const llvm::MachO::mach_header &header,
4897 const lldb_private::DataExtractor &data,
4898 lldb::offset_t lc_offset,
4899 ArchSpec &arch) {
4900 arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4901
4902 if (arch.IsValid()) {
4903 llvm::Triple &triple = arch.GetTriple();
4904
4905 // Set OS to an unspecified unknown or a "*" so it can match any OS
4906 triple.setOS(llvm::Triple::UnknownOS);
4907 triple.setOSName(llvm::StringRef());
4908
4909 if (header.filetype == MH_PRELOAD) {
4910 if (header.cputype == CPU_TYPE_ARM) {
Adrian Prantl05097242018-04-30 16:49:04 +00004911 // If this is a 32-bit arm binary, and it's a standalone binary, force
4912 // the Vendor to Apple so we don't accidentally pick up the generic
4913 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4914 // frame pointer register; most other armv7 ABIs use a combination of
4915 // r7 and r11.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004916 triple.setVendor(llvm::Triple::Apple);
4917 } else {
4918 // Set vendor to an unspecified unknown or a "*" so it can match any
Adrian Prantl05097242018-04-30 16:49:04 +00004919 // vendor This is required for correct behavior of EFI debugging on
4920 // x86_64
Kate Stoneb9c1b512016-09-06 20:57:50 +00004921 triple.setVendor(llvm::Triple::UnknownVendor);
4922 triple.setVendorName(llvm::StringRef());
4923 }
4924 return true;
4925 } else {
4926 struct load_command load_cmd;
4927
4928 lldb::offset_t offset = lc_offset;
4929 for (uint32_t i = 0; i < header.ncmds; ++i) {
Greg Claytonf4d6de62013-04-24 22:29:28 +00004930 const lldb::offset_t cmd_offset = offset;
4931 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004932 break;
4933
Adrian Prantl9702c962018-05-11 00:41:20 +00004934 uint32_t major, minor, patch;
4935 struct version_min_command version_min;
4936
4937 llvm::SmallString<16> os_name;
4938 llvm::raw_svector_ostream os(os_name);
4939
Kate Stoneb9c1b512016-09-06 20:57:50 +00004940 switch (load_cmd.cmd) {
4941 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004942 case llvm::MachO::LC_VERSION_MIN_MACOSX:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004943 case llvm::MachO::LC_VERSION_MIN_TVOS:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004944 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
Adrian Prantl9702c962018-05-11 00:41:20 +00004945 if (load_cmd.cmdsize != sizeof(version_min))
4946 break;
4947 data.ExtractBytes(cmd_offset,
4948 sizeof(version_min), data.GetByteOrder(),
4949 &version_min);
4950 major = version_min.version >> 16;
4951 minor = (version_min.version >> 8) & 0xffu;
4952 patch = version_min.version & 0xffu;
4953 os << GetOSName(load_cmd.cmd) << major << '.' << minor << '.'
4954 << patch;
4955 triple.setOSName(os.str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004956 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004957 default:
4958 break;
Greg Claytonf4d6de62013-04-24 22:29:28 +00004959 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004960
Greg Claytonf4d6de62013-04-24 22:29:28 +00004961 offset = cmd_offset + load_cmd.cmdsize;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004962 }
4963
4964 if (header.filetype != MH_KEXT_BUNDLE) {
4965 // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
4966 // so lets not say our Vendor is Apple, leave it as an unspecified
4967 // unknown
4968 triple.setVendor(llvm::Triple::UnknownVendor);
4969 triple.setVendorName(llvm::StringRef());
4970 }
Greg Claytonf4d6de62013-04-24 22:29:28 +00004971 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004972 }
4973 return arch.IsValid();
Greg Claytonf4d6de62013-04-24 22:29:28 +00004974}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004975
Kate Stoneb9c1b512016-09-06 20:57:50 +00004976bool ObjectFileMachO::GetUUID(lldb_private::UUID *uuid) {
4977 ModuleSP module_sp(GetModule());
4978 if (module_sp) {
4979 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4980 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4981 return GetUUID(m_header, m_data, offset, *uuid);
4982 }
4983 return false;
Greg Clayton7ab7f892014-05-29 21:33:45 +00004984}
4985
Kate Stoneb9c1b512016-09-06 20:57:50 +00004986uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
4987 uint32_t count = 0;
4988 ModuleSP module_sp(GetModule());
4989 if (module_sp) {
4990 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4991 struct load_command load_cmd;
4992 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4993 std::vector<std::string> rpath_paths;
4994 std::vector<std::string> rpath_relative_paths;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00004995 std::vector<std::string> at_exec_relative_paths;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996 const bool resolve_path = false; // Don't resolve the dependent file paths
Adrian Prantl05097242018-04-30 16:49:04 +00004997 // since they may not reside on this
4998 // system
Kate Stoneb9c1b512016-09-06 20:57:50 +00004999 uint32_t i;
5000 for (i = 0; i < m_header.ncmds; ++i) {
5001 const uint32_t cmd_offset = offset;
5002 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5003 break;
5004
5005 switch (load_cmd.cmd) {
5006 case LC_RPATH:
5007 case LC_LOAD_DYLIB:
5008 case LC_LOAD_WEAK_DYLIB:
5009 case LC_REEXPORT_DYLIB:
5010 case LC_LOAD_DYLINKER:
5011 case LC_LOADFVMLIB:
5012 case LC_LOAD_UPWARD_DYLIB: {
5013 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5014 const char *path = m_data.PeekCStr(name_offset);
5015 if (path) {
5016 if (load_cmd.cmd == LC_RPATH)
5017 rpath_paths.push_back(path);
5018 else {
5019 if (path[0] == '@') {
5020 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5021 rpath_relative_paths.push_back(path + strlen("@rpath"));
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005022 else if (strncmp(path, "@executable_path",
5023 strlen("@executable_path")) == 0)
5024 at_exec_relative_paths.push_back(path
5025 + strlen("@executable_path"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005026 } else {
5027 FileSpec file_spec(path, resolve_path);
5028 if (files.AppendIfUnique(file_spec))
5029 count++;
5030 }
5031 }
5032 }
5033 } break;
5034
5035 default:
5036 break;
5037 }
5038 offset = cmd_offset + load_cmd.cmdsize;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005039 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005040
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005041 FileSpec this_file_spec(m_file);
5042 this_file_spec.ResolvePath();
5043
Kate Stoneb9c1b512016-09-06 20:57:50 +00005044 if (!rpath_paths.empty()) {
5045 // Fixup all LC_RPATH values to be absolute paths
Kate Stoneb9c1b512016-09-06 20:57:50 +00005046 std::string loader_path("@loader_path");
5047 std::string executable_path("@executable_path");
5048 for (auto &rpath : rpath_paths) {
5049 if (rpath.find(loader_path) == 0) {
5050 rpath.erase(0, loader_path.size());
5051 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5052 } else if (rpath.find(executable_path) == 0) {
5053 rpath.erase(0, executable_path.size());
5054 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5055 }
5056 }
5057
5058 for (const auto &rpath_relative_path : rpath_relative_paths) {
5059 for (const auto &rpath : rpath_paths) {
5060 std::string path = rpath;
5061 path += rpath_relative_path;
Adrian Prantl05097242018-04-30 16:49:04 +00005062 // It is OK to resolve this path because we must find a file on disk
5063 // for us to accept it anyway if it is rpath relative.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005064 FileSpec file_spec(path, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005065 if (file_spec.Exists() && files.AppendIfUnique(file_spec)) {
5066 count++;
5067 break;
5068 }
5069 }
5070 }
5071 }
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005072
5073 // We may have @executable_paths but no RPATHS. Figure those out here.
5074 // Only do this if this object file is the executable. We have no way to
5075 // get back to the actual executable otherwise, so we won't get the right
5076 // path.
5077 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5078 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5079 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5080 FileSpec file_spec =
5081 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
Adrian Prantl5ec76fe2018-01-30 18:29:16 +00005082 if (file_spec.Exists() && files.AppendIfUnique(file_spec))
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005083 count++;
Jim Ingham1aa0ed42017-03-20 19:21:31 +00005084 }
5085 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005086 }
5087 return count;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005088}
5089
Kate Stoneb9c1b512016-09-06 20:57:50 +00005090lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5091 // If the object file is not an executable it can't hold the entry point.
Adrian Prantl05097242018-04-30 16:49:04 +00005092 // m_entry_point_address is initialized to an invalid address, so we can just
5093 // return that. If m_entry_point_address is valid it means we've found it
5094 // already, so return the cached value.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005095
Kate Stoneb9c1b512016-09-06 20:57:50 +00005096 if (!IsExecutable() || m_entry_point_address.IsValid())
Jim Ingham672e6f52011-03-07 23:44:08 +00005097 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00005098
Kate Stoneb9c1b512016-09-06 20:57:50 +00005099 // Otherwise, look for the UnixThread or Thread command. The data for the
Adrian Prantl05097242018-04-30 16:49:04 +00005100 // Thread command is given in /usr/include/mach-o.h, but it is basically:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005101 //
5102 // uint32_t flavor - this is the flavor argument you would pass to
5103 // thread_get_state
5104 // uint32_t count - this is the count of longs in the thread state data
5105 // struct XXX_thread_state state - this is the structure from
5106 // <machine/thread_status.h> corresponding to the flavor.
5107 // <repeat this trio>
5108 //
5109 // So we just keep reading the various register flavors till we find the GPR
5110 // one, then read the PC out of there.
5111 // FIXME: We will need to have a "RegisterContext data provider" class at some
5112 // point that can get all the registers
5113 // out of data in this form & attach them to a given thread. That should
Adrian Prantl05097242018-04-30 16:49:04 +00005114 // underlie the MacOS X User process plugin, and we'll also need it for the
5115 // MacOS X Core File process plugin. When we have that we can also use it
5116 // here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005117 //
5118 // For now we hard-code the offsets and flavors we need:
5119 //
5120 //
Greg Claytonc9660542012-02-05 02:38:54 +00005121
Kate Stoneb9c1b512016-09-06 20:57:50 +00005122 ModuleSP module_sp(GetModule());
5123 if (module_sp) {
5124 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5125 struct load_command load_cmd;
5126 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5127 uint32_t i;
5128 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5129 bool done = false;
5130
5131 for (i = 0; i < m_header.ncmds; ++i) {
5132 const lldb::offset_t cmd_offset = offset;
5133 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5134 break;
5135
5136 switch (load_cmd.cmd) {
5137 case LC_UNIXTHREAD:
5138 case LC_THREAD: {
5139 while (offset < cmd_offset + load_cmd.cmdsize) {
5140 uint32_t flavor = m_data.GetU32(&offset);
5141 uint32_t count = m_data.GetU32(&offset);
5142 if (count == 0) {
5143 // We've gotten off somehow, log and exit;
5144 return m_entry_point_address;
5145 }
5146
5147 switch (m_header.cputype) {
5148 case llvm::MachO::CPU_TYPE_ARM:
5149 if (flavor == 1 ||
5150 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 from
5151 // mach/arm/thread_status.h
Greg Claytonc3776bf2012-02-09 06:16:32 +00005152 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005153 offset += 60; // This is the offset of pc in the GPR thread state
5154 // data structure.
5155 start_address = m_data.GetU32(&offset);
5156 done = true;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005157 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005158 break;
5159 case llvm::MachO::CPU_TYPE_ARM64:
5160 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5161 {
5162 offset += 256; // This is the offset of pc in the GPR thread state
5163 // data structure.
5164 start_address = m_data.GetU64(&offset);
5165 done = true;
5166 }
5167 break;
5168 case llvm::MachO::CPU_TYPE_I386:
5169 if (flavor ==
5170 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5171 {
5172 offset += 40; // This is the offset of eip in the GPR thread state
5173 // data structure.
5174 start_address = m_data.GetU32(&offset);
5175 done = true;
5176 }
5177 break;
5178 case llvm::MachO::CPU_TYPE_X86_64:
5179 if (flavor ==
5180 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5181 {
5182 offset += 16 * 8; // This is the offset of rip in the GPR thread
5183 // state data structure.
5184 start_address = m_data.GetU64(&offset);
5185 done = true;
5186 }
5187 break;
5188 default:
5189 return m_entry_point_address;
5190 }
5191 // Haven't found the GPR flavor yet, skip over the data for this
5192 // flavor:
5193 if (done)
5194 break;
5195 offset += count * 4;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005196 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005197 } break;
5198 case LC_MAIN: {
5199 ConstString text_segment_name("__TEXT");
5200 uint64_t entryoffset = m_data.GetU64(&offset);
5201 SectionSP text_segment_sp =
5202 GetSectionList()->FindSectionByName(text_segment_name);
5203 if (text_segment_sp) {
5204 done = true;
5205 start_address = text_segment_sp->GetFileAddress() + entryoffset;
5206 }
5207 } break;
5208
5209 default:
5210 break;
5211 }
5212 if (done)
5213 break;
5214
5215 // Go to the next load command:
5216 offset = cmd_offset + load_cmd.cmdsize;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005217 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005218
5219 if (start_address != LLDB_INVALID_ADDRESS) {
5220 // We got the start address from the load commands, so now resolve that
Adrian Prantl05097242018-04-30 16:49:04 +00005221 // address in the sections of this ObjectFile:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005222 if (!m_entry_point_address.ResolveAddressUsingFileSections(
5223 start_address, GetSectionList())) {
5224 m_entry_point_address.Clear();
5225 }
5226 } else {
5227 // We couldn't read the UnixThread load command - maybe it wasn't there.
Adrian Prantl05097242018-04-30 16:49:04 +00005228 // As a fallback look for the "start" symbol in the main executable.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005229
5230 ModuleSP module_sp(GetModule());
5231
5232 if (module_sp) {
5233 SymbolContextList contexts;
5234 SymbolContext context;
5235 if (module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5236 eSymbolTypeCode, contexts)) {
5237 if (contexts.GetContextAtIndex(0, context))
5238 m_entry_point_address = context.symbol->GetAddress();
5239 }
5240 }
5241 }
5242 }
5243
5244 return m_entry_point_address;
5245}
5246
5247lldb_private::Address ObjectFileMachO::GetHeaderAddress() {
5248 lldb_private::Address header_addr;
5249 SectionList *section_list = GetSectionList();
5250 if (section_list) {
5251 SectionSP text_segment_sp(
5252 section_list->FindSectionByName(GetSegmentNameTEXT()));
5253 if (text_segment_sp) {
5254 header_addr.SetSection(text_segment_sp);
5255 header_addr.SetOffset(0);
5256 }
5257 }
5258 return header_addr;
5259}
5260
5261uint32_t ObjectFileMachO::GetNumThreadContexts() {
5262 ModuleSP module_sp(GetModule());
5263 if (module_sp) {
5264 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5265 if (!m_thread_context_offsets_valid) {
5266 m_thread_context_offsets_valid = true;
5267 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5268 FileRangeArray::Entry file_range;
5269 thread_command thread_cmd;
5270 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5271 const uint32_t cmd_offset = offset;
5272 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5273 break;
5274
5275 if (thread_cmd.cmd == LC_THREAD) {
5276 file_range.SetRangeBase(offset);
5277 file_range.SetByteSize(thread_cmd.cmdsize - 8);
5278 m_thread_context_offsets.Append(file_range);
5279 }
5280 offset = cmd_offset + thread_cmd.cmdsize;
5281 }
5282 }
5283 }
5284 return m_thread_context_offsets.GetSize();
Greg Claytonc3776bf2012-02-09 06:16:32 +00005285}
5286
Jason Molenda3533cec2017-04-06 01:50:11 +00005287std::string ObjectFileMachO::GetIdentifierString() {
5288 std::string result;
5289 ModuleSP module_sp(GetModule());
5290 if (module_sp) {
5291 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005292
Adrian Prantl05097242018-04-30 16:49:04 +00005293 // First, look over the load commands for an LC_NOTE load command with
5294 // data_owner string "kern ver str" & use that if found.
Jason Molenda3533cec2017-04-06 01:50:11 +00005295 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5296 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5297 const uint32_t cmd_offset = offset;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005298 load_command lc;
5299 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5300 break;
5301 if (lc.cmd == LC_NOTE)
5302 {
5303 char data_owner[17];
5304 m_data.CopyData (offset, 16, data_owner);
5305 data_owner[16] = '\0';
5306 offset += 16;
5307 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5308 uint64_t size = m_data.GetU64_unchecked (&offset);
5309
Adrian Prantl05097242018-04-30 16:49:04 +00005310 // "kern ver str" has a uint32_t version and then a nul terminated
5311 // c-string.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005312 if (strcmp ("kern ver str", data_owner) == 0)
5313 {
5314 offset = fileoff;
5315 uint32_t version;
5316 if (m_data.GetU32 (&offset, &version, 1) != nullptr)
5317 {
5318 if (version == 1)
5319 {
5320 uint32_t strsize = size - sizeof (uint32_t);
5321 char *buf = (char*) malloc (strsize);
5322 if (buf)
5323 {
5324 m_data.CopyData (offset, strsize, buf);
5325 buf[strsize - 1] = '\0';
5326 result = buf;
5327 if (buf)
5328 free (buf);
5329 return result;
5330 }
5331 }
5332 }
5333 }
5334 }
5335 offset = cmd_offset + lc.cmdsize;
5336 }
5337
Adrian Prantl05097242018-04-30 16:49:04 +00005338 // Second, make a pass over the load commands looking for an obsolete
5339 // LC_IDENT load command.
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005340 offset = MachHeaderSizeFromMagic(m_header.magic);
5341 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5342 const uint32_t cmd_offset = offset;
Jason Molenda3533cec2017-04-06 01:50:11 +00005343 struct ident_command ident_command;
5344 if (m_data.GetU32(&offset, &ident_command, 2) == NULL)
5345 break;
5346 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005347 char *buf = (char *) malloc (ident_command.cmdsize);
Jason Molenda3533cec2017-04-06 01:50:11 +00005348 if (buf != nullptr
5349 && m_data.CopyData (offset, ident_command.cmdsize, buf) == ident_command.cmdsize) {
5350 buf[ident_command.cmdsize - 1] = '\0';
5351 result = buf;
5352 }
5353 if (buf)
5354 free (buf);
5355 }
5356 offset = cmd_offset + ident_command.cmdsize;
5357 }
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005358
Jason Molenda3533cec2017-04-06 01:50:11 +00005359 }
5360 return result;
5361}
5362
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005363bool ObjectFileMachO::GetCorefileMainBinaryInfo (addr_t &address, UUID &uuid) {
5364 address = LLDB_INVALID_ADDRESS;
5365 uuid.Clear();
5366 ModuleSP module_sp(GetModule());
5367 if (module_sp) {
5368 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5369 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5370 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5371 const uint32_t cmd_offset = offset;
5372 load_command lc;
5373 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5374 break;
5375 if (lc.cmd == LC_NOTE)
5376 {
5377 char data_owner[17];
5378 memset (data_owner, 0, sizeof (data_owner));
5379 m_data.CopyData (offset, 16, data_owner);
5380 offset += 16;
5381 uint64_t fileoff = m_data.GetU64_unchecked (&offset);
5382 uint64_t size = m_data.GetU64_unchecked (&offset);
5383
Adrian Prantl05097242018-04-30 16:49:04 +00005384 // "main bin spec" (main binary specification) data payload is
5385 // formatted:
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005386 // uint32_t version [currently 1]
5387 // uint32_t type [0 == unspecified, 1 == kernel, 2 == user process]
5388 // uint64_t address [ UINT64_MAX if address not specified ]
5389 // uuid_t uuid [ all zero's if uuid not specified ]
5390 // uint32_t log2_pagesize [ process page size in log base 2, e.g. 4k pages are 12. 0 for unspecified ]
5391
5392 if (strcmp ("main bin spec", data_owner) == 0 && size >= 32)
5393 {
5394 offset = fileoff;
5395 uint32_t version;
5396 if (m_data.GetU32 (&offset, &version, 1) != nullptr && version == 1)
5397 {
5398 uint32_t type = 0;
5399 uuid_t raw_uuid;
Jason Molenda3f608292017-04-13 02:12:32 +00005400 memset (raw_uuid, 0, sizeof (uuid_t));
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005401
Pavel Labath2f93fd12018-06-26 15:12:20 +00005402 if (m_data.GetU32(&offset, &type, 1) &&
5403 m_data.GetU64(&offset, &address, 1) &&
5404 m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
5405 uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t));
5406 return true;
Jason Molenda9b7fcdc2017-04-12 23:33:30 +00005407 }
5408 }
5409 }
5410 }
5411 offset = cmd_offset + lc.cmdsize;
5412 }
5413 }
5414 return false;
5415}
5416
Greg Claytonc3776bf2012-02-09 06:16:32 +00005417lldb::RegisterContextSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005418ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5419 lldb_private::Thread &thread) {
5420 lldb::RegisterContextSP reg_ctx_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00005421
Kate Stoneb9c1b512016-09-06 20:57:50 +00005422 ModuleSP module_sp(GetModule());
5423 if (module_sp) {
5424 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5425 if (!m_thread_context_offsets_valid)
5426 GetNumThreadContexts();
Greg Claytona1743492012-03-13 23:14:29 +00005427
Kate Stoneb9c1b512016-09-06 20:57:50 +00005428 const FileRangeArray::Entry *thread_context_file_range =
5429 m_thread_context_offsets.GetEntryAtIndex(idx);
5430 if (thread_context_file_range) {
Jason Molenda4e7511e2013-03-06 23:19:17 +00005431
Kate Stoneb9c1b512016-09-06 20:57:50 +00005432 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5433 thread_context_file_range->GetByteSize());
Jim Ingham28eb5712012-10-12 17:34:26 +00005434
Kate Stoneb9c1b512016-09-06 20:57:50 +00005435 switch (m_header.cputype) {
5436 case llvm::MachO::CPU_TYPE_ARM64:
5437 reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data));
5438 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005439
Kate Stoneb9c1b512016-09-06 20:57:50 +00005440 case llvm::MachO::CPU_TYPE_ARM:
5441 reg_ctx_sp.reset(new RegisterContextDarwin_arm_Mach(thread, data));
5442 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005443
Kate Stoneb9c1b512016-09-06 20:57:50 +00005444 case llvm::MachO::CPU_TYPE_I386:
5445 reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data));
5446 break;
5447
5448 case llvm::MachO::CPU_TYPE_X86_64:
5449 reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data));
5450 break;
5451 }
Greg Claytonc3776bf2012-02-09 06:16:32 +00005452 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005453 }
5454 return reg_ctx_sp;
Greg Claytonc3776bf2012-02-09 06:16:32 +00005455}
5456
Kate Stoneb9c1b512016-09-06 20:57:50 +00005457ObjectFile::Type ObjectFileMachO::CalculateType() {
5458 switch (m_header.filetype) {
5459 case MH_OBJECT: // 0x1u
5460 if (GetAddressByteSize() == 4) {
5461 // 32 bit kexts are just object files, but they do have a valid
5462 // UUID load command.
5463 UUID uuid;
5464 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005465 // this checking for the UUID load command is not enough we could
5466 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5467 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005468 if (m_strata == eStrataInvalid)
5469 m_strata = eStrataKernel;
5470 return eTypeSharedLibrary;
5471 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005472 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005473 return eTypeObjectFile;
5474
5475 case MH_EXECUTE:
5476 return eTypeExecutable; // 0x2u
5477 case MH_FVMLIB:
5478 return eTypeSharedLibrary; // 0x3u
5479 case MH_CORE:
5480 return eTypeCoreFile; // 0x4u
5481 case MH_PRELOAD:
5482 return eTypeSharedLibrary; // 0x5u
5483 case MH_DYLIB:
5484 return eTypeSharedLibrary; // 0x6u
5485 case MH_DYLINKER:
5486 return eTypeDynamicLinker; // 0x7u
5487 case MH_BUNDLE:
5488 return eTypeSharedLibrary; // 0x8u
5489 case MH_DYLIB_STUB:
5490 return eTypeStubLibrary; // 0x9u
5491 case MH_DSYM:
5492 return eTypeDebugInfo; // 0xAu
5493 case MH_KEXT_BUNDLE:
5494 return eTypeSharedLibrary; // 0xBu
5495 default:
5496 break;
5497 }
5498 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005499}
5500
Kate Stoneb9c1b512016-09-06 20:57:50 +00005501ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5502 switch (m_header.filetype) {
5503 case MH_OBJECT: // 0x1u
5504 {
5505 // 32 bit kexts are just object files, but they do have a valid
5506 // UUID load command.
5507 UUID uuid;
5508 if (GetUUID(&uuid)) {
Adrian Prantl05097242018-04-30 16:49:04 +00005509 // this checking for the UUID load command is not enough we could
5510 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5511 // this is required of kexts
Kate Stoneb9c1b512016-09-06 20:57:50 +00005512 if (m_type == eTypeInvalid)
5513 m_type = eTypeSharedLibrary;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005514
Kate Stoneb9c1b512016-09-06 20:57:50 +00005515 return eStrataKernel;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005516 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005517 }
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005518 return eStrataUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005519
5520 case MH_EXECUTE: // 0x2u
5521 // Check for the MH_DYLDLINK bit in the flags
5522 if (m_header.flags & MH_DYLDLINK) {
5523 return eStrataUser;
5524 } else {
5525 SectionList *section_list = GetSectionList();
5526 if (section_list) {
5527 static ConstString g_kld_section_name("__KLD");
5528 if (section_list->FindSectionByName(g_kld_section_name))
5529 return eStrataKernel;
5530 }
5531 }
5532 return eStrataRawImage;
5533
5534 case MH_FVMLIB:
5535 return eStrataUser; // 0x3u
5536 case MH_CORE:
5537 return eStrataUnknown; // 0x4u
5538 case MH_PRELOAD:
5539 return eStrataRawImage; // 0x5u
5540 case MH_DYLIB:
5541 return eStrataUser; // 0x6u
5542 case MH_DYLINKER:
5543 return eStrataUser; // 0x7u
5544 case MH_BUNDLE:
5545 return eStrataUser; // 0x8u
5546 case MH_DYLIB_STUB:
5547 return eStrataUser; // 0x9u
5548 case MH_DSYM:
5549 return eStrataUnknown; // 0xAu
5550 case MH_KEXT_BUNDLE:
5551 return eStrataKernel; // 0xBu
5552 default:
5553 break;
5554 }
5555 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00005556}
5557
Pavel Labath2272c482018-06-18 15:02:23 +00005558llvm::VersionTuple ObjectFileMachO::GetVersion() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005559 ModuleSP module_sp(GetModule());
5560 if (module_sp) {
5561 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5562 struct dylib_command load_cmd;
5563 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5564 uint32_t version_cmd = 0;
5565 uint64_t version = 0;
5566 uint32_t i;
5567 for (i = 0; i < m_header.ncmds; ++i) {
5568 const lldb::offset_t cmd_offset = offset;
5569 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5570 break;
Jason Molenda4e7511e2013-03-06 23:19:17 +00005571
Kate Stoneb9c1b512016-09-06 20:57:50 +00005572 if (load_cmd.cmd == LC_ID_DYLIB) {
5573 if (version_cmd == 0) {
5574 version_cmd = load_cmd.cmd;
5575 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5576 break;
5577 version = load_cmd.dylib.current_version;
Greg Claytonc2ff9312012-02-22 19:41:02 +00005578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005579 break; // Break for now unless there is another more complete version
5580 // number load command in the future.
5581 }
5582 offset = cmd_offset + load_cmd.cmdsize;
5583 }
Jason Molenda4e7511e2013-03-06 23:19:17 +00005584
Kate Stoneb9c1b512016-09-06 20:57:50 +00005585 if (version_cmd == LC_ID_DYLIB) {
Pavel Labath2272c482018-06-18 15:02:23 +00005586 unsigned major = (version & 0xFFFF0000ull) >> 16;
5587 unsigned minor = (version & 0x0000FF00ull) >> 8;
5588 unsigned subminor = (version & 0x000000FFull);
5589 return llvm::VersionTuple(major, minor, subminor);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005590 }
5591 }
Pavel Labath2272c482018-06-18 15:02:23 +00005592 return llvm::VersionTuple();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005593}
5594
5595bool ObjectFileMachO::GetArchitecture(ArchSpec &arch) {
5596 ModuleSP module_sp(GetModule());
5597 if (module_sp) {
5598 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5599 return GetArchitecture(m_header, m_data,
5600 MachHeaderSizeFromMagic(m_header.magic), arch);
5601 }
5602 return false;
5603}
5604
Jason Molenda07580ff2018-05-04 00:59:37 +00005605void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process, addr_t &base_addr, UUID &uuid) {
5606 uuid.Clear();
5607 base_addr = LLDB_INVALID_ADDRESS;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005608 if (process && process->GetDynamicLoader()) {
5609 DynamicLoader *dl = process->GetDynamicLoader();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005610 LazyBool using_shared_cache;
5611 LazyBool private_shared_cache;
Jason Molenda07580ff2018-05-04 00:59:37 +00005612 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
Kate Stoneb9c1b512016-09-06 20:57:50 +00005613 private_shared_cache);
5614 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005615 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005616 if (log)
Jason Molenda07580ff2018-05-04 00:59:37 +00005617 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 +00005618}
5619
Jason Molenda07580ff2018-05-04 00:59:37 +00005620// From dyld SPI header dyld_process_info.h
5621typedef void *dyld_process_info;
5622struct lldb_copy__dyld_process_cache_info {
5623 uuid_t cacheUUID; // UUID of cache used by process
5624 uint64_t cacheBaseAddress; // load address of dyld shared cache
5625 bool noCache; // process is running without a dyld cache
5626 bool privateCache; // process is using a private copy of its dyld cache
5627};
5628
5629// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with llvm
5630// enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile errors.
5631// So we need to use the actual underlying types of task_t and kern_return_t
5632// below.
5633extern "C" unsigned int /*task_t*/ mach_task_self();
5634
5635void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5636 uuid.Clear();
5637 base_addr = LLDB_INVALID_ADDRESS;
5638
Kate Stoneb9c1b512016-09-06 20:57:50 +00005639#if defined(__APPLE__) && \
5640 (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5641 uint8_t *(*dyld_get_all_image_infos)(void);
5642 dyld_get_all_image_infos =
5643 (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5644 if (dyld_get_all_image_infos) {
5645 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5646 if (dyld_all_image_infos_address) {
5647 uint32_t *version = (uint32_t *)
5648 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5649 if (*version >= 13) {
5650 uuid_t *sharedCacheUUID_address = 0;
5651 int wordsize = sizeof(uint8_t *);
5652 if (wordsize == 8) {
5653 sharedCacheUUID_address =
5654 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5655 160); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005656 if (*version >= 15)
5657 base_addr = *(uint64_t *) ((uint8_t *) dyld_all_image_infos_address
5658 + 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +00005659 } else {
5660 sharedCacheUUID_address =
5661 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5662 84); // sharedCacheUUID <mach-o/dyld_images.h>
Jason Molenda07580ff2018-05-04 00:59:37 +00005663 if (*version >= 15) {
5664 base_addr = 0;
5665 base_addr = *(uint32_t *) ((uint8_t *) dyld_all_image_infos_address
5666 + 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5667 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005668 }
Pavel Labath2f93fd12018-06-26 15:12:20 +00005669 uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005670 }
Greg Claytonc2ff9312012-02-22 19:41:02 +00005671 }
Jason Molendafd443e92018-02-07 01:28:29 +00005672 } else {
5673 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
Jason Molenda07580ff2018-05-04 00:59:37 +00005674 dyld_process_info (*dyld_process_info_create)(unsigned int /* task_t */ task, uint64_t timestamp, unsigned int /*kern_return_t*/ *kernelError);
5675 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5676 void (*dyld_process_info_release)(dyld_process_info info);
5677
5678 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, unsigned int /*kern_return_t*/ *))
5679 dlsym (RTLD_DEFAULT, "_dyld_process_info_create");
5680 dyld_process_info_get_cache = (void (*)(void *, void *))
5681 dlsym (RTLD_DEFAULT, "_dyld_process_info_get_cache");
5682 dyld_process_info_release = (void (*)(void *))
5683 dlsym (RTLD_DEFAULT, "_dyld_process_info_release");
5684
5685 if (dyld_process_info_create && dyld_process_info_get_cache) {
5686 unsigned int /*kern_return_t */ kern_ret;
5687 dyld_process_info process_info = dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5688 if (process_info) {
5689 struct lldb_copy__dyld_process_cache_info sc_info;
5690 memset (&sc_info, 0, sizeof (struct lldb_copy__dyld_process_cache_info));
5691 dyld_process_info_get_cache (process_info, &sc_info);
5692 if (sc_info.cacheBaseAddress != 0) {
5693 base_addr = sc_info.cacheBaseAddress;
Pavel Labath2f93fd12018-06-26 15:12:20 +00005694 uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
Jason Molenda07580ff2018-05-04 00:59:37 +00005695 }
5696 dyld_process_info_release (process_info);
5697 }
Jason Molendafd443e92018-02-07 01:28:29 +00005698 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005699 }
Jason Molenda07580ff2018-05-04 00:59:37 +00005700 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
Jason Molendafd443e92018-02-07 01:28:29 +00005701 if (log && uuid.IsValid())
Jason Molenda07580ff2018-05-04 00:59:37 +00005702 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 +00005703#endif
Jason Molenda0e0954c2013-04-16 06:24:42 +00005704}
5705
Pavel Labath2272c482018-06-18 15:02:23 +00005706llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5707 if (!m_min_os_version) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005708 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
Pavel Labath2272c482018-06-18 15:02:23 +00005709 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005710 const lldb::offset_t load_cmd_offset = offset;
5711
5712 version_min_command lc;
5713 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5714 break;
5715 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5716 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5717 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5718 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5719 if (m_data.GetU32(&offset, &lc.version,
5720 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5721 const uint32_t xxxx = lc.version >> 16;
5722 const uint32_t yy = (lc.version >> 8) & 0xffu;
5723 const uint32_t zz = lc.version & 0xffu;
5724 if (xxxx) {
Pavel Labath2272c482018-06-18 15:02:23 +00005725 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5726 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005727 }
Greg Clayton9b234982013-10-24 22:54:08 +00005728 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005729 }
5730 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005732
Pavel Labath2272c482018-06-18 15:02:23 +00005733 if (!m_min_os_version) {
5734 // Set version to an empty value so we don't keep trying to
5735 m_min_os_version = llvm::VersionTuple();
Greg Clayton9b234982013-10-24 22:54:08 +00005736 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005737 }
5738
Pavel Labath2272c482018-06-18 15:02:23 +00005739 return *m_min_os_version;
Greg Clayton9b234982013-10-24 22:54:08 +00005740}
5741
Kate Stoneb9c1b512016-09-06 20:57:50 +00005742uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions,
5743 uint32_t num_versions) {
5744 if (m_sdk_versions.empty()) {
5745 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5746 bool success = false;
5747 for (uint32_t i = 0; success == false && i < m_header.ncmds; ++i) {
5748 const lldb::offset_t load_cmd_offset = offset;
5749
5750 version_min_command lc;
5751 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5752 break;
5753 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5754 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5755 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5756 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5757 if (m_data.GetU32(&offset, &lc.version,
5758 (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5759 const uint32_t xxxx = lc.sdk >> 16;
5760 const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5761 const uint32_t zz = lc.sdk & 0xffu;
5762 if (xxxx) {
5763 m_sdk_versions.push_back(xxxx);
5764 m_sdk_versions.push_back(yy);
5765 m_sdk_versions.push_back(zz);
Jason Molenda32a91422018-06-25 23:45:39 +00005766 success = true;
5767 } else {
5768 GetModule()->ReportWarning(
5769 "minimum OS version load command with invalid (0) version found.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005770 }
Greg Clayton9b234982013-10-24 22:54:08 +00005771 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005772 }
5773 offset = load_cmd_offset + lc.cmdsize;
Greg Clayton9b234982013-10-24 22:54:08 +00005774 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005775
5776 if (success == false) {
Jason Molenda32a91422018-06-25 23:45:39 +00005777 // Push an invalid value so we don't try to find
5778 // the version # again on the next call to this
5779 // method.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005780 m_sdk_versions.push_back(UINT32_MAX);
Greg Clayton9b234982013-10-24 22:54:08 +00005781 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005782 }
5783
Jason Molenda32a91422018-06-25 23:45:39 +00005784 // Legitimate version numbers will have 3 entries pushed
5785 // on to m_sdk_versions. If we only have one value, it's
5786 // the sentinel value indicating that this object file
5787 // does not have a valid minimum os version #.
5788 if (m_sdk_versions.size() > 1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005789 if (versions != NULL && num_versions > 0) {
5790 for (size_t i = 0; i < num_versions; ++i) {
5791 if (i < m_sdk_versions.size())
5792 versions[i] = m_sdk_versions[i];
5793 else
5794 versions[i] = 0;
5795 }
5796 }
5797 return m_sdk_versions.size();
5798 }
5799 // Call the superclasses version that will empty out the data
5800 return ObjectFile::GetSDKVersion(versions, num_versions);
Greg Clayton9b234982013-10-24 22:54:08 +00005801}
5802
Kate Stoneb9c1b512016-09-06 20:57:50 +00005803bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5804 return m_header.filetype == llvm::MachO::MH_DYLINKER;
Greg Clayton08928f32015-02-05 02:01:34 +00005805}
5806
Kate Stoneb9c1b512016-09-06 20:57:50 +00005807bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5808 return m_allow_assembly_emulation_unwind_plans;
Jason Molenda955dcf22016-05-04 03:09:40 +00005809}
5810
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005811//------------------------------------------------------------------
5812// PluginInterface protocol
5813//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00005814lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5815 return GetPluginNameStatic();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005816}
5817
Kate Stoneb9c1b512016-09-06 20:57:50 +00005818uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005819
Kate Stoneb9c1b512016-09-06 20:57:50 +00005820Section *ObjectFileMachO::GetMachHeaderSection() {
Adrian Prantl05097242018-04-30 16:49:04 +00005821 // Find the first address of the mach header which is the first non-zero file
5822 // sized section whose file offset is zero. This is the base file address of
5823 // the mach-o file which can be subtracted from the vmaddr of the other
Kate Stoneb9c1b512016-09-06 20:57:50 +00005824 // segments found in memory and added to the load address
5825 ModuleSP module_sp = GetModule();
5826 if (module_sp) {
5827 SectionList *section_list = GetSectionList();
5828 if (section_list) {
5829 lldb::addr_t mach_base_file_addr = LLDB_INVALID_ADDRESS;
5830 const size_t num_sections = section_list->GetSize();
Greg Clayton07347372015-06-08 21:53:11 +00005831
Kate Stoneb9c1b512016-09-06 20:57:50 +00005832 for (size_t sect_idx = 0; sect_idx < num_sections &&
5833 mach_base_file_addr == LLDB_INVALID_ADDRESS;
5834 ++sect_idx) {
5835 Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5836 if (section && section->GetFileSize() > 0 &&
5837 section->GetFileOffset() == 0 &&
5838 section->IsThreadSpecific() == false &&
5839 module_sp.get() == section->GetModule().get()) {
5840 return section;
Greg Clayton07347372015-06-08 21:53:11 +00005841 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005842 }
Greg Clayton07347372015-06-08 21:53:11 +00005843 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005844 }
5845 return nullptr;
Greg Clayton07347372015-06-08 21:53:11 +00005846}
5847
Kate Stoneb9c1b512016-09-06 20:57:50 +00005848lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
5849 lldb::addr_t mach_header_load_address, const Section *mach_header_section,
5850 const Section *section) {
5851 ModuleSP module_sp = GetModule();
5852 if (module_sp && mach_header_section && section &&
5853 mach_header_load_address != LLDB_INVALID_ADDRESS) {
5854 lldb::addr_t mach_header_file_addr = mach_header_section->GetFileAddress();
5855 if (mach_header_file_addr != LLDB_INVALID_ADDRESS) {
5856 if (section && section->GetFileSize() > 0 &&
5857 section->IsThreadSpecific() == false &&
5858 module_sp.get() == section->GetModule().get()) {
5859 // Ignore __LINKEDIT and __DWARF segments
5860 if (section->GetName() == GetSegmentNameLINKEDIT()) {
Adrian Prantl05097242018-04-30 16:49:04 +00005861 // Only map __LINKEDIT if we have an in memory image and this isn't a
5862 // kernel binary like a kext or mach_kernel.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005863 const bool is_memory_image = (bool)m_process_wp.lock();
5864 const Strata strata = GetStrata();
5865 if (is_memory_image == false || strata == eStrataKernel)
5866 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00005867 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005868 return section->GetFileAddress() - mach_header_file_addr +
5869 mach_header_load_address;
5870 }
Greg Clayton07347372015-06-08 21:53:11 +00005871 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005872 }
5873 return LLDB_INVALID_ADDRESS;
Greg Clayton07347372015-06-08 21:53:11 +00005874}
5875
Kate Stoneb9c1b512016-09-06 20:57:50 +00005876bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
5877 bool value_is_offset) {
5878 ModuleSP module_sp = GetModule();
5879 if (module_sp) {
5880 size_t num_loaded_sections = 0;
5881 SectionList *section_list = GetSectionList();
5882 if (section_list) {
5883 const size_t num_sections = section_list->GetSize();
Greg Clayton7524e092014-02-06 20:10:16 +00005884
Kate Stoneb9c1b512016-09-06 20:57:50 +00005885 if (value_is_offset) {
5886 // "value" is an offset to apply to each top level segment
5887 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +00005888 // Iterate through the object file sections to find all of the
5889 // sections that size on disk (to avoid __PAGEZERO) and load them
Kate Stoneb9c1b512016-09-06 20:57:50 +00005890 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5891 if (section_sp && section_sp->GetFileSize() > 0 &&
5892 section_sp->IsThreadSpecific() == false &&
5893 module_sp.get() == section_sp->GetModule().get()) {
5894 // Ignore __LINKEDIT and __DWARF segments
5895 if (section_sp->GetName() == GetSegmentNameLINKEDIT()) {
5896 // Only map __LINKEDIT if we have an in memory image and this
Adrian Prantl05097242018-04-30 16:49:04 +00005897 // isn't a kernel binary like a kext or mach_kernel.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005898 const bool is_memory_image = (bool)m_process_wp.lock();
5899 const Strata strata = GetStrata();
5900 if (is_memory_image == false || strata == eStrataKernel)
5901 continue;
Greg Clayton7524e092014-02-06 20:10:16 +00005902 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005903 if (target.GetSectionLoadList().SetSectionLoadAddress(
5904 section_sp, section_sp->GetFileAddress() + value))
5905 ++num_loaded_sections;
5906 }
Greg Clayton7524e092014-02-06 20:10:16 +00005907 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005908 } else {
5909 // "value" is the new base address of the mach_header, adjust each
5910 // section accordingly
5911
5912 Section *mach_header_section = GetMachHeaderSection();
5913 if (mach_header_section) {
5914 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5915 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5916
5917 lldb::addr_t section_load_addr =
5918 CalculateSectionLoadAddressForMemoryImage(
5919 value, mach_header_section, section_sp.get());
5920 if (section_load_addr != LLDB_INVALID_ADDRESS) {
5921 if (target.GetSectionLoadList().SetSectionLoadAddress(
5922 section_sp, section_load_addr))
5923 ++num_loaded_sections;
5924 }
5925 }
5926 }
5927 }
Greg Clayton7524e092014-02-06 20:10:16 +00005928 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005929 return num_loaded_sections > 0;
5930 }
5931 return false;
Greg Clayton7524e092014-02-06 20:10:16 +00005932}
5933
Kate Stoneb9c1b512016-09-06 20:57:50 +00005934bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
Zachary Turner97206d52017-05-12 04:51:55 +00005935 const FileSpec &outfile, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005936 if (process_sp) {
5937 Target &target = process_sp->GetTarget();
5938 const ArchSpec target_arch = target.GetArchitecture();
5939 const llvm::Triple &target_triple = target_arch.GetTriple();
5940 if (target_triple.getVendor() == llvm::Triple::Apple &&
5941 (target_triple.getOS() == llvm::Triple::MacOSX ||
5942 target_triple.getOS() == llvm::Triple::IOS ||
5943 target_triple.getOS() == llvm::Triple::WatchOS ||
5944 target_triple.getOS() == llvm::Triple::TvOS)) {
5945 bool make_core = false;
5946 switch (target_arch.GetMachine()) {
5947 case llvm::Triple::aarch64:
5948 case llvm::Triple::arm:
5949 case llvm::Triple::thumb:
5950 case llvm::Triple::x86:
5951 case llvm::Triple::x86_64:
5952 make_core = true;
5953 break;
5954 default:
5955 error.SetErrorStringWithFormat("unsupported core architecture: %s",
5956 target_triple.str().c_str());
5957 break;
5958 }
5959
5960 if (make_core) {
5961 std::vector<segment_command_64> segment_load_commands;
5962 // uint32_t range_info_idx = 0;
5963 MemoryRegionInfo range_info;
Zachary Turner97206d52017-05-12 04:51:55 +00005964 Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005965 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
5966 const ByteOrder byte_order = target_arch.GetByteOrder();
5967 if (range_error.Success()) {
5968 while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
5969 const addr_t addr = range_info.GetRange().GetRangeBase();
5970 const addr_t size = range_info.GetRange().GetByteSize();
5971
5972 if (size == 0)
5973 break;
5974
5975 // Calculate correct protections
5976 uint32_t prot = 0;
5977 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
5978 prot |= VM_PROT_READ;
5979 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
5980 prot |= VM_PROT_WRITE;
5981 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
5982 prot |= VM_PROT_EXECUTE;
5983
5984 // printf ("[%3u] [0x%16.16" PRIx64 " -
5985 // 0x%16.16" PRIx64 ") %c%c%c\n",
5986 // range_info_idx,
5987 // addr,
5988 // size,
5989 // (prot & VM_PROT_READ ) ? 'r' :
5990 // '-',
5991 // (prot & VM_PROT_WRITE ) ? 'w' :
5992 // '-',
5993 // (prot & VM_PROT_EXECUTE) ? 'x' :
5994 // '-');
5995
5996 if (prot != 0) {
5997 uint32_t cmd_type = LC_SEGMENT_64;
5998 uint32_t segment_size = sizeof(segment_command_64);
5999 if (addr_byte_size == 4) {
6000 cmd_type = LC_SEGMENT;
6001 segment_size = sizeof(segment_command);
6002 }
6003 segment_command_64 segment = {
6004 cmd_type, // uint32_t cmd;
6005 segment_size, // uint32_t cmdsize;
6006 {0}, // char segname[16];
6007 addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
6008 size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
6009 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
6010 size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
6011 prot, // uint32_t maxprot;
6012 prot, // uint32_t initprot;
6013 0, // uint32_t nsects;
6014 0}; // uint32_t flags;
6015 segment_load_commands.push_back(segment);
6016 } else {
6017 // No protections and a size of 1 used to be returned from old
6018 // debugservers when we asked about a region that was past the
6019 // last memory region and it indicates the end...
6020 if (size == 1)
6021 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006022 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006023
Kate Stoneb9c1b512016-09-06 20:57:50 +00006024 range_error = process_sp->GetMemoryRegionInfo(
6025 range_info.GetRange().GetRangeEnd(), range_info);
6026 if (range_error.Fail())
6027 break;
6028 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006029
Kate Stoneb9c1b512016-09-06 20:57:50 +00006030 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
Greg Claytona2715cf2014-06-13 00:54:12 +00006031
Kate Stoneb9c1b512016-09-06 20:57:50 +00006032 mach_header_64 mach_header;
6033 if (addr_byte_size == 8) {
6034 mach_header.magic = MH_MAGIC_64;
6035 } else {
6036 mach_header.magic = MH_MAGIC;
6037 }
6038 mach_header.cputype = target_arch.GetMachOCPUType();
6039 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6040 mach_header.filetype = MH_CORE;
6041 mach_header.ncmds = segment_load_commands.size();
6042 mach_header.flags = 0;
6043 mach_header.reserved = 0;
6044 ThreadList &thread_list = process_sp->GetThreadList();
6045 const uint32_t num_threads = thread_list.GetSize();
Greg Claytona2715cf2014-06-13 00:54:12 +00006046
Adrian Prantl05097242018-04-30 16:49:04 +00006047 // Make an array of LC_THREAD data items. Each one contains the
6048 // contents of the LC_THREAD load command. The data doesn't contain
6049 // the load command + load command size, we will add the load command
6050 // and load command size as we emit the data.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006051 std::vector<StreamString> LC_THREAD_datas(num_threads);
6052 for (auto &LC_THREAD_data : LC_THREAD_datas) {
6053 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6054 LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6055 LC_THREAD_data.SetByteOrder(byte_order);
6056 }
6057 for (uint32_t thread_idx = 0; thread_idx < num_threads;
6058 ++thread_idx) {
6059 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6060 if (thread_sp) {
6061 switch (mach_header.cputype) {
6062 case llvm::MachO::CPU_TYPE_ARM64:
6063 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6064 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6065 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006066
Kate Stoneb9c1b512016-09-06 20:57:50 +00006067 case llvm::MachO::CPU_TYPE_ARM:
6068 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6069 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6070 break;
Greg Claytona2715cf2014-06-13 00:54:12 +00006071
Kate Stoneb9c1b512016-09-06 20:57:50 +00006072 case llvm::MachO::CPU_TYPE_I386:
6073 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6074 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6075 break;
Jason Molenda22952582014-11-12 01:11:36 +00006076
Kate Stoneb9c1b512016-09-06 20:57:50 +00006077 case llvm::MachO::CPU_TYPE_X86_64:
6078 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6079 thread_sp.get(), LC_THREAD_datas[thread_idx]);
6080 break;
6081 }
Greg Claytona2715cf2014-06-13 00:54:12 +00006082 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006083 }
6084
6085 // The size of the load command is the size of the segments...
6086 if (addr_byte_size == 8) {
6087 mach_header.sizeofcmds = segment_load_commands.size() *
6088 sizeof(struct segment_command_64);
6089 } else {
6090 mach_header.sizeofcmds =
6091 segment_load_commands.size() * sizeof(struct segment_command);
6092 }
6093
6094 // and the size of all LC_THREAD load command
6095 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6096 ++mach_header.ncmds;
6097 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6098 }
6099
6100 printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x "
6101 "0x%8.8x 0x%8.8x\n",
6102 mach_header.magic, mach_header.cputype, mach_header.cpusubtype,
6103 mach_header.filetype, mach_header.ncmds,
6104 mach_header.sizeofcmds, mach_header.flags,
6105 mach_header.reserved);
6106
6107 // Write the mach header
6108 buffer.PutHex32(mach_header.magic);
6109 buffer.PutHex32(mach_header.cputype);
6110 buffer.PutHex32(mach_header.cpusubtype);
6111 buffer.PutHex32(mach_header.filetype);
6112 buffer.PutHex32(mach_header.ncmds);
6113 buffer.PutHex32(mach_header.sizeofcmds);
6114 buffer.PutHex32(mach_header.flags);
6115 if (addr_byte_size == 8) {
6116 buffer.PutHex32(mach_header.reserved);
6117 }
6118
6119 // Skip the mach header and all load commands and align to the next
6120 // 0x1000 byte boundary
6121 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6122 if (file_offset & 0x00000fff) {
6123 file_offset += 0x00001000ull;
6124 file_offset &= (~0x00001000ull + 1);
6125 }
6126
6127 for (auto &segment : segment_load_commands) {
6128 segment.fileoff = file_offset;
6129 file_offset += segment.filesize;
6130 }
6131
6132 // Write out all of the LC_THREAD load commands
6133 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6134 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6135 buffer.PutHex32(LC_THREAD);
6136 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
Zachary Turnerc1564272016-11-16 21:15:24 +00006137 buffer.Write(LC_THREAD_data.GetString().data(),
6138 LC_THREAD_data_size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00006139 }
6140
6141 // Write out all of the segment load commands
6142 for (const auto &segment : segment_load_commands) {
6143 printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6144 ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6145 ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6146 segment.cmd, segment.cmdsize, segment.vmaddr,
6147 segment.vmaddr + segment.vmsize, segment.fileoff,
6148 segment.filesize, segment.maxprot, segment.initprot,
6149 segment.nsects, segment.flags);
6150
6151 buffer.PutHex32(segment.cmd);
6152 buffer.PutHex32(segment.cmdsize);
6153 buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6154 if (addr_byte_size == 8) {
6155 buffer.PutHex64(segment.vmaddr);
6156 buffer.PutHex64(segment.vmsize);
6157 buffer.PutHex64(segment.fileoff);
6158 buffer.PutHex64(segment.filesize);
6159 } else {
6160 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6161 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6162 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6163 buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6164 }
6165 buffer.PutHex32(segment.maxprot);
6166 buffer.PutHex32(segment.initprot);
6167 buffer.PutHex32(segment.nsects);
6168 buffer.PutHex32(segment.flags);
6169 }
6170
6171 File core_file;
6172 std::string core_file_path(outfile.GetPath());
6173 error = core_file.Open(core_file_path.c_str(),
6174 File::eOpenOptionWrite |
6175 File::eOpenOptionTruncate |
6176 File::eOpenOptionCanCreate);
6177 if (error.Success()) {
6178 // Read 1 page at a time
6179 uint8_t bytes[0x1000];
6180 // Write the mach header and load commands out to the core file
6181 size_t bytes_written = buffer.GetString().size();
6182 error = core_file.Write(buffer.GetString().data(), bytes_written);
6183 if (error.Success()) {
6184 // Now write the file data for all memory segments in the process
6185 for (const auto &segment : segment_load_commands) {
6186 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6187 error.SetErrorStringWithFormat(
6188 "unable to seek to offset 0x%" PRIx64 " in '%s'",
6189 segment.fileoff, core_file_path.c_str());
6190 break;
6191 }
6192
6193 printf("Saving %" PRId64
6194 " bytes of data for memory region at 0x%" PRIx64 "\n",
6195 segment.vmsize, segment.vmaddr);
6196 addr_t bytes_left = segment.vmsize;
6197 addr_t addr = segment.vmaddr;
Zachary Turner97206d52017-05-12 04:51:55 +00006198 Status memory_read_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006199 while (bytes_left > 0 && error.Success()) {
6200 const size_t bytes_to_read =
6201 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6202 const size_t bytes_read = process_sp->ReadMemory(
6203 addr, bytes, bytes_to_read, memory_read_error);
6204 if (bytes_read == bytes_to_read) {
6205 size_t bytes_written = bytes_read;
6206 error = core_file.Write(bytes, bytes_written);
6207 bytes_left -= bytes_read;
6208 addr += bytes_read;
6209 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00006210 // Some pages within regions are not readable, those should
6211 // be zero filled
Kate Stoneb9c1b512016-09-06 20:57:50 +00006212 memset(bytes, 0, bytes_to_read);
6213 size_t bytes_written = bytes_to_read;
6214 error = core_file.Write(bytes, bytes_written);
6215 bytes_left -= bytes_to_read;
6216 addr += bytes_to_read;
6217 }
6218 }
6219 }
6220 }
6221 }
6222 } else {
6223 error.SetErrorString(
6224 "process doesn't support getting memory region info");
Greg Claytona2715cf2014-06-13 00:54:12 +00006225 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006226 }
6227 return true; // This is the right plug to handle saving core files for
6228 // this process
Greg Claytona2715cf2014-06-13 00:54:12 +00006229 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006230 }
6231 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00006232}