1 //===-- SystemRuntimeMacOSX.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 
10 
11 #include "lldb/Breakpoint/StoppointCallbackContext.h"
12 #include "lldb/Core/Log.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/ModuleSpec.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/DataExtractor.h"
17 #include "lldb/Core/DataBufferHeap.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Expression/ClangFunction.h"
20 #include "lldb/Expression/ClangUtilityFunction.h"
21 #include "lldb/Host/FileSpec.h"
22 #include "lldb/Symbol/ObjectFile.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "Plugins/Process/Utility/HistoryThread.h"
25 #include "lldb/Target/Queue.h"
26 #include "lldb/Target/QueueList.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
29 #include "lldb/Target/Process.h"
30 
31 
32 #include "SystemRuntimeMacOSX.h"
33 
34 using namespace lldb;
35 using namespace lldb_private;
36 
37 //----------------------------------------------------------------------
38 // Create an instance of this class. This function is filled into
39 // the plugin info class that gets handed out by the plugin factory and
40 // allows the lldb to instantiate an instance of this class.
41 //----------------------------------------------------------------------
42 SystemRuntime *
43 SystemRuntimeMacOSX::CreateInstance (Process* process)
44 {
45     bool create = false;
46     if (!create)
47     {
48         create = true;
49         Module* exe_module = process->GetTarget().GetExecutableModulePointer();
50         if (exe_module)
51         {
52             ObjectFile *object_file = exe_module->GetObjectFile();
53             if (object_file)
54             {
55                 create = (object_file->GetStrata() == ObjectFile::eStrataUser);
56             }
57         }
58 
59         if (create)
60         {
61             const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
62             switch (triple_ref.getOS())
63             {
64                 case llvm::Triple::Darwin:
65                 case llvm::Triple::MacOSX:
66                 case llvm::Triple::IOS:
67                     create = triple_ref.getVendor() == llvm::Triple::Apple;
68                     break;
69                 default:
70                     create = false;
71                     break;
72             }
73         }
74     }
75 
76     if (create)
77         return new SystemRuntimeMacOSX (process);
78     return NULL;
79 }
80 
81 //----------------------------------------------------------------------
82 // Constructor
83 //----------------------------------------------------------------------
84 SystemRuntimeMacOSX::SystemRuntimeMacOSX (Process* process) :
85     SystemRuntime(process),
86     m_break_id(LLDB_INVALID_BREAK_ID),
87     m_mutex(Mutex::eMutexTypeRecursive),
88     m_get_queues_handler(process),
89     m_get_pending_items_handler(process),
90     m_get_item_info_handler(process),
91     m_get_thread_item_info_handler(process),
92     m_page_to_free(LLDB_INVALID_ADDRESS),
93     m_page_to_free_size(0),
94     m_lib_backtrace_recording_info(),
95     m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
96     m_libdispatch_offsets()
97 {
98 }
99 
100 //----------------------------------------------------------------------
101 // Destructor
102 //----------------------------------------------------------------------
103 SystemRuntimeMacOSX::~SystemRuntimeMacOSX()
104 {
105     Clear (true);
106 }
107 
108 void
109 SystemRuntimeMacOSX::Detach ()
110 {
111         m_get_queues_handler.Detach();
112         m_get_pending_items_handler.Detach();
113         m_get_item_info_handler.Detach();
114         m_get_thread_item_info_handler.Detach();
115 }
116 
117 //----------------------------------------------------------------------
118 // Clear out the state of this class.
119 //----------------------------------------------------------------------
120 void
121 SystemRuntimeMacOSX::Clear (bool clear_process)
122 {
123     Mutex::Locker locker(m_mutex);
124 
125     if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
126         m_process->ClearBreakpointSiteByID(m_break_id);
127 
128     if (clear_process)
129         m_process = NULL;
130     m_break_id = LLDB_INVALID_BREAK_ID;
131 }
132 
133 
134 std::string
135 SystemRuntimeMacOSX::GetQueueNameFromThreadQAddress (addr_t dispatch_qaddr)
136 {
137     std::string dispatch_queue_name;
138     if (dispatch_qaddr == LLDB_INVALID_ADDRESS || dispatch_qaddr == 0)
139         return "";
140 
141     ReadLibdispatchOffsets ();
142     if (m_libdispatch_offsets.IsValid ())
143     {
144         // dispatch_qaddr is from a thread_info(THREAD_IDENTIFIER_INFO) call for a thread -
145         // deref it to get the address of the dispatch_queue_t structure for this thread's
146         // queue.
147         Error error;
148         addr_t dispatch_queue_addr = m_process->ReadPointerFromMemory (dispatch_qaddr, error);
149         if (error.Success())
150         {
151             if (m_libdispatch_offsets.dqo_version >= 4)
152             {
153                 // libdispatch versions 4+, pointer to dispatch name is in the
154                 // queue structure.
155                 addr_t pointer_to_label_address = dispatch_queue_addr + m_libdispatch_offsets.dqo_label;
156                 addr_t label_addr = m_process->ReadPointerFromMemory (pointer_to_label_address, error);
157                 if (error.Success())
158                 {
159                     m_process->ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
160                 }
161             }
162             else
163             {
164                 // libdispatch versions 1-3, dispatch name is a fixed width char array
165                 // in the queue structure.
166                 addr_t label_addr = dispatch_queue_addr + m_libdispatch_offsets.dqo_label;
167                 dispatch_queue_name.resize (m_libdispatch_offsets.dqo_label_size, '\0');
168                 size_t bytes_read = m_process->ReadMemory (label_addr, &dispatch_queue_name[0], m_libdispatch_offsets.dqo_label_size, error);
169                 if (bytes_read < m_libdispatch_offsets.dqo_label_size)
170                     dispatch_queue_name.erase (bytes_read);
171             }
172         }
173     }
174     return dispatch_queue_name;
175 }
176 
177 lldb::queue_id_t
178 SystemRuntimeMacOSX::GetQueueIDFromThreadQAddress (lldb::addr_t dispatch_qaddr)
179 {
180     queue_id_t queue_id = LLDB_INVALID_QUEUE_ID;
181 
182     if (dispatch_qaddr == LLDB_INVALID_ADDRESS || dispatch_qaddr == 0)
183         return queue_id;
184 
185     ReadLibdispatchOffsets ();
186     if (m_libdispatch_offsets.IsValid ())
187     {
188         // dispatch_qaddr is from a thread_info(THREAD_IDENTIFIER_INFO) call for a thread -
189         // deref it to get the address of the dispatch_queue_t structure for this thread's
190         // queue.
191         Error error;
192         uint64_t dispatch_queue_addr = m_process->ReadPointerFromMemory (dispatch_qaddr, error);
193         if (error.Success())
194         {
195             addr_t serialnum_address = dispatch_queue_addr + m_libdispatch_offsets.dqo_serialnum;
196             queue_id_t serialnum = m_process->ReadUnsignedIntegerFromMemory (serialnum_address, m_libdispatch_offsets.dqo_serialnum_size, LLDB_INVALID_QUEUE_ID, error);
197             if (error.Success())
198             {
199                 queue_id = serialnum;
200             }
201         }
202     }
203 
204     return queue_id;
205 }
206 
207 
208 void
209 SystemRuntimeMacOSX::ReadLibdispatchOffsetsAddress ()
210 {
211     if (m_dispatch_queue_offsets_addr != LLDB_INVALID_ADDRESS)
212         return;
213 
214     static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
215     const Symbol *dispatch_queue_offsets_symbol = NULL;
216 
217     // libdispatch symbols were in libSystem.B.dylib up through Mac OS X 10.6 ("Snow Leopard")
218     ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
219     ModuleSP module_sp(m_process->GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
220     if (module_sp)
221         dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
222 
223     // libdispatch symbols are in their own dylib as of Mac OS X 10.7 ("Lion") and later
224     if (dispatch_queue_offsets_symbol == NULL)
225     {
226         ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
227         module_sp = m_process->GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
228         if (module_sp)
229             dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
230     }
231     if (dispatch_queue_offsets_symbol)
232         m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_process->GetTarget());
233 }
234 
235 void
236 SystemRuntimeMacOSX::ReadLibdispatchOffsets ()
237 {
238     if (m_libdispatch_offsets.IsValid())
239         return;
240 
241     ReadLibdispatchOffsetsAddress ();
242 
243     uint8_t memory_buffer[sizeof (struct LibdispatchOffsets)];
244     DataExtractor data (memory_buffer,
245                         sizeof(memory_buffer),
246                         m_process->GetByteOrder(),
247                         m_process->GetAddressByteSize());
248 
249     Error error;
250     if (m_process->ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(memory_buffer), error) == sizeof(memory_buffer))
251     {
252         lldb::offset_t data_offset = 0;
253 
254         // The struct LibdispatchOffsets is a series of uint16_t's - extract them all
255         // in one big go.
256         data.GetU16 (&data_offset, &m_libdispatch_offsets.dqo_version, sizeof (struct LibdispatchOffsets) / sizeof (uint16_t));
257     }
258 }
259 
260 
261 ThreadSP
262 SystemRuntimeMacOSX::GetExtendedBacktraceThread (ThreadSP real_thread, ConstString type)
263 {
264     ThreadSP originating_thread_sp;
265     if (BacktraceRecordingHeadersInitialized() && type == ConstString ("libdispatch"))
266     {
267         Error error;
268 
269         // real_thread is either an actual, live thread (in which case we need to call into
270         // libBacktraceRecording to find its originator) or it is an extended backtrace itself,
271         // in which case we get the token from it and call into libBacktraceRecording to find
272         // the originator of that token.
273 
274         if (real_thread->GetExtendedBacktraceToken() != LLDB_INVALID_ADDRESS)
275         {
276             originating_thread_sp = GetExtendedBacktraceFromItemRef (real_thread->GetExtendedBacktraceToken());
277         }
278         else
279         {
280             ThreadSP cur_thread_sp (m_process->GetThreadList().GetSelectedThread());
281             AppleGetThreadItemInfoHandler::GetThreadItemInfoReturnInfo ret = m_get_thread_item_info_handler.GetThreadItemInfo (*cur_thread_sp.get(), real_thread->GetID(), m_page_to_free, m_page_to_free_size, error);
282             if (ret.item_buffer_ptr != 0 &&  ret.item_buffer_ptr != LLDB_INVALID_ADDRESS && ret.item_buffer_size > 0)
283             {
284                 DataBufferHeap data (ret.item_buffer_size, 0);
285                 if (m_process->ReadMemory (ret.item_buffer_ptr, data.GetBytes(), ret.item_buffer_size, error) && error.Success())
286                 {
287                     DataExtractor extractor (data.GetBytes(), data.GetByteSize(), m_process->GetByteOrder(), m_process->GetAddressByteSize());
288                     ItemInfo item = ExtractItemInfoFromBuffer (extractor);
289                     bool stop_id_is_valid = true;
290                     if (item.stop_id == 0)
291                         stop_id_is_valid = false;
292                     originating_thread_sp.reset (new HistoryThread (*m_process,
293                                                                     item.enqueuing_thread_id,
294                                                                     item.enqueuing_callstack,
295                                                                     item.stop_id,
296                                                                     stop_id_is_valid));
297                     originating_thread_sp->SetExtendedBacktraceToken (item.item_that_enqueued_this);
298                     originating_thread_sp->SetQueueName (item.enqueuing_queue_label.c_str());
299                     originating_thread_sp->SetQueueID (item.enqueuing_queue_serialnum);
300 //                    originating_thread_sp->SetThreadName (item.enqueuing_thread_label.c_str());
301                 }
302                 m_page_to_free = ret.item_buffer_ptr;
303                 m_page_to_free_size = ret.item_buffer_size;
304             }
305         }
306     }
307     return originating_thread_sp;
308 }
309 
310 ThreadSP
311 SystemRuntimeMacOSX::GetExtendedBacktraceFromItemRef (lldb::addr_t item_ref)
312 {
313     ThreadSP return_thread_sp;
314 
315     AppleGetItemInfoHandler::GetItemInfoReturnInfo ret;
316     ThreadSP cur_thread_sp (m_process->GetThreadList().GetSelectedThread());
317     Error error;
318     ret = m_get_item_info_handler.GetItemInfo (*cur_thread_sp.get(), item_ref, m_page_to_free, m_page_to_free_size, error);
319     if (ret.item_buffer_ptr != 0 &&  ret.item_buffer_ptr != LLDB_INVALID_ADDRESS && ret.item_buffer_size > 0)
320     {
321         DataBufferHeap data (ret.item_buffer_size, 0);
322         if (m_process->ReadMemory (ret.item_buffer_ptr, data.GetBytes(), ret.item_buffer_size, error) && error.Success())
323         {
324             DataExtractor extractor (data.GetBytes(), data.GetByteSize(), m_process->GetByteOrder(), m_process->GetAddressByteSize());
325             ItemInfo item = ExtractItemInfoFromBuffer (extractor);
326             bool stop_id_is_valid = true;
327             if (item.stop_id == 0)
328                 stop_id_is_valid = false;
329             return_thread_sp.reset (new HistoryThread (*m_process,
330                                                             item.enqueuing_thread_id,
331                                                             item.enqueuing_callstack,
332                                                             item.stop_id,
333                                                             stop_id_is_valid));
334             return_thread_sp->SetExtendedBacktraceToken (item.item_that_enqueued_this);
335             return_thread_sp->SetQueueName (item.enqueuing_queue_label.c_str());
336             return_thread_sp->SetQueueID (item.enqueuing_queue_serialnum);
337 //            return_thread_sp->SetThreadName (item.enqueuing_thread_label.c_str());
338 
339             m_page_to_free = ret.item_buffer_ptr;
340             m_page_to_free_size = ret.item_buffer_size;
341         }
342     }
343     return return_thread_sp;
344 }
345 
346 ThreadSP
347 SystemRuntimeMacOSX::GetExtendedBacktraceForQueueItem (QueueItemSP queue_item_sp, ConstString type)
348 {
349     ThreadSP extended_thread_sp;
350     if (type != ConstString("libdispatch"))
351         return extended_thread_sp;
352 
353     bool stop_id_is_valid = true;
354     if (queue_item_sp->GetStopID() == 0)
355         stop_id_is_valid = false;
356 
357     extended_thread_sp.reset (new HistoryThread (*m_process,
358                                                  queue_item_sp->GetEnqueueingThreadID(),
359                                                  queue_item_sp->GetEnqueueingBacktrace(),
360                                                  queue_item_sp->GetStopID(),
361                                                  stop_id_is_valid));
362     extended_thread_sp->SetExtendedBacktraceToken (queue_item_sp->GetItemThatEnqueuedThis());
363     extended_thread_sp->SetQueueName (queue_item_sp->GetQueueLabel().c_str());
364     extended_thread_sp->SetQueueID (queue_item_sp->GetEnqueueingQueueID());
365 //    extended_thread_sp->SetThreadName (queue_item_sp->GetThreadLabel().c_str());
366 
367     return extended_thread_sp;
368 }
369 
370 /* Returns true if we were able to get the version / offset information
371  * out of libBacktraceRecording.  false means we were unable to retrieve
372  * this; the queue_info_version field will be 0.
373  */
374 
375 bool
376 SystemRuntimeMacOSX::BacktraceRecordingHeadersInitialized ()
377 {
378     if (m_lib_backtrace_recording_info.queue_info_version != 0)
379         return true;
380 
381     addr_t queue_info_version_address = LLDB_INVALID_ADDRESS;
382     addr_t queue_info_data_offset_address = LLDB_INVALID_ADDRESS;
383     addr_t item_info_version_address = LLDB_INVALID_ADDRESS;
384     addr_t item_info_data_offset_address = LLDB_INVALID_ADDRESS;
385     Target &target = m_process->GetTarget();
386 
387 
388     static ConstString introspection_dispatch_queue_info_version ("__introspection_dispatch_queue_info_version");
389     SymbolContextList sc_list;
390     if (m_process->GetTarget().GetImages().FindSymbolsWithNameAndType (introspection_dispatch_queue_info_version, eSymbolTypeData, sc_list) > 0)
391     {
392         SymbolContext sc;
393         sc_list.GetContextAtIndex (0, sc);
394         AddressRange addr_range;
395         sc.GetAddressRange (eSymbolContextSymbol, 0, false, addr_range);
396         queue_info_version_address = addr_range.GetBaseAddress().GetLoadAddress(&target);
397     }
398     sc_list.Clear();
399 
400     static ConstString introspection_dispatch_queue_info_data_offset ("__introspection_dispatch_queue_info_data_offset");
401     if (m_process->GetTarget().GetImages().FindSymbolsWithNameAndType (introspection_dispatch_queue_info_data_offset, eSymbolTypeData, sc_list) > 0)
402     {
403         SymbolContext sc;
404         sc_list.GetContextAtIndex (0, sc);
405         AddressRange addr_range;
406         sc.GetAddressRange (eSymbolContextSymbol, 0, false, addr_range);
407         queue_info_data_offset_address = addr_range.GetBaseAddress().GetLoadAddress(&target);
408     }
409     sc_list.Clear();
410 
411     static ConstString introspection_dispatch_item_info_version ("__introspection_dispatch_item_info_version");
412     if (m_process->GetTarget().GetImages().FindSymbolsWithNameAndType (introspection_dispatch_item_info_version, eSymbolTypeData, sc_list) > 0)
413     {
414         SymbolContext sc;
415         sc_list.GetContextAtIndex (0, sc);
416         AddressRange addr_range;
417         sc.GetAddressRange (eSymbolContextSymbol, 0, false, addr_range);
418         item_info_version_address = addr_range.GetBaseAddress().GetLoadAddress(&target);
419     }
420     sc_list.Clear();
421 
422     static ConstString introspection_dispatch_item_info_data_offset ("__introspection_dispatch_item_info_data_offset");
423     if (m_process->GetTarget().GetImages().FindSymbolsWithNameAndType (introspection_dispatch_item_info_data_offset, eSymbolTypeData, sc_list) > 0)
424     {
425         SymbolContext sc;
426         sc_list.GetContextAtIndex (0, sc);
427         AddressRange addr_range;
428         sc.GetAddressRange (eSymbolContextSymbol, 0, false, addr_range);
429         item_info_data_offset_address = addr_range.GetBaseAddress().GetLoadAddress(&target);
430     }
431 
432     if (queue_info_version_address != LLDB_INVALID_ADDRESS
433         && queue_info_data_offset_address != LLDB_INVALID_ADDRESS
434         && item_info_version_address != LLDB_INVALID_ADDRESS
435         && item_info_data_offset_address != LLDB_INVALID_ADDRESS)
436     {
437         Error error;
438         m_lib_backtrace_recording_info.queue_info_version = m_process->ReadUnsignedIntegerFromMemory (queue_info_version_address, 2, 0, error);
439         if (error.Success())
440         {
441             m_lib_backtrace_recording_info.queue_info_data_offset = m_process->ReadUnsignedIntegerFromMemory (queue_info_data_offset_address, 2, 0, error);
442             if (error.Success())
443             {
444                 m_lib_backtrace_recording_info.item_info_version = m_process->ReadUnsignedIntegerFromMemory (item_info_version_address, 2, 0, error);
445                 if (error.Success())
446                 {
447                     m_lib_backtrace_recording_info.item_info_data_offset = m_process->ReadUnsignedIntegerFromMemory (item_info_data_offset_address, 2, 0, error);
448                     if (!error.Success())
449                     {
450                         m_lib_backtrace_recording_info.queue_info_version = 0;
451                     }
452                 }
453                 else
454                 {
455                     m_lib_backtrace_recording_info.queue_info_version = 0;
456                 }
457             }
458             else
459             {
460                 m_lib_backtrace_recording_info.queue_info_version = 0;
461             }
462         }
463     }
464 
465     return m_lib_backtrace_recording_info.queue_info_version != 0;
466 }
467 
468 const std::vector<ConstString> &
469 SystemRuntimeMacOSX::GetExtendedBacktraceTypes ()
470 {
471     if (m_types.size () == 0)
472     {
473         m_types.push_back(ConstString("libdispatch"));
474         // We could have pthread as another type in the future if we have a way of
475         // gathering that information & it's useful to distinguish between them.
476     }
477     return m_types;
478 }
479 
480 void
481 SystemRuntimeMacOSX::PopulateQueueList (lldb_private::QueueList &queue_list)
482 {
483     if (!BacktraceRecordingHeadersInitialized())
484     {
485         // We don't have libBacktraceRecording -- build the list of queues by looking at
486         // all extant threads, and the queues that they currently belong to.
487 
488         for (ThreadSP thread_sp : m_process->Threads())
489         {
490             if (thread_sp->GetQueueID() != LLDB_INVALID_QUEUE_ID)
491             {
492                 if (queue_list.FindQueueByID (thread_sp->GetQueueID()).get() == NULL)
493                 {
494                     QueueSP queue_sp (new Queue(m_process->shared_from_this(), thread_sp->GetQueueID(), thread_sp->GetQueueName()));
495                     queue_list.AddQueue (queue_sp);
496                 }
497             }
498         }
499     }
500     else
501     {
502         AppleGetQueuesHandler::GetQueuesReturnInfo queue_info_pointer;
503         ThreadSP cur_thread_sp (m_process->GetThreadList().GetSelectedThread());
504         if (cur_thread_sp)
505         {
506             Error error;
507             queue_info_pointer = m_get_queues_handler.GetCurrentQueues (*cur_thread_sp.get(), m_page_to_free, m_page_to_free_size, error);
508             if (error.Success())
509             {
510                 m_page_to_free = LLDB_INVALID_ADDRESS;
511                 m_page_to_free_size = 0;
512 
513                 if (queue_info_pointer.count > 0
514                     && queue_info_pointer.queues_buffer_size > 0
515                     && queue_info_pointer.queues_buffer_ptr != 0
516                     && queue_info_pointer.queues_buffer_ptr != LLDB_INVALID_ADDRESS)
517                 {
518                     PopulateQueuesUsingLibBTR (queue_info_pointer.queues_buffer_ptr, queue_info_pointer.queues_buffer_size, queue_info_pointer.count, queue_list);
519                 }
520             }
521         }
522     }
523 }
524 
525 void
526 SystemRuntimeMacOSX::PopulatePendingItemsForQueue (Queue *queue)
527 {
528     if (BacktraceRecordingHeadersInitialized())
529     {
530         std::vector<addr_t> pending_item_refs = GetPendingItemRefsForQueue (queue->GetLibdispatchQueueAddress());
531         for (addr_t pending_item : pending_item_refs)
532         {
533             AppleGetItemInfoHandler::GetItemInfoReturnInfo ret;
534             ThreadSP cur_thread_sp (m_process->GetThreadList().GetSelectedThread());
535             Error error;
536             ret = m_get_item_info_handler.GetItemInfo (*cur_thread_sp.get(), pending_item, m_page_to_free, m_page_to_free_size, error);
537             if (ret.item_buffer_ptr != 0 &&  ret.item_buffer_ptr != LLDB_INVALID_ADDRESS && ret.item_buffer_size > 0)
538             {
539                 DataBufferHeap data (ret.item_buffer_size, 0);
540                 if (m_process->ReadMemory (ret.item_buffer_ptr, data.GetBytes(), ret.item_buffer_size, error) && error.Success())
541                 {
542                     DataExtractor extractor (data.GetBytes(), data.GetByteSize(), m_process->GetByteOrder(), m_process->GetAddressByteSize());
543                     ItemInfo item = ExtractItemInfoFromBuffer (extractor);
544                     QueueItemSP queue_item_sp (new QueueItem (queue->shared_from_this()));
545                     queue_item_sp->SetItemThatEnqueuedThis (item.item_that_enqueued_this);
546 
547                     Address addr;
548                     if (!m_process->GetTarget().ResolveLoadAddress (item.function_or_block, addr, item.stop_id))
549                     {
550                         m_process->GetTarget().ResolveLoadAddress (item.function_or_block, addr);
551                     }
552                     queue_item_sp->SetAddress (addr);
553                     queue_item_sp->SetEnqueueingThreadID (item.enqueuing_thread_id);
554                     queue_item_sp->SetTargetQueueID (item.enqueuing_thread_id);
555                     queue_item_sp->SetStopID (item.stop_id);
556                     queue_item_sp->SetEnqueueingBacktrace (item.enqueuing_callstack);
557                     queue_item_sp->SetThreadLabel (item.enqueuing_thread_label);
558                     queue_item_sp->SetQueueLabel (item.enqueuing_queue_label);
559                     queue_item_sp->SetTargetQueueLabel (item.target_queue_label);
560 
561                     queue->PushPendingQueueItem (queue_item_sp);
562                 }
563                 m_page_to_free = ret.item_buffer_ptr;
564                 m_page_to_free_size = ret.item_buffer_size;
565             }
566         }
567     }
568 }
569 
570 // Returns an array of introspection_dispatch_item_info_ref's for the pending items on
571 // a queue.  The information about each of these pending items then needs to be fetched
572 // individually by passing the ref to libBacktraceRecording.
573 
574 std::vector<lldb::addr_t>
575 SystemRuntimeMacOSX::GetPendingItemRefsForQueue (lldb::addr_t queue)
576 {
577     std::vector<addr_t> pending_item_refs;
578     AppleGetPendingItemsHandler::GetPendingItemsReturnInfo pending_items_pointer;
579     ThreadSP cur_thread_sp (m_process->GetThreadList().GetSelectedThread());
580     if (cur_thread_sp)
581     {
582         Error error;
583         pending_items_pointer = m_get_pending_items_handler.GetPendingItems (*cur_thread_sp.get(), queue, m_page_to_free, m_page_to_free_size, error);
584         if (error.Success())
585         {
586             m_page_to_free = LLDB_INVALID_ADDRESS;
587             m_page_to_free_size = 0;
588             if (pending_items_pointer.count > 0
589                 && pending_items_pointer.items_buffer_size > 0
590                 && pending_items_pointer.items_buffer_ptr != 0
591                 && pending_items_pointer.items_buffer_ptr != LLDB_INVALID_ADDRESS)
592             {
593                 DataBufferHeap data (pending_items_pointer.items_buffer_size, 0);
594                 if (m_process->ReadMemory (pending_items_pointer.items_buffer_ptr, data.GetBytes(), pending_items_pointer.items_buffer_size, error))
595                 {
596                     offset_t offset = 0;
597                     DataExtractor extractor (data.GetBytes(), data.GetByteSize(), m_process->GetByteOrder(), m_process->GetAddressByteSize());
598                     int i = 0;
599                     while (offset < pending_items_pointer.items_buffer_size && i < pending_items_pointer.count)
600                     {
601                         pending_item_refs.push_back (extractor.GetPointer (&offset));
602                         i++;
603                     }
604                 }
605                 m_page_to_free = pending_items_pointer.items_buffer_ptr;
606                 m_page_to_free_size = pending_items_pointer.items_buffer_size;
607             }
608         }
609     }
610     return pending_item_refs;
611 }
612 
613 
614 void
615 SystemRuntimeMacOSX::PopulateQueuesUsingLibBTR (lldb::addr_t queues_buffer, uint64_t queues_buffer_size,
616                                                 uint64_t count, lldb_private::QueueList &queue_list)
617 {
618     Error error;
619     DataBufferHeap data (queues_buffer_size, 0);
620     if (m_process->ReadMemory (queues_buffer, data.GetBytes(), queues_buffer_size, error) == queues_buffer_size && error.Success())
621     {
622         // We've read the information out of inferior memory; free it on the next call we make
623         m_page_to_free = queues_buffer;
624         m_page_to_free_size = queues_buffer_size;
625 
626         DataExtractor extractor (data.GetBytes(), data.GetByteSize(), m_process->GetByteOrder(), m_process->GetAddressByteSize());
627         offset_t offset = 0;
628         uint64_t queues_read = 0;
629 
630         // The information about the queues is stored in this format (v1):
631         // typedef struct introspection_dispatch_queue_info_s {
632         //     uint32_t offset_to_next;
633         //     dispatch_queue_t queue;
634         //     uint64_t serialnum;     // queue's serialnum in the process, as provided by libdispatch
635         //     uint32_t running_work_items_count;
636         //     uint32_t pending_work_items_count;
637         //
638         //     char data[];     // Starting here, we have variable-length data:
639         //     // char queue_label[];
640         // } introspection_dispatch_queue_info_s;
641 
642         while (queues_read < count && offset < queues_buffer_size)
643         {
644             offset_t    start_of_this_item = offset;
645 
646             uint32_t    offset_to_next = extractor.GetU32 (&offset);
647             /* on 64-bit architectures, the pointer will be 8-byte aligned so there's 4 bytes of
648              * padding between these fields.
649              */
650             if (m_process->GetAddressByteSize() == 8)
651                 offset += 4;
652             addr_t      queue = extractor.GetPointer (&offset);
653             uint64_t    serialnum = extractor.GetU64 (&offset);
654             uint32_t    running_work_items_count = extractor.GetU32 (&offset);
655             uint32_t    pending_work_items_count = extractor.GetU32 (&offset);
656 
657             // Read the first field of the variable length data
658             offset = start_of_this_item + m_lib_backtrace_recording_info.queue_info_data_offset;
659             const char *queue_label = extractor.GetCStr (&offset);
660             if (queue_label == NULL)
661                 queue_label = "";
662 
663             offset_t    start_of_next_item = start_of_this_item + offset_to_next;
664             offset = start_of_next_item;
665 
666             QueueSP queue_sp (new Queue (m_process->shared_from_this(), serialnum, queue_label));
667             queue_sp->SetNumRunningWorkItems (running_work_items_count);
668             queue_sp->SetNumPendingWorkItems (pending_work_items_count);
669             queue_sp->SetLibdispatchQueueAddress (queue);
670             queue_list.AddQueue (queue_sp);
671             queues_read++;
672         }
673     }
674 }
675 
676 SystemRuntimeMacOSX::ItemInfo
677 SystemRuntimeMacOSX::ExtractItemInfoFromBuffer (lldb_private::DataExtractor &extractor)
678 {
679     ItemInfo item;
680 
681     offset_t offset = 0;
682 
683     item.item_that_enqueued_this = extractor.GetPointer (&offset);
684     item.function_or_block = extractor.GetPointer (&offset);
685     item.enqueuing_thread_id = extractor.GetU64 (&offset);
686     item.enqueuing_queue_serialnum = extractor.GetU64 (&offset);
687     item.target_queue_serialnum = extractor.GetU64 (&offset);
688     item.enqueuing_callstack_frame_count = extractor.GetU32 (&offset);
689     item.stop_id = extractor.GetU32 (&offset);
690 
691     offset = m_lib_backtrace_recording_info.item_info_data_offset;
692 
693     for (uint32_t i = 0; i < item.enqueuing_callstack_frame_count; i++)
694     {
695         item.enqueuing_callstack.push_back (extractor.GetPointer (&offset));
696     }
697     item.enqueuing_thread_label = extractor.GetCStr (&offset);
698     item.enqueuing_queue_label = extractor.GetCStr (&offset);
699     item.target_queue_label = extractor.GetCStr (&offset);
700 
701     return item;
702 }
703 
704 void
705 SystemRuntimeMacOSX::Initialize()
706 {
707     PluginManager::RegisterPlugin (GetPluginNameStatic(),
708                                    GetPluginDescriptionStatic(),
709                                    CreateInstance);
710 }
711 
712 void
713 SystemRuntimeMacOSX::Terminate()
714 {
715     PluginManager::UnregisterPlugin (CreateInstance);
716 }
717 
718 
719 lldb_private::ConstString
720 SystemRuntimeMacOSX::GetPluginNameStatic()
721 {
722     static ConstString g_name("systemruntime-macosx");
723     return g_name;
724 }
725 
726 const char *
727 SystemRuntimeMacOSX::GetPluginDescriptionStatic()
728 {
729     return "System runtime plugin for Mac OS X native libraries.";
730 }
731 
732 
733 //------------------------------------------------------------------
734 // PluginInterface protocol
735 //------------------------------------------------------------------
736 lldb_private::ConstString
737 SystemRuntimeMacOSX::GetPluginName()
738 {
739     return GetPluginNameStatic();
740 }
741 
742 uint32_t
743 SystemRuntimeMacOSX::GetPluginVersion()
744 {
745     return 1;
746 }
747