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