GenerateStubsWhiteList.cpp revision 12398d81f32e5e0479d02b8608a83c75cd991bb3
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 { 203 const char* c = findManglingOfBuiltInType(tokens); 204 if (c) { 205 // It's a basic type. We don't use those directly for compression. 206 delta = c; 207 isTerminal = true; 208 canBeCompressed = false; 209 } else if (tokens->size() > 0) { 210 // It's a complex type name. 211 delta = mangleLongName(tokens->front()); 212 isTerminal = true; 213 tokens->pop_front(); 214 } 215 } 216 217 if (isTerminal) { 218 // If we're the terminal node, there should be nothing left to mangle. 219 if (tokens->size() > 0) { 220 cerr << "Expected nothing else but found"; 221 for (const auto& t : *tokens) { 222 cerr << " " << t; 223 } 224 cerr << "\n"; 225 return false; 226 } 227 *mangling = delta; 228 *compressedMangling = delta; 229 } else { 230 // We're not terminal. Recurse and prefix what we've translated this pass. 231 if (tokens->size() == 0) { 232 cerr << "Expected a more complete type\n"; 233 return false; 234 } 235 string rest, compressedRest; 236 if (!mangleType(vectorSize, tokens, previousManglings, &rest, &compressedRest)) { 237 return false; 238 } 239 *mangling = delta + rest; 240 *compressedMangling = delta + compressedRest; 241 } 242 243 /* If it's a built-in type, we don't look at previously emitted ones and we 244 * don't keep track of it. 245 */ 246 if (!canBeCompressed) { 247 return true; 248 } 249 250 // See if we've encountered this mangling before. 251 for (size_t i = 0; i < previousManglings->size(); ++i) { 252 if ((*previousManglings)[i] == *mangling) { 253 // We have a match, construct an index reference to that previously emitted mangling. 254 ostringstream stream2; 255 stream2 << 'S'; 256 if (i > 0) { 257 stream2 << (char)('0' + i - 1); 258 } 259 stream2 << '_'; 260 *compressedMangling = stream2.str(); 261 return true; 262 } 263 } 264 265 // We have not encountered this before. Add it to the list. 266 previousManglings->push_back(*mangling); 267 return true; 268} 269 270// Write to the stream the mangled representation of each parameter. 271static bool writeParameters(ostringstream* stream, const std::vector<ParameterDefinition*>& params, 272 unsigned int apiLevel, int intSize) { 273 if (params.empty()) { 274 *stream << "v"; 275 return true; 276 } 277 /* We keep track of the previously generated parameter types, as type mangling 278 * is compressed by reusing previous manglings. 279 */ 280 vector<string> previousManglings; 281 for (ParameterDefinition* p : params) { 282 // Expand the typedefs and create a tokenized list. 283 list<string> tokens = expandTypedefs(p->rsType, apiLevel, intSize); 284 if (p->isOutParameter) { 285 tokens.push_back("*"); 286 } 287 string mangling, compressedMangling; 288 if (!mangleType(p->mVectorSize, &tokens, &previousManglings, &mangling, 289 &compressedMangling)) { 290 return false; 291 } 292 *stream << compressedMangling; 293 } 294 return true; 295} 296 297/* Add the mangling for this permutation of the function. apiLevel and intSize is used 298 * to select the correct type when expanding complex type. 299 */ 300static bool addFunctionManglingToSet(const Function& function, 301 const FunctionPermutation& permutation, bool overloadable, 302 unsigned int apiLevel, int intSize, set<string>* allManglings) { 303 const string& functionName = permutation.getName(); 304 string mangling; 305 if (overloadable) { 306 ostringstream stream; 307 stream << "_Z" << mangleLongName(functionName); 308 if (!writeParameters(&stream, permutation.getParams(), apiLevel, intSize)) { 309 cerr << "Error mangling " << functionName << ". See above message.\n"; 310 return false; 311 } 312 mangling = stream.str(); 313 } else { 314 mangling = functionName; 315 } 316 allManglings->insert(mangling); 317 return true; 318} 319 320/* Add to the set the mangling of each function prototype that can be generated from this 321 * specification, i.e. for all the versions covered and for 32/64 bits. We call this 322 * for each API level because the implementation of a type may have changed in the range 323 * of API levels covered. 324 */ 325static bool addManglingsForSpecification(const Function& function, 326 const FunctionSpecification& spec, unsigned int lastApiLevel, 327 set<string>* allManglings) { 328 // If the function is inlined, we won't generate an unresolved external for that. 329 if (spec.hasInline()) { 330 return true; 331 } 332 const VersionInfo info = spec.getVersionInfo(); 333 unsigned int minApiLevel, maxApiLevel; 334 minApiLevel = info.minVersion ? info.minVersion : kMinimumApiLevelForTests; 335 maxApiLevel = info.maxVersion ? info.maxVersion : lastApiLevel; 336 const bool overloadable = spec.isOverloadable(); 337 338 /* We track success rather than aborting early in case of failure so that we 339 * generate all the error messages. 340 */ 341 bool success = true; 342 // Use 64-bit integer here for the loop count to avoid overflow 343 // (minApiLevel == maxApiLevel == UINT_MAX for unreleased API) 344 for (int64_t apiLevel = minApiLevel; apiLevel <= maxApiLevel; ++apiLevel) { 345 for (auto permutation : spec.getPermutations()) { 346 if (info.intSize == 0 || info.intSize == 32) { 347 if (!addFunctionManglingToSet(function, *permutation, overloadable, apiLevel, 32, 348 allManglings)) { 349 success = false; 350 } 351 } 352 if (apiLevel >= kApiLevelWithFirst64Bit && (info.intSize == 0 || info.intSize == 64)) { 353 if (!addFunctionManglingToSet(function, *permutation, overloadable, apiLevel, 64, 354 allManglings)) { 355 success = false; 356 } 357 } 358 } 359 } 360 return success; 361} 362 363/* Generate the white list file of the mangled function prototypes. This generated list is used 364 * to validate unresolved external references. 'lastApiLevel' is the largest api level found in 365 * all spec files. 366 */ 367static bool generateWhiteListFile(unsigned int lastApiLevel) { 368 bool success = true; 369 // We generate all the manglings in a set to remove duplicates and to order them. 370 set<string> allManglings; 371 for (auto f : systemSpecification.getFunctions()) { 372 const Function* function = f.second; 373 for (auto spec : function->getSpecifications()) { 374 // Compiler intrinsics are not runtime APIs. Do not include them in the whitelist. 375 if (spec->isIntrinsic()) { 376 continue; 377 } 378 if (!addManglingsForSpecification(*function, *spec, lastApiLevel, &allManglings)) { 379 success = false; // We continue so we can generate all errors. 380 } 381 } 382 } 383 384 if (success) { 385 GeneratedFile file; 386 if (!file.start(".", "RSStubsWhiteList.cpp")) { 387 return false; 388 } 389 390 file.writeNotices(); 391 file << "#include \"RSStubsWhiteList.h\"\n\n"; 392 file << "std::vector<std::string> stubList = {\n"; 393 for (const auto& e : allManglings) { 394 file << "\"" << e << "\",\n"; 395 } 396 file << "};\n"; 397 } 398 return success; 399} 400 401// Add a uniquely named variable definition to the file and return its name. 402static const string addVariable(GeneratedFile* file, unsigned int* variableNumber) { 403 const string name = "buf" + to_string((*variableNumber)++); 404 /* Some data structures like rs_tm can't be exported. We'll just use a dumb buffer 405 * and cast its address later on. 406 */ 407 *file << "char " << name << "[200];\n"; 408 return name; 409} 410 411/* Write to the file the globals needed to make the call for this permutation. The actual 412 * call is stored in 'calls', as we'll need to generate all the global variable declarations 413 * before the function definition. 414 */ 415static void generateTestCall(GeneratedFile* file, ostringstream* calls, 416 unsigned int* variableNumber, const Function& function, 417 const FunctionPermutation& permutation) { 418 *calls << " "; 419 420 // Handle the return type. 421 const auto ret = permutation.getReturn(); 422 if (ret && ret->rsType != "void" && ret->rsType != "const void") { 423 *calls << "*(" << ret->rsType << "*)" << addVariable(file, variableNumber) << " = "; 424 } 425 426 *calls << permutation.getName() << "("; 427 428 // Generate the arguments. 429 const char* separator = ""; 430 for (auto p : permutation.getParams()) { 431 *calls << separator; 432 // Special case for the kernel context, as it has a special existence. 433 if (p->rsType == "rs_kernel_context") { 434 *calls << "context"; 435 } else if (p->isOutParameter) { 436 *calls << "(" << p->rsType << "*) " << addVariable(file, variableNumber); 437 } else { 438 *calls << "*(" << p->rsType << "*)" << addVariable(file, variableNumber); 439 } 440 separator = ", "; 441 } 442 *calls << ");\n"; 443} 444 445/* Generate a test file that will be used in the frameworks/compile/slang/tests unit tests. 446 * This file tests that all RenderScript APIs can be called for the specified API level. 447 * To avoid the compiler agressively pruning out our calls, we use globals as inputs and outputs. 448 * 449 * Since some structures can't be defined at the global level, we use casts of simple byte 450 * buffers to get around that restriction. 451 * 452 * This file can be used to verify the white list that's also generated in this file. To do so, 453 * run "llvm-nm -undefined-only -just-symbol-name" on the resulting bit code. 454 */ 455static bool generateApiTesterFile(const string& slangTestDirectory, unsigned int apiLevel) { 456 GeneratedFile file; 457 if (!file.start(slangTestDirectory, "all" + to_string(apiLevel) + ".rs")) { 458 return false; 459 } 460 461 /* This unusual comment is used by slang/tests/test.py to know which parameter to pass 462 * to llvm-rs-cc when compiling the test. 463 */ 464 file << "// -target-api " << apiLevel << " -Wno-deprecated-declarations\n"; 465 466 file.writeNotices(); 467 file << "#pragma version(1)\n"; 468 file << "#pragma rs java_package_name(com.example.renderscript.testallapi)\n\n"; 469 if (apiLevel < 23) { // All rs_graphics APIs were deprecated in api level 23. 470 file << "#include \"rs_graphics.rsh\"\n\n"; 471 } 472 473 /* The code below emits globals and calls to functions in parallel. We store 474 * the calls in a stream so that we can emit them in the file in the proper order. 475 */ 476 ostringstream calls; 477 unsigned int variableNumber = 0; // Used to generate unique names. 478 for (auto f : systemSpecification.getFunctions()) { 479 const Function* function = f.second; 480 for (auto spec : function->getSpecifications()) { 481 // Do not include internal APIs in the API tests. 482 if (spec->isInternal()) { 483 continue; 484 } 485 VersionInfo info = spec->getVersionInfo(); 486 if (!info.includesVersion(apiLevel)) { 487 continue; 488 } 489 if (info.intSize == 32) { 490 calls << "#ifndef __LP64__\n"; 491 } else if (info.intSize == 64) { 492 calls << "#ifdef __LP64__\n"; 493 } 494 for (auto permutation : spec->getPermutations()) { 495 generateTestCall(&file, &calls, &variableNumber, *function, *permutation); 496 } 497 if (info.intSize != 0) { 498 calls << "#endif\n"; 499 } 500 } 501 } 502 file << "\n"; 503 504 // Modify the style of kernel as required by the API level. 505 if (apiLevel >= 23) { 506 file << "void RS_KERNEL test(int in, rs_kernel_context context) {\n"; 507 } else if (apiLevel >= 17) { 508 file << "void RS_KERNEL test(int in) {\n"; 509 } else { 510 file << "void root(const int* in) {\n"; 511 } 512 file << calls.str(); 513 file << "}\n"; 514 515 return true; 516} 517 518bool generateStubsWhiteList(const string& slangTestDirectory, unsigned int maxApiLevel) { 519 unsigned int lastApiLevel = min(systemSpecification.getMaximumApiLevel(), maxApiLevel); 520 if (!generateWhiteListFile(lastApiLevel)) { 521 return false; 522 } 523 // Generate a test file for each apiLevel. 524 for (unsigned int i = kMinimumApiLevelForTests; i <= lastApiLevel; ++i) { 525 if (!generateApiTesterFile(slangTestDirectory, i)) { 526 return false; 527 } 528 } 529 return true; 530} 531