summaryrefslogtreecommitdiffstats
path: root/llvm/lib/Support/WindowsManifestMerger.cpp
blob: b003fdd7dd51c18eb6913443ca196f885eaa8a97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//===-- WindowsManifestMerger.cpp ------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//
//
// This file implements the .manifest merger class.
//
//===---------------------------------------------------------------------===//

#include "llvm/Support/WindowsManifestMerger.h"
#include "llvm/Support/MemoryBuffer.h"

#include <stdarg.h>

#define TO_XML_CHAR(X) reinterpret_cast<const unsigned char *>(X)
#define FROM_XML_CHAR(X) reinterpret_cast<const char *>(X)

using namespace llvm;

namespace llvm {

char WindowsManifestError::ID = 0;

WindowsManifestError::WindowsManifestError(const Twine &Msg) : Msg(Msg.str()) {}

void WindowsManifestError::log(raw_ostream &OS) const { OS << Msg; }

static bool xmlStringsEqual(const unsigned char *A, const unsigned char *B) {
  return strcmp(FROM_XML_CHAR(A), FROM_XML_CHAR(B)) == 0;
}

bool isMergeableElement(const unsigned char *ElementName) {
  for (StringRef S : {"application", "assembly", "assemblyIdentity",
                      "compatibility", "noInherit", "requestedExecutionLevel",
                      "requestedPrivileges", "security", "trustInfo"}) {
    if (S == FROM_XML_CHAR(ElementName))
      return true;
  }
  return false;
}

XMLNodeImpl getChildWithName(XMLNodeImpl Parent,
                             const unsigned char *ElementName) {
#if LLVM_LIBXML2_ENABLED
  for (XMLNodeImpl Child = Parent->children; Child; Child = Child->next)
    if (xmlStringsEqual(Child->name, ElementName)) {
      return Child;
    }
#endif
  return nullptr;
}

const unsigned char *getAttribute(XMLNodeImpl Node,
                                  const unsigned char *AttributeName) {
#if LLVM_LIBXML2_ENABLED
  for (xmlAttrPtr Attribute = Node->properties; Attribute != nullptr;
       Attribute = Attribute->next) {
    if (xmlStringsEqual(Attribute->name, AttributeName))
      return Attribute->children->content;
  }
#endif
  return nullptr;
}

Error mergeAttributes(XMLNodeImpl OriginalNode, XMLNodeImpl AdditionalNode) {
#if LLVM_LIBXML2_ENABLED
  for (xmlAttrPtr Attribute = AdditionalNode->properties; Attribute != nullptr;
       Attribute = Attribute->next) {
    if (const unsigned char *OriginalValue =
            getAttribute(OriginalNode, Attribute->name)) {
      // Attributes of the same name must also have the same value.  Otherwise
      // an error is thrown.
      if (!xmlStringsEqual(OriginalValue, Attribute->children->content))
        return make_error<WindowsManifestError>(
            Twine("conflicting attributes for ") +
            FROM_XML_CHAR(OriginalNode->name));
    } else {
      char *NameCopy = strdup(FROM_XML_CHAR(Attribute->name));
      char *ContentCopy = strdup(FROM_XML_CHAR(Attribute->children->content));
      xmlNewProp(OriginalNode, TO_XML_CHAR(NameCopy), TO_XML_CHAR(ContentCopy));
    }
  }
#endif
  return Error::success();
}

Error treeMerge(XMLNodeImpl OriginalRoot, XMLNodeImpl AdditionalRoot) {
#if LLVM_LIBXML2_ENABLED
  XMLNodeImpl AdditionalFirstChild = AdditionalRoot->children;
  for (XMLNodeImpl Child = AdditionalFirstChild; Child; Child = Child->next) {
    XMLNodeImpl OriginalChildWithName;
    if (!isMergeableElement(Child->name) ||
        !(OriginalChildWithName =
              getChildWithName(OriginalRoot, Child->name))) {
      XMLNodeImpl NewChild = xmlCopyNode(Child, 1);
      if (!NewChild)
        return make_error<WindowsManifestError>(Twine("error when copying ") +
                                                FROM_XML_CHAR(Child->name));
      if (NewChild->ns)
        xmlFreeNs(NewChild->ns); // xmlCopyNode explicitly defines default
                                 // namespace, undo this here.
      if (!xmlAddChild(OriginalRoot, NewChild))
        return make_error<WindowsManifestError>(Twine("could not merge ") +
                                                FROM_XML_CHAR(NewChild->name));
    } else if (auto E = treeMerge(OriginalChildWithName, Child)) {
      return E;
    }
  }
  if (auto E = mergeAttributes(OriginalRoot, AdditionalRoot))
    return E;
#endif
  return Error::success();
}

void stripCommentsAndText(XMLNodeImpl Root) {
  xmlNode StoreNext;
  for (XMLNodeImpl Child = Root->children; Child; Child = Child->next) {
    if (!xmlStringsEqual(Child->name, TO_XML_CHAR("text")) &&
        !xmlStringsEqual(Child->name, TO_XML_CHAR("comment"))) {
      stripCommentsAndText(Child);
    } else {
      StoreNext.next = Child->next;
      XMLNodeImpl Remove = Child;
      Child = &StoreNext;
      xmlUnlinkNode(Remove);
      xmlFreeNode(Remove);
    }
  }
}

WindowsManifestMerger::~WindowsManifestMerger() {
#if LLVM_LIBXML2_ENABLED
  for (auto &Doc : MergedDocs)
    xmlFreeDoc(Doc);
#endif
}

Error WindowsManifestMerger::merge(const MemoryBuffer &Manifest) {
#if LLVM_LIBXML2_ENABLED
  if (Manifest.getBufferSize() == 0)
    return make_error<WindowsManifestError>(
        "attempted to merge empty manifest");
  xmlSetGenericErrorFunc((void *)this, WindowsManifestMerger::errorCallback);
  XMLDocumentImpl ManifestXML =
      xmlReadMemory(Manifest.getBufferStart(), Manifest.getBufferSize(),
                    "manifest.xml", nullptr, XML_PARSE_NOBLANKS);
  xmlSetGenericErrorFunc(nullptr, nullptr);
  if (auto E = getParseError())
    return E;
  XMLNodeImpl AdditionalRoot = xmlDocGetRootElement(ManifestXML);
  stripCommentsAndText(AdditionalRoot);
  if (CombinedDoc == nullptr) {
    CombinedDoc = ManifestXML;
  } else {
    XMLNodeImpl CombinedRoot = xmlDocGetRootElement(CombinedDoc);
    if (xmlStringsEqual(CombinedRoot->name, AdditionalRoot->name) &&
        isMergeableElement(AdditionalRoot->name)) {
      if (auto E = treeMerge(CombinedRoot, AdditionalRoot)) {
        return E;
      }
    } else {
      XMLNodeImpl NewChild = xmlCopyNode(AdditionalRoot, 1);
      if (!NewChild)
        return make_error<WindowsManifestError>("could not copy manifest");
      if (!xmlAddChild(CombinedRoot, NewChild))
        return make_error<WindowsManifestError>("could not append manifest");
    }
  }
  MergedDocs.push_back(ManifestXML);
#endif
  return Error::success();
}

std::unique_ptr<MemoryBuffer> WindowsManifestMerger::getMergedManifest() {
#if LLVM_LIBXML2_ENABLED
  unsigned char *XmlBuff;
  int BufferSize = 0;
  if (CombinedDoc) {
    std::unique_ptr<xmlDoc> OutputDoc(xmlNewDoc((const unsigned char *)"1.0"));
    xmlDocSetRootElement(OutputDoc.get(), xmlDocGetRootElement(CombinedDoc));
    xmlKeepBlanksDefault(0);
    xmlDocDumpFormatMemory(OutputDoc.get(), &XmlBuff, &BufferSize, 1);
  }
  if (BufferSize == 0)
    return nullptr;
  return MemoryBuffer::getMemBuffer(
      StringRef(FROM_XML_CHAR(XmlBuff), (size_t)BufferSize));
#else
  return nullptr;
#endif
}

void WindowsManifestMerger::errorCallback(void *Ctx, const char *Format, ...) {
  auto *Merger = (WindowsManifestMerger *)Ctx;
  Merger->ParseErrorOccurred = true;
}

Error WindowsManifestMerger::getParseError() {
  if (!ParseErrorOccurred)
    return Error::success();
  return make_error<WindowsManifestError>("invalid xml document");
}

} // namespace llvm
OpenPOWER on IntegriCloud