lp_bld_debug.cpp revision 1795372feec77e62cbe150f5853e063b9e53acd2
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#if HAVE_LLVM >= 0x0300
214   const MCSubtargetInfo *STI = T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), "");
215   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
216#else
217   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler());
218#endif
219   if (!DisAsm) {
220      debug_printf("error: no disassembler for target %s\n", Triple.c_str());
221      return;
222   }
223
224   raw_debug_ostream Out;
225
226#if HAVE_LLVM >= 0x0300
227   unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
228#else
229   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
230#endif
231
232#if HAVE_LLVM >= 0x0300
233   OwningPtr<MCInstPrinter> Printer(
234         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *STI));
235#elif HAVE_LLVM >= 0x0208
236   OwningPtr<MCInstPrinter> Printer(
237         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo));
238#else
239   OwningPtr<MCInstPrinter> Printer(
240         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out));
241#endif
242   if (!Printer) {
243      debug_printf("error: no instruction printer for target %s\n", Triple.c_str());
244      return;
245   }
246
247#if HAVE_LLVM >= 0x0300
248   TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "");
249#else
250   TargetMachine *TM = T->createTargetMachine(Triple, "");
251#endif
252
253   const TargetInstrInfo *TII = TM->getInstrInfo();
254
255   /*
256    * Wrap the data in a MemoryObject
257    */
258   BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
259
260   uint64_t pc;
261   pc = 0;
262   while (true) {
263      MCInst Inst;
264      uint64_t Size;
265
266      /*
267       * Print address.  We use addresses relative to the start of the function,
268       * so that between runs.
269       */
270
271      debug_printf("%6lu:\t", (unsigned long)pc);
272
273      if (!DisAsm->getInstruction(Inst, Size, memoryObject,
274                                 pc,
275                                 nulls())) {
276         debug_printf("invalid\n");
277         pc += 1;
278      }
279
280      /*
281       * Output the bytes in hexidecimal format.
282       */
283
284      if (0) {
285         unsigned i;
286         for (i = 0; i < Size; ++i) {
287            debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]);
288         }
289         for (; i < 16; ++i) {
290            debug_printf("   ");
291         }
292      }
293
294      /*
295       * Print the instruction.
296       */
297
298#if HAVE_LLVM >= 0x208
299      Printer->printInst(&Inst, Out);
300#else
301      Printer->printInst(&Inst);
302#endif
303      Out.flush();
304
305      /*
306       * Advance.
307       */
308
309      pc += Size;
310
311#if HAVE_LLVM >= 0x0300
312      const MCInstrDesc &TID = TII->get(Inst.getOpcode());
313#else
314      const TargetInstrDesc &TID = TII->get(Inst.getOpcode());
315#endif
316
317      /*
318       * Keep track of forward jumps to a nearby address.
319       */
320
321      if (TID.isBranch()) {
322         for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
323            const MCOperand &operand = Inst.getOperand(i);
324            if (operand.isImm()) {
325               uint64_t jump;
326
327               /*
328                * FIXME: Handle both relative and absolute addresses correctly.
329                * EDInstInfo actually has this info, but operandTypes and
330                * operandFlags enums are not exposed in the public interface.
331                */
332
333               if (1) {
334                  /*
335                   * PC relative addr.
336                   */
337
338                  jump = pc + operand.getImm();
339               } else {
340                  /*
341                   * Absolute addr.
342                   */
343
344                  jump = (uint64_t)operand.getImm();
345               }
346
347               /*
348                * Output the address relative to the function start, given
349                * that MC will print the addresses relative the current pc.
350                */
351               debug_printf("\t\t; %lu", (unsigned long)jump);
352
353               /*
354                * Ignore far jumps given it could be actually a tail return to
355                * a random address.
356                */
357
358               if (jump > max_pc &&
359                   jump < extent) {
360                  max_pc = jump;
361               }
362            }
363         }
364      }
365
366      debug_printf("\n");
367
368      /*
369       * Stop disassembling on return statements, if there is no record of a
370       * jump to a successive address.
371       */
372
373      if (TID.isReturn()) {
374         if (pc > max_pc) {
375            break;
376         }
377      }
378   }
379
380   /*
381    * Print GDB command, useful to verify output.
382    */
383
384   if (0) {
385      debug_printf("disassemble %p %p\n", bytes, bytes + pc);
386   }
387
388   debug_printf("\n");
389#else /* HAVE_LLVM < 0x0207 */
390   (void)func;
391#endif /* HAVE_LLVM < 0x0207 */
392}
393
394