18f19343aSMarek Sokolowski //===-- ResourceFileWriter.cpp --------------------------------*- C++-*-===//
28f19343aSMarek Sokolowski //
38f19343aSMarek Sokolowski //                     The LLVM Compiler Infrastructure
48f19343aSMarek Sokolowski //
58f19343aSMarek Sokolowski // This file is distributed under the University of Illinois Open Source
68f19343aSMarek Sokolowski // License. See LICENSE.TXT for details.
78f19343aSMarek Sokolowski //
88f19343aSMarek Sokolowski //===---------------------------------------------------------------------===//
98f19343aSMarek Sokolowski //
108f19343aSMarek Sokolowski // This implements the visitor serializing resources to a .res stream.
118f19343aSMarek Sokolowski //
128f19343aSMarek Sokolowski //===---------------------------------------------------------------------===//
138f19343aSMarek Sokolowski 
148f19343aSMarek Sokolowski #include "ResourceFileWriter.h"
158f19343aSMarek Sokolowski 
168f19343aSMarek Sokolowski #include "llvm/Object/WindowsResource.h"
178f19343aSMarek Sokolowski #include "llvm/Support/ConvertUTF.h"
188f19343aSMarek Sokolowski #include "llvm/Support/Endian.h"
198f19343aSMarek Sokolowski #include "llvm/Support/EndianStream.h"
20*fa0ca6cbSZachary Turner #include "llvm/Support/Path.h"
21*fa0ca6cbSZachary Turner #include "llvm/Support/Process.h"
228f19343aSMarek Sokolowski 
238f19343aSMarek Sokolowski using namespace llvm::support;
248f19343aSMarek Sokolowski 
258f19343aSMarek Sokolowski // Take an expression returning llvm::Error and forward the error if it exists.
268f19343aSMarek Sokolowski #define RETURN_IF_ERROR(Expr)                                                  \
278f19343aSMarek Sokolowski   if (auto Err = (Expr))                                                       \
288f19343aSMarek Sokolowski     return Err;
298f19343aSMarek Sokolowski 
308f19343aSMarek Sokolowski namespace llvm {
318f19343aSMarek Sokolowski namespace rc {
328f19343aSMarek Sokolowski 
3307bc04ffSZachary Turner // Class that employs RAII to save the current FileWriter object state
3422fccd64SMarek Sokolowski // and revert to it as soon as we leave the scope. This is useful if resources
3522fccd64SMarek Sokolowski // declare their own resource-local statements.
3622fccd64SMarek Sokolowski class ContextKeeper {
3722fccd64SMarek Sokolowski   ResourceFileWriter *FileWriter;
3822fccd64SMarek Sokolowski   ResourceFileWriter::ObjectInfo SavedInfo;
3922fccd64SMarek Sokolowski 
4022fccd64SMarek Sokolowski public:
4122fccd64SMarek Sokolowski   ContextKeeper(ResourceFileWriter *V)
4222fccd64SMarek Sokolowski       : FileWriter(V), SavedInfo(V->ObjectData) {}
4322fccd64SMarek Sokolowski   ~ContextKeeper() { FileWriter->ObjectData = SavedInfo; }
4422fccd64SMarek Sokolowski };
4522fccd64SMarek Sokolowski 
46*fa0ca6cbSZachary Turner static Error createError(const Twine &Message,
478f19343aSMarek Sokolowski                          std::errc Type = std::errc::invalid_argument) {
488f19343aSMarek Sokolowski   return make_error<StringError>(Message, std::make_error_code(Type));
498f19343aSMarek Sokolowski }
508f19343aSMarek Sokolowski 
51*fa0ca6cbSZachary Turner static Error checkNumberFits(uint32_t Number, size_t MaxBits,
52*fa0ca6cbSZachary Turner                              const Twine &FieldName) {
538f19343aSMarek Sokolowski   assert(1 <= MaxBits && MaxBits <= 32);
548f19343aSMarek Sokolowski   if (!(Number >> MaxBits))
558f19343aSMarek Sokolowski     return Error::success();
568f19343aSMarek Sokolowski   return createError(FieldName + " (" + Twine(Number) + ") does not fit in " +
578f19343aSMarek Sokolowski                          Twine(MaxBits) + " bits.",
588f19343aSMarek Sokolowski                      std::errc::value_too_large);
598f19343aSMarek Sokolowski }
608f19343aSMarek Sokolowski 
618f19343aSMarek Sokolowski template <typename FitType>
62*fa0ca6cbSZachary Turner static Error checkNumberFits(uint32_t Number, const Twine &FieldName) {
638f19343aSMarek Sokolowski   return checkNumberFits(Number, sizeof(FitType) * 8, FieldName);
648f19343aSMarek Sokolowski }
658f19343aSMarek Sokolowski 
667f7745c0SMarek Sokolowski // A similar function for signed integers.
677f7745c0SMarek Sokolowski template <typename FitType>
68*fa0ca6cbSZachary Turner static Error checkSignedNumberFits(uint32_t Number, const Twine &FieldName,
697f7745c0SMarek Sokolowski                                    bool CanBeNegative) {
707f7745c0SMarek Sokolowski   int32_t SignedNum = Number;
717f7745c0SMarek Sokolowski   if (SignedNum < std::numeric_limits<FitType>::min() ||
727f7745c0SMarek Sokolowski       SignedNum > std::numeric_limits<FitType>::max())
737f7745c0SMarek Sokolowski     return createError(FieldName + " (" + Twine(SignedNum) +
747f7745c0SMarek Sokolowski                            ") does not fit in " + Twine(sizeof(FitType) * 8) +
757f7745c0SMarek Sokolowski                            "-bit signed integer type.",
767f7745c0SMarek Sokolowski                        std::errc::value_too_large);
777f7745c0SMarek Sokolowski 
787f7745c0SMarek Sokolowski   if (!CanBeNegative && SignedNum < 0)
797f7745c0SMarek Sokolowski     return createError(FieldName + " (" + Twine(SignedNum) +
807f7745c0SMarek Sokolowski                        ") cannot be negative.");
817f7745c0SMarek Sokolowski 
827f7745c0SMarek Sokolowski   return Error::success();
837f7745c0SMarek Sokolowski }
847f7745c0SMarek Sokolowski 
85*fa0ca6cbSZachary Turner static Error checkRCInt(RCInt Number, const Twine &FieldName) {
8607bc04ffSZachary Turner   if (Number.isLong())
8707bc04ffSZachary Turner     return Error::success();
8807bc04ffSZachary Turner   return checkNumberFits<uint16_t>(Number, FieldName);
8907bc04ffSZachary Turner }
9007bc04ffSZachary Turner 
91*fa0ca6cbSZachary Turner static Error checkIntOrString(IntOrString Value, const Twine &FieldName) {
928f19343aSMarek Sokolowski   if (!Value.isInt())
938f19343aSMarek Sokolowski     return Error::success();
948f19343aSMarek Sokolowski   return checkNumberFits<uint16_t>(Value.getInt(), FieldName);
958f19343aSMarek Sokolowski }
968f19343aSMarek Sokolowski 
978f19343aSMarek Sokolowski static bool stripQuotes(StringRef &Str, bool &IsLongString) {
988f19343aSMarek Sokolowski   if (!Str.contains('"'))
998f19343aSMarek Sokolowski     return false;
1008f19343aSMarek Sokolowski 
1018f19343aSMarek Sokolowski   // Just take the contents of the string, checking if it's been marked long.
1028f19343aSMarek Sokolowski   IsLongString = Str.startswith_lower("L");
1038f19343aSMarek Sokolowski   if (IsLongString)
1048f19343aSMarek Sokolowski     Str = Str.drop_front();
1058f19343aSMarek Sokolowski 
1068f19343aSMarek Sokolowski   bool StripSuccess = Str.consume_front("\"") && Str.consume_back("\"");
1078f19343aSMarek Sokolowski   (void)StripSuccess;
1088f19343aSMarek Sokolowski   assert(StripSuccess && "Strings should be enclosed in quotes.");
1098f19343aSMarek Sokolowski   return true;
1108f19343aSMarek Sokolowski }
1118f19343aSMarek Sokolowski 
1128f19343aSMarek Sokolowski // Describes a way to handle '\0' characters when processing the string.
1138f19343aSMarek Sokolowski // rc.exe tool sometimes behaves in a weird way in postprocessing.
1148f19343aSMarek Sokolowski // If the string to be output is equivalent to a C-string (e.g. in MENU
1158f19343aSMarek Sokolowski // titles), string is (predictably) truncated after first 0-byte.
1168f19343aSMarek Sokolowski // When outputting a string table, the behavior is equivalent to appending
1178f19343aSMarek Sokolowski // '\0\0' at the end of the string, and then stripping the string
1188f19343aSMarek Sokolowski // before the first '\0\0' occurrence.
1198f19343aSMarek Sokolowski // Finally, when handling strings in user-defined resources, 0-bytes
1208f19343aSMarek Sokolowski // aren't stripped, nor do they terminate the string.
1218f19343aSMarek Sokolowski 
1228f19343aSMarek Sokolowski enum class NullHandlingMethod {
1238f19343aSMarek Sokolowski   UserResource,   // Don't terminate string on '\0'.
1248f19343aSMarek Sokolowski   CutAtNull,      // Terminate string on '\0'.
1258f19343aSMarek Sokolowski   CutAtDoubleNull // Terminate string on '\0\0'; strip final '\0'.
1268f19343aSMarek Sokolowski };
1278f19343aSMarek Sokolowski 
128a92eb33aSZachary Turner // Parses an identifier or string and returns a processed version of it:
129a92eb33aSZachary Turner //   * String the string boundary quotes.
1308f19343aSMarek Sokolowski //   * Squash "" to a single ".
1318f19343aSMarek Sokolowski //   * Replace the escape sequences with their processed version.
1328f19343aSMarek Sokolowski // For identifiers, this is no-op.
1338f19343aSMarek Sokolowski static Error processString(StringRef Str, NullHandlingMethod NullHandler,
1348f19343aSMarek Sokolowski                            bool &IsLongString, SmallVectorImpl<UTF16> &Result) {
1358f19343aSMarek Sokolowski   bool IsString = stripQuotes(Str, IsLongString);
136a92eb33aSZachary Turner   SmallVector<UTF16, 128> Chars;
137a92eb33aSZachary Turner   convertUTF8ToUTF16String(Str, Chars);
1388f19343aSMarek Sokolowski 
1398f19343aSMarek Sokolowski   if (!IsString) {
1408f19343aSMarek Sokolowski     // It's an identifier if it's not a string. Make all characters uppercase.
141a92eb33aSZachary Turner     for (UTF16 &Ch : Chars) {
1428f19343aSMarek Sokolowski       assert(Ch <= 0x7F && "We didn't allow identifiers to be non-ASCII");
1438f19343aSMarek Sokolowski       Ch = toupper(Ch);
1448f19343aSMarek Sokolowski     }
145a92eb33aSZachary Turner     Result.swap(Chars);
1468f19343aSMarek Sokolowski     return Error::success();
1478f19343aSMarek Sokolowski   }
148a92eb33aSZachary Turner   Result.reserve(Chars.size());
149a92eb33aSZachary Turner   size_t Pos = 0;
150a92eb33aSZachary Turner 
151a92eb33aSZachary Turner   auto AddRes = [&Result, NullHandler, IsLongString](UTF16 Char) -> Error {
152a92eb33aSZachary Turner     if (!IsLongString) {
153a92eb33aSZachary Turner       if (NullHandler == NullHandlingMethod::UserResource) {
154a92eb33aSZachary Turner         // Narrow strings in user-defined resources are *not* output in
155a92eb33aSZachary Turner         // UTF-16 format.
156a92eb33aSZachary Turner         if (Char > 0xFF)
157a92eb33aSZachary Turner           return createError("Non-8-bit codepoint (" + Twine(Char) +
158a92eb33aSZachary Turner                              ") can't occur in a user-defined narrow string");
159a92eb33aSZachary Turner 
160a92eb33aSZachary Turner       } else {
161a92eb33aSZachary Turner         // In case of narrow non-user strings, Windows RC converts
162a92eb33aSZachary Turner         // [0x80, 0xFF] chars according to the current codepage.
163a92eb33aSZachary Turner         // There is no 'codepage' concept settled in every supported platform,
164a92eb33aSZachary Turner         // so we should reject such inputs.
165a92eb33aSZachary Turner         if (Char > 0x7F && Char <= 0xFF)
166a92eb33aSZachary Turner           return createError("Non-ASCII 8-bit codepoint (" + Twine(Char) +
167a92eb33aSZachary Turner                              ") can't "
168a92eb33aSZachary Turner                              "occur in a non-Unicode string");
169a92eb33aSZachary Turner       }
170a92eb33aSZachary Turner     }
171a92eb33aSZachary Turner 
1721e2c8b11SZachary Turner     Result.push_back(Char);
173a92eb33aSZachary Turner     return Error::success();
174a92eb33aSZachary Turner   };
175a92eb33aSZachary Turner 
176a92eb33aSZachary Turner   while (Pos < Chars.size()) {
177a92eb33aSZachary Turner     UTF16 CurChar = Chars[Pos];
178a92eb33aSZachary Turner     ++Pos;
179a92eb33aSZachary Turner 
180a92eb33aSZachary Turner     // Strip double "".
181a92eb33aSZachary Turner     if (CurChar == '"') {
182a92eb33aSZachary Turner       if (Pos == Chars.size() || Chars[Pos] != '"')
183a92eb33aSZachary Turner         return createError("Expected \"\"");
184a92eb33aSZachary Turner       ++Pos;
185a92eb33aSZachary Turner       RETURN_IF_ERROR(AddRes('"'));
186a92eb33aSZachary Turner       continue;
187a92eb33aSZachary Turner     }
188a92eb33aSZachary Turner 
189a92eb33aSZachary Turner     if (CurChar == '\\') {
190a92eb33aSZachary Turner       UTF16 TypeChar = Chars[Pos];
191a92eb33aSZachary Turner       ++Pos;
192a92eb33aSZachary Turner 
193a92eb33aSZachary Turner       if (TypeChar == 'x' || TypeChar == 'X') {
194a92eb33aSZachary Turner         // Read a hex number. Max number of characters to read differs between
195a92eb33aSZachary Turner         // narrow and wide strings.
196a92eb33aSZachary Turner         UTF16 ReadInt = 0;
197a92eb33aSZachary Turner         size_t RemainingChars = IsLongString ? 4 : 2;
198a92eb33aSZachary Turner         // We don't want to read non-ASCII hex digits. std:: functions past
199a92eb33aSZachary Turner         // 0xFF invoke UB.
200a92eb33aSZachary Turner         //
201a92eb33aSZachary Turner         // FIXME: actually, Microsoft version probably doesn't check this
202a92eb33aSZachary Turner         // condition and uses their Unicode version of 'isxdigit'. However,
203a92eb33aSZachary Turner         // there are some hex-digit Unicode character outside of ASCII, and
204a92eb33aSZachary Turner         // some of these are actually accepted by rc.exe, the notable example
205a92eb33aSZachary Turner         // being fullwidth forms (U+FF10..U+FF19 etc.) These can be written
206a92eb33aSZachary Turner         // instead of ASCII digits in \x... escape sequence and get accepted.
207a92eb33aSZachary Turner         // However, the resulting hexcodes seem totally unpredictable.
208a92eb33aSZachary Turner         // We think it's infeasible to try to reproduce this behavior, nor to
209a92eb33aSZachary Turner         // put effort in order to detect it.
210a92eb33aSZachary Turner         while (RemainingChars && Pos < Chars.size() && Chars[Pos] < 0x80) {
211a92eb33aSZachary Turner           if (!isxdigit(Chars[Pos]))
212a92eb33aSZachary Turner             break;
213a92eb33aSZachary Turner           char Digit = tolower(Chars[Pos]);
214a92eb33aSZachary Turner           ++Pos;
215a92eb33aSZachary Turner 
216a92eb33aSZachary Turner           ReadInt <<= 4;
217a92eb33aSZachary Turner           if (isdigit(Digit))
218a92eb33aSZachary Turner             ReadInt |= Digit - '0';
219a92eb33aSZachary Turner           else
220a92eb33aSZachary Turner             ReadInt |= Digit - 'a' + 10;
221a92eb33aSZachary Turner 
222a92eb33aSZachary Turner           --RemainingChars;
223a92eb33aSZachary Turner         }
224a92eb33aSZachary Turner 
225a92eb33aSZachary Turner         RETURN_IF_ERROR(AddRes(ReadInt));
226a92eb33aSZachary Turner         continue;
227a92eb33aSZachary Turner       }
228a92eb33aSZachary Turner 
229a92eb33aSZachary Turner       if (TypeChar >= '0' && TypeChar < '8') {
230a92eb33aSZachary Turner         // Read an octal number. Note that we've already read the first digit.
231a92eb33aSZachary Turner         UTF16 ReadInt = TypeChar - '0';
232a92eb33aSZachary Turner         size_t RemainingChars = IsLongString ? 6 : 2;
233a92eb33aSZachary Turner 
234a92eb33aSZachary Turner         while (RemainingChars && Pos < Chars.size() && Chars[Pos] >= '0' &&
235a92eb33aSZachary Turner                Chars[Pos] < '8') {
236a92eb33aSZachary Turner           ReadInt <<= 3;
237a92eb33aSZachary Turner           ReadInt |= Chars[Pos] - '0';
238a92eb33aSZachary Turner           --RemainingChars;
239a92eb33aSZachary Turner           ++Pos;
240a92eb33aSZachary Turner         }
241a92eb33aSZachary Turner 
242a92eb33aSZachary Turner         RETURN_IF_ERROR(AddRes(ReadInt));
243a92eb33aSZachary Turner 
244a92eb33aSZachary Turner         continue;
245a92eb33aSZachary Turner       }
246a92eb33aSZachary Turner 
247a92eb33aSZachary Turner       switch (TypeChar) {
248a92eb33aSZachary Turner       case 'A':
249a92eb33aSZachary Turner       case 'a':
250a92eb33aSZachary Turner         // Windows '\a' translates into '\b' (Backspace).
251a92eb33aSZachary Turner         RETURN_IF_ERROR(AddRes('\b'));
252a92eb33aSZachary Turner         break;
253a92eb33aSZachary Turner 
254a92eb33aSZachary Turner       case 'n': // Somehow, RC doesn't recognize '\N' and '\R'.
255a92eb33aSZachary Turner         RETURN_IF_ERROR(AddRes('\n'));
256a92eb33aSZachary Turner         break;
257a92eb33aSZachary Turner 
258a92eb33aSZachary Turner       case 'r':
259a92eb33aSZachary Turner         RETURN_IF_ERROR(AddRes('\r'));
260a92eb33aSZachary Turner         break;
261a92eb33aSZachary Turner 
262a92eb33aSZachary Turner       case 'T':
263a92eb33aSZachary Turner       case 't':
264a92eb33aSZachary Turner         RETURN_IF_ERROR(AddRes('\t'));
265a92eb33aSZachary Turner         break;
266a92eb33aSZachary Turner 
267a92eb33aSZachary Turner       case '\\':
268a92eb33aSZachary Turner         RETURN_IF_ERROR(AddRes('\\'));
269a92eb33aSZachary Turner         break;
270a92eb33aSZachary Turner 
271a92eb33aSZachary Turner       case '"':
272a92eb33aSZachary Turner         // RC accepts \" only if another " comes afterwards; then, \"" means
273a92eb33aSZachary Turner         // a single ".
274a92eb33aSZachary Turner         if (Pos == Chars.size() || Chars[Pos] != '"')
275a92eb33aSZachary Turner           return createError("Expected \\\"\"");
276a92eb33aSZachary Turner         ++Pos;
277a92eb33aSZachary Turner         RETURN_IF_ERROR(AddRes('"'));
278a92eb33aSZachary Turner         break;
279a92eb33aSZachary Turner 
280a92eb33aSZachary Turner       default:
281a92eb33aSZachary Turner         // If TypeChar means nothing, \ is should be output to stdout with
282a92eb33aSZachary Turner         // following char. However, rc.exe consumes these characters when
283a92eb33aSZachary Turner         // dealing with wide strings.
284a92eb33aSZachary Turner         if (!IsLongString) {
285a92eb33aSZachary Turner           RETURN_IF_ERROR(AddRes('\\'));
286a92eb33aSZachary Turner           RETURN_IF_ERROR(AddRes(TypeChar));
287a92eb33aSZachary Turner         }
288a92eb33aSZachary Turner         break;
289a92eb33aSZachary Turner       }
290a92eb33aSZachary Turner 
291a92eb33aSZachary Turner       continue;
292a92eb33aSZachary Turner     }
293a92eb33aSZachary Turner 
294a92eb33aSZachary Turner     // If nothing interesting happens, just output the character.
295a92eb33aSZachary Turner     RETURN_IF_ERROR(AddRes(CurChar));
296a92eb33aSZachary Turner   }
2978f19343aSMarek Sokolowski 
298da366693SZachary Turner   switch (NullHandler) {
299da366693SZachary Turner   case NullHandlingMethod::CutAtNull:
3008f19343aSMarek Sokolowski     for (size_t Pos = 0; Pos < Result.size(); ++Pos)
3018f19343aSMarek Sokolowski       if (Result[Pos] == '\0')
3028f19343aSMarek Sokolowski         Result.resize(Pos);
303da366693SZachary Turner     break;
304da366693SZachary Turner 
305da366693SZachary Turner   case NullHandlingMethod::CutAtDoubleNull:
306da366693SZachary Turner     for (size_t Pos = 0; Pos + 1 < Result.size(); ++Pos)
307da366693SZachary Turner       if (Result[Pos] == '\0' && Result[Pos + 1] == '\0')
308da366693SZachary Turner         Result.resize(Pos);
309da366693SZachary Turner     if (Result.size() > 0 && Result.back() == '\0')
310da366693SZachary Turner       Result.pop_back();
311da366693SZachary Turner     break;
312da366693SZachary Turner 
313da366693SZachary Turner   case NullHandlingMethod::UserResource:
314da366693SZachary Turner     break;
315da366693SZachary Turner   }
3168f19343aSMarek Sokolowski 
3178f19343aSMarek Sokolowski   return Error::success();
3188f19343aSMarek Sokolowski }
3198f19343aSMarek Sokolowski 
3208f19343aSMarek Sokolowski uint64_t ResourceFileWriter::writeObject(const ArrayRef<uint8_t> Data) {
3218f19343aSMarek Sokolowski   uint64_t Result = tell();
3228f19343aSMarek Sokolowski   FS->write((const char *)Data.begin(), Data.size());
3238f19343aSMarek Sokolowski   return Result;
3248f19343aSMarek Sokolowski }
3258f19343aSMarek Sokolowski 
3268f19343aSMarek Sokolowski Error ResourceFileWriter::writeCString(StringRef Str, bool WriteTerminator) {
3278f19343aSMarek Sokolowski   SmallVector<UTF16, 128> ProcessedString;
3288f19343aSMarek Sokolowski   bool IsLongString;
3298f19343aSMarek Sokolowski   RETURN_IF_ERROR(processString(Str, NullHandlingMethod::CutAtNull,
3308f19343aSMarek Sokolowski                                 IsLongString, ProcessedString));
3318f19343aSMarek Sokolowski   for (auto Ch : ProcessedString)
3328f19343aSMarek Sokolowski     writeInt<uint16_t>(Ch);
3338f19343aSMarek Sokolowski   if (WriteTerminator)
3348f19343aSMarek Sokolowski     writeInt<uint16_t>(0);
3358f19343aSMarek Sokolowski   return Error::success();
3368f19343aSMarek Sokolowski }
3378f19343aSMarek Sokolowski 
3388f19343aSMarek Sokolowski Error ResourceFileWriter::writeIdentifier(const IntOrString &Ident) {
3398f19343aSMarek Sokolowski   return writeIntOrString(Ident);
3408f19343aSMarek Sokolowski }
3418f19343aSMarek Sokolowski 
3428f19343aSMarek Sokolowski Error ResourceFileWriter::writeIntOrString(const IntOrString &Value) {
3438f19343aSMarek Sokolowski   if (!Value.isInt())
3448f19343aSMarek Sokolowski     return writeCString(Value.getString());
3458f19343aSMarek Sokolowski 
3468f19343aSMarek Sokolowski   writeInt<uint16_t>(0xFFFF);
3478f19343aSMarek Sokolowski   writeInt<uint16_t>(Value.getInt());
3488f19343aSMarek Sokolowski   return Error::success();
3498f19343aSMarek Sokolowski }
3508f19343aSMarek Sokolowski 
35107bc04ffSZachary Turner void ResourceFileWriter::writeRCInt(RCInt Value) {
35207bc04ffSZachary Turner   if (Value.isLong())
353b12792a4SZachary Turner     writeInt<uint32_t>(Value);
35407bc04ffSZachary Turner   else
355b12792a4SZachary Turner     writeInt<uint16_t>(Value);
35607bc04ffSZachary Turner }
35707bc04ffSZachary Turner 
3588f19343aSMarek Sokolowski Error ResourceFileWriter::appendFile(StringRef Filename) {
3598f19343aSMarek Sokolowski   bool IsLong;
3608f19343aSMarek Sokolowski   stripQuotes(Filename, IsLong);
3618f19343aSMarek Sokolowski 
362*fa0ca6cbSZachary Turner   auto File = loadFile(Filename);
3638f19343aSMarek Sokolowski   if (!File)
364*fa0ca6cbSZachary Turner     return File.takeError();
365*fa0ca6cbSZachary Turner 
3668f19343aSMarek Sokolowski   *FS << (*File)->getBuffer();
3678f19343aSMarek Sokolowski   return Error::success();
3688f19343aSMarek Sokolowski }
3698f19343aSMarek Sokolowski 
3708f19343aSMarek Sokolowski void ResourceFileWriter::padStream(uint64_t Length) {
3718f19343aSMarek Sokolowski   assert(Length > 0);
3728f19343aSMarek Sokolowski   uint64_t Location = tell();
3738f19343aSMarek Sokolowski   Location %= Length;
3748f19343aSMarek Sokolowski   uint64_t Pad = (Length - Location) % Length;
3758f19343aSMarek Sokolowski   for (uint64_t i = 0; i < Pad; ++i)
3768f19343aSMarek Sokolowski     writeInt<uint8_t>(0);
3778f19343aSMarek Sokolowski }
3788f19343aSMarek Sokolowski 
379514b7105SZachary Turner Error ResourceFileWriter::handleError(Error Err, const RCResource *Res) {
3808f19343aSMarek Sokolowski   if (Err)
3818f19343aSMarek Sokolowski     return joinErrors(createError("Error in " + Res->getResourceTypeName() +
3828f19343aSMarek Sokolowski                                   " statement (ID " + Twine(Res->ResName) +
3838f19343aSMarek Sokolowski                                   "): "),
3848f19343aSMarek Sokolowski                       std::move(Err));
3858f19343aSMarek Sokolowski   return Error::success();
3868f19343aSMarek Sokolowski }
3878f19343aSMarek Sokolowski 
3888f19343aSMarek Sokolowski Error ResourceFileWriter::visitNullResource(const RCResource *Res) {
3898f19343aSMarek Sokolowski   return writeResource(Res, &ResourceFileWriter::writeNullBody);
3908f19343aSMarek Sokolowski }
3918f19343aSMarek Sokolowski 
39222fccd64SMarek Sokolowski Error ResourceFileWriter::visitAcceleratorsResource(const RCResource *Res) {
39322fccd64SMarek Sokolowski   return writeResource(Res, &ResourceFileWriter::writeAcceleratorsBody);
39422fccd64SMarek Sokolowski }
39522fccd64SMarek Sokolowski 
396c3ab013aSZachary Turner Error ResourceFileWriter::visitCursorResource(const RCResource *Res) {
397c3ab013aSZachary Turner   return handleError(visitIconOrCursorResource(Res), Res);
398c3ab013aSZachary Turner }
399c3ab013aSZachary Turner 
4007f7745c0SMarek Sokolowski Error ResourceFileWriter::visitDialogResource(const RCResource *Res) {
4017f7745c0SMarek Sokolowski   return writeResource(Res, &ResourceFileWriter::writeDialogBody);
4027f7745c0SMarek Sokolowski }
4037f7745c0SMarek Sokolowski 
404c3ab013aSZachary Turner Error ResourceFileWriter::visitIconResource(const RCResource *Res) {
405c3ab013aSZachary Turner   return handleError(visitIconOrCursorResource(Res), Res);
406c3ab013aSZachary Turner }
407c3ab013aSZachary Turner 
408420090afSZachary Turner Error ResourceFileWriter::visitCaptionStmt(const CaptionStmt *Stmt) {
409420090afSZachary Turner   ObjectData.Caption = Stmt->Value;
410420090afSZachary Turner   return Error::success();
411420090afSZachary Turner }
412420090afSZachary Turner 
4138f19343aSMarek Sokolowski Error ResourceFileWriter::visitHTMLResource(const RCResource *Res) {
4148f19343aSMarek Sokolowski   return writeResource(Res, &ResourceFileWriter::writeHTMLBody);
4158f19343aSMarek Sokolowski }
4168f19343aSMarek Sokolowski 
41742f494d6SMarek Sokolowski Error ResourceFileWriter::visitMenuResource(const RCResource *Res) {
41842f494d6SMarek Sokolowski   return writeResource(Res, &ResourceFileWriter::writeMenuBody);
41942f494d6SMarek Sokolowski }
42042f494d6SMarek Sokolowski 
421da366693SZachary Turner Error ResourceFileWriter::visitStringTableResource(const RCResource *Base) {
422da366693SZachary Turner   const auto *Res = cast<StringTableResource>(Base);
423da366693SZachary Turner 
424da366693SZachary Turner   ContextKeeper RAII(this);
425da366693SZachary Turner   RETURN_IF_ERROR(Res->applyStmts(this));
426da366693SZachary Turner 
427da366693SZachary Turner   for (auto &String : Res->Table) {
428da366693SZachary Turner     RETURN_IF_ERROR(checkNumberFits<uint16_t>(String.first, "String ID"));
429da366693SZachary Turner     uint16_t BundleID = String.first >> 4;
430da366693SZachary Turner     StringTableInfo::BundleKey Key(BundleID, ObjectData.LanguageInfo);
431da366693SZachary Turner     auto &BundleData = StringTableData.BundleData;
432da366693SZachary Turner     auto Iter = BundleData.find(Key);
433da366693SZachary Turner 
434da366693SZachary Turner     if (Iter == BundleData.end()) {
435da366693SZachary Turner       // Need to create a bundle.
436da366693SZachary Turner       StringTableData.BundleList.push_back(Key);
437da366693SZachary Turner       auto EmplaceResult =
438da366693SZachary Turner           BundleData.emplace(Key, StringTableInfo::Bundle(ObjectData));
439da366693SZachary Turner       assert(EmplaceResult.second && "Could not create a bundle");
440da366693SZachary Turner       Iter = EmplaceResult.first;
441da366693SZachary Turner     }
442da366693SZachary Turner 
443da366693SZachary Turner     RETURN_IF_ERROR(
444da366693SZachary Turner         insertStringIntoBundle(Iter->second, String.first, String.second));
445da366693SZachary Turner   }
446da366693SZachary Turner 
447da366693SZachary Turner   return Error::success();
448da366693SZachary Turner }
449da366693SZachary Turner 
4509d8b358aSZachary Turner Error ResourceFileWriter::visitUserDefinedResource(const RCResource *Res) {
4519d8b358aSZachary Turner   return writeResource(Res, &ResourceFileWriter::writeUserDefinedBody);
4529d8b358aSZachary Turner }
4539d8b358aSZachary Turner 
45407bc04ffSZachary Turner Error ResourceFileWriter::visitVersionInfoResource(const RCResource *Res) {
45507bc04ffSZachary Turner   return writeResource(Res, &ResourceFileWriter::writeVersionInfoBody);
45607bc04ffSZachary Turner }
45707bc04ffSZachary Turner 
45822fccd64SMarek Sokolowski Error ResourceFileWriter::visitCharacteristicsStmt(
45922fccd64SMarek Sokolowski     const CharacteristicsStmt *Stmt) {
46022fccd64SMarek Sokolowski   ObjectData.Characteristics = Stmt->Value;
46122fccd64SMarek Sokolowski   return Error::success();
46222fccd64SMarek Sokolowski }
46322fccd64SMarek Sokolowski 
464420090afSZachary Turner Error ResourceFileWriter::visitFontStmt(const FontStmt *Stmt) {
465420090afSZachary Turner   RETURN_IF_ERROR(checkNumberFits<uint16_t>(Stmt->Size, "Font size"));
466420090afSZachary Turner   RETURN_IF_ERROR(checkNumberFits<uint16_t>(Stmt->Weight, "Font weight"));
467420090afSZachary Turner   RETURN_IF_ERROR(checkNumberFits<uint8_t>(Stmt->Charset, "Font charset"));
468420090afSZachary Turner   ObjectInfo::FontInfo Font{Stmt->Size, Stmt->Name, Stmt->Weight, Stmt->Italic,
469420090afSZachary Turner                             Stmt->Charset};
470420090afSZachary Turner   ObjectData.Font.emplace(Font);
471420090afSZachary Turner   return Error::success();
472420090afSZachary Turner }
473420090afSZachary Turner 
4748f19343aSMarek Sokolowski Error ResourceFileWriter::visitLanguageStmt(const LanguageResource *Stmt) {
4758f19343aSMarek Sokolowski   RETURN_IF_ERROR(checkNumberFits(Stmt->Lang, 10, "Primary language ID"));
4768f19343aSMarek Sokolowski   RETURN_IF_ERROR(checkNumberFits(Stmt->SubLang, 6, "Sublanguage ID"));
4778f19343aSMarek Sokolowski   ObjectData.LanguageInfo = Stmt->Lang | (Stmt->SubLang << 10);
4788f19343aSMarek Sokolowski   return Error::success();
4798f19343aSMarek Sokolowski }
4808f19343aSMarek Sokolowski 
481420090afSZachary Turner Error ResourceFileWriter::visitStyleStmt(const StyleStmt *Stmt) {
482420090afSZachary Turner   ObjectData.Style = Stmt->Value;
483420090afSZachary Turner   return Error::success();
484420090afSZachary Turner }
485420090afSZachary Turner 
48622fccd64SMarek Sokolowski Error ResourceFileWriter::visitVersionStmt(const VersionStmt *Stmt) {
48722fccd64SMarek Sokolowski   ObjectData.VersionInfo = Stmt->Value;
48822fccd64SMarek Sokolowski   return Error::success();
48922fccd64SMarek Sokolowski }
49022fccd64SMarek Sokolowski 
4918f19343aSMarek Sokolowski Error ResourceFileWriter::writeResource(
4928f19343aSMarek Sokolowski     const RCResource *Res,
4938f19343aSMarek Sokolowski     Error (ResourceFileWriter::*BodyWriter)(const RCResource *)) {
4948f19343aSMarek Sokolowski   // We don't know the sizes yet.
4958f19343aSMarek Sokolowski   object::WinResHeaderPrefix HeaderPrefix{ulittle32_t(0U), ulittle32_t(0U)};
4968f19343aSMarek Sokolowski   uint64_t HeaderLoc = writeObject(HeaderPrefix);
4978f19343aSMarek Sokolowski 
4988f19343aSMarek Sokolowski   auto ResType = Res->getResourceType();
4998f19343aSMarek Sokolowski   RETURN_IF_ERROR(checkIntOrString(ResType, "Resource type"));
5008f19343aSMarek Sokolowski   RETURN_IF_ERROR(checkIntOrString(Res->ResName, "Resource ID"));
5018f19343aSMarek Sokolowski   RETURN_IF_ERROR(handleError(writeIdentifier(ResType), Res));
5028f19343aSMarek Sokolowski   RETURN_IF_ERROR(handleError(writeIdentifier(Res->ResName), Res));
5038f19343aSMarek Sokolowski 
50422fccd64SMarek Sokolowski   // Apply the resource-local optional statements.
50522fccd64SMarek Sokolowski   ContextKeeper RAII(this);
50622fccd64SMarek Sokolowski   RETURN_IF_ERROR(handleError(Res->applyStmts(this), Res));
50722fccd64SMarek Sokolowski 
5088f19343aSMarek Sokolowski   padStream(sizeof(uint32_t));
5098f19343aSMarek Sokolowski   object::WinResHeaderSuffix HeaderSuffix{
5108f19343aSMarek Sokolowski       ulittle32_t(0), // DataVersion; seems to always be 0
5118f19343aSMarek Sokolowski       ulittle16_t(Res->getMemoryFlags()), ulittle16_t(ObjectData.LanguageInfo),
51222fccd64SMarek Sokolowski       ulittle32_t(ObjectData.VersionInfo),
51322fccd64SMarek Sokolowski       ulittle32_t(ObjectData.Characteristics)};
5148f19343aSMarek Sokolowski   writeObject(HeaderSuffix);
5158f19343aSMarek Sokolowski 
5168f19343aSMarek Sokolowski   uint64_t DataLoc = tell();
5178f19343aSMarek Sokolowski   RETURN_IF_ERROR(handleError((this->*BodyWriter)(Res), Res));
5188f19343aSMarek Sokolowski   // RETURN_IF_ERROR(handleError(dumpResource(Ctx)));
5198f19343aSMarek Sokolowski 
5208f19343aSMarek Sokolowski   // Update the sizes.
5218f19343aSMarek Sokolowski   HeaderPrefix.DataSize = tell() - DataLoc;
5228f19343aSMarek Sokolowski   HeaderPrefix.HeaderSize = DataLoc - HeaderLoc;
5238f19343aSMarek Sokolowski   writeObjectAt(HeaderPrefix, HeaderLoc);
5248f19343aSMarek Sokolowski   padStream(sizeof(uint32_t));
5258f19343aSMarek Sokolowski 
5268f19343aSMarek Sokolowski   return Error::success();
5278f19343aSMarek Sokolowski }
5288f19343aSMarek Sokolowski 
52922fccd64SMarek Sokolowski // --- NullResource helpers. --- //
53022fccd64SMarek Sokolowski 
5318f19343aSMarek Sokolowski Error ResourceFileWriter::writeNullBody(const RCResource *) {
5328f19343aSMarek Sokolowski   return Error::success();
5338f19343aSMarek Sokolowski }
5348f19343aSMarek Sokolowski 
53522fccd64SMarek Sokolowski // --- AcceleratorsResource helpers. --- //
53622fccd64SMarek Sokolowski 
53722fccd64SMarek Sokolowski Error ResourceFileWriter::writeSingleAccelerator(
53822fccd64SMarek Sokolowski     const AcceleratorsResource::Accelerator &Obj, bool IsLastItem) {
53922fccd64SMarek Sokolowski   using Accelerator = AcceleratorsResource::Accelerator;
54022fccd64SMarek Sokolowski   using Opt = Accelerator::Options;
54122fccd64SMarek Sokolowski 
54222fccd64SMarek Sokolowski   struct AccelTableEntry {
54322fccd64SMarek Sokolowski     ulittle16_t Flags;
54422fccd64SMarek Sokolowski     ulittle16_t ANSICode;
54522fccd64SMarek Sokolowski     ulittle16_t Id;
54622fccd64SMarek Sokolowski     uint16_t Padding;
54722fccd64SMarek Sokolowski   } Entry{ulittle16_t(0), ulittle16_t(0), ulittle16_t(0), 0};
54822fccd64SMarek Sokolowski 
54922fccd64SMarek Sokolowski   bool IsASCII = Obj.Flags & Opt::ASCII, IsVirtKey = Obj.Flags & Opt::VIRTKEY;
55022fccd64SMarek Sokolowski 
55122fccd64SMarek Sokolowski   // Remove ASCII flags (which doesn't occur in .res files).
55222fccd64SMarek Sokolowski   Entry.Flags = Obj.Flags & ~Opt::ASCII;
55322fccd64SMarek Sokolowski 
55422fccd64SMarek Sokolowski   if (IsLastItem)
55522fccd64SMarek Sokolowski     Entry.Flags |= 0x80;
55622fccd64SMarek Sokolowski 
55722fccd64SMarek Sokolowski   RETURN_IF_ERROR(checkNumberFits<uint16_t>(Obj.Id, "ACCELERATORS entry ID"));
55822fccd64SMarek Sokolowski   Entry.Id = ulittle16_t(Obj.Id);
55922fccd64SMarek Sokolowski 
56022fccd64SMarek Sokolowski   auto createAccError = [&Obj](const char *Msg) {
56122fccd64SMarek Sokolowski     return createError("Accelerator ID " + Twine(Obj.Id) + ": " + Msg);
56222fccd64SMarek Sokolowski   };
56322fccd64SMarek Sokolowski 
56422fccd64SMarek Sokolowski   if (IsASCII && IsVirtKey)
56522fccd64SMarek Sokolowski     return createAccError("Accelerator can't be both ASCII and VIRTKEY");
56622fccd64SMarek Sokolowski 
56722fccd64SMarek Sokolowski   if (!IsVirtKey && (Obj.Flags & (Opt::ALT | Opt::SHIFT | Opt::CONTROL)))
56822fccd64SMarek Sokolowski     return createAccError("Can only apply ALT, SHIFT or CONTROL to VIRTKEY"
56922fccd64SMarek Sokolowski                           " accelerators");
57022fccd64SMarek Sokolowski 
57122fccd64SMarek Sokolowski   if (Obj.Event.isInt()) {
57222fccd64SMarek Sokolowski     if (!IsASCII && !IsVirtKey)
57322fccd64SMarek Sokolowski       return createAccError(
57422fccd64SMarek Sokolowski           "Accelerator with a numeric event must be either ASCII"
57522fccd64SMarek Sokolowski           " or VIRTKEY");
57622fccd64SMarek Sokolowski 
57722fccd64SMarek Sokolowski     uint32_t EventVal = Obj.Event.getInt();
57822fccd64SMarek Sokolowski     RETURN_IF_ERROR(
57922fccd64SMarek Sokolowski         checkNumberFits<uint16_t>(EventVal, "Numeric event key ID"));
58022fccd64SMarek Sokolowski     Entry.ANSICode = ulittle16_t(EventVal);
58122fccd64SMarek Sokolowski     writeObject(Entry);
58222fccd64SMarek Sokolowski     return Error::success();
58322fccd64SMarek Sokolowski   }
58422fccd64SMarek Sokolowski 
58522fccd64SMarek Sokolowski   StringRef Str = Obj.Event.getString();
58622fccd64SMarek Sokolowski   bool IsWide;
58722fccd64SMarek Sokolowski   stripQuotes(Str, IsWide);
58822fccd64SMarek Sokolowski 
58922fccd64SMarek Sokolowski   if (Str.size() == 0 || Str.size() > 2)
59022fccd64SMarek Sokolowski     return createAccError(
59122fccd64SMarek Sokolowski         "Accelerator string events should have length 1 or 2");
59222fccd64SMarek Sokolowski 
59322fccd64SMarek Sokolowski   if (Str[0] == '^') {
59422fccd64SMarek Sokolowski     if (Str.size() == 1)
59522fccd64SMarek Sokolowski       return createAccError("No character following '^' in accelerator event");
59622fccd64SMarek Sokolowski     if (IsVirtKey)
59722fccd64SMarek Sokolowski       return createAccError(
59822fccd64SMarek Sokolowski           "VIRTKEY accelerator events can't be preceded by '^'");
59922fccd64SMarek Sokolowski 
60022fccd64SMarek Sokolowski     char Ch = Str[1];
60122fccd64SMarek Sokolowski     if (Ch >= 'a' && Ch <= 'z')
60222fccd64SMarek Sokolowski       Entry.ANSICode = ulittle16_t(Ch - 'a' + 1);
60322fccd64SMarek Sokolowski     else if (Ch >= 'A' && Ch <= 'Z')
60422fccd64SMarek Sokolowski       Entry.ANSICode = ulittle16_t(Ch - 'A' + 1);
60522fccd64SMarek Sokolowski     else
60622fccd64SMarek Sokolowski       return createAccError("Control character accelerator event should be"
60722fccd64SMarek Sokolowski                             " alphabetic");
60822fccd64SMarek Sokolowski 
60922fccd64SMarek Sokolowski     writeObject(Entry);
61022fccd64SMarek Sokolowski     return Error::success();
61122fccd64SMarek Sokolowski   }
61222fccd64SMarek Sokolowski 
61322fccd64SMarek Sokolowski   if (Str.size() == 2)
61422fccd64SMarek Sokolowski     return createAccError("Event string should be one-character, possibly"
61522fccd64SMarek Sokolowski                           " preceded by '^'");
61622fccd64SMarek Sokolowski 
61722fccd64SMarek Sokolowski   uint8_t EventCh = Str[0];
61822fccd64SMarek Sokolowski   // The original tool just warns in this situation. We chose to fail.
61922fccd64SMarek Sokolowski   if (IsVirtKey && !isalnum(EventCh))
62022fccd64SMarek Sokolowski     return createAccError("Non-alphanumeric characters cannot describe virtual"
62122fccd64SMarek Sokolowski                           " keys");
62222fccd64SMarek Sokolowski   if (EventCh > 0x7F)
62322fccd64SMarek Sokolowski     return createAccError("Non-ASCII description of accelerator");
62422fccd64SMarek Sokolowski 
62522fccd64SMarek Sokolowski   if (IsVirtKey)
62622fccd64SMarek Sokolowski     EventCh = toupper(EventCh);
62722fccd64SMarek Sokolowski   Entry.ANSICode = ulittle16_t(EventCh);
62822fccd64SMarek Sokolowski   writeObject(Entry);
62922fccd64SMarek Sokolowski   return Error::success();
63022fccd64SMarek Sokolowski }
63122fccd64SMarek Sokolowski 
63222fccd64SMarek Sokolowski Error ResourceFileWriter::writeAcceleratorsBody(const RCResource *Base) {
63322fccd64SMarek Sokolowski   auto *Res = cast<AcceleratorsResource>(Base);
63422fccd64SMarek Sokolowski   size_t AcceleratorId = 0;
63522fccd64SMarek Sokolowski   for (auto &Acc : Res->Accelerators) {
63622fccd64SMarek Sokolowski     ++AcceleratorId;
63722fccd64SMarek Sokolowski     RETURN_IF_ERROR(
63822fccd64SMarek Sokolowski         writeSingleAccelerator(Acc, AcceleratorId == Res->Accelerators.size()));
63922fccd64SMarek Sokolowski   }
64022fccd64SMarek Sokolowski   return Error::success();
64122fccd64SMarek Sokolowski }
64222fccd64SMarek Sokolowski 
643c3ab013aSZachary Turner // --- CursorResource and IconResource helpers. --- //
644c3ab013aSZachary Turner 
645c3ab013aSZachary Turner // ICONRESDIR structure. Describes a single icon in resouce group.
646c3ab013aSZachary Turner //
647c3ab013aSZachary Turner // Ref: msdn.microsoft.com/en-us/library/windows/desktop/ms648016.aspx
648c3ab013aSZachary Turner struct IconResDir {
649c3ab013aSZachary Turner   uint8_t Width;
650c3ab013aSZachary Turner   uint8_t Height;
651c3ab013aSZachary Turner   uint8_t ColorCount;
652c3ab013aSZachary Turner   uint8_t Reserved;
653c3ab013aSZachary Turner };
654c3ab013aSZachary Turner 
655c3ab013aSZachary Turner // CURSORDIR structure. Describes a single cursor in resource group.
656c3ab013aSZachary Turner //
657c3ab013aSZachary Turner // Ref: msdn.microsoft.com/en-us/library/windows/desktop/ms648011(v=vs.85).aspx
658c3ab013aSZachary Turner struct CursorDir {
659c3ab013aSZachary Turner   ulittle16_t Width;
660c3ab013aSZachary Turner   ulittle16_t Height;
661c3ab013aSZachary Turner };
662c3ab013aSZachary Turner 
663c3ab013aSZachary Turner // RESDIRENTRY structure, stripped from the last item. Stripping made
664c3ab013aSZachary Turner // for compatibility with RESDIR.
665c3ab013aSZachary Turner //
666c3ab013aSZachary Turner // Ref: msdn.microsoft.com/en-us/library/windows/desktop/ms648026(v=vs.85).aspx
667c3ab013aSZachary Turner struct ResourceDirEntryStart {
668c3ab013aSZachary Turner   union {
669c3ab013aSZachary Turner     CursorDir Cursor; // Used in CURSOR resources.
670c3ab013aSZachary Turner     IconResDir Icon;  // Used in .ico and .cur files, and ICON resources.
671c3ab013aSZachary Turner   };
672c3ab013aSZachary Turner   ulittle16_t Planes;   // HotspotX (.cur files but not CURSOR resource).
673c3ab013aSZachary Turner   ulittle16_t BitCount; // HotspotY (.cur files but not CURSOR resource).
674c3ab013aSZachary Turner   ulittle32_t Size;
675c3ab013aSZachary Turner   // ulittle32_t ImageOffset;  // Offset to image data (ICONDIRENTRY only).
676c3ab013aSZachary Turner   // ulittle16_t IconID;       // Resource icon ID (RESDIR only).
677c3ab013aSZachary Turner };
678c3ab013aSZachary Turner 
679c3ab013aSZachary Turner // BITMAPINFOHEADER structure. Describes basic information about the bitmap
680c3ab013aSZachary Turner // being read.
681c3ab013aSZachary Turner //
682c3ab013aSZachary Turner // Ref: msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx
683c3ab013aSZachary Turner struct BitmapInfoHeader {
684c3ab013aSZachary Turner   ulittle32_t Size;
685c3ab013aSZachary Turner   ulittle32_t Width;
686c3ab013aSZachary Turner   ulittle32_t Height;
687c3ab013aSZachary Turner   ulittle16_t Planes;
688c3ab013aSZachary Turner   ulittle16_t BitCount;
689c3ab013aSZachary Turner   ulittle32_t Compression;
690c3ab013aSZachary Turner   ulittle32_t SizeImage;
691c3ab013aSZachary Turner   ulittle32_t XPelsPerMeter;
692c3ab013aSZachary Turner   ulittle32_t YPelsPerMeter;
693c3ab013aSZachary Turner   ulittle32_t ClrUsed;
694c3ab013aSZachary Turner   ulittle32_t ClrImportant;
695c3ab013aSZachary Turner };
696c3ab013aSZachary Turner 
697c3ab013aSZachary Turner // Group icon directory header. Called ICONDIR in .ico/.cur files and
698c3ab013aSZachary Turner // NEWHEADER in .res files.
699c3ab013aSZachary Turner //
700c3ab013aSZachary Turner // Ref: msdn.microsoft.com/en-us/library/windows/desktop/ms648023(v=vs.85).aspx
701c3ab013aSZachary Turner struct GroupIconDir {
702c3ab013aSZachary Turner   ulittle16_t Reserved; // Always 0.
703c3ab013aSZachary Turner   ulittle16_t ResType;  // 1 for icons, 2 for cursors.
704c3ab013aSZachary Turner   ulittle16_t ResCount; // Number of items.
705c3ab013aSZachary Turner };
706c3ab013aSZachary Turner 
707c3ab013aSZachary Turner enum class IconCursorGroupType { Icon, Cursor };
708c3ab013aSZachary Turner 
709c3ab013aSZachary Turner class SingleIconCursorResource : public RCResource {
710c3ab013aSZachary Turner public:
711c3ab013aSZachary Turner   IconCursorGroupType Type;
712c3ab013aSZachary Turner   const ResourceDirEntryStart &Header;
713c3ab013aSZachary Turner   ArrayRef<uint8_t> Image;
714c3ab013aSZachary Turner 
715c3ab013aSZachary Turner   SingleIconCursorResource(IconCursorGroupType ResourceType,
716c3ab013aSZachary Turner                            const ResourceDirEntryStart &HeaderEntry,
717c3ab013aSZachary Turner                            ArrayRef<uint8_t> ImageData)
718c3ab013aSZachary Turner       : Type(ResourceType), Header(HeaderEntry), Image(ImageData) {}
719c3ab013aSZachary Turner 
720c3ab013aSZachary Turner   Twine getResourceTypeName() const override { return "Icon/cursor image"; }
721c3ab013aSZachary Turner   IntOrString getResourceType() const override {
722c3ab013aSZachary Turner     return Type == IconCursorGroupType::Icon ? RkSingleIcon : RkSingleCursor;
723c3ab013aSZachary Turner   }
724c3ab013aSZachary Turner   uint16_t getMemoryFlags() const override {
725c3ab013aSZachary Turner     return MfDiscardable | MfMoveable;
726c3ab013aSZachary Turner   }
727c3ab013aSZachary Turner   ResourceKind getKind() const override { return RkSingleCursorOrIconRes; }
728c3ab013aSZachary Turner   static bool classof(const RCResource *Res) {
729c3ab013aSZachary Turner     return Res->getKind() == RkSingleCursorOrIconRes;
730c3ab013aSZachary Turner   }
731c3ab013aSZachary Turner };
732c3ab013aSZachary Turner 
733c3ab013aSZachary Turner class IconCursorGroupResource : public RCResource {
734c3ab013aSZachary Turner public:
735c3ab013aSZachary Turner   IconCursorGroupType Type;
736c3ab013aSZachary Turner   GroupIconDir Header;
737c3ab013aSZachary Turner   std::vector<ResourceDirEntryStart> ItemEntries;
738c3ab013aSZachary Turner 
739c3ab013aSZachary Turner   IconCursorGroupResource(IconCursorGroupType ResourceType,
740c3ab013aSZachary Turner                           const GroupIconDir &HeaderData,
741c3ab013aSZachary Turner                           std::vector<ResourceDirEntryStart> &&Entries)
742c3ab013aSZachary Turner       : Type(ResourceType), Header(HeaderData),
743c3ab013aSZachary Turner         ItemEntries(std::move(Entries)) {}
744c3ab013aSZachary Turner 
745c3ab013aSZachary Turner   Twine getResourceTypeName() const override { return "Icon/cursor group"; }
746c3ab013aSZachary Turner   IntOrString getResourceType() const override {
747c3ab013aSZachary Turner     return Type == IconCursorGroupType::Icon ? RkIconGroup : RkCursorGroup;
748c3ab013aSZachary Turner   }
749c3ab013aSZachary Turner   ResourceKind getKind() const override { return RkCursorOrIconGroupRes; }
750c3ab013aSZachary Turner   static bool classof(const RCResource *Res) {
751c3ab013aSZachary Turner     return Res->getKind() == RkCursorOrIconGroupRes;
752c3ab013aSZachary Turner   }
753c3ab013aSZachary Turner };
754c3ab013aSZachary Turner 
755c3ab013aSZachary Turner Error ResourceFileWriter::writeSingleIconOrCursorBody(const RCResource *Base) {
756c3ab013aSZachary Turner   auto *Res = cast<SingleIconCursorResource>(Base);
757c3ab013aSZachary Turner   if (Res->Type == IconCursorGroupType::Cursor) {
758c3ab013aSZachary Turner     // In case of cursors, two WORDS are appended to the beginning
759c3ab013aSZachary Turner     // of the resource: HotspotX (Planes in RESDIRENTRY),
760c3ab013aSZachary Turner     // and HotspotY (BitCount).
761c3ab013aSZachary Turner     //
762c3ab013aSZachary Turner     // Ref: msdn.microsoft.com/en-us/library/windows/desktop/ms648026.aspx
763c3ab013aSZachary Turner     //  (Remarks section).
764c3ab013aSZachary Turner     writeObject(Res->Header.Planes);
765c3ab013aSZachary Turner     writeObject(Res->Header.BitCount);
766c3ab013aSZachary Turner   }
767c3ab013aSZachary Turner 
768c3ab013aSZachary Turner   writeObject(Res->Image);
769c3ab013aSZachary Turner   return Error::success();
770c3ab013aSZachary Turner }
771c3ab013aSZachary Turner 
772c3ab013aSZachary Turner Error ResourceFileWriter::writeIconOrCursorGroupBody(const RCResource *Base) {
773c3ab013aSZachary Turner   auto *Res = cast<IconCursorGroupResource>(Base);
774c3ab013aSZachary Turner   writeObject(Res->Header);
775c3ab013aSZachary Turner   for (auto Item : Res->ItemEntries) {
776c3ab013aSZachary Turner     writeObject(Item);
777b12792a4SZachary Turner     writeInt(IconCursorID++);
778c3ab013aSZachary Turner   }
779c3ab013aSZachary Turner   return Error::success();
780c3ab013aSZachary Turner }
781c3ab013aSZachary Turner 
782c3ab013aSZachary Turner Error ResourceFileWriter::visitSingleIconOrCursor(const RCResource *Res) {
783c3ab013aSZachary Turner   return writeResource(Res, &ResourceFileWriter::writeSingleIconOrCursorBody);
784c3ab013aSZachary Turner }
785c3ab013aSZachary Turner 
786c3ab013aSZachary Turner Error ResourceFileWriter::visitIconOrCursorGroup(const RCResource *Res) {
787c3ab013aSZachary Turner   return writeResource(Res, &ResourceFileWriter::writeIconOrCursorGroupBody);
788c3ab013aSZachary Turner }
789c3ab013aSZachary Turner 
790c3ab013aSZachary Turner Error ResourceFileWriter::visitIconOrCursorResource(const RCResource *Base) {
791c3ab013aSZachary Turner   IconCursorGroupType Type;
792c3ab013aSZachary Turner   StringRef FileStr;
793c3ab013aSZachary Turner   IntOrString ResName = Base->ResName;
794c3ab013aSZachary Turner 
795c3ab013aSZachary Turner   if (auto *IconRes = dyn_cast<IconResource>(Base)) {
796c3ab013aSZachary Turner     FileStr = IconRes->IconLoc;
797c3ab013aSZachary Turner     Type = IconCursorGroupType::Icon;
798c3ab013aSZachary Turner   } else {
799c3ab013aSZachary Turner     auto *CursorRes = dyn_cast<CursorResource>(Base);
800c3ab013aSZachary Turner     FileStr = CursorRes->CursorLoc;
801c3ab013aSZachary Turner     Type = IconCursorGroupType::Cursor;
802c3ab013aSZachary Turner   }
803c3ab013aSZachary Turner 
804c3ab013aSZachary Turner   bool IsLong;
805c3ab013aSZachary Turner   stripQuotes(FileStr, IsLong);
806*fa0ca6cbSZachary Turner   auto File = loadFile(FileStr);
807c3ab013aSZachary Turner 
808c3ab013aSZachary Turner   if (!File)
809*fa0ca6cbSZachary Turner     return File.takeError();
810c3ab013aSZachary Turner 
811c3ab013aSZachary Turner   BinaryStreamReader Reader((*File)->getBuffer(), support::little);
812c3ab013aSZachary Turner 
813c3ab013aSZachary Turner   // Read the file headers.
814c3ab013aSZachary Turner   //   - At the beginning, ICONDIR/NEWHEADER header.
815c3ab013aSZachary Turner   //   - Then, a number of RESDIR headers follow. These contain offsets
816c3ab013aSZachary Turner   //       to data.
817c3ab013aSZachary Turner   const GroupIconDir *Header;
818c3ab013aSZachary Turner 
819c3ab013aSZachary Turner   RETURN_IF_ERROR(Reader.readObject(Header));
820c3ab013aSZachary Turner   if (Header->Reserved != 0)
821c3ab013aSZachary Turner     return createError("Incorrect icon/cursor Reserved field; should be 0.");
822c3ab013aSZachary Turner   uint16_t NeededType = Type == IconCursorGroupType::Icon ? 1 : 2;
823c3ab013aSZachary Turner   if (Header->ResType != NeededType)
824c3ab013aSZachary Turner     return createError("Incorrect icon/cursor ResType field; should be " +
825c3ab013aSZachary Turner                        Twine(NeededType) + ".");
826c3ab013aSZachary Turner 
827c3ab013aSZachary Turner   uint16_t NumItems = Header->ResCount;
828c3ab013aSZachary Turner 
829c3ab013aSZachary Turner   // Read single ico/cur headers.
830c3ab013aSZachary Turner   std::vector<ResourceDirEntryStart> ItemEntries;
831c3ab013aSZachary Turner   ItemEntries.reserve(NumItems);
832c3ab013aSZachary Turner   std::vector<uint32_t> ItemOffsets(NumItems);
833c3ab013aSZachary Turner   for (size_t ID = 0; ID < NumItems; ++ID) {
834c3ab013aSZachary Turner     const ResourceDirEntryStart *Object;
835c3ab013aSZachary Turner     RETURN_IF_ERROR(Reader.readObject(Object));
836c3ab013aSZachary Turner     ItemEntries.push_back(*Object);
837c3ab013aSZachary Turner     RETURN_IF_ERROR(Reader.readInteger(ItemOffsets[ID]));
838c3ab013aSZachary Turner   }
839c3ab013aSZachary Turner 
840c3ab013aSZachary Turner   // Now write each icon/cursors one by one. At first, all the contents
841c3ab013aSZachary Turner   // without ICO/CUR header. This is described by SingleIconCursorResource.
842c3ab013aSZachary Turner   for (size_t ID = 0; ID < NumItems; ++ID) {
843c3ab013aSZachary Turner     // Load the fragment of file.
844c3ab013aSZachary Turner     Reader.setOffset(ItemOffsets[ID]);
845c3ab013aSZachary Turner     ArrayRef<uint8_t> Image;
846c3ab013aSZachary Turner     RETURN_IF_ERROR(Reader.readArray(Image, ItemEntries[ID].Size));
847c3ab013aSZachary Turner     SingleIconCursorResource SingleRes(Type, ItemEntries[ID], Image);
848c3ab013aSZachary Turner     SingleRes.setName(IconCursorID + ID);
849c3ab013aSZachary Turner     RETURN_IF_ERROR(visitSingleIconOrCursor(&SingleRes));
850c3ab013aSZachary Turner   }
851c3ab013aSZachary Turner 
852c3ab013aSZachary Turner   // Now, write all the headers concatenated into a separate resource.
853c3ab013aSZachary Turner   for (size_t ID = 0; ID < NumItems; ++ID) {
854c3ab013aSZachary Turner     if (Type == IconCursorGroupType::Icon) {
855c3ab013aSZachary Turner       // rc.exe seems to always set NumPlanes to 1. No idea why it happens.
856c3ab013aSZachary Turner       ItemEntries[ID].Planes = 1;
857c3ab013aSZachary Turner       continue;
858c3ab013aSZachary Turner     }
859c3ab013aSZachary Turner 
860c3ab013aSZachary Turner     // We need to rewrite the cursor headers.
861c3ab013aSZachary Turner     const auto &OldHeader = ItemEntries[ID];
862c3ab013aSZachary Turner     ResourceDirEntryStart NewHeader;
863c3ab013aSZachary Turner     NewHeader.Cursor.Width = OldHeader.Icon.Width;
864c3ab013aSZachary Turner     // Each cursor in fact stores two bitmaps, one under another.
865c3ab013aSZachary Turner     // Height provided in cursor definition describes the height of the
866c3ab013aSZachary Turner     // cursor, whereas the value existing in resource definition describes
867c3ab013aSZachary Turner     // the height of the bitmap. Therefore, we need to double this height.
868c3ab013aSZachary Turner     NewHeader.Cursor.Height = OldHeader.Icon.Height * 2;
869c3ab013aSZachary Turner 
870c3ab013aSZachary Turner     // Now, we actually need to read the bitmap header to find
871c3ab013aSZachary Turner     // the number of planes and the number of bits per pixel.
872c3ab013aSZachary Turner     Reader.setOffset(ItemOffsets[ID]);
873c3ab013aSZachary Turner     const BitmapInfoHeader *BMPHeader;
874c3ab013aSZachary Turner     RETURN_IF_ERROR(Reader.readObject(BMPHeader));
875c3ab013aSZachary Turner     NewHeader.Planes = BMPHeader->Planes;
876c3ab013aSZachary Turner     NewHeader.BitCount = BMPHeader->BitCount;
877c3ab013aSZachary Turner 
878c3ab013aSZachary Turner     // Two WORDs were written at the beginning of the resource (hotspot
879c3ab013aSZachary Turner     // location). This is reflected in Size field.
880c3ab013aSZachary Turner     NewHeader.Size = OldHeader.Size + 2 * sizeof(uint16_t);
881c3ab013aSZachary Turner 
882c3ab013aSZachary Turner     ItemEntries[ID] = NewHeader;
883c3ab013aSZachary Turner   }
884c3ab013aSZachary Turner 
885c3ab013aSZachary Turner   IconCursorGroupResource HeaderRes(Type, *Header, std::move(ItemEntries));
886c3ab013aSZachary Turner   HeaderRes.setName(ResName);
887c3ab013aSZachary Turner   RETURN_IF_ERROR(visitIconOrCursorGroup(&HeaderRes));
888c3ab013aSZachary Turner 
889c3ab013aSZachary Turner   return Error::success();
890c3ab013aSZachary Turner }
891c3ab013aSZachary Turner 
8927f7745c0SMarek Sokolowski // --- DialogResource helpers. --- //
89322fccd64SMarek Sokolowski 
8947f7745c0SMarek Sokolowski Error ResourceFileWriter::writeSingleDialogControl(const Control &Ctl,
8957f7745c0SMarek Sokolowski                                                    bool IsExtended) {
8967f7745c0SMarek Sokolowski   // Each control should be aligned to DWORD.
8977f7745c0SMarek Sokolowski   padStream(sizeof(uint32_t));
8987f7745c0SMarek Sokolowski 
8997f7745c0SMarek Sokolowski   auto TypeInfo = Control::SupportedCtls.lookup(Ctl.Type);
9007f7745c0SMarek Sokolowski   uint32_t CtlStyle = TypeInfo.Style | Ctl.Style.getValueOr(0);
9017f7745c0SMarek Sokolowski   uint32_t CtlExtStyle = Ctl.ExtStyle.getValueOr(0);
9027f7745c0SMarek Sokolowski 
9037f7745c0SMarek Sokolowski   // DIALOG(EX) item header prefix.
9047f7745c0SMarek Sokolowski   if (!IsExtended) {
9057f7745c0SMarek Sokolowski     struct {
9067f7745c0SMarek Sokolowski       ulittle32_t Style;
9077f7745c0SMarek Sokolowski       ulittle32_t ExtStyle;
9087f7745c0SMarek Sokolowski     } Prefix{ulittle32_t(CtlStyle), ulittle32_t(CtlExtStyle)};
9097f7745c0SMarek Sokolowski     writeObject(Prefix);
9107f7745c0SMarek Sokolowski   } else {
9117f7745c0SMarek Sokolowski     struct {
9127f7745c0SMarek Sokolowski       ulittle32_t HelpID;
9137f7745c0SMarek Sokolowski       ulittle32_t ExtStyle;
9147f7745c0SMarek Sokolowski       ulittle32_t Style;
9157f7745c0SMarek Sokolowski     } Prefix{ulittle32_t(Ctl.HelpID.getValueOr(0)), ulittle32_t(CtlExtStyle),
9167f7745c0SMarek Sokolowski              ulittle32_t(CtlStyle)};
9177f7745c0SMarek Sokolowski     writeObject(Prefix);
9187f7745c0SMarek Sokolowski   }
9197f7745c0SMarek Sokolowski 
9207f7745c0SMarek Sokolowski   // Common fixed-length part.
9217f7745c0SMarek Sokolowski   RETURN_IF_ERROR(checkSignedNumberFits<int16_t>(
9227f7745c0SMarek Sokolowski       Ctl.X, "Dialog control x-coordinate", true));
9237f7745c0SMarek Sokolowski   RETURN_IF_ERROR(checkSignedNumberFits<int16_t>(
9247f7745c0SMarek Sokolowski       Ctl.Y, "Dialog control y-coordinate", true));
9257f7745c0SMarek Sokolowski   RETURN_IF_ERROR(
9267f7745c0SMarek Sokolowski       checkSignedNumberFits<int16_t>(Ctl.Width, "Dialog control width", false));
9277f7745c0SMarek Sokolowski   RETURN_IF_ERROR(checkSignedNumberFits<int16_t>(
9287f7745c0SMarek Sokolowski       Ctl.Height, "Dialog control height", false));
9297f7745c0SMarek Sokolowski   struct {
9307f7745c0SMarek Sokolowski     ulittle16_t X;
9317f7745c0SMarek Sokolowski     ulittle16_t Y;
9327f7745c0SMarek Sokolowski     ulittle16_t Width;
9337f7745c0SMarek Sokolowski     ulittle16_t Height;
9347f7745c0SMarek Sokolowski   } Middle{ulittle16_t(Ctl.X), ulittle16_t(Ctl.Y), ulittle16_t(Ctl.Width),
9357f7745c0SMarek Sokolowski            ulittle16_t(Ctl.Height)};
9367f7745c0SMarek Sokolowski   writeObject(Middle);
9377f7745c0SMarek Sokolowski 
9387f7745c0SMarek Sokolowski   // ID; it's 16-bit in DIALOG and 32-bit in DIALOGEX.
9397f7745c0SMarek Sokolowski   if (!IsExtended) {
9407f7745c0SMarek Sokolowski     RETURN_IF_ERROR(checkNumberFits<uint16_t>(
9417f7745c0SMarek Sokolowski         Ctl.ID, "Control ID in simple DIALOG resource"));
9427f7745c0SMarek Sokolowski     writeInt<uint16_t>(Ctl.ID);
9437f7745c0SMarek Sokolowski   } else {
9447f7745c0SMarek Sokolowski     writeInt<uint32_t>(Ctl.ID);
9457f7745c0SMarek Sokolowski   }
9467f7745c0SMarek Sokolowski 
9477f7745c0SMarek Sokolowski   // Window class - either 0xFFFF + 16-bit integer or a string.
9487f7745c0SMarek Sokolowski   RETURN_IF_ERROR(writeIntOrString(IntOrString(TypeInfo.CtlClass)));
9497f7745c0SMarek Sokolowski 
9507f7745c0SMarek Sokolowski   // Element caption/reference ID. ID is preceded by 0xFFFF.
9517f7745c0SMarek Sokolowski   RETURN_IF_ERROR(checkIntOrString(Ctl.Title, "Control reference ID"));
9527f7745c0SMarek Sokolowski   RETURN_IF_ERROR(writeIntOrString(Ctl.Title));
9537f7745c0SMarek Sokolowski 
9547f7745c0SMarek Sokolowski   // # bytes of extra creation data count. Don't pass any.
9557f7745c0SMarek Sokolowski   writeInt<uint16_t>(0);
9567f7745c0SMarek Sokolowski 
9577f7745c0SMarek Sokolowski   return Error::success();
9587f7745c0SMarek Sokolowski }
9597f7745c0SMarek Sokolowski 
9607f7745c0SMarek Sokolowski Error ResourceFileWriter::writeDialogBody(const RCResource *Base) {
9617f7745c0SMarek Sokolowski   auto *Res = cast<DialogResource>(Base);
9627f7745c0SMarek Sokolowski 
9637f7745c0SMarek Sokolowski   // Default style: WS_POPUP | WS_BORDER | WS_SYSMENU.
964420090afSZachary Turner   const uint32_t DefaultStyle = 0x80880000;
965420090afSZachary Turner   const uint32_t StyleFontFlag = 0x40;
966420090afSZachary Turner   const uint32_t StyleCaptionFlag = 0x00C00000;
967420090afSZachary Turner 
968420090afSZachary Turner   uint32_t UsedStyle = ObjectData.Style.getValueOr(DefaultStyle);
969420090afSZachary Turner   if (ObjectData.Font)
970420090afSZachary Turner     UsedStyle |= StyleFontFlag;
971420090afSZachary Turner   else
972420090afSZachary Turner     UsedStyle &= ~StyleFontFlag;
973420090afSZachary Turner 
974420090afSZachary Turner   // Actually, in case of empty (but existent) caption, the examined field
975420090afSZachary Turner   // is equal to "\"\"". That's why empty captions are still noticed.
976420090afSZachary Turner   if (ObjectData.Caption != "")
977420090afSZachary Turner     UsedStyle |= StyleCaptionFlag;
978420090afSZachary Turner 
979420090afSZachary Turner   const uint16_t DialogExMagic = 0xFFFF;
9807f7745c0SMarek Sokolowski 
9817f7745c0SMarek Sokolowski   // Write DIALOG(EX) header prefix. These are pretty different.
9827f7745c0SMarek Sokolowski   if (!Res->IsExtended) {
983420090afSZachary Turner     // We cannot let the higher word of DefaultStyle be equal to 0xFFFF.
984420090afSZachary Turner     // In such a case, whole object (in .res file) is equivalent to a
985420090afSZachary Turner     // DIALOGEX. It might lead to access violation/segmentation fault in
986420090afSZachary Turner     // resource readers. For example,
987420090afSZachary Turner     //   1 DIALOG 0, 0, 0, 65432
988420090afSZachary Turner     //   STYLE 0xFFFF0001 {}
989420090afSZachary Turner     // would be compiled to a DIALOGEX with 65432 controls.
990420090afSZachary Turner     if ((UsedStyle >> 16) == DialogExMagic)
991420090afSZachary Turner       return createError("16 higher bits of DIALOG resource style cannot be"
992420090afSZachary Turner                          " equal to 0xFFFF");
993420090afSZachary Turner 
9947f7745c0SMarek Sokolowski     struct {
9957f7745c0SMarek Sokolowski       ulittle32_t Style;
9967f7745c0SMarek Sokolowski       ulittle32_t ExtStyle;
9977f7745c0SMarek Sokolowski     } Prefix{ulittle32_t(UsedStyle),
9987f7745c0SMarek Sokolowski              ulittle32_t(0)}; // As of now, we don't keep EXSTYLE.
9997f7745c0SMarek Sokolowski 
10007f7745c0SMarek Sokolowski     writeObject(Prefix);
10017f7745c0SMarek Sokolowski   } else {
10027f7745c0SMarek Sokolowski     struct {
10037f7745c0SMarek Sokolowski       ulittle16_t Version;
10047f7745c0SMarek Sokolowski       ulittle16_t Magic;
10057f7745c0SMarek Sokolowski       ulittle32_t HelpID;
10067f7745c0SMarek Sokolowski       ulittle32_t ExtStyle;
10077f7745c0SMarek Sokolowski       ulittle32_t Style;
10087f7745c0SMarek Sokolowski     } Prefix{ulittle16_t(1), ulittle16_t(DialogExMagic),
10097f7745c0SMarek Sokolowski              ulittle32_t(Res->HelpID), ulittle32_t(0), ulittle32_t(UsedStyle)};
10107f7745c0SMarek Sokolowski 
10117f7745c0SMarek Sokolowski     writeObject(Prefix);
10127f7745c0SMarek Sokolowski   }
10137f7745c0SMarek Sokolowski 
10147f7745c0SMarek Sokolowski   // Now, a common part. First, fixed-length fields.
10157f7745c0SMarek Sokolowski   RETURN_IF_ERROR(checkNumberFits<uint16_t>(Res->Controls.size(),
10167f7745c0SMarek Sokolowski                                             "Number of dialog controls"));
10177f7745c0SMarek Sokolowski   RETURN_IF_ERROR(
10187f7745c0SMarek Sokolowski       checkSignedNumberFits<int16_t>(Res->X, "Dialog x-coordinate", true));
10197f7745c0SMarek Sokolowski   RETURN_IF_ERROR(
10207f7745c0SMarek Sokolowski       checkSignedNumberFits<int16_t>(Res->Y, "Dialog y-coordinate", true));
10217f7745c0SMarek Sokolowski   RETURN_IF_ERROR(
10227f7745c0SMarek Sokolowski       checkSignedNumberFits<int16_t>(Res->Width, "Dialog width", false));
10237f7745c0SMarek Sokolowski   RETURN_IF_ERROR(
10247f7745c0SMarek Sokolowski       checkSignedNumberFits<int16_t>(Res->Height, "Dialog height", false));
10257f7745c0SMarek Sokolowski   struct {
10267f7745c0SMarek Sokolowski     ulittle16_t Count;
10277f7745c0SMarek Sokolowski     ulittle16_t PosX;
10287f7745c0SMarek Sokolowski     ulittle16_t PosY;
10297f7745c0SMarek Sokolowski     ulittle16_t DialogWidth;
10307f7745c0SMarek Sokolowski     ulittle16_t DialogHeight;
10317f7745c0SMarek Sokolowski   } Middle{ulittle16_t(Res->Controls.size()), ulittle16_t(Res->X),
10327f7745c0SMarek Sokolowski            ulittle16_t(Res->Y), ulittle16_t(Res->Width),
10337f7745c0SMarek Sokolowski            ulittle16_t(Res->Height)};
10347f7745c0SMarek Sokolowski   writeObject(Middle);
10357f7745c0SMarek Sokolowski 
10367f7745c0SMarek Sokolowski   // MENU field. As of now, we don't keep them in the state and can peacefully
10377f7745c0SMarek Sokolowski   // think there is no menu attached to the dialog.
10387f7745c0SMarek Sokolowski   writeInt<uint16_t>(0);
10397f7745c0SMarek Sokolowski 
10407f7745c0SMarek Sokolowski   // Window CLASS field. Not kept here.
10417f7745c0SMarek Sokolowski   writeInt<uint16_t>(0);
10427f7745c0SMarek Sokolowski 
1043420090afSZachary Turner   // Window title or a single word equal to 0.
1044420090afSZachary Turner   RETURN_IF_ERROR(writeCString(ObjectData.Caption));
1045420090afSZachary Turner 
1046420090afSZachary Turner   // If there *is* a window font declared, output its data.
1047420090afSZachary Turner   auto &Font = ObjectData.Font;
1048420090afSZachary Turner   if (Font) {
1049420090afSZachary Turner     writeInt<uint16_t>(Font->Size);
1050420090afSZachary Turner     // Additional description occurs only in DIALOGEX.
1051420090afSZachary Turner     if (Res->IsExtended) {
1052420090afSZachary Turner       writeInt<uint16_t>(Font->Weight);
1053420090afSZachary Turner       writeInt<uint8_t>(Font->IsItalic);
1054420090afSZachary Turner       writeInt<uint8_t>(Font->Charset);
1055420090afSZachary Turner     }
1056420090afSZachary Turner     RETURN_IF_ERROR(writeCString(Font->Typeface));
1057420090afSZachary Turner   }
10587f7745c0SMarek Sokolowski 
10597f7745c0SMarek Sokolowski   auto handleCtlError = [&](Error &&Err, const Control &Ctl) -> Error {
10607f7745c0SMarek Sokolowski     if (!Err)
10617f7745c0SMarek Sokolowski       return Error::success();
10627f7745c0SMarek Sokolowski     return joinErrors(createError("Error in " + Twine(Ctl.Type) +
10637f7745c0SMarek Sokolowski                                   " control  (ID " + Twine(Ctl.ID) + "):"),
10647f7745c0SMarek Sokolowski                       std::move(Err));
10657f7745c0SMarek Sokolowski   };
10667f7745c0SMarek Sokolowski 
10677f7745c0SMarek Sokolowski   for (auto &Ctl : Res->Controls)
10687f7745c0SMarek Sokolowski     RETURN_IF_ERROR(
10697f7745c0SMarek Sokolowski         handleCtlError(writeSingleDialogControl(Ctl, Res->IsExtended), Ctl));
10707f7745c0SMarek Sokolowski 
10717f7745c0SMarek Sokolowski   return Error::success();
10727f7745c0SMarek Sokolowski }
10737f7745c0SMarek Sokolowski 
10747f7745c0SMarek Sokolowski // --- HTMLResource helpers. --- //
107522fccd64SMarek Sokolowski 
10768f19343aSMarek Sokolowski Error ResourceFileWriter::writeHTMLBody(const RCResource *Base) {
10778f19343aSMarek Sokolowski   return appendFile(cast<HTMLResource>(Base)->HTMLLoc);
10788f19343aSMarek Sokolowski }
10798f19343aSMarek Sokolowski 
108042f494d6SMarek Sokolowski // --- MenuResource helpers. --- //
108142f494d6SMarek Sokolowski 
108242f494d6SMarek Sokolowski Error ResourceFileWriter::writeMenuDefinition(
108342f494d6SMarek Sokolowski     const std::unique_ptr<MenuDefinition> &Def, uint16_t Flags) {
108442f494d6SMarek Sokolowski   assert(Def);
108542f494d6SMarek Sokolowski   const MenuDefinition *DefPtr = Def.get();
108642f494d6SMarek Sokolowski 
108742f494d6SMarek Sokolowski   if (auto *MenuItemPtr = dyn_cast<MenuItem>(DefPtr)) {
108842f494d6SMarek Sokolowski     writeInt<uint16_t>(Flags);
108942f494d6SMarek Sokolowski     RETURN_IF_ERROR(
109042f494d6SMarek Sokolowski         checkNumberFits<uint16_t>(MenuItemPtr->Id, "MENUITEM action ID"));
109142f494d6SMarek Sokolowski     writeInt<uint16_t>(MenuItemPtr->Id);
109242f494d6SMarek Sokolowski     RETURN_IF_ERROR(writeCString(MenuItemPtr->Name));
109342f494d6SMarek Sokolowski     return Error::success();
109442f494d6SMarek Sokolowski   }
109542f494d6SMarek Sokolowski 
109642f494d6SMarek Sokolowski   if (isa<MenuSeparator>(DefPtr)) {
109742f494d6SMarek Sokolowski     writeInt<uint16_t>(Flags);
109842f494d6SMarek Sokolowski     writeInt<uint32_t>(0);
109942f494d6SMarek Sokolowski     return Error::success();
110042f494d6SMarek Sokolowski   }
110142f494d6SMarek Sokolowski 
110242f494d6SMarek Sokolowski   auto *PopupPtr = cast<PopupItem>(DefPtr);
110342f494d6SMarek Sokolowski   writeInt<uint16_t>(Flags);
110442f494d6SMarek Sokolowski   RETURN_IF_ERROR(writeCString(PopupPtr->Name));
110542f494d6SMarek Sokolowski   return writeMenuDefinitionList(PopupPtr->SubItems);
110642f494d6SMarek Sokolowski }
110742f494d6SMarek Sokolowski 
110842f494d6SMarek Sokolowski Error ResourceFileWriter::writeMenuDefinitionList(
110942f494d6SMarek Sokolowski     const MenuDefinitionList &List) {
111042f494d6SMarek Sokolowski   for (auto &Def : List.Definitions) {
111142f494d6SMarek Sokolowski     uint16_t Flags = Def->getResFlags();
111242f494d6SMarek Sokolowski     // Last element receives an additional 0x80 flag.
111342f494d6SMarek Sokolowski     const uint16_t LastElementFlag = 0x0080;
111442f494d6SMarek Sokolowski     if (&Def == &List.Definitions.back())
111542f494d6SMarek Sokolowski       Flags |= LastElementFlag;
111642f494d6SMarek Sokolowski 
111742f494d6SMarek Sokolowski     RETURN_IF_ERROR(writeMenuDefinition(Def, Flags));
111842f494d6SMarek Sokolowski   }
111942f494d6SMarek Sokolowski   return Error::success();
112042f494d6SMarek Sokolowski }
112142f494d6SMarek Sokolowski 
112242f494d6SMarek Sokolowski Error ResourceFileWriter::writeMenuBody(const RCResource *Base) {
112342f494d6SMarek Sokolowski   // At first, MENUHEADER structure. In fact, these are two WORDs equal to 0.
112442f494d6SMarek Sokolowski   // Ref: msdn.microsoft.com/en-us/library/windows/desktop/ms648018.aspx
11251e2c8b11SZachary Turner   writeInt<uint32_t>(0);
112642f494d6SMarek Sokolowski 
112742f494d6SMarek Sokolowski   return writeMenuDefinitionList(cast<MenuResource>(Base)->Elements);
112842f494d6SMarek Sokolowski }
112942f494d6SMarek Sokolowski 
1130da366693SZachary Turner // --- StringTableResource helpers. --- //
1131da366693SZachary Turner 
1132da366693SZachary Turner class BundleResource : public RCResource {
1133da366693SZachary Turner public:
1134da366693SZachary Turner   using BundleType = ResourceFileWriter::StringTableInfo::Bundle;
1135da366693SZachary Turner   BundleType Bundle;
1136da366693SZachary Turner 
1137da366693SZachary Turner   BundleResource(const BundleType &StrBundle) : Bundle(StrBundle) {}
1138da366693SZachary Turner   IntOrString getResourceType() const override { return 6; }
1139da366693SZachary Turner 
1140da366693SZachary Turner   ResourceKind getKind() const override { return RkStringTableBundle; }
1141da366693SZachary Turner   static bool classof(const RCResource *Res) {
1142da366693SZachary Turner     return Res->getKind() == RkStringTableBundle;
1143da366693SZachary Turner   }
1144da366693SZachary Turner };
1145da366693SZachary Turner 
1146da366693SZachary Turner Error ResourceFileWriter::visitStringTableBundle(const RCResource *Res) {
1147da366693SZachary Turner   return writeResource(Res, &ResourceFileWriter::writeStringTableBundleBody);
1148da366693SZachary Turner }
1149da366693SZachary Turner 
1150da366693SZachary Turner Error ResourceFileWriter::insertStringIntoBundle(
1151da366693SZachary Turner     StringTableInfo::Bundle &Bundle, uint16_t StringID, StringRef String) {
1152da366693SZachary Turner   uint16_t StringLoc = StringID & 15;
1153da366693SZachary Turner   if (Bundle.Data[StringLoc])
1154da366693SZachary Turner     return createError("Multiple STRINGTABLE strings located under ID " +
1155da366693SZachary Turner                        Twine(StringID));
1156da366693SZachary Turner   Bundle.Data[StringLoc] = String;
1157da366693SZachary Turner   return Error::success();
1158da366693SZachary Turner }
1159da366693SZachary Turner 
1160da366693SZachary Turner Error ResourceFileWriter::writeStringTableBundleBody(const RCResource *Base) {
1161da366693SZachary Turner   auto *Res = cast<BundleResource>(Base);
1162da366693SZachary Turner   for (size_t ID = 0; ID < Res->Bundle.Data.size(); ++ID) {
1163da366693SZachary Turner     // The string format is a tiny bit different here. We
1164da366693SZachary Turner     // first output the size of the string, and then the string itself
1165da366693SZachary Turner     // (which is not null-terminated).
1166da366693SZachary Turner     bool IsLongString;
1167da366693SZachary Turner     SmallVector<UTF16, 128> Data;
1168da366693SZachary Turner     RETURN_IF_ERROR(processString(Res->Bundle.Data[ID].getValueOr(StringRef()),
1169da366693SZachary Turner                                   NullHandlingMethod::CutAtDoubleNull,
1170da366693SZachary Turner                                   IsLongString, Data));
1171da366693SZachary Turner     if (AppendNull && Res->Bundle.Data[ID])
1172da366693SZachary Turner       Data.push_back('\0');
1173da366693SZachary Turner     RETURN_IF_ERROR(
1174da366693SZachary Turner         checkNumberFits<uint16_t>(Data.size(), "STRINGTABLE string size"));
1175b12792a4SZachary Turner     writeInt<uint16_t>(Data.size());
1176da366693SZachary Turner     for (auto Char : Data)
1177b12792a4SZachary Turner       writeInt(Char);
1178da366693SZachary Turner   }
1179da366693SZachary Turner   return Error::success();
1180da366693SZachary Turner }
1181da366693SZachary Turner 
1182da366693SZachary Turner Error ResourceFileWriter::dumpAllStringTables() {
1183da366693SZachary Turner   for (auto Key : StringTableData.BundleList) {
1184da366693SZachary Turner     auto Iter = StringTableData.BundleData.find(Key);
1185da366693SZachary Turner     assert(Iter != StringTableData.BundleData.end());
1186da366693SZachary Turner 
1187da366693SZachary Turner     // For a moment, revert the context info to moment of bundle declaration.
1188da366693SZachary Turner     ContextKeeper RAII(this);
1189da366693SZachary Turner     ObjectData = Iter->second.DeclTimeInfo;
1190da366693SZachary Turner 
1191da366693SZachary Turner     BundleResource Res(Iter->second);
1192da366693SZachary Turner     // Bundle #(k+1) contains keys [16k, 16k + 15].
1193da366693SZachary Turner     Res.setName(Key.first + 1);
1194da366693SZachary Turner     RETURN_IF_ERROR(visitStringTableBundle(&Res));
1195da366693SZachary Turner   }
1196da366693SZachary Turner   return Error::success();
1197da366693SZachary Turner }
1198da366693SZachary Turner 
11999d8b358aSZachary Turner // --- UserDefinedResource helpers. --- //
12009d8b358aSZachary Turner 
12019d8b358aSZachary Turner Error ResourceFileWriter::writeUserDefinedBody(const RCResource *Base) {
12029d8b358aSZachary Turner   auto *Res = cast<UserDefinedResource>(Base);
12039d8b358aSZachary Turner 
12049d8b358aSZachary Turner   if (Res->IsFileResource)
12059d8b358aSZachary Turner     return appendFile(Res->FileLoc);
12069d8b358aSZachary Turner 
12079d8b358aSZachary Turner   for (auto &Elem : Res->Contents) {
12089d8b358aSZachary Turner     if (Elem.isInt()) {
12099d8b358aSZachary Turner       RETURN_IF_ERROR(
12109d8b358aSZachary Turner           checkRCInt(Elem.getInt(), "Number in user-defined resource"));
12119d8b358aSZachary Turner       writeRCInt(Elem.getInt());
12129d8b358aSZachary Turner       continue;
12139d8b358aSZachary Turner     }
12149d8b358aSZachary Turner 
12159d8b358aSZachary Turner     SmallVector<UTF16, 128> ProcessedString;
12169d8b358aSZachary Turner     bool IsLongString;
12179d8b358aSZachary Turner     RETURN_IF_ERROR(processString(Elem.getString(),
12189d8b358aSZachary Turner                                   NullHandlingMethod::UserResource,
12199d8b358aSZachary Turner                                   IsLongString, ProcessedString));
12209d8b358aSZachary Turner 
12219d8b358aSZachary Turner     for (auto Ch : ProcessedString) {
12229d8b358aSZachary Turner       if (IsLongString) {
1223b12792a4SZachary Turner         writeInt(Ch);
12249d8b358aSZachary Turner         continue;
12259d8b358aSZachary Turner       }
12269d8b358aSZachary Turner 
12279d8b358aSZachary Turner       RETURN_IF_ERROR(checkNumberFits<uint8_t>(
122875f9ae2bSSimon Dardis           Ch, "Character in narrow string in user-defined resource"));
1229b12792a4SZachary Turner       writeInt<uint8_t>(Ch);
12309d8b358aSZachary Turner     }
12319d8b358aSZachary Turner   }
12329d8b358aSZachary Turner 
12339d8b358aSZachary Turner   return Error::success();
12349d8b358aSZachary Turner }
12359d8b358aSZachary Turner 
123607bc04ffSZachary Turner // --- VersionInfoResourceResource helpers. --- //
123707bc04ffSZachary Turner 
123807bc04ffSZachary Turner Error ResourceFileWriter::writeVersionInfoBlock(const VersionInfoBlock &Blk) {
123907bc04ffSZachary Turner   // Output the header if the block has name.
124007bc04ffSZachary Turner   bool OutputHeader = Blk.Name != "";
124107bc04ffSZachary Turner   uint64_t LengthLoc;
124207bc04ffSZachary Turner 
124307bc04ffSZachary Turner   if (OutputHeader) {
12441e2c8b11SZachary Turner     LengthLoc = writeInt<uint16_t>(0);
12451e2c8b11SZachary Turner     writeInt<uint16_t>(0);
12461e2c8b11SZachary Turner     writeInt<uint16_t>(1); // true
124707bc04ffSZachary Turner     RETURN_IF_ERROR(writeCString(Blk.Name));
124807bc04ffSZachary Turner     padStream(sizeof(uint32_t));
124907bc04ffSZachary Turner   }
125007bc04ffSZachary Turner 
125107bc04ffSZachary Turner   for (const std::unique_ptr<VersionInfoStmt> &Item : Blk.Stmts) {
125207bc04ffSZachary Turner     VersionInfoStmt *ItemPtr = Item.get();
125307bc04ffSZachary Turner 
125407bc04ffSZachary Turner     if (auto *BlockPtr = dyn_cast<VersionInfoBlock>(ItemPtr)) {
125507bc04ffSZachary Turner       RETURN_IF_ERROR(writeVersionInfoBlock(*BlockPtr));
125607bc04ffSZachary Turner       continue;
125707bc04ffSZachary Turner     }
125807bc04ffSZachary Turner 
125907bc04ffSZachary Turner     auto *ValuePtr = cast<VersionInfoValue>(ItemPtr);
126007bc04ffSZachary Turner     RETURN_IF_ERROR(writeVersionInfoValue(*ValuePtr));
126107bc04ffSZachary Turner   }
126207bc04ffSZachary Turner 
126307bc04ffSZachary Turner   if (OutputHeader) {
126407bc04ffSZachary Turner     uint64_t CurLoc = tell();
126507bc04ffSZachary Turner     writeObjectAt(ulittle16_t(CurLoc - LengthLoc), LengthLoc);
126607bc04ffSZachary Turner   }
126707bc04ffSZachary Turner 
126807bc04ffSZachary Turner   padStream(sizeof(uint32_t));
126907bc04ffSZachary Turner   return Error::success();
127007bc04ffSZachary Turner }
127107bc04ffSZachary Turner 
127207bc04ffSZachary Turner Error ResourceFileWriter::writeVersionInfoValue(const VersionInfoValue &Val) {
127307bc04ffSZachary Turner   // rc has a peculiar algorithm to output VERSIONINFO VALUEs. Each VALUE
127407bc04ffSZachary Turner   // is a mapping from the key (string) to the value (a sequence of ints or
127507bc04ffSZachary Turner   // a sequence of strings).
127607bc04ffSZachary Turner   //
127707bc04ffSZachary Turner   // If integers are to be written: width of each integer written depends on
127807bc04ffSZachary Turner   // whether it's been declared 'long' (it's DWORD then) or not (it's WORD).
127907bc04ffSZachary Turner   // ValueLength defined in structure referenced below is then the total
128007bc04ffSZachary Turner   // number of bytes taken by these integers.
128107bc04ffSZachary Turner   //
128207bc04ffSZachary Turner   // If strings are to be written: characters are always WORDs.
128307bc04ffSZachary Turner   // Moreover, '\0' character is written after the last string, and between
128407bc04ffSZachary Turner   // every two strings separated by comma (if strings are not comma-separated,
128507bc04ffSZachary Turner   // they're simply concatenated). ValueLength is equal to the number of WORDs
128607bc04ffSZachary Turner   // written (that is, half of the bytes written).
128707bc04ffSZachary Turner   //
128807bc04ffSZachary Turner   // Ref: msdn.microsoft.com/en-us/library/windows/desktop/ms646994.aspx
128907bc04ffSZachary Turner   bool HasStrings = false, HasInts = false;
129007bc04ffSZachary Turner   for (auto &Item : Val.Values)
129107bc04ffSZachary Turner     (Item.isInt() ? HasInts : HasStrings) = true;
129207bc04ffSZachary Turner 
129307bc04ffSZachary Turner   assert((HasStrings || HasInts) && "VALUE must have at least one argument");
129407bc04ffSZachary Turner   if (HasStrings && HasInts)
129507bc04ffSZachary Turner     return createError(Twine("VALUE ") + Val.Key +
129607bc04ffSZachary Turner                        " cannot contain both strings and integers");
129707bc04ffSZachary Turner 
12981e2c8b11SZachary Turner   auto LengthLoc = writeInt<uint16_t>(0);
12991e2c8b11SZachary Turner   auto ValLengthLoc = writeInt<uint16_t>(0);
13001e2c8b11SZachary Turner   writeInt<uint16_t>(HasStrings);
130107bc04ffSZachary Turner   RETURN_IF_ERROR(writeCString(Val.Key));
130207bc04ffSZachary Turner   padStream(sizeof(uint32_t));
130307bc04ffSZachary Turner 
130407bc04ffSZachary Turner   auto DataLoc = tell();
130507bc04ffSZachary Turner   for (size_t Id = 0; Id < Val.Values.size(); ++Id) {
130607bc04ffSZachary Turner     auto &Item = Val.Values[Id];
130707bc04ffSZachary Turner     if (Item.isInt()) {
130807bc04ffSZachary Turner       auto Value = Item.getInt();
130907bc04ffSZachary Turner       RETURN_IF_ERROR(checkRCInt(Value, "VERSIONINFO integer value"));
131007bc04ffSZachary Turner       writeRCInt(Value);
131107bc04ffSZachary Turner       continue;
131207bc04ffSZachary Turner     }
131307bc04ffSZachary Turner 
131407bc04ffSZachary Turner     bool WriteTerminator =
131507bc04ffSZachary Turner         Id == Val.Values.size() - 1 || Val.HasPrecedingComma[Id + 1];
131607bc04ffSZachary Turner     RETURN_IF_ERROR(writeCString(Item.getString(), WriteTerminator));
131707bc04ffSZachary Turner   }
131807bc04ffSZachary Turner 
131907bc04ffSZachary Turner   auto CurLoc = tell();
132007bc04ffSZachary Turner   auto ValueLength = CurLoc - DataLoc;
132107bc04ffSZachary Turner   if (HasStrings) {
132207bc04ffSZachary Turner     assert(ValueLength % 2 == 0);
132307bc04ffSZachary Turner     ValueLength /= 2;
132407bc04ffSZachary Turner   }
132507bc04ffSZachary Turner   writeObjectAt(ulittle16_t(CurLoc - LengthLoc), LengthLoc);
132607bc04ffSZachary Turner   writeObjectAt(ulittle16_t(ValueLength), ValLengthLoc);
132707bc04ffSZachary Turner   padStream(sizeof(uint32_t));
132807bc04ffSZachary Turner   return Error::success();
132907bc04ffSZachary Turner }
133007bc04ffSZachary Turner 
133107bc04ffSZachary Turner template <typename Ty>
133207bc04ffSZachary Turner static Ty getWithDefault(const StringMap<Ty> &Map, StringRef Key,
133307bc04ffSZachary Turner                          const Ty &Default) {
133407bc04ffSZachary Turner   auto Iter = Map.find(Key);
133507bc04ffSZachary Turner   if (Iter != Map.end())
133607bc04ffSZachary Turner     return Iter->getValue();
133707bc04ffSZachary Turner   return Default;
133807bc04ffSZachary Turner }
133907bc04ffSZachary Turner 
134007bc04ffSZachary Turner Error ResourceFileWriter::writeVersionInfoBody(const RCResource *Base) {
134107bc04ffSZachary Turner   auto *Res = cast<VersionInfoResource>(Base);
134207bc04ffSZachary Turner 
134307bc04ffSZachary Turner   const auto &FixedData = Res->FixedData;
134407bc04ffSZachary Turner 
134507bc04ffSZachary Turner   struct /* VS_FIXEDFILEINFO */ {
134607bc04ffSZachary Turner     ulittle32_t Signature = ulittle32_t(0xFEEF04BD);
134707bc04ffSZachary Turner     ulittle32_t StructVersion = ulittle32_t(0x10000);
134807bc04ffSZachary Turner     // It's weird to have most-significant DWORD first on the little-endian
134907bc04ffSZachary Turner     // machines, but let it be this way.
135007bc04ffSZachary Turner     ulittle32_t FileVersionMS;
135107bc04ffSZachary Turner     ulittle32_t FileVersionLS;
135207bc04ffSZachary Turner     ulittle32_t ProductVersionMS;
135307bc04ffSZachary Turner     ulittle32_t ProductVersionLS;
135407bc04ffSZachary Turner     ulittle32_t FileFlagsMask;
135507bc04ffSZachary Turner     ulittle32_t FileFlags;
135607bc04ffSZachary Turner     ulittle32_t FileOS;
135707bc04ffSZachary Turner     ulittle32_t FileType;
135807bc04ffSZachary Turner     ulittle32_t FileSubtype;
135907bc04ffSZachary Turner     // MS implementation seems to always set these fields to 0.
136007bc04ffSZachary Turner     ulittle32_t FileDateMS = ulittle32_t(0);
136107bc04ffSZachary Turner     ulittle32_t FileDateLS = ulittle32_t(0);
136207bc04ffSZachary Turner   } FixedInfo;
136307bc04ffSZachary Turner 
136407bc04ffSZachary Turner   // First, VS_VERSIONINFO.
1365b12792a4SZachary Turner   auto LengthLoc = writeInt<uint16_t>(0);
1366b12792a4SZachary Turner   writeInt<uint16_t>(sizeof(FixedInfo));
1367b12792a4SZachary Turner   writeInt<uint16_t>(0);
136807bc04ffSZachary Turner   cantFail(writeCString("VS_VERSION_INFO"));
136907bc04ffSZachary Turner   padStream(sizeof(uint32_t));
137007bc04ffSZachary Turner 
137107bc04ffSZachary Turner   using VersionInfoFixed = VersionInfoResource::VersionInfoFixed;
137207bc04ffSZachary Turner   auto GetField = [&](VersionInfoFixed::VersionInfoFixedType Type) {
137307bc04ffSZachary Turner     static const SmallVector<uint32_t, 4> DefaultOut{0, 0, 0, 0};
137407bc04ffSZachary Turner     if (!FixedData.IsTypePresent[(int)Type])
137507bc04ffSZachary Turner       return DefaultOut;
137607bc04ffSZachary Turner     return FixedData.FixedInfo[(int)Type];
137707bc04ffSZachary Turner   };
137807bc04ffSZachary Turner 
137907bc04ffSZachary Turner   auto FileVer = GetField(VersionInfoFixed::FtFileVersion);
138007bc04ffSZachary Turner   RETURN_IF_ERROR(checkNumberFits<uint16_t>(
138107bc04ffSZachary Turner       *std::max_element(FileVer.begin(), FileVer.end()), "FILEVERSION fields"));
138207bc04ffSZachary Turner   FixedInfo.FileVersionMS = (FileVer[0] << 16) | FileVer[1];
138307bc04ffSZachary Turner   FixedInfo.FileVersionLS = (FileVer[2] << 16) | FileVer[3];
138407bc04ffSZachary Turner 
138507bc04ffSZachary Turner   auto ProdVer = GetField(VersionInfoFixed::FtProductVersion);
138607bc04ffSZachary Turner   RETURN_IF_ERROR(checkNumberFits<uint16_t>(
138707bc04ffSZachary Turner       *std::max_element(ProdVer.begin(), ProdVer.end()),
138807bc04ffSZachary Turner       "PRODUCTVERSION fields"));
138907bc04ffSZachary Turner   FixedInfo.ProductVersionMS = (ProdVer[0] << 16) | ProdVer[1];
139007bc04ffSZachary Turner   FixedInfo.ProductVersionLS = (ProdVer[2] << 16) | ProdVer[3];
139107bc04ffSZachary Turner 
139207bc04ffSZachary Turner   FixedInfo.FileFlagsMask = GetField(VersionInfoFixed::FtFileFlagsMask)[0];
139307bc04ffSZachary Turner   FixedInfo.FileFlags = GetField(VersionInfoFixed::FtFileFlags)[0];
139407bc04ffSZachary Turner   FixedInfo.FileOS = GetField(VersionInfoFixed::FtFileOS)[0];
139507bc04ffSZachary Turner   FixedInfo.FileType = GetField(VersionInfoFixed::FtFileType)[0];
139607bc04ffSZachary Turner   FixedInfo.FileSubtype = GetField(VersionInfoFixed::FtFileSubtype)[0];
139707bc04ffSZachary Turner 
139807bc04ffSZachary Turner   writeObject(FixedInfo);
139907bc04ffSZachary Turner   padStream(sizeof(uint32_t));
140007bc04ffSZachary Turner 
140107bc04ffSZachary Turner   RETURN_IF_ERROR(writeVersionInfoBlock(Res->MainBlock));
140207bc04ffSZachary Turner 
140307bc04ffSZachary Turner   // FIXME: check overflow?
140407bc04ffSZachary Turner   writeObjectAt(ulittle16_t(tell() - LengthLoc), LengthLoc);
140507bc04ffSZachary Turner 
140607bc04ffSZachary Turner   return Error::success();
140707bc04ffSZachary Turner }
140807bc04ffSZachary Turner 
1409*fa0ca6cbSZachary Turner Expected<std::unique_ptr<MemoryBuffer>>
1410*fa0ca6cbSZachary Turner ResourceFileWriter::loadFile(StringRef File) const {
1411*fa0ca6cbSZachary Turner   SmallString<128> Path;
1412*fa0ca6cbSZachary Turner   SmallString<128> Cwd;
1413*fa0ca6cbSZachary Turner   std::unique_ptr<MemoryBuffer> Result;
1414*fa0ca6cbSZachary Turner 
1415*fa0ca6cbSZachary Turner   // 1. The current working directory.
1416*fa0ca6cbSZachary Turner   sys::fs::current_path(Cwd);
1417*fa0ca6cbSZachary Turner   Path.assign(Cwd.begin(), Cwd.end());
1418*fa0ca6cbSZachary Turner   sys::path::append(Path, File);
1419*fa0ca6cbSZachary Turner   if (sys::fs::exists(Path))
1420*fa0ca6cbSZachary Turner     return errorOrToExpected(MemoryBuffer::getFile(Path, -1i64, false));
1421*fa0ca6cbSZachary Turner 
1422*fa0ca6cbSZachary Turner   // 2. The directory of the input resource file, if it is different from the
1423*fa0ca6cbSZachary Turner   // current
1424*fa0ca6cbSZachary Turner   //    working directory.
1425*fa0ca6cbSZachary Turner   StringRef InputFileDir = sys::path::parent_path(Params.InputFilePath);
1426*fa0ca6cbSZachary Turner   Path.assign(InputFileDir.begin(), InputFileDir.end());
1427*fa0ca6cbSZachary Turner   sys::path::append(Path, File);
1428*fa0ca6cbSZachary Turner   if (sys::fs::exists(Path))
1429*fa0ca6cbSZachary Turner     return errorOrToExpected(MemoryBuffer::getFile(Path, -1i64, false));
1430*fa0ca6cbSZachary Turner 
1431*fa0ca6cbSZachary Turner   // 3. All of the include directories specified on the command line.
1432*fa0ca6cbSZachary Turner   for (StringRef ForceInclude : Params.Include) {
1433*fa0ca6cbSZachary Turner     Path.assign(ForceInclude.begin(), ForceInclude.end());
1434*fa0ca6cbSZachary Turner     sys::path::append(Path, File);
1435*fa0ca6cbSZachary Turner     if (sys::fs::exists(Path))
1436*fa0ca6cbSZachary Turner       return errorOrToExpected(MemoryBuffer::getFile(Path, -1i64, false));
1437*fa0ca6cbSZachary Turner   }
1438*fa0ca6cbSZachary Turner 
1439*fa0ca6cbSZachary Turner   if (auto Result =
1440*fa0ca6cbSZachary Turner           llvm::sys::Process::FindInEnvPath("INCLUDE", File, Params.NoInclude))
1441*fa0ca6cbSZachary Turner     return errorOrToExpected(MemoryBuffer::getFile(*Result, -1i64, false));
1442*fa0ca6cbSZachary Turner 
1443*fa0ca6cbSZachary Turner   return make_error<StringError>("error : file not found : " + Twine(File),
1444*fa0ca6cbSZachary Turner                                  inconvertibleErrorCode());
1445*fa0ca6cbSZachary Turner }
1446*fa0ca6cbSZachary Turner 
14478f19343aSMarek Sokolowski } // namespace rc
14488f19343aSMarek Sokolowski } // namespace llvm
1449