llvm-project
94 строки · 3.0 Кб
1/*===-- disassemble.c - tool for testing libLLVM and llvm-c API -----------===*\
2|* *|
3|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
4|* Exceptions. *|
5|* See https://llvm.org/LICENSE.txt for license information. *|
6|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
7|* *|
8|*===----------------------------------------------------------------------===*|
9|* *|
10|* This file implements the --disassemble command in llvm-c-test. *|
11|* --disassemble reads lines from stdin, parses them as a triple and hex *|
12|* machine code, and prints disassembly of the machine code. *|
13|* *|
14\*===----------------------------------------------------------------------===*/
15
16#include "llvm-c-test.h"17#include "llvm-c/Disassembler.h"18#include "llvm-c/Target.h"19#include <stdio.h>20#include <stdlib.h>21#include <string.h>22
23static void pprint(int pos, unsigned char *buf, int len, const char *disasm) {24int i;25printf("%04x: ", pos);26for (i = 0; i < 8; i++) {27if (i < len) {28printf("%02x ", buf[i]);29} else {30printf(" ");31}32}33
34printf(" %s\n", disasm);35}
36
37static void do_disassemble(const char *triple, const char *features,38unsigned char *buf, int siz) {39LLVMDisasmContextRef D = LLVMCreateDisasmCPUFeatures(triple, "", features,40NULL, 0, NULL, NULL);41char outline[1024];42int pos;43
44if (!D) {45printf("ERROR: Couldn't create disassembler for triple %s\n", triple);46return;47}48
49pos = 0;50while (pos < siz) {51size_t l = LLVMDisasmInstruction(D, buf + pos, siz - pos, 0, outline,52sizeof(outline));53if (!l) {54pprint(pos, buf + pos, 1, "\t???");55pos++;56} else {57pprint(pos, buf + pos, l, outline);58pos += l;59}60}61
62LLVMDisasmDispose(D);63}
64
65static void handle_line(char **tokens, int ntokens) {66unsigned char disbuf[128];67size_t disbuflen = 0;68const char *triple = tokens[0];69const char *features = tokens[1];70int i;71
72printf("triple: %s, features: %s\n", triple, features);73if (!strcmp(features, "NULL"))74features = "";75
76for (i = 2; i < ntokens; i++) {77disbuf[disbuflen++] = strtol(tokens[i], NULL, 16);78if (disbuflen >= sizeof(disbuf)) {79fprintf(stderr, "Warning: Too long line, truncating\n");80break;81}82}83do_disassemble(triple, features, disbuf, disbuflen);84}
85
86int llvm_disassemble(void) {87LLVMInitializeAllTargetInfos();88LLVMInitializeAllTargetMCs();89LLVMInitializeAllDisassemblers();90
91llvm_tokenize_stdin(handle_line);92
93return 0;94}
95