lp_bld_debug.cpp revision c27e58c10940a6442705a4399c5100c82c122a6e
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/TargetRegistry.h>
31#include <llvm/Target/TargetSelect.h>
32#include <llvm/Target/TargetInstrInfo.h>
33#include <llvm/Support/raw_ostream.h>
34#include <llvm/Support/MemoryObject.h>
35#include <llvm/System/Host.h>
36
37#if HAVE_LLVM >= 0x0207
38#include <llvm/MC/MCDisassembler.h>
39#include <llvm/MC/MCAsmInfo.h>
40#include <llvm/MC/MCInst.h>
41#include <llvm/MC/MCInstPrinter.h>
42#endif /* HAVE_LLVM >= 0x0207 */
43
44#include "util/u_math.h"
45#include "util/u_debug.h"
46
47#include "lp_bld_debug.h"
48
49
50
51/**
52 * Check alignment.
53 *
54 * It is important that this check is not implemented as a macro or inlined
55 * function, as the compiler assumptions in respect to alignment of global
56 * and stack variables would often make the check a no op, defeating the
57 * whole purpose of the exercise.
58 */
59extern "C" boolean
60lp_check_alignment(const void *ptr, unsigned alignment)
61{
62   assert(util_is_power_of_two(alignment));
63   return ((uintptr_t)ptr & (alignment - 1)) == 0;
64}
65
66
67class raw_debug_ostream :
68   public llvm::raw_ostream
69{
70   uint64_t pos;
71
72   void write_impl(const char *Ptr, size_t Size);
73   uint64_t current_pos() { return pos; }
74   uint64_t current_pos() const { return pos; }
75
76#if HAVE_LLVM >= 0x207
77   uint64_t preferred_buffer_size() { return 512; }
78#else
79   size_t preferred_buffer_size() { return 512; }
80#endif
81};
82
83
84void
85raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
86{
87   if (Size > 0) {
88      char *lastPtr = (char *)&Ptr[Size];
89      char last = *lastPtr;
90      *lastPtr = 0;
91      _debug_printf("%*s", Size, Ptr);
92      *lastPtr = last;
93      pos += Size;
94   }
95}
96
97
98/**
99 * Same as LLVMDumpValue, but through our debugging channels.
100 */
101extern "C" void
102lp_debug_dump_value(LLVMValueRef value)
103{
104#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
105   raw_debug_ostream os;
106   llvm::unwrap(value)->print(os);
107   os.flush();
108#else
109   LLVMDumpValue(value);
110#endif
111}
112
113
114#if HAVE_LLVM >= 0x0207
115/*
116 * MemoryObject wrapper around a buffer of memory, to be used by MC
117 * disassembler.
118 */
119class BufferMemoryObject:
120   public llvm::MemoryObject
121{
122private:
123   const uint8_t *Bytes;
124   uint64_t Length;
125public:
126   BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
127      Bytes(bytes), Length(length)
128   {
129   }
130
131   uint64_t getBase() const
132   {
133      return 0;
134   }
135
136   uint64_t getExtent() const
137   {
138      return Length;
139   }
140
141   int readByte(uint64_t addr, uint8_t *byte) const
142   {
143      if (addr > getExtent())
144         return -1;
145      *byte = Bytes[addr];
146      return 0;
147   }
148};
149#endif /* HAVE_LLVM >= 0x0207 */
150
151
152/*
153 * Disassemble a function, using the LLVM MC disassembler.
154 *
155 * See also:
156 * - http://blog.llvm.org/2010/01/x86-disassembler.html
157 * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
158 */
159extern "C" void
160lp_disassemble(const void* func)
161{
162#if HAVE_LLVM >= 0x0207
163   using namespace llvm;
164
165   const uint8_t *bytes = (const uint8_t *)func;
166
167   /*
168    * Limit disassembly to this extent
169    */
170   const uint64_t extent = 0x10000;
171
172   uint64_t max_pc = 0;
173
174   /*
175    * Initialize all used objects.
176    */
177
178   std::string Triple = sys::getHostTriple();
179
180   std::string Error;
181   const Target *T = TargetRegistry::lookupTarget(Triple, Error);
182
183#if HAVE_LLVM >= 0x0208
184   InitializeNativeTargetAsmPrinter();
185#else
186   InitializeAllAsmPrinters();
187#endif
188
189   InitializeAllDisassemblers();
190
191   OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple));
192
193   if (!AsmInfo) {
194      debug_printf("error: no assembly info for target %s\n", Triple.c_str());
195      return;
196   }
197
198   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler());
199   if (!DisAsm) {
200      debug_printf("error: no disassembler for target %s\n", Triple.c_str());
201      return;
202   }
203
204   raw_debug_ostream Out;
205
206   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
207#if HAVE_LLVM >= 0x0208
208   OwningPtr<MCInstPrinter> Printer(
209         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo));
210#else
211   OwningPtr<MCInstPrinter> Printer(
212         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out));
213#endif
214   if (!Printer) {
215      debug_printf("error: no instruction printer for target %s\n", Triple.c_str());
216      return;
217   }
218
219   TargetMachine *TM = T->createTargetMachine(Triple, "");
220
221   const TargetInstrInfo *TII = TM->getInstrInfo();
222
223   /*
224    * Wrap the data in a MemoryObject
225    */
226   BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
227
228   uint64_t pc;
229   pc = 0;
230   while (true) {
231      MCInst Inst;
232      uint64_t Size;
233
234      /*
235       * Print address.  We use addresses relative to the start of the function,
236       * so that between runs.
237       */
238
239      debug_printf("%6lu:\t", (unsigned long)pc);
240
241      if (!DisAsm->getInstruction(Inst, Size, memoryObject,
242                                 pc,
243                                 nulls())) {
244         debug_printf("invalid\n");
245         pc += 1;
246      }
247
248      /*
249       * Output the bytes in hexidecimal format.
250       */
251
252      if (0) {
253         unsigned i;
254         for (i = 0; i < Size; ++i) {
255            debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]);
256         }
257         for (; i < 16; ++i) {
258            debug_printf("   ");
259         }
260      }
261
262      /*
263       * Print the instruction.
264       */
265
266#if HAVE_LLVM >= 0x208
267      Printer->printInst(&Inst, Out);
268#else
269      Printer->printInst(&Inst);
270#endif
271      Out.flush();
272
273      /*
274       * Advance.
275       */
276
277      pc += Size;
278
279      const TargetInstrDesc &TID = TII->get(Inst.getOpcode());
280
281      /*
282       * Keep track of forward jumps to a nearby address.
283       */
284
285      if (TID.isBranch()) {
286         for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
287            const MCOperand &operand = Inst.getOperand(i);
288            if (operand.isImm()) {
289               uint64_t jump;
290
291               /*
292                * FIXME: Handle both relative and absolute addresses correctly.
293                * EDInstInfo actually has this info, but operandTypes and
294                * operandFlags enums are not exposed in the public interface.
295                */
296
297               if (1) {
298                  /*
299                   * PC relative addr.
300                   */
301
302                  jump = pc + operand.getImm();
303               } else {
304                  /*
305                   * Absolute addr.
306                   */
307
308                  jump = (uint64_t)operand.getImm();
309               }
310
311               /*
312                * Output the address relative to the function start, given
313                * that MC will print the addresses relative the current pc.
314                */
315               debug_printf("\t\t; %lu", (unsigned long)jump);
316
317               /*
318                * Ignore far jumps given it could be actually a tail return to
319                * a random address.
320                */
321
322               if (jump > max_pc &&
323                   jump < extent) {
324                  max_pc = jump;
325               }
326            }
327         }
328      }
329
330      debug_printf("\n");
331
332      /*
333       * Stop disassembling on return statements, if there is no record of a
334       * jump to a successive address.
335       */
336
337      if (TID.isReturn()) {
338         if (pc > max_pc) {
339            break;
340         }
341      }
342   }
343
344   /*
345    * Print GDB command, useful to verify output.
346    */
347
348   if (0) {
349      debug_printf("disassemble %p %p\n", bytes, bytes + pc);
350   }
351
352   debug_printf("\n");
353#else /* HAVE_LLVM < 0x0207 */
354   (void)func;
355#endif /* HAVE_LLVM < 0x0207 */
356}
357
358