1//===- llvm-cvtres.cpp - Serialize .res files into .obj ---------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Serialize .res files into .obj files. This is intended to be a
10// platform-independent port of Microsoft's cvtres.exe.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/BinaryFormat/Magic.h"
15#include "llvm/Object/Binary.h"
16#include "llvm/Object/WindowsMachineFlag.h"
17#include "llvm/Object/WindowsResource.h"
18#include "llvm/Option/Arg.h"
19#include "llvm/Option/ArgList.h"
20#include "llvm/Option/Option.h"
21#include "llvm/Support/Error.h"
22#include "llvm/Support/InitLLVM.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/PrettyStackTrace.h"
25#include "llvm/Support/Process.h"
26#include "llvm/Support/ScopedPrinter.h"
27#include "llvm/Support/Signals.h"
28#include "llvm/Support/raw_ostream.h"
29
30#include <system_error>
31
32using namespace llvm;
33using namespace object;
34
35namespace {
36
37enum ID {
38 OPT_INVALID = 0, // This is not an option ID.
39#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
40#include "Opts.inc"
41#undef OPTION
42};
43
44using namespace llvm::opt;
45#define OPTTABLE_CODE
46#include "Opts.inc"
47
48class CvtResOptTable : public opt::OptTable {
49public:
50 CvtResOptTable() : opt::OptTable(optionTables(), true) {}
51};
52}
53
54[[noreturn]] static void reportError(Twine Msg) {
55 errs() << Msg;
56 exit(status: 1);
57}
58
59static void reportError(StringRef Input, std::error_code EC) {
60 reportError(Msg: Twine(Input) + ": " + EC.message() + ".\n");
61}
62
63static void error(StringRef Input, Error EC) {
64 if (!EC)
65 return;
66 handleAllErrors(E: std::move(EC), Handlers: [&](const ErrorInfoBase &EI) {
67 reportError(Msg: Twine(Input) + ": " + EI.message() + ".\n");
68 });
69}
70
71static void error(Error EC) {
72 if (!EC)
73 return;
74 handleAllErrors(E: std::move(EC),
75 Handlers: [&](const ErrorInfoBase &EI) { reportError(Msg: EI.message()); });
76}
77
78static uint32_t getTime() {
79 std::time_t Now = time(timer: nullptr);
80 if (Now < 0 || !isUInt<32>(x: Now))
81 return UINT32_MAX;
82 return static_cast<uint32_t>(Now);
83}
84
85template <typename T> T error(Expected<T> EC) {
86 if (!EC)
87 error(EC.takeError());
88 return std::move(EC.get());
89}
90
91template <typename T> T error(StringRef Input, Expected<T> EC) {
92 if (!EC)
93 error(Input, EC.takeError());
94 return std::move(EC.get());
95}
96
97template <typename T> T error(StringRef Input, ErrorOr<T> &&EC) {
98 return error(Input, errorOrToExpected(std::move(EC)));
99}
100
101int main(int Argc, const char **Argv) {
102 InitLLVM X(Argc, Argv);
103
104 CvtResOptTable T;
105 unsigned MAI, MAC;
106 ArrayRef<const char *> ArgsArr = ArrayRef(Argv + 1, Argc - 1);
107 opt::InputArgList InputArgs = T.ParseArgs(Args: ArgsArr, MissingArgIndex&: MAI, MissingArgCount&: MAC);
108
109 if (InputArgs.hasArg(Ids: OPT_HELP)) {
110 T.printHelp(OS&: outs(), Usage: "llvm-cvtres [options] file...", Title: "Resource Converter");
111 return 0;
112 }
113
114 bool Verbose = InputArgs.hasArg(Ids: OPT_VERBOSE);
115
116 COFF::MachineTypes MachineType;
117
118 if (opt::Arg *Arg = InputArgs.getLastArg(Ids: OPT_MACHINE)) {
119 MachineType = getMachineType(S: Arg->getValue());
120 if (MachineType == COFF::IMAGE_FILE_MACHINE_UNKNOWN) {
121 reportError(Msg: Twine("Unsupported machine architecture ") + Arg->getValue() +
122 "\n");
123 }
124 } else {
125 if (Verbose)
126 outs() << "Machine architecture not specified; assumed X64.\n";
127 MachineType = COFF::IMAGE_FILE_MACHINE_AMD64;
128 }
129
130 std::vector<std::string> InputFiles = InputArgs.getAllArgValues(Id: OPT_INPUT);
131
132 if (InputFiles.size() == 0) {
133 reportError(Msg: "No input file specified.\n");
134 }
135
136 SmallString<128> OutputFile;
137
138 if (opt::Arg *Arg = InputArgs.getLastArg(Ids: OPT_OUT)) {
139 OutputFile = Arg->getValue();
140 } else {
141 OutputFile = sys::path::filename(path: StringRef(InputFiles[0]));
142 sys::path::replace_extension(path&: OutputFile, extension: ".obj");
143 }
144
145 uint32_t DateTimeStamp;
146 if (llvm::opt::Arg *Arg = InputArgs.getLastArg(Ids: OPT_TIMESTAMP)) {
147 StringRef Value(Arg->getValue());
148 if (Value.getAsInteger(Radix: 0, Result&: DateTimeStamp))
149 reportError(Msg: Twine("invalid timestamp: ") + Value +
150 ". Expected 32-bit integer\n");
151 } else {
152 DateTimeStamp = getTime();
153 }
154
155 if (Verbose)
156 outs() << "Machine: " << machineToStr(MT: MachineType) << '\n';
157
158 WindowsResourceParser Parser;
159
160 for (const auto &File : InputFiles) {
161 std::unique_ptr<MemoryBuffer> Buffer = error(
162 Input: File, EC: MemoryBuffer::getFileOrSTDIN(Filename: File, /*IsText=*/false,
163 /*RequiresNullTerminator=*/false));
164 file_magic Type = identify_magic(magic: Buffer->getMemBufferRef().getBuffer());
165 if (Type != file_magic::windows_resource)
166 reportError(Msg: File + ": unrecognized file format.\n");
167 std::unique_ptr<WindowsResource> Binary = error(
168 Input: File,
169 EC: WindowsResource::createWindowsResource(Source: Buffer->getMemBufferRef()));
170
171 WindowsResource *RF = Binary.get();
172
173 if (Verbose) {
174 int EntryNumber = 0;
175 ResourceEntryRef Entry = error(EC: RF->getHeadEntry());
176 bool End = false;
177 while (!End) {
178 error(EC: Entry.moveNext(End));
179 EntryNumber++;
180 }
181 outs() << "Number of resources: " << EntryNumber << "\n";
182 }
183
184 std::vector<std::string> Duplicates;
185 error(EC: Parser.parse(WR: RF, Duplicates));
186 for (const auto& DupeDiag : Duplicates)
187 reportError(Msg: DupeDiag);
188 }
189
190 if (Verbose) {
191 Parser.printTree(OS&: outs());
192 }
193
194 std::unique_ptr<MemoryBuffer> OutputBuffer =
195 error(EC: llvm::object::writeWindowsResourceCOFF(MachineType, Parser,
196 TimeDateStamp: DateTimeStamp));
197 auto FileOrErr =
198 FileOutputBuffer::create(FilePath: OutputFile, Size: OutputBuffer->getBufferSize());
199 if (!FileOrErr)
200 reportError(Input: OutputFile, EC: errorToErrorCode(Err: FileOrErr.takeError()));
201 std::unique_ptr<FileOutputBuffer> FileBuffer = std::move(*FileOrErr);
202 std::copy(first: OutputBuffer->getBufferStart(), last: OutputBuffer->getBufferEnd(),
203 result: FileBuffer->getBufferStart());
204 error(EC: FileBuffer->commit());
205
206 if (Verbose) {
207 std::unique_ptr<MemoryBuffer> Buffer =
208 error(Input: OutputFile,
209 EC: MemoryBuffer::getFileOrSTDIN(Filename: OutputFile, /*IsText=*/false,
210 /*RequiresNullTerminator=*/false));
211
212 ScopedPrinter W(errs());
213 W.printBinaryBlock(Label: "Output File Raw Data",
214 Value: Buffer->getMemBufferRef().getBuffer());
215 }
216
217 return 0;
218}
219