1 //===- Formatters.cpp -----------------------------------------------------===//
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 #include "llvm/DebugInfo/CodeView/Formatters.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/DebugInfo/CodeView/GUID.h"
12 #include "llvm/Support/Endian.h"
13 #include "llvm/Support/ErrorHandling.h"
14 #include "llvm/Support/Format.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include <cassert>
17 
18 using namespace llvm;
19 using namespace llvm::codeview;
20 using namespace llvm::codeview::detail;
21 
22 GuidAdapter::GuidAdapter(StringRef Guid)
23     : FormatAdapter(makeArrayRef(Guid.bytes_begin(), Guid.bytes_end())) {}
24 
25 GuidAdapter::GuidAdapter(ArrayRef<uint8_t> Guid)
26     : FormatAdapter(std::move(Guid)) {}
27 
28 // From https://docs.microsoft.com/en-us/windows/win32/msi/guid documentation:
29 // The GUID data type is a text string representing a Class identifier (ID).
30 // All GUIDs must be authored in uppercase.
31 // The valid format for a GUID is {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} where
32 // X is a hex digit (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F).
33 //
34 // The individual string components must be padded to comply with the specific
35 // lengths of {8-4-4-4-12} characters.
36 // The llvm-yaml2obj tool checks that a GUID follow that format:
37 // - the total length to be 38 (including the curly braces.
38 // - there is a dash at the positions: 8, 13, 18 and 23.
39 void GuidAdapter::format(raw_ostream &Stream, StringRef Style) {
40   assert(Item.size() == 16 && "Expected 16-byte GUID");
41   struct MSGuid {
42     support::ulittle32_t Data1;
43     support::ulittle16_t Data2;
44     support::ulittle16_t Data3;
45     support::ubig64_t Data4;
46   };
47   const MSGuid *G = reinterpret_cast<const MSGuid *>(Item.data());
48   Stream
49       << '{' << format_hex_no_prefix(G->Data1, 8, /*Upper=*/true)
50       << '-' << format_hex_no_prefix(G->Data2, 4, /*Upper=*/true)
51       << '-' << format_hex_no_prefix(G->Data3, 4, /*Upper=*/true)
52       << '-' << format_hex_no_prefix(G->Data4 >> 48, 4, /*Upper=*/true) << '-'
53       << format_hex_no_prefix(G->Data4 & ((1ULL << 48) - 1), 12, /*Upper=*/true)
54       << '}';
55 }
56 
57 raw_ostream &llvm::codeview::operator<<(raw_ostream &OS, const GUID &Guid) {
58   codeview::detail::GuidAdapter A(Guid.Guid);
59   A.format(OS, "");
60   return OS;
61 }
62