summaryrefslogtreecommitdiffstats
path: root/audio/common/all-versions/test/utility/src/ValidateXml.cpp
blob: 126873d6f041de810f796bef1a569aef52025e56 (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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "ValidateAudioConfig"
#include <utils/Log.h>

#include <numeric>

#define LIBXML_SCHEMAS_ENABLED
#include <libxml/xmlschemastypes.h>
#define LIBXML_XINCLUDE_ENABLED
#include <libxml/xinclude.h>
#define LIBXML_XPATH_ENABLED
#include <libxml/xpath.h>

#include <memory>
#include <string>

#include "ValidateXml.h"

namespace android {
namespace hardware {
namespace audio {
namespace common {
namespace test {
namespace utility {

/** Map libxml2 structures to their corresponding deleters. */
template <class T>
constexpr void (*xmlDeleter)(T* t);
template <>
constexpr auto xmlDeleter<xmlSchema> = xmlSchemaFree;
template <>
constexpr auto xmlDeleter<xmlDoc> = xmlFreeDoc;
template <>
constexpr auto xmlDeleter<xmlSchemaParserCtxt> = xmlSchemaFreeParserCtxt;
template <>
constexpr auto xmlDeleter<xmlSchemaValidCtxt> = xmlSchemaFreeValidCtxt;
template <>
constexpr auto xmlDeleter<xmlXPathContext> = xmlXPathFreeContext;
template <>
constexpr auto xmlDeleter<xmlXPathObject> = xmlXPathFreeObject;

/** @return a unique_ptr with the correct deleter for the libxml2 object. */
template <class T>
constexpr auto make_xmlUnique(T* t) {
    // Wrap deleter in lambda to enable empty base optimization
    auto deleter = [](T* t) { xmlDeleter<T>(t); };
    return std::unique_ptr<T, decltype(deleter)>{t, deleter};
}

/** Class that handles libxml2 initialization and cleanup. NOT THREAD SAFE*/
struct Libxml2Global {
    Libxml2Global() {
        xmlLineNumbersDefault(1);  // Better error message
        xmlSetGenericErrorFunc(this, errorCb);
    }
    ~Libxml2Global() {
        // TODO: check if all those cleanup are needed
        xmlSetGenericErrorFunc(nullptr, nullptr);
        xmlSchemaCleanupTypes();
        xmlCleanupParser();
        xmlCleanupThreads();
    }

    const std::string& getErrors() { return errors; }

   private:
    static void errorCb(void* ctxt, const char* msg, ...) {
        auto* self = static_cast<Libxml2Global*>(ctxt);
        va_list args;
        va_start(args, msg);

        char* formatedMsg;
        if (vasprintf(&formatedMsg, msg, args) >= 0) {
            LOG_PRI(ANDROID_LOG_ERROR, LOG_TAG, "%s", formatedMsg);
            self->errors += "Error: ";
            self->errors += formatedMsg;
        }
        free(formatedMsg);

        va_end(args);
    }
    std::string errors;
};

::testing::AssertionResult validateXml(const char* xmlFilePathExpr, const char* xsdFilePathExpr,
                                       const char* xmlFilePath, const char* xsdFilePath) {
    Libxml2Global libxml2;

    auto context = [&]() {
        return std::string() + "  While validating: " + xmlFilePathExpr +
               "\n          Which is: " + xmlFilePath + "\nAgainst the schema: " + xsdFilePathExpr +
               "\n          Which is: " + xsdFilePath + "\nLibxml2 errors:\n" + libxml2.getErrors();
    };

    auto schemaParserCtxt = make_xmlUnique(xmlSchemaNewParserCtxt(xsdFilePath));
    auto schema = make_xmlUnique(xmlSchemaParse(schemaParserCtxt.get()));
    if (schema == nullptr) {
        return ::testing::AssertionFailure() << "Failed to parse schema (xsd)\n" << context();
    }

    auto doc = make_xmlUnique(xmlReadFile(xmlFilePath, nullptr, 0));
    if (doc == nullptr) {
        return ::testing::AssertionFailure() << "Failed to parse xml\n" << context();
    }

    if (xmlXIncludeProcess(doc.get()) == -1) {
        return ::testing::AssertionFailure() << "Failed to resolve xincludes in xml\n" << context();
    }

    auto schemaCtxt = make_xmlUnique(xmlSchemaNewValidCtxt(schema.get()));
    int ret = xmlSchemaValidateDoc(schemaCtxt.get(), doc.get());
    if (ret > 0) {
        return ::testing::AssertionFailure() << "XML is not valid according to the xsd\n"
                                             << context();
    }
    if (ret < 0) {
        return ::testing::AssertionFailure() << "Internal or API error\n" << context();
    }

    return ::testing::AssertionSuccess();
}

std::vector<std::string> findValidXmlFiles(
    const char* xsdFilePathExpr,
    const char* xmlFileName, std::vector<const char*> xmlFileLocations, const char* xsdFilePath,
    std::vector<std::string>* errors) {
    using namespace std::string_literals;
    std::vector<std::string> foundFiles;
    for (const char* location : xmlFileLocations) {
        std::string xmlFilePath = location + "/"s + xmlFileName;
        if (access(xmlFilePath.c_str(), F_OK) != 0) {
            // If the file does not exist ignore this location and fallback on the next one
            continue;
        }
        auto result = validateXml("xmlFilePath", xsdFilePathExpr, xmlFilePath.c_str(), xsdFilePath);
        if (!result) {
            if (errors != nullptr) errors->push_back(result.message());
        } else {
            foundFiles.push_back(xmlFilePath);
        }
    }
    return foundFiles;
}

template <bool atLeastOneRequired>
::testing::AssertionResult validateXmlMultipleLocations(
    const char* xmlFileNameExpr, const char* xmlFileLocationsExpr, const char* xsdFilePathExpr,
    const char* xmlFileName, std::vector<const char*> xmlFileLocations, const char* xsdFilePath) {
    using namespace std::string_literals;

    std::vector<std::string> errors;
    std::vector<std::string> foundFiles = findValidXmlFiles(
            xsdFilePathExpr, xmlFileName, xmlFileLocations, xsdFilePath, &errors);

    if (atLeastOneRequired && foundFiles.empty()) {
        errors.push_back("No xml file found in provided locations.\n");
    }

    return ::testing::AssertionResult(errors.empty())
           << errors.size() << " error" << (errors.size() == 1 ? " " : "s ")
           << std::accumulate(begin(errors), end(errors), "occurred during xml validation:\n"s)
           << "     While validating all: " << xmlFileNameExpr
           << "\n                 Which is: " << xmlFileName
           << "\n In the following folders: " << xmlFileLocationsExpr
           << "\n                 Which is: " << ::testing::PrintToString(xmlFileLocations)
           << (atLeastOneRequired ? "Where at least one file must be found."
                                  : "Where no file might exist.");
}

template ::testing::AssertionResult validateXmlMultipleLocations<true>(const char*, const char*,
                                                                       const char*, const char*,
                                                                       std::vector<const char*>,
                                                                       const char*);
template ::testing::AssertionResult validateXmlMultipleLocations<false>(const char*, const char*,
                                                                        const char*, const char*,
                                                                        std::vector<const char*>,
                                                                        const char*);

::testing::AssertionResult isNonEmptyXpath(
        const char* xmlFilePath, const char* xpathQuery, bool* result) {
    Libxml2Global libxml2;

    auto context = [&]() {
        return std::string() + "  In: " + xmlFilePath + "\nLibxml2 errors:\n" + libxml2.getErrors();
    };

    auto doc = make_xmlUnique(xmlReadFile(xmlFilePath, nullptr, 0));
    if (doc == nullptr) {
        return ::testing::AssertionFailure() << "Failed to parse xml\n" << context();
    }
    if (xmlXIncludeProcess(doc.get()) == -1) {
        return ::testing::AssertionFailure() << "Failed to resolve xincludes in xml\n" << context();
    }
    auto xpathCtxt = make_xmlUnique(xmlXPathNewContext(doc.get()));
    if (xpathCtxt == nullptr) {
        return ::testing::AssertionFailure() << "Failed to create xpath context\n" << context();
    }
    auto xpathObj = make_xmlUnique(xmlXPathEvalExpression(BAD_CAST xpathQuery, xpathCtxt.get()));
    if (xpathObj == nullptr) {
        return ::testing::AssertionFailure() <<
                "Failed to evaluate xpath: \'" << xpathQuery << "\'\n" << context();
    }
    auto nodeSet = xpathObj.get()->nodesetval;
    *result = nodeSet ? nodeSet->nodeNr != 0 : false;
    return ::testing::AssertionSuccess();
}

}  // namespace utility
}  // namespace test
}  // namespace common
}  // namespace audio
}  // namespace hardware
}  // namespace android