lp_bld_debug.cpp revision 4a468de2d78fc5a9e6de40a9dae09669ec556fc5
1/**************************************************************************
2 *
3 * Copyright 2009-2011 VMware, Inc.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28#include <llvm-c/Core.h>
29#include <llvm/Target/TargetMachine.h>
30#include <llvm/Target/TargetInstrInfo.h>
31#include <llvm/Support/raw_ostream.h>
32#include <llvm/Support/MemoryObject.h>
33
34#if HAVE_LLVM >= 0x0300
35#include <llvm/Support/TargetRegistry.h>
36#include <llvm/Support/TargetSelect.h>
37#else /* HAVE_LLVM < 0x0300 */
38#include <llvm/Target/TargetRegistry.h>
39#include <llvm/Target/TargetSelect.h>
40#endif /* HAVE_LLVM < 0x0300 */
41
42#if HAVE_LLVM >= 0x0209
43#include <llvm/Support/Host.h>
44#else /* HAVE_LLVM < 0x0209 */
45#include <llvm/System/Host.h>
46#endif /* HAVE_LLVM < 0x0209 */
47
48#if HAVE_LLVM >= 0x0207
49#include <llvm/MC/MCDisassembler.h>
50#include <llvm/MC/MCAsmInfo.h>
51#include <llvm/MC/MCInst.h>
52#include <llvm/MC/MCInstPrinter.h>
53#endif /* HAVE_LLVM >= 0x0207 */
54
55#include "util/u_math.h"
56#include "util/u_debug.h"
57
58#include "lp_bld_debug.h"
59
60
61
62/**
63 * Check alignment.
64 *
65 * It is important that this check is not implemented as a macro or inlined
66 * function, as the compiler assumptions in respect to alignment of global
67 * and stack variables would often make the check a no op, defeating the
68 * whole purpose of the exercise.
69 */
70extern "C" boolean
71lp_check_alignment(const void *ptr, unsigned alignment)
72{
73   assert(util_is_power_of_two(alignment));
74   return ((uintptr_t)ptr & (alignment - 1)) == 0;
75}
76
77
78class raw_debug_ostream :
79   public llvm::raw_ostream
80{
81   uint64_t pos;
82
83   void write_impl(const char *Ptr, size_t Size);
84   uint64_t current_pos() { return pos; }
85   uint64_t current_pos() const { return pos; }
86
87#if HAVE_LLVM >= 0x207
88   uint64_t preferred_buffer_size() { return 512; }
89#else
90   size_t preferred_buffer_size() { return 512; }
91#endif
92};
93
94
95void
96raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
97{
98   if (Size > 0) {
99      char *lastPtr = (char *)&Ptr[Size];
100      char last = *lastPtr;
101      *lastPtr = 0;
102      _debug_printf("%*s", Size, Ptr);
103      *lastPtr = last;
104      pos += Size;
105   }
106}
107
108
109/**
110 * Same as LLVMDumpValue, but through our debugging channels.
111 */
112extern "C" void
113lp_debug_dump_value(LLVMValueRef value)
114{
115#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
116   raw_debug_ostream os;
117   llvm::unwrap(value)->print(os);
118   os.flush();
119#else
120   LLVMDumpValue(value);
121#endif
122}
123
124
125#if HAVE_LLVM >= 0x0207
126/*
127 * MemoryObject wrapper around a buffer of memory, to be used by MC
128 * disassembler.
129 */
130class BufferMemoryObject:
131   public llvm::MemoryObject
132{
133private:
134   const uint8_t *Bytes;
135   uint64_t Length;
136public:
137   BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
138      Bytes(bytes), Length(length)
139   {
140   }
141
142   uint64_t getBase() const
143   {
144      return 0;
145   }
146
147   uint64_t getExtent() const
148   {
149      return Length;
150   }
151
152   int readByte(uint64_t addr, uint8_t *byte) const
153   {
154      if (addr > getExtent())
155         return -1;
156      *byte = Bytes[addr];
157      return 0;
158   }
159};
160#endif /* HAVE_LLVM >= 0x0207 */
161
162
163/*
164 * Disassemble a function, using the LLVM MC disassembler.
165 *
166 * See also:
167 * - http://blog.llvm.org/2010/01/x86-disassembler.html
168 * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
169 */
170extern "C" void
171lp_disassemble(const void* func)
172{
173#if HAVE_LLVM >= 0x0207
174   using namespace llvm;
175
176   const uint8_t *bytes = (const uint8_t *)func;
177
178   /*
179    * Limit disassembly to this extent
180    */
181   const uint64_t extent = 0x10000;
182
183   uint64_t max_pc = 0;
184
185   /*
186    * Initialize all used objects.
187    */
188
189   std::string Triple = sys::getHostTriple();
190
191   std::string Error;
192   const Target *T = TargetRegistry::lookupTarget(Triple, Error);
193
194#if HAVE_LLVM >= 0x0208
195   InitializeNativeTargetAsmPrinter();
196#else
197   InitializeAllAsmPrinters();
198#endif
199
200   InitializeAllDisassemblers();
201
202#if HAVE_LLVM >= 0x0300
203   OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
204#else
205   OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple));
206#endif
207
208   if (!AsmInfo) {
209      debug_printf("error: no assembly info for target %s\n", Triple.c_str());
210      return;
211   }
212
213   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler());
214   if (!DisAsm) {
215      debug_printf("error: no disassembler for target %s\n", Triple.c_str());
216      return;
217   }
218
219   raw_debug_ostream Out;
220
221#if HAVE_LLVM >= 0x0300
222   unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
223#else
224   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
225#endif
226#if HAVE_LLVM >= 0x0208
227   OwningPtr<MCInstPrinter> Printer(
228         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo));
229#else
230   OwningPtr<MCInstPrinter> Printer(
231         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out));
232#endif
233   if (!Printer) {
234      debug_printf("error: no instruction printer for target %s\n", Triple.c_str());
235      return;
236   }
237
238#if HAVE_LLVM >= 0x0300
239   TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "");
240#else
241   TargetMachine *TM = T->createTargetMachine(Triple, "");
242#endif
243
244   const TargetInstrInfo *TII = TM->getInstrInfo();
245
246   /*
247    * Wrap the data in a MemoryObject
248    */
249   BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
250
251   uint64_t pc;
252   pc = 0;
253   while (true) {
254      MCInst Inst;
255      uint64_t Size;
256
257      /*
258       * Print address.  We use addresses relative to the start of the function,
259       * so that between runs.
260       */
261
262      debug_printf("%6lu:\t", (unsigned long)pc);
263
264      if (!DisAsm->getInstruction(Inst, Size, memoryObject,
265                                 pc,
266                                 nulls())) {
267         debug_printf("invalid\n");
268         pc += 1;
269      }
270
271      /*
272       * Output the bytes in hexidecimal format.
273       */
274
275      if (0) {
276         unsigned i;
277         for (i = 0; i < Size; ++i) {
278            debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]);
279         }
280         for (; i < 16; ++i) {
281            debug_printf("   ");
282         }
283      }
284
285      /*
286       * Print the instruction.
287       */
288
289#if HAVE_LLVM >= 0x208
290      Printer->printInst(&Inst, Out);
291#else
292      Printer->printInst(&Inst);
293#endif
294      Out.flush();
295
296      /*
297       * Advance.
298       */
299
300      pc += Size;
301
302#if HAVE_LLVM >= 0x0300
303      const MCInstrDesc &TID = TII->get(Inst.getOpcode());
304#else
305      const TargetInstrDesc &TID = TII->get(Inst.getOpcode());
306#endif
307
308      /*
309       * Keep track of forward jumps to a nearby address.
310       */
311
312      if (TID.isBranch()) {
313         for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
314            const MCOperand &operand = Inst.getOperand(i);
315            if (operand.isImm()) {
316               uint64_t jump;
317
318               /*
319                * FIXME: Handle both relative and absolute addresses correctly.
320                * EDInstInfo actually has this info, but operandTypes and
321                * operandFlags enums are not exposed in the public interface.
322                */
323
324               if (1) {
325                  /*
326                   * PC relative addr.
327                   */
328
329                  jump = pc + operand.getImm();
330               } else {
331                  /*
332                   * Absolute addr.
333                   */
334
335                  jump = (uint64_t)operand.getImm();
336               }
337
338               /*
339                * Output the address relative to the function start, given
340                * that MC will print the addresses relative the current pc.
341                */
342               debug_printf("\t\t; %lu", (unsigned long)jump);
343
344               /*
345                * Ignore far jumps given it could be actually a tail return to
346                * a random address.
347                */
348
349               if (jump > max_pc &&
350                   jump < extent) {
351                  max_pc = jump;
352               }
353            }
354         }
355      }
356
357      debug_printf("\n");
358
359      /*
360       * Stop disassembling on return statements, if there is no record of a
361       * jump to a successive address.
362       */
363
364      if (TID.isReturn()) {
365         if (pc > max_pc) {
366            break;
367         }
368      }
369   }
370
371   /*
372    * Print GDB command, useful to verify output.
373    */
374
375   if (0) {
376      debug_printf("disassemble %p %p\n", bytes, bytes + pc);
377   }
378
379   debug_printf("\n");
380#else /* HAVE_LLVM < 0x0207 */
381   (void)func;
382#endif /* HAVE_LLVM < 0x0207 */
383}
384
385