121
|
1 //===-- llvm-modextract.cpp - LLVM module extractor utility ---------------===//
|
|
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 // This program is for testing features that rely on multi-module bitcode files.
|
|
11 // It takes a multi-module bitcode file, extracts one of the modules and writes
|
|
12 // it to the output file.
|
|
13 //
|
|
14 //===----------------------------------------------------------------------===//
|
|
15
|
|
16 #include "llvm/Bitcode/BitcodeReader.h"
|
|
17 #include "llvm/Bitcode/BitcodeWriter.h"
|
|
18 #include "llvm/Support/CommandLine.h"
|
|
19 #include "llvm/Support/Error.h"
|
|
20 #include "llvm/Support/FileSystem.h"
|
|
21 #include "llvm/Support/ToolOutputFile.h"
|
|
22
|
|
23 using namespace llvm;
|
|
24
|
|
25 static cl::opt<bool>
|
|
26 BinaryExtract("b", cl::desc("Whether to perform binary extraction"));
|
|
27
|
|
28 static cl::opt<std::string> OutputFilename("o", cl::Required,
|
|
29 cl::desc("Output filename"),
|
|
30 cl::value_desc("filename"));
|
|
31
|
|
32 static cl::opt<std::string>
|
|
33 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
|
|
34
|
|
35 static cl::opt<unsigned> ModuleIndex("n", cl::Required,
|
|
36 cl::desc("Index of module to extract"),
|
|
37 cl::value_desc("index"));
|
|
38
|
|
39 int main(int argc, char **argv) {
|
|
40 cl::ParseCommandLineOptions(argc, argv, "Module extractor");
|
|
41
|
|
42 ExitOnError ExitOnErr("llvm-modextract: error: ");
|
|
43
|
|
44 std::unique_ptr<MemoryBuffer> MB =
|
|
45 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
|
|
46 std::vector<BitcodeModule> Ms = ExitOnErr(getBitcodeModuleList(*MB));
|
|
47
|
|
48 LLVMContext Context;
|
|
49 if (ModuleIndex >= Ms.size()) {
|
|
50 errs() << "llvm-modextract: error: module index out of range; bitcode file "
|
|
51 "contains "
|
|
52 << Ms.size() << " module(s)\n";
|
|
53 return 1;
|
|
54 }
|
|
55
|
|
56 std::error_code EC;
|
|
57 std::unique_ptr<ToolOutputFile> Out(
|
|
58 new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
|
|
59 ExitOnErr(errorCodeToError(EC));
|
|
60
|
|
61 if (BinaryExtract) {
|
|
62 SmallVector<char, 0> Result;
|
|
63 BitcodeWriter Writer(Result);
|
|
64 Result.append(Ms[ModuleIndex].getBuffer().begin(),
|
|
65 Ms[ModuleIndex].getBuffer().end());
|
|
66 Writer.copyStrtab(Ms[ModuleIndex].getStrtab());
|
|
67 Out->os() << Result;
|
|
68 Out->keep();
|
|
69 return 0;
|
|
70 }
|
|
71
|
|
72 std::unique_ptr<Module> M = ExitOnErr(Ms[ModuleIndex].parseModule(Context));
|
134
|
73 WriteBitcodeToFile(*M, Out->os());
|
121
|
74
|
|
75 Out->keep();
|
|
76 return 0;
|
|
77 }
|