GenerateStubsWhiteList.cpp revision fab6947a18e00964f79e6c802dc70bbaed981730
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <algorithm>
18#include <climits>
19#include <iostream>
20#include <iterator>
21#include <sstream>
22
23#include "Generator.h"
24#include "Specification.h"
25#include "Utilities.h"
26
27using namespace std;
28
29const unsigned int kMinimumApiLevelForTests = 11;
30const unsigned int kApiLevelWithFirst64Bit = 21;
31
32// Used to map the built-in types to their mangled representations
33struct BuiltInMangling {
34    const char* token[3];     // The last two entries can be nullptr
35    const char* equivalence;  // The mangled equivalent
36};
37
38BuiltInMangling builtInMangling[] = {
39            {{"long", "long"}, "x"},
40            {{"unsigned", "long", "long"}, "y"},
41            {{"long"}, "l"},
42            {{"unsigned", "long"}, "m"},
43            {{"int"}, "i"},
44            {{"unsigned", "int"}, "j"},
45            {{"short"}, "s"},
46            {{"unsigned", "short"}, "t"},
47            {{"char"}, "c"},
48            {{"unsigned", "char"}, "h"},
49            {{"signed", "char"}, "a"},
50            {{"void"}, "v"},
51            {{"wchar_t"}, "w"},
52            {{"bool"}, "b"},
53            {{"__fp16"}, "Dh"},
54            {{"float"}, "f"},
55            {{"double"}, "d"},
56};
57
58/* For the given API level and bitness (e.g. 32 or 64 bit), try to find a
59 * substitution for the provided type name, as would be done (mostly) by a
60 * preprocessor.  Returns empty string if there's no substitution.
61 */
62static string findSubstitute(const string& typeName, unsigned int apiLevel, int intSize) {
63    const auto& types = systemSpecification.getTypes();
64    const auto type = types.find(typeName);
65    if (type != types.end()) {
66        for (TypeSpecification* spec : type->second->getSpecifications()) {
67            // Verify this specification applies
68            const VersionInfo info = spec->getVersionInfo();
69            if (!info.includesVersion(apiLevel) || (info.intSize != 0 && info.intSize != intSize)) {
70                continue;
71            }
72            switch (spec->getKind()) {
73                case SIMPLE: {
74                    return spec->getSimpleType();
75                }
76                case RS_OBJECT: {
77                    // Do nothing for RS object types.
78                    break;
79                }
80                case STRUCT: {
81                    return spec->getStructName();
82                }
83                case ENUM:
84                    // Do nothing
85                    break;
86            }
87        }
88    }
89    return "";
90}
91
92/* Expand the typedefs found in 'type' into their equivalents and tokenize
93 * the resulting list.  'apiLevel' and 'intSize' specifies the API level and bitness
94 * we are currently processing.
95 */
96list<string> expandTypedefs(const string type, unsigned int apiLevel, int intSize) {
97    // Split the string in tokens.
98    istringstream stream(type);
99    list<string> tokens{istream_iterator<string>{stream}, istream_iterator<string>{}};
100    // Try to substitue each token.
101    for (auto i = tokens.begin(); i != tokens.end();) {
102        const string substitute = findSubstitute(*i, apiLevel, intSize);
103        if (substitute.empty()) {
104            // No substitution possible, just go to the next token.
105            i++;
106        } else {
107            // Split the replacement string in tokens.
108            istringstream stream(substitute);
109            list<string> newTokens{istream_iterator<string>{stream}, istream_iterator<string>{}};
110            // Replace the token with the substitution. Don't advance, as the new substitution
111            // might itself be replaced.
112            auto prev = i;
113            --prev;
114            tokens.insert(i, newTokens.begin(), newTokens.end());
115            tokens.erase(i);
116            advance(i, -newTokens.size());
117        }
118    }
119    return tokens;
120}
121
122// Remove the first element of the list if it equals 'prefix'.  Return true in that case.
123static bool eatFront(list<string>* tokens, const char* prefix) {
124    if (tokens->front() == prefix) {
125        tokens->pop_front();
126        return true;
127    }
128    return false;
129}
130
131/* Search the table of translations for the built-ins for the mangling that
132 * corresponds to this list of tokens.  If a match is found, consume these tokens
133 * and return a pointer to the string.  If not, return nullptr.
134 */
135static const char* findManglingOfBuiltInType(list<string>* tokens) {
136    for (const BuiltInMangling& a : builtInMangling) {
137        auto t = tokens->begin();
138        auto end = tokens->end();
139        bool match = true;
140        // We match up to three tokens.
141        for (int i = 0; i < 3; i++) {
142            if (!a.token[i]) {
143                // No more tokens
144                break;
145            }
146            if (t == end || *t++ != a.token[i]) {
147                match = false;
148            }
149        }
150        if (match) {
151            tokens->erase(tokens->begin(), t);
152            return a.equivalence;
153        }
154    }
155    return nullptr;
156}
157
158// Mangle a long name by prefixing it with its length, e.g. "13rs_allocation".
159static inline string mangleLongName(const string& name) {
160    return to_string(name.size()) + name;
161}
162
163/* Mangle the type name that's represented by the vector size and list of tokens.
164 * The mangling will be returned in full form in 'mangling'.  'compressedMangling'
165 * will have the compressed equivalent.  This is built using the 'previousManglings'
166 * list.  false is returned if an error is encountered.
167 *
168 * This function is recursive because compression is possible at each level of the definition.
169 * See http://mentorembedded.github.io/cxx-abi/abi.html#mangle.type for a description
170 * of the Itanium mangling used by llvm.
171 *
172 * This function mangles correctly the types currently used by RenderScript.  It does
173 * not currently mangle more complicated types like function pointers, namespaces,
174 * or other C++ types.  In particular, we don't deal correctly with parenthesis.
175 */
176static bool mangleType(string vectorSize, list<string>* tokens, vector<string>* previousManglings,
177                       string* mangling, string* compressedMangling) {
178    string delta;                 // The part of the mangling we're generating for this recursion.
179    bool isTerminal = false;      // True if this iteration parses a terminal node in the production.
180    bool canBeCompressed = true;  // Will be false for manglings of builtins.
181
182    if (tokens->back() == "*") {
183        delta = "P";
184        tokens->pop_back();
185    } else if (eatFront(tokens, "const")) {
186        delta = "K";
187    } else if (eatFront(tokens, "volatile")) {
188        delta = "V";
189    } else if (vectorSize != "1" && vectorSize != "") {
190        // For vector, prefix with the abbreviation for a vector, including the size.
191        delta = "Dv" + vectorSize + "_";
192        vectorSize.clear();  // Reset to mark the size as consumed.
193    } else if (eatFront(tokens, "struct")) {
194        // For a structure, we just use the structure name
195        if (tokens->size() == 0) {
196            cerr << "Expected a name after struct\n";
197            return false;
198        }
199        delta = mangleLongName(tokens->front());
200        isTerminal = true;
201        tokens->pop_front();
202    } else if (eatFront(tokens, "...")) {
203        delta = "z";
204        isTerminal = true;
205    } else {
206        const char* c = findManglingOfBuiltInType(tokens);
207        if (c) {
208            // It's a basic type.  We don't use those directly for compression.
209            delta = c;
210            isTerminal = true;
211            canBeCompressed = false;
212        } else if (tokens->size() > 0) {
213            // It's a complex type name.
214            delta = mangleLongName(tokens->front());
215            isTerminal = true;
216            tokens->pop_front();
217        }
218    }
219
220    if (isTerminal) {
221        // If we're the terminal node, there should be nothing left to mangle.
222        if (tokens->size() > 0) {
223            cerr << "Expected nothing else but found";
224            for (const auto& t : *tokens) {
225                cerr << " " << t;
226            }
227            cerr << "\n";
228            return false;
229        }
230        *mangling = delta;
231        *compressedMangling = delta;
232    } else {
233        // We're not terminal.  Recurse and prefix what we've translated this pass.
234        if (tokens->size() == 0) {
235            cerr << "Expected a more complete type\n";
236            return false;
237        }
238        string rest, compressedRest;
239        if (!mangleType(vectorSize, tokens, previousManglings, &rest, &compressedRest)) {
240            return false;
241        }
242        *mangling = delta + rest;
243        *compressedMangling = delta + compressedRest;
244    }
245
246    /* If it's a built-in type, we don't look at previously emitted ones and we
247     * don't keep track of it.
248     */
249    if (!canBeCompressed) {
250        return true;
251    }
252
253    // See if we've encountered this mangling before.
254    for (size_t i = 0; i < previousManglings->size(); ++i) {
255        if ((*previousManglings)[i] == *mangling) {
256            // We have a match, construct an index reference to that previously emitted mangling.
257            ostringstream stream2;
258            stream2 << 'S';
259            if (i > 0) {
260                stream2 << (char)('0' + i - 1);
261            }
262            stream2 << '_';
263            *compressedMangling = stream2.str();
264            return true;
265        }
266    }
267
268    // We have not encountered this before.  Add it to the list.
269    previousManglings->push_back(*mangling);
270    return true;
271}
272
273// Write to the stream the mangled representation of each parameter.
274static bool writeParameters(ostringstream* stream, const std::vector<ParameterDefinition*>& params,
275                            unsigned int apiLevel, int intSize) {
276    if (params.empty()) {
277        *stream << "v";
278        return true;
279    }
280    /* We keep track of the previously generated parameter types, as type mangling
281     * is compressed by reusing previous manglings.
282     */
283    vector<string> previousManglings;
284    for (ParameterDefinition* p : params) {
285        // Expand the typedefs and create a tokenized list.
286        list<string> tokens = expandTypedefs(p->rsType, apiLevel, intSize);
287        if (p->isOutParameter) {
288            tokens.push_back("*");
289        }
290        string mangling, compressedMangling;
291        if (!mangleType(p->mVectorSize, &tokens, &previousManglings, &mangling,
292                        &compressedMangling)) {
293            return false;
294        }
295        *stream << compressedMangling;
296    }
297    return true;
298}
299
300/* Add the mangling for this permutation of the function.  apiLevel and intSize is used
301 * to select the correct type when expanding complex type.
302 */
303static bool addFunctionManglingToSet(const Function& function,
304                                     const FunctionPermutation& permutation, bool overloadable,
305                                     unsigned int apiLevel, int intSize, set<string>* allManglings) {
306    const string& functionName = permutation.getName();
307    string mangling;
308    if (overloadable) {
309        ostringstream stream;
310        stream << "_Z" << mangleLongName(functionName);
311        if (!writeParameters(&stream, permutation.getParams(), apiLevel, intSize)) {
312            cerr << "Error mangling " << functionName << ".  See above message.\n";
313            return false;
314        }
315        mangling = stream.str();
316    } else {
317        mangling = functionName;
318    }
319    allManglings->insert(mangling);
320    return true;
321}
322
323/* Add to the set the mangling of each function prototype that can be generated from this
324 * specification, i.e. for all the versions covered and for 32/64 bits.  We call this
325 * for each API level because the implementation of a type may have changed in the range
326 * of API levels covered.
327 */
328static bool addManglingsForSpecification(const Function& function,
329                                         const FunctionSpecification& spec, unsigned int lastApiLevel,
330                                         set<string>* allManglings) {
331    // If the function is inlined, we won't generate an unresolved external for that.
332    if (spec.hasInline()) {
333        return true;
334    }
335    const VersionInfo info = spec.getVersionInfo();
336    unsigned int minApiLevel, maxApiLevel;
337    minApiLevel = info.minVersion ? info.minVersion : kMinimumApiLevelForTests;
338    maxApiLevel = info.maxVersion ? info.maxVersion : lastApiLevel;
339    const bool overloadable = spec.isOverloadable();
340
341    /* We track success rather than aborting early in case of failure so that we
342     * generate all the error messages.
343     */
344    bool success = true;
345    // Use 64-bit integer here for the loop count to avoid overflow
346    // (minApiLevel == maxApiLevel == UINT_MAX for unreleased API)
347    for (int64_t apiLevel = minApiLevel; apiLevel <= maxApiLevel; ++apiLevel) {
348        for (auto permutation : spec.getPermutations()) {
349            if (info.intSize == 0 || info.intSize == 32) {
350                if (!addFunctionManglingToSet(function, *permutation, overloadable, apiLevel, 32,
351                                              allManglings)) {
352                    success = false;
353                }
354            }
355            if (apiLevel >= kApiLevelWithFirst64Bit && (info.intSize == 0 || info.intSize == 64)) {
356                if (!addFunctionManglingToSet(function, *permutation, overloadable, apiLevel, 64,
357                                              allManglings)) {
358                    success = false;
359                }
360            }
361        }
362    }
363    return success;
364}
365
366/* Generate the white list file of the mangled function prototypes.  This generated list is used
367 * to validate unresolved external references.  'lastApiLevel' is the largest api level found in
368 * all spec files.
369 */
370static bool generateWhiteListFile(unsigned int lastApiLevel) {
371    bool success = true;
372    // We generate all the manglings in a set to remove duplicates and to order them.
373    set<string> allManglings;
374    for (auto f : systemSpecification.getFunctions()) {
375        const Function* function = f.second;
376        for (auto spec : function->getSpecifications()) {
377            // Compiler intrinsics are not runtime APIs. Do not include them in the whitelist.
378            if (spec->isIntrinsic()) {
379                continue;
380            }
381            if (!addManglingsForSpecification(*function, *spec, lastApiLevel, &allManglings)) {
382                success = false;  // We continue so we can generate all errors.
383            }
384        }
385    }
386
387    if (success) {
388        GeneratedFile file;
389        if (!file.start(".", "RSStubsWhiteList.cpp")) {
390            return false;
391        }
392
393        file.writeNotices();
394        file << "#include \"RSStubsWhiteList.h\"\n\n";
395        file << "std::vector<std::string> stubList = {\n";
396        for (const auto& e : allManglings) {
397            file << "\"" << e << "\",\n";
398        }
399        file << "};\n";
400    }
401    return success;
402}
403
404// Add a uniquely named variable definition to the file and return its name.
405static const string addVariable(GeneratedFile* file, unsigned int* variableNumber) {
406    const string name = "buf" + to_string((*variableNumber)++);
407    /* Some data structures like rs_tm can't be exported.  We'll just use a dumb buffer
408     * and cast its address later on.
409     */
410    *file << "char " << name << "[200];\n";
411    return name;
412}
413
414/* Write to the file the globals needed to make the call for this permutation.  The actual
415 * call is stored in 'calls', as we'll need to generate all the global variable declarations
416 * before the function definition.
417 */
418static void generateTestCall(GeneratedFile* file, ostringstream* calls,
419                             unsigned int* variableNumber, const Function& function,
420                             const FunctionPermutation& permutation) {
421    *calls << "    ";
422
423    // Handle the return type.
424    const auto ret = permutation.getReturn();
425    if (ret && ret->rsType != "void" && ret->rsType != "const void") {
426        *calls << "*(" << ret->rsType << "*)" << addVariable(file, variableNumber) << " = ";
427    }
428
429    *calls << permutation.getName() << "(";
430
431    // Generate the arguments.
432    const char* separator = "";
433    for (auto p : permutation.getParams()) {
434        *calls << separator;
435        // Special case for the kernel context, as it has a special existence.
436        if (p->rsType == "rs_kernel_context") {
437            *calls << "context";
438        } else if (p->isOutParameter) {
439            *calls << "(" << p->rsType << "*) " << addVariable(file, variableNumber);
440        } else {
441            *calls << "*(" << p->rsType << "*)" << addVariable(file, variableNumber);
442        }
443        separator = ", ";
444    }
445    *calls << ");\n";
446}
447
448/* Generate a test file that will be used in the frameworks/compile/slang/tests unit tests.
449 * This file tests that all RenderScript APIs can be called for the specified API level.
450 * To avoid the compiler agressively pruning out our calls, we use globals as inputs and outputs.
451 *
452 * Since some structures can't be defined at the global level, we use casts of simple byte
453 * buffers to get around that restriction.
454 *
455 * This file can be used to verify the white list that's also generated in this file.  To do so,
456 * run "llvm-nm -undefined-only -just-symbol-name" on the resulting bit code.
457 */
458static bool generateApiTesterFile(const string& slangTestDirectory, unsigned int apiLevel) {
459    GeneratedFile file;
460    if (!file.start(slangTestDirectory, "all" + to_string(apiLevel) + ".rs")) {
461        return false;
462    }
463
464    /* This unusual comment is used by slang/tests/test.py to know which parameter to pass
465     * to llvm-rs-cc when compiling the test.
466     */
467    file << "// -target-api " << apiLevel << " -Wno-deprecated-declarations\n";
468
469    file.writeNotices();
470    file << "#pragma version(1)\n";
471    file << "#pragma rs java_package_name(com.example.renderscript.testallapi)\n\n";
472    if (apiLevel < 23) {  // All rs_graphics APIs were deprecated in api level 23.
473        file << "#include \"rs_graphics.rsh\"\n\n";
474    }
475
476    /* The code below emits globals and calls to functions in parallel.  We store
477     * the calls in a stream so that we can emit them in the file in the proper order.
478     */
479    ostringstream calls;
480    unsigned int variableNumber = 0;  // Used to generate unique names.
481    for (auto f : systemSpecification.getFunctions()) {
482        const Function* function = f.second;
483        for (auto spec : function->getSpecifications()) {
484            // Do not include internal APIs in the API tests.
485            if (spec->isInternal()) {
486                continue;
487            }
488            VersionInfo info = spec->getVersionInfo();
489            if (!info.includesVersion(apiLevel)) {
490                continue;
491            }
492            if (info.intSize == 32) {
493                calls << "#ifndef __LP64__\n";
494            } else if (info.intSize == 64) {
495                calls << "#ifdef __LP64__\n";
496            }
497            for (auto permutation : spec->getPermutations()) {
498                generateTestCall(&file, &calls, &variableNumber, *function, *permutation);
499            }
500            if (info.intSize != 0) {
501                calls << "#endif\n";
502            }
503        }
504    }
505    file << "\n";
506
507    // Modify the style of kernel as required by the API level.
508    if (apiLevel >= 23) {
509        file << "void RS_KERNEL test(int in, rs_kernel_context context) {\n";
510    } else if (apiLevel >= 17) {
511        file << "void RS_KERNEL test(int in) {\n";
512    } else {
513        file << "void root(const int* in) {\n";
514    }
515    file << calls.str();
516    file << "}\n";
517
518    return true;
519}
520
521bool generateStubsWhiteList(const string& slangTestDirectory, unsigned int maxApiLevel) {
522    unsigned int lastApiLevel = min(systemSpecification.getMaximumApiLevel(), maxApiLevel);
523    if (!generateWhiteListFile(lastApiLevel)) {
524        return false;
525    }
526    // Generate a test file for each apiLevel.
527    for (unsigned int i = kMinimumApiLevelForTests; i <= lastApiLevel; ++i) {
528        if (!generateApiTesterFile(slangTestDirectory, i)) {
529            return false;
530        }
531    }
532    return true;
533}
534