StandAlone.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  1. //
  2. // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
  3. // Copyright (C) 2013-2016 LunarG, Inc.
  4. //
  5. // All rights reserved.
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions
  9. // are met:
  10. //
  11. // Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. //
  14. // Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following
  16. // disclaimer in the documentation and/or other materials provided
  17. // with the distribution.
  18. //
  19. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  20. // contributors may be used to endorse or promote products derived
  21. // from this software without specific prior written permission.
  22. //
  23. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  26. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  27. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  28. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  29. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  30. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  31. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  33. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  34. // POSSIBILITY OF SUCH DAMAGE.
  35. //
  36. // this only applies to the standalone wrapper, not the front end in general
  37. #ifndef _CRT_SECURE_NO_WARNINGS
  38. #define _CRT_SECURE_NO_WARNINGS
  39. #endif
  40. #include "ResourceLimits.h"
  41. #include "Worklist.h"
  42. #include "DirStackFileIncluder.h"
  43. #include "./../glslang/Include/ShHandle.h"
  44. #include "./../glslang/Include/revision.h"
  45. #include "./../glslang/Public/ShaderLang.h"
  46. #include "../SPIRV/GlslangToSpv.h"
  47. #include "../SPIRV/GLSL.std.450.h"
  48. #include "../SPIRV/doc.h"
  49. #include "../SPIRV/disassemble.h"
  50. #include <cstring>
  51. #include <cstdlib>
  52. #include <cctype>
  53. #include <cmath>
  54. #include <array>
  55. #include <map>
  56. #include <memory>
  57. #include <thread>
  58. #include "../glslang/OSDependent/osinclude.h"
  59. extern "C" {
  60. SH_IMPORT_EXPORT void ShOutputHtml();
  61. }
  62. // Command-line options
  63. enum TOptions {
  64. EOptionNone = 0,
  65. EOptionIntermediate = (1 << 0),
  66. EOptionSuppressInfolog = (1 << 1),
  67. EOptionMemoryLeakMode = (1 << 2),
  68. EOptionRelaxedErrors = (1 << 3),
  69. EOptionGiveWarnings = (1 << 4),
  70. EOptionLinkProgram = (1 << 5),
  71. EOptionMultiThreaded = (1 << 6),
  72. EOptionDumpConfig = (1 << 7),
  73. EOptionDumpReflection = (1 << 8),
  74. EOptionSuppressWarnings = (1 << 9),
  75. EOptionDumpVersions = (1 << 10),
  76. EOptionSpv = (1 << 11),
  77. EOptionHumanReadableSpv = (1 << 12),
  78. EOptionVulkanRules = (1 << 13),
  79. EOptionDefaultDesktop = (1 << 14),
  80. EOptionOutputPreprocessed = (1 << 15),
  81. EOptionOutputHexadecimal = (1 << 16),
  82. EOptionReadHlsl = (1 << 17),
  83. EOptionCascadingErrors = (1 << 18),
  84. EOptionAutoMapBindings = (1 << 19),
  85. EOptionFlattenUniformArrays = (1 << 20),
  86. EOptionNoStorageFormat = (1 << 21),
  87. EOptionKeepUncalled = (1 << 22),
  88. EOptionHlslOffsets = (1 << 23),
  89. EOptionHlslIoMapping = (1 << 24),
  90. EOptionAutoMapLocations = (1 << 25),
  91. EOptionDebug = (1 << 26),
  92. EOptionStdin = (1 << 27),
  93. EOptionOptimizeDisable = (1 << 28),
  94. EOptionOptimizeSize = (1 << 29),
  95. EOptionInvertY = (1 << 30),
  96. EOptionDumpBareVersion = (1 << 31),
  97. };
  98. bool targetHlslFunctionality1 = false;
  99. bool SpvToolsDisassembler = false;
  100. bool SpvToolsValidate = false;
  101. bool NaNClamp = false;
  102. //
  103. // Return codes from main/exit().
  104. //
  105. enum TFailCode {
  106. ESuccess = 0,
  107. EFailUsage,
  108. EFailCompile,
  109. EFailLink,
  110. EFailCompilerCreate,
  111. EFailThreadCreate,
  112. EFailLinkerCreate
  113. };
  114. //
  115. // Forward declarations.
  116. //
  117. EShLanguage FindLanguage(const std::string& name, bool parseSuffix=true);
  118. void CompileFile(const char* fileName, ShHandle);
  119. void usage();
  120. char* ReadFileData(const char* fileName);
  121. void FreeFileData(char* data);
  122. void InfoLogMsg(const char* msg, const char* name, const int num);
  123. // Globally track if any compile or link failure.
  124. bool CompileFailed = false;
  125. bool LinkFailed = false;
  126. // array of unique places to leave the shader names and infologs for the asynchronous compiles
  127. std::vector<std::unique_ptr<glslang::TWorkItem>> WorkItems;
  128. TBuiltInResource Resources;
  129. std::string ConfigFile;
  130. //
  131. // Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
  132. //
  133. void ProcessConfigFile()
  134. {
  135. if (ConfigFile.size() == 0)
  136. Resources = glslang::DefaultTBuiltInResource;
  137. else {
  138. char* configString = ReadFileData(ConfigFile.c_str());
  139. glslang::DecodeResourceLimits(&Resources, configString);
  140. FreeFileData(configString);
  141. }
  142. }
  143. int ReflectOptions = EShReflectionDefault;
  144. int Options = 0;
  145. const char* ExecutableName = nullptr;
  146. const char* binaryFileName = nullptr;
  147. const char* entryPointName = nullptr;
  148. const char* sourceEntryPointName = nullptr;
  149. const char* shaderStageName = nullptr;
  150. const char* variableName = nullptr;
  151. bool HlslEnable16BitTypes = false;
  152. bool HlslDX9compatible = false;
  153. bool DumpBuiltinSymbols = false;
  154. std::vector<std::string> IncludeDirectoryList;
  155. // Source environment
  156. // (source 'Client' is currently the same as target 'Client')
  157. int ClientInputSemanticsVersion = 100;
  158. // Target environment
  159. glslang::EShClient Client = glslang::EShClientNone; // will stay EShClientNone if only validating
  160. glslang::EShTargetClientVersion ClientVersion; // not valid until Client is set
  161. glslang::EShTargetLanguage TargetLanguage = glslang::EShTargetNone;
  162. glslang::EShTargetLanguageVersion TargetVersion; // not valid until TargetLanguage is set
  163. std::vector<std::string> Processes; // what should be recorded by OpModuleProcessed, or equivalent
  164. // Per descriptor-set binding base data
  165. typedef std::map<unsigned int, unsigned int> TPerSetBaseBinding;
  166. std::vector<std::pair<std::string, int>> uniformLocationOverrides;
  167. int uniformBase = 0;
  168. std::array<std::array<unsigned int, EShLangCount>, glslang::EResCount> baseBinding;
  169. std::array<std::array<TPerSetBaseBinding, EShLangCount>, glslang::EResCount> baseBindingForSet;
  170. std::array<std::vector<std::string>, EShLangCount> baseResourceSetBinding;
  171. // Add things like "#define ..." to a preamble to use in the beginning of the shader.
  172. class TPreamble {
  173. public:
  174. TPreamble() { }
  175. bool isSet() const { return text.size() > 0; }
  176. const char* get() const { return text.c_str(); }
  177. // #define...
  178. void addDef(std::string def)
  179. {
  180. text.append("#define ");
  181. fixLine(def);
  182. Processes.push_back("D");
  183. Processes.back().append(def);
  184. // The first "=" needs to turn into a space
  185. const size_t equal = def.find_first_of("=");
  186. if (equal != def.npos)
  187. def[equal] = ' ';
  188. text.append(def);
  189. text.append("\n");
  190. }
  191. // #undef...
  192. void addUndef(std::string undef)
  193. {
  194. text.append("#undef ");
  195. fixLine(undef);
  196. Processes.push_back("U");
  197. Processes.back().append(undef);
  198. text.append(undef);
  199. text.append("\n");
  200. }
  201. protected:
  202. void fixLine(std::string& line)
  203. {
  204. // Can't go past a newline in the line
  205. const size_t end = line.find_first_of("\n");
  206. if (end != line.npos)
  207. line = line.substr(0, end);
  208. }
  209. std::string text; // contents of preamble
  210. };
  211. TPreamble UserPreamble;
  212. //
  213. // Create the default name for saving a binary if -o is not provided.
  214. //
  215. const char* GetBinaryName(EShLanguage stage)
  216. {
  217. const char* name;
  218. if (binaryFileName == nullptr) {
  219. switch (stage) {
  220. case EShLangVertex: name = "vert.spv"; break;
  221. case EShLangTessControl: name = "tesc.spv"; break;
  222. case EShLangTessEvaluation: name = "tese.spv"; break;
  223. case EShLangGeometry: name = "geom.spv"; break;
  224. case EShLangFragment: name = "frag.spv"; break;
  225. case EShLangCompute: name = "comp.spv"; break;
  226. #ifdef NV_EXTENSIONS
  227. case EShLangRayGenNV: name = "rgen.spv"; break;
  228. case EShLangIntersectNV: name = "rint.spv"; break;
  229. case EShLangAnyHitNV: name = "rahit.spv"; break;
  230. case EShLangClosestHitNV: name = "rchit.spv"; break;
  231. case EShLangMissNV: name = "rmiss.spv"; break;
  232. case EShLangCallableNV: name = "rcall.spv"; break;
  233. case EShLangMeshNV: name = "mesh.spv"; break;
  234. case EShLangTaskNV: name = "task.spv"; break;
  235. #endif
  236. default: name = "unknown"; break;
  237. }
  238. } else
  239. name = binaryFileName;
  240. return name;
  241. }
  242. //
  243. // *.conf => this is a config file that can set limits/resources
  244. //
  245. bool SetConfigFile(const std::string& name)
  246. {
  247. if (name.size() < 5)
  248. return false;
  249. if (name.compare(name.size() - 5, 5, ".conf") == 0) {
  250. ConfigFile = name;
  251. return true;
  252. }
  253. return false;
  254. }
  255. //
  256. // Give error and exit with failure code.
  257. //
  258. void Error(const char* message)
  259. {
  260. fprintf(stderr, "%s: Error %s (use -h for usage)\n", ExecutableName, message);
  261. exit(EFailUsage);
  262. }
  263. //
  264. // Process an optional binding base of one the forms:
  265. // --argname [stage] base // base for stage (if given) or all stages (if not)
  266. // --argname [stage] [base set]... // set/base pairs: set the base for given binding set.
  267. // Where stage is one of the forms accepted by FindLanguage, and base is an integer
  268. //
  269. void ProcessBindingBase(int& argc, char**& argv, glslang::TResourceType res)
  270. {
  271. if (argc < 2)
  272. usage();
  273. EShLanguage lang = EShLangCount;
  274. int singleBase = 0;
  275. TPerSetBaseBinding perSetBase;
  276. int arg = 1;
  277. // Parse stage, if given
  278. if (!isdigit(argv[arg][0])) {
  279. if (argc < 3) // this form needs one more argument
  280. usage();
  281. lang = FindLanguage(argv[arg++], false);
  282. }
  283. if ((argc - arg) > 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
  284. // Parse a per-set binding base
  285. while ((argc - arg) > 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
  286. const int baseNum = atoi(argv[arg++]);
  287. const int setNum = atoi(argv[arg++]);
  288. perSetBase[setNum] = baseNum;
  289. }
  290. } else {
  291. // Parse single binding base
  292. singleBase = atoi(argv[arg++]);
  293. }
  294. argc -= (arg-1);
  295. argv += (arg-1);
  296. // Set one or all languages
  297. const int langMin = (lang < EShLangCount) ? lang+0 : 0;
  298. const int langMax = (lang < EShLangCount) ? lang+1 : EShLangCount;
  299. for (int lang = langMin; lang < langMax; ++lang) {
  300. if (!perSetBase.empty())
  301. baseBindingForSet[res][lang].insert(perSetBase.begin(), perSetBase.end());
  302. else
  303. baseBinding[res][lang] = singleBase;
  304. }
  305. }
  306. void ProcessResourceSetBindingBase(int& argc, char**& argv, std::array<std::vector<std::string>, EShLangCount>& base)
  307. {
  308. if (argc < 2)
  309. usage();
  310. if (!isdigit(argv[1][0])) {
  311. if (argc < 3) // this form needs one more argument
  312. usage();
  313. // Parse form: --argname stage [regname set base...], or:
  314. // --argname stage set
  315. const EShLanguage lang = FindLanguage(argv[1], false);
  316. argc--;
  317. argv++;
  318. while (argc > 1 && argv[1] != nullptr && argv[1][0] != '-') {
  319. base[lang].push_back(argv[1]);
  320. argc--;
  321. argv++;
  322. }
  323. // Must have one arg, or a multiple of three (for [regname set binding] triples)
  324. if (base[lang].size() != 1 && (base[lang].size() % 3) != 0)
  325. usage();
  326. } else {
  327. // Parse form: --argname set
  328. for (int lang=0; lang<EShLangCount; ++lang)
  329. base[lang].push_back(argv[1]);
  330. argc--;
  331. argv++;
  332. }
  333. }
  334. //
  335. // Do all command-line argument parsing. This includes building up the work-items
  336. // to be processed later, and saving all the command-line options.
  337. //
  338. // Does not return (it exits) if command-line is fatally flawed.
  339. //
  340. void ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>>& workItems, int argc, char* argv[])
  341. {
  342. for (int res = 0; res < glslang::EResCount; ++res)
  343. baseBinding[res].fill(0);
  344. ExecutableName = argv[0];
  345. workItems.reserve(argc);
  346. const auto bumpArg = [&]() {
  347. if (argc > 0) {
  348. argc--;
  349. argv++;
  350. }
  351. };
  352. // read a string directly attached to a single-letter option
  353. const auto getStringOperand = [&](const char* desc) {
  354. if (argv[0][2] == 0) {
  355. printf("%s must immediately follow option (no spaces)\n", desc);
  356. exit(EFailUsage);
  357. }
  358. return argv[0] + 2;
  359. };
  360. // read a number attached to a single-letter option
  361. const auto getAttachedNumber = [&](const char* desc) {
  362. int num = atoi(argv[0] + 2);
  363. if (num == 0) {
  364. printf("%s: expected attached non-0 number\n", desc);
  365. exit(EFailUsage);
  366. }
  367. return num;
  368. };
  369. // minimum needed (without overriding something else) to target Vulkan SPIR-V
  370. const auto setVulkanSpv = []() {
  371. if (Client == glslang::EShClientNone)
  372. ClientVersion = glslang::EShTargetVulkan_1_0;
  373. Client = glslang::EShClientVulkan;
  374. Options |= EOptionSpv;
  375. Options |= EOptionVulkanRules;
  376. Options |= EOptionLinkProgram;
  377. };
  378. // minimum needed (without overriding something else) to target OpenGL SPIR-V
  379. const auto setOpenGlSpv = []() {
  380. if (Client == glslang::EShClientNone)
  381. ClientVersion = glslang::EShTargetOpenGL_450;
  382. Client = glslang::EShClientOpenGL;
  383. Options |= EOptionSpv;
  384. Options |= EOptionLinkProgram;
  385. // undo a -H default to Vulkan
  386. Options &= ~EOptionVulkanRules;
  387. };
  388. const auto getUniformOverride = [getStringOperand]() {
  389. const char *arg = getStringOperand("-u<name>:<location>");
  390. const char *split = strchr(arg, ':');
  391. if (split == NULL) {
  392. printf("%s: missing location\n", arg);
  393. exit(EFailUsage);
  394. }
  395. errno = 0;
  396. int location = ::strtol(split + 1, NULL, 10);
  397. if (errno) {
  398. printf("%s: invalid location\n", arg);
  399. exit(EFailUsage);
  400. }
  401. return std::make_pair(std::string(arg, split - arg), location);
  402. };
  403. for (bumpArg(); argc >= 1; bumpArg()) {
  404. if (argv[0][0] == '-') {
  405. switch (argv[0][1]) {
  406. case '-':
  407. {
  408. std::string lowerword(argv[0]+2);
  409. std::transform(lowerword.begin(), lowerword.end(), lowerword.begin(), ::tolower);
  410. // handle --word style options
  411. if (lowerword == "auto-map-bindings" || // synonyms
  412. lowerword == "auto-map-binding" ||
  413. lowerword == "amb") {
  414. Options |= EOptionAutoMapBindings;
  415. } else if (lowerword == "auto-map-locations" || // synonyms
  416. lowerword == "aml") {
  417. Options |= EOptionAutoMapLocations;
  418. } else if (lowerword == "uniform-base") {
  419. if (argc <= 1)
  420. Error("no <base> provided for --uniform-base");
  421. uniformBase = ::strtol(argv[1], NULL, 10);
  422. bumpArg();
  423. break;
  424. } else if (lowerword == "client") {
  425. if (argc > 1) {
  426. if (strcmp(argv[1], "vulkan100") == 0)
  427. setVulkanSpv();
  428. else if (strcmp(argv[1], "opengl100") == 0)
  429. setOpenGlSpv();
  430. else
  431. Error("--client expects vulkan100 or opengl100");
  432. }
  433. bumpArg();
  434. } else if (lowerword == "dump-builtin-symbols") {
  435. DumpBuiltinSymbols = true;
  436. } else if (lowerword == "entry-point") {
  437. entryPointName = argv[1];
  438. if (argc <= 1)
  439. Error("no <name> provided for --entry-point");
  440. bumpArg();
  441. } else if (lowerword == "flatten-uniform-arrays" || // synonyms
  442. lowerword == "flatten-uniform-array" ||
  443. lowerword == "fua") {
  444. Options |= EOptionFlattenUniformArrays;
  445. } else if (lowerword == "hlsl-offsets") {
  446. Options |= EOptionHlslOffsets;
  447. } else if (lowerword == "hlsl-iomap" ||
  448. lowerword == "hlsl-iomapper" ||
  449. lowerword == "hlsl-iomapping") {
  450. Options |= EOptionHlslIoMapping;
  451. } else if (lowerword == "hlsl-enable-16bit-types") {
  452. HlslEnable16BitTypes = true;
  453. } else if (lowerword == "hlsl-dx9-compatible") {
  454. HlslDX9compatible = true;
  455. } else if (lowerword == "invert-y" || // synonyms
  456. lowerword == "iy") {
  457. Options |= EOptionInvertY;
  458. } else if (lowerword == "keep-uncalled" || // synonyms
  459. lowerword == "ku") {
  460. Options |= EOptionKeepUncalled;
  461. } else if (lowerword == "nan-clamp") {
  462. NaNClamp = true;
  463. } else if (lowerword == "no-storage-format" || // synonyms
  464. lowerword == "nsf") {
  465. Options |= EOptionNoStorageFormat;
  466. } else if (lowerword == "relaxed-errors") {
  467. Options |= EOptionRelaxedErrors;
  468. } else if (lowerword == "reflect-strict-array-suffix") {
  469. ReflectOptions |= EShReflectionStrictArraySuffix;
  470. } else if (lowerword == "reflect-basic-array-suffix") {
  471. ReflectOptions |= EShReflectionBasicArraySuffix;
  472. } else if (lowerword == "reflect-intermediate-io") {
  473. ReflectOptions |= EShReflectionIntermediateIO;
  474. } else if (lowerword == "reflect-separate-buffers") {
  475. ReflectOptions |= EShReflectionSeparateBuffers;
  476. } else if (lowerword == "reflect-all-block-variables") {
  477. ReflectOptions |= EShReflectionAllBlockVariables;
  478. } else if (lowerword == "reflect-unwrap-io-blocks") {
  479. ReflectOptions |= EShReflectionUnwrapIOBlocks;
  480. } else if (lowerword == "resource-set-bindings" || // synonyms
  481. lowerword == "resource-set-binding" ||
  482. lowerword == "rsb") {
  483. ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
  484. } else if (lowerword == "shift-image-bindings" || // synonyms
  485. lowerword == "shift-image-binding" ||
  486. lowerword == "sib") {
  487. ProcessBindingBase(argc, argv, glslang::EResImage);
  488. } else if (lowerword == "shift-sampler-bindings" || // synonyms
  489. lowerword == "shift-sampler-binding" ||
  490. lowerword == "ssb") {
  491. ProcessBindingBase(argc, argv, glslang::EResSampler);
  492. } else if (lowerword == "shift-uav-bindings" || // synonyms
  493. lowerword == "shift-uav-binding" ||
  494. lowerword == "suavb") {
  495. ProcessBindingBase(argc, argv, glslang::EResUav);
  496. } else if (lowerword == "shift-texture-bindings" || // synonyms
  497. lowerword == "shift-texture-binding" ||
  498. lowerword == "stb") {
  499. ProcessBindingBase(argc, argv, glslang::EResTexture);
  500. } else if (lowerword == "shift-ubo-bindings" || // synonyms
  501. lowerword == "shift-ubo-binding" ||
  502. lowerword == "shift-cbuffer-bindings" ||
  503. lowerword == "shift-cbuffer-binding" ||
  504. lowerword == "sub" ||
  505. lowerword == "scb") {
  506. ProcessBindingBase(argc, argv, glslang::EResUbo);
  507. } else if (lowerword == "shift-ssbo-bindings" || // synonyms
  508. lowerword == "shift-ssbo-binding" ||
  509. lowerword == "sbb") {
  510. ProcessBindingBase(argc, argv, glslang::EResSsbo);
  511. } else if (lowerword == "source-entrypoint" || // synonyms
  512. lowerword == "sep") {
  513. if (argc <= 1)
  514. Error("no <entry-point> provided for --source-entrypoint");
  515. sourceEntryPointName = argv[1];
  516. bumpArg();
  517. break;
  518. } else if (lowerword == "spirv-dis") {
  519. SpvToolsDisassembler = true;
  520. } else if (lowerword == "spirv-val") {
  521. SpvToolsValidate = true;
  522. } else if (lowerword == "stdin") {
  523. Options |= EOptionStdin;
  524. shaderStageName = argv[1];
  525. } else if (lowerword == "suppress-warnings") {
  526. Options |= EOptionSuppressWarnings;
  527. } else if (lowerword == "target-env") {
  528. if (argc > 1) {
  529. if (strcmp(argv[1], "vulkan1.0") == 0) {
  530. setVulkanSpv();
  531. ClientVersion = glslang::EShTargetVulkan_1_0;
  532. } else if (strcmp(argv[1], "vulkan1.1") == 0) {
  533. setVulkanSpv();
  534. ClientVersion = glslang::EShTargetVulkan_1_1;
  535. } else if (strcmp(argv[1], "opengl") == 0) {
  536. setOpenGlSpv();
  537. ClientVersion = glslang::EShTargetOpenGL_450;
  538. } else if (strcmp(argv[1], "spirv1.0") == 0) {
  539. TargetLanguage = glslang::EShTargetSpv;
  540. TargetVersion = glslang::EShTargetSpv_1_0;
  541. } else if (strcmp(argv[1], "spirv1.1") == 0) {
  542. TargetLanguage = glslang::EShTargetSpv;
  543. TargetVersion = glslang::EShTargetSpv_1_1;
  544. } else if (strcmp(argv[1], "spirv1.2") == 0) {
  545. TargetLanguage = glslang::EShTargetSpv;
  546. TargetVersion = glslang::EShTargetSpv_1_2;
  547. } else if (strcmp(argv[1], "spirv1.3") == 0) {
  548. TargetLanguage = glslang::EShTargetSpv;
  549. TargetVersion = glslang::EShTargetSpv_1_3;
  550. } else if (strcmp(argv[1], "spirv1.4") == 0) {
  551. TargetLanguage = glslang::EShTargetSpv;
  552. TargetVersion = glslang::EShTargetSpv_1_4;
  553. } else
  554. Error("--target-env expected one of: vulkan1.0, vulkan1.1, opengl, spirv1.0, spirv1.1, spirv1.2, or spirv1.3");
  555. }
  556. bumpArg();
  557. } else if (lowerword == "variable-name" || // synonyms
  558. lowerword == "vn") {
  559. Options |= EOptionOutputHexadecimal;
  560. if (argc <= 1)
  561. Error("no <C-variable-name> provided for --variable-name");
  562. variableName = argv[1];
  563. bumpArg();
  564. break;
  565. } else if (lowerword == "version") {
  566. Options |= EOptionDumpVersions;
  567. } else {
  568. usage();
  569. }
  570. }
  571. break;
  572. case 'C':
  573. Options |= EOptionCascadingErrors;
  574. break;
  575. case 'D':
  576. if (argv[0][2] == 0)
  577. Options |= EOptionReadHlsl;
  578. else
  579. UserPreamble.addDef(getStringOperand("-D<macro> macro name"));
  580. break;
  581. case 'u':
  582. uniformLocationOverrides.push_back(getUniformOverride());
  583. break;
  584. case 'E':
  585. Options |= EOptionOutputPreprocessed;
  586. break;
  587. case 'G':
  588. // OpenGL client
  589. setOpenGlSpv();
  590. if (argv[0][2] != 0)
  591. ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
  592. break;
  593. case 'H':
  594. Options |= EOptionHumanReadableSpv;
  595. if ((Options & EOptionSpv) == 0) {
  596. // default to Vulkan
  597. setVulkanSpv();
  598. }
  599. break;
  600. case 'I':
  601. IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
  602. break;
  603. case 'O':
  604. if (argv[0][2] == 'd')
  605. Options |= EOptionOptimizeDisable;
  606. else if (argv[0][2] == 's')
  607. #if ENABLE_OPT
  608. Options |= EOptionOptimizeSize;
  609. #else
  610. Error("-Os not available; optimizer not linked");
  611. #endif
  612. else
  613. Error("unknown -O option");
  614. break;
  615. case 'S':
  616. if (argc <= 1)
  617. Error("no <stage> specified for -S");
  618. shaderStageName = argv[1];
  619. bumpArg();
  620. break;
  621. case 'U':
  622. UserPreamble.addUndef(getStringOperand("-U<macro>: macro name"));
  623. break;
  624. case 'V':
  625. setVulkanSpv();
  626. if (argv[0][2] != 0)
  627. ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
  628. break;
  629. case 'c':
  630. Options |= EOptionDumpConfig;
  631. break;
  632. case 'd':
  633. if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
  634. strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
  635. Options |= EOptionDumpBareVersion;
  636. else
  637. Options |= EOptionDefaultDesktop;
  638. break;
  639. case 'e':
  640. entryPointName = argv[1];
  641. if (argc <= 1)
  642. Error("no <name> provided for -e");
  643. bumpArg();
  644. break;
  645. case 'f':
  646. if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
  647. targetHlslFunctionality1 = true;
  648. else
  649. Error("-f: expected hlsl_functionality1");
  650. break;
  651. case 'g':
  652. Options |= EOptionDebug;
  653. break;
  654. case 'h':
  655. usage();
  656. break;
  657. case 'i':
  658. Options |= EOptionIntermediate;
  659. break;
  660. case 'l':
  661. Options |= EOptionLinkProgram;
  662. break;
  663. case 'm':
  664. Options |= EOptionMemoryLeakMode;
  665. break;
  666. case 'o':
  667. if (argc <= 1)
  668. Error("no <file> provided for -o");
  669. binaryFileName = argv[1];
  670. bumpArg();
  671. break;
  672. case 'q':
  673. Options |= EOptionDumpReflection;
  674. break;
  675. case 'r':
  676. Options |= EOptionRelaxedErrors;
  677. break;
  678. case 's':
  679. Options |= EOptionSuppressInfolog;
  680. break;
  681. case 't':
  682. Options |= EOptionMultiThreaded;
  683. break;
  684. case 'v':
  685. Options |= EOptionDumpVersions;
  686. break;
  687. case 'w':
  688. Options |= EOptionSuppressWarnings;
  689. break;
  690. case 'x':
  691. Options |= EOptionOutputHexadecimal;
  692. break;
  693. default:
  694. usage();
  695. break;
  696. }
  697. } else {
  698. std::string name(argv[0]);
  699. if (! SetConfigFile(name)) {
  700. workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
  701. }
  702. }
  703. }
  704. // Make sure that -S is always specified if --stdin is specified
  705. if ((Options & EOptionStdin) && shaderStageName == nullptr)
  706. Error("must provide -S when --stdin is given");
  707. // Make sure that -E is not specified alongside linking (which includes SPV generation)
  708. if ((Options & EOptionOutputPreprocessed) && (Options & EOptionLinkProgram))
  709. Error("can't use -E when linking is selected");
  710. // -o or -x makes no sense if there is no target binary
  711. if (binaryFileName && (Options & EOptionSpv) == 0)
  712. Error("no binary generation requested (e.g., -V)");
  713. if ((Options & EOptionFlattenUniformArrays) != 0 &&
  714. (Options & EOptionReadHlsl) == 0)
  715. Error("uniform array flattening only valid when compiling HLSL source.");
  716. // rationalize client and target language
  717. if (TargetLanguage == glslang::EShTargetNone) {
  718. switch (ClientVersion) {
  719. case glslang::EShTargetVulkan_1_0:
  720. TargetLanguage = glslang::EShTargetSpv;
  721. TargetVersion = glslang::EShTargetSpv_1_0;
  722. break;
  723. case glslang::EShTargetVulkan_1_1:
  724. TargetLanguage = glslang::EShTargetSpv;
  725. TargetVersion = glslang::EShTargetSpv_1_3;
  726. break;
  727. case glslang::EShTargetOpenGL_450:
  728. TargetLanguage = glslang::EShTargetSpv;
  729. TargetVersion = glslang::EShTargetSpv_1_0;
  730. break;
  731. default:
  732. break;
  733. }
  734. }
  735. if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
  736. Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
  737. }
  738. //
  739. // Translate the meaningful subset of command-line options to parser-behavior options.
  740. //
  741. void SetMessageOptions(EShMessages& messages)
  742. {
  743. if (Options & EOptionRelaxedErrors)
  744. messages = (EShMessages)(messages | EShMsgRelaxedErrors);
  745. if (Options & EOptionIntermediate)
  746. messages = (EShMessages)(messages | EShMsgAST);
  747. if (Options & EOptionSuppressWarnings)
  748. messages = (EShMessages)(messages | EShMsgSuppressWarnings);
  749. if (Options & EOptionSpv)
  750. messages = (EShMessages)(messages | EShMsgSpvRules);
  751. if (Options & EOptionVulkanRules)
  752. messages = (EShMessages)(messages | EShMsgVulkanRules);
  753. if (Options & EOptionOutputPreprocessed)
  754. messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
  755. if (Options & EOptionReadHlsl)
  756. messages = (EShMessages)(messages | EShMsgReadHlsl);
  757. if (Options & EOptionCascadingErrors)
  758. messages = (EShMessages)(messages | EShMsgCascadingErrors);
  759. if (Options & EOptionKeepUncalled)
  760. messages = (EShMessages)(messages | EShMsgKeepUncalled);
  761. if (Options & EOptionHlslOffsets)
  762. messages = (EShMessages)(messages | EShMsgHlslOffsets);
  763. if (Options & EOptionDebug)
  764. messages = (EShMessages)(messages | EShMsgDebugInfo);
  765. if (HlslEnable16BitTypes)
  766. messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
  767. if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
  768. messages = (EShMessages)(messages | EShMsgHlslLegalization);
  769. if (HlslDX9compatible)
  770. messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
  771. if (DumpBuiltinSymbols)
  772. messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
  773. }
  774. //
  775. // Thread entry point, for non-linking asynchronous mode.
  776. //
  777. void CompileShaders(glslang::TWorklist& worklist)
  778. {
  779. if (Options & EOptionDebug)
  780. Error("cannot generate debug information unless linking to generate code");
  781. glslang::TWorkItem* workItem;
  782. if (Options & EOptionStdin) {
  783. if (worklist.remove(workItem)) {
  784. ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), Options);
  785. if (compiler == nullptr)
  786. return;
  787. CompileFile("stdin", compiler);
  788. if (! (Options & EOptionSuppressInfolog))
  789. workItem->results = ShGetInfoLog(compiler);
  790. ShDestruct(compiler);
  791. }
  792. } else {
  793. while (worklist.remove(workItem)) {
  794. ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), Options);
  795. if (compiler == 0)
  796. return;
  797. CompileFile(workItem->name.c_str(), compiler);
  798. if (! (Options & EOptionSuppressInfolog))
  799. workItem->results = ShGetInfoLog(compiler);
  800. ShDestruct(compiler);
  801. }
  802. }
  803. }
  804. // Outputs the given string, but only if it is non-null and non-empty.
  805. // This prevents erroneous newlines from appearing.
  806. void PutsIfNonEmpty(const char* str)
  807. {
  808. if (str && str[0]) {
  809. puts(str);
  810. }
  811. }
  812. // Outputs the given string to stderr, but only if it is non-null and non-empty.
  813. // This prevents erroneous newlines from appearing.
  814. void StderrIfNonEmpty(const char* str)
  815. {
  816. if (str && str[0])
  817. fprintf(stderr, "%s\n", str);
  818. }
  819. // Simple bundling of what makes a compilation unit for ease in passing around,
  820. // and separation of handling file IO versus API (programmatic) compilation.
  821. struct ShaderCompUnit {
  822. EShLanguage stage;
  823. static const int maxCount = 1;
  824. int count; // live number of strings/names
  825. const char* text[maxCount]; // memory owned/managed externally
  826. std::string fileName[maxCount]; // hold's the memory, but...
  827. const char* fileNameList[maxCount]; // downstream interface wants pointers
  828. ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
  829. ShaderCompUnit(const ShaderCompUnit& rhs)
  830. {
  831. stage = rhs.stage;
  832. count = rhs.count;
  833. for (int i = 0; i < count; ++i) {
  834. fileName[i] = rhs.fileName[i];
  835. text[i] = rhs.text[i];
  836. fileNameList[i] = rhs.fileName[i].c_str();
  837. }
  838. }
  839. void addString(std::string& ifileName, const char* itext)
  840. {
  841. assert(count < maxCount);
  842. fileName[count] = ifileName;
  843. text[count] = itext;
  844. fileNameList[count] = fileName[count].c_str();
  845. ++count;
  846. }
  847. };
  848. //
  849. // For linking mode: Will independently parse each compilation unit, but then put them
  850. // in the same program and link them together, making at most one linked module per
  851. // pipeline stage.
  852. //
  853. // Uses the new C++ interface instead of the old handle-based interface.
  854. //
  855. void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
  856. {
  857. // keep track of what to free
  858. std::list<glslang::TShader*> shaders;
  859. EShMessages messages = EShMsgDefault;
  860. SetMessageOptions(messages);
  861. //
  862. // Per-shader processing...
  863. //
  864. glslang::TProgram& program = *new glslang::TProgram;
  865. for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
  866. const auto &compUnit = *it;
  867. glslang::TShader* shader = new glslang::TShader(compUnit.stage);
  868. shader->setStringsWithLengthsAndNames(compUnit.text, NULL, compUnit.fileNameList, compUnit.count);
  869. if (entryPointName)
  870. shader->setEntryPoint(entryPointName);
  871. if (sourceEntryPointName) {
  872. if (entryPointName == nullptr)
  873. printf("Warning: Changing source entry point name without setting an entry-point name.\n"
  874. "Use '-e <name>'.\n");
  875. shader->setSourceEntryPoint(sourceEntryPointName);
  876. }
  877. if (UserPreamble.isSet())
  878. shader->setPreamble(UserPreamble.get());
  879. shader->addProcesses(Processes);
  880. // Set IO mapper binding shift values
  881. for (int r = 0; r < glslang::EResCount; ++r) {
  882. const glslang::TResourceType res = glslang::TResourceType(r);
  883. // Set base bindings
  884. shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
  885. // Set bindings for particular resource sets
  886. // TODO: use a range based for loop here, when available in all environments.
  887. for (auto i = baseBindingForSet[res][compUnit.stage].begin();
  888. i != baseBindingForSet[res][compUnit.stage].end(); ++i)
  889. shader->setShiftBindingForSet(res, i->second, i->first);
  890. }
  891. shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
  892. shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
  893. shader->setNanMinMaxClamp(NaNClamp);
  894. shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
  895. if (Options & EOptionHlslIoMapping)
  896. shader->setHlslIoMapping(true);
  897. if (Options & EOptionAutoMapBindings)
  898. shader->setAutoMapBindings(true);
  899. if (Options & EOptionAutoMapLocations)
  900. shader->setAutoMapLocations(true);
  901. if (Options & EOptionInvertY)
  902. shader->setInvertY(true);
  903. for (auto& uniOverride : uniformLocationOverrides) {
  904. shader->addUniformLocationOverride(uniOverride.first.c_str(),
  905. uniOverride.second);
  906. }
  907. shader->setUniformLocationBase(uniformBase);
  908. // Set up the environment, some subsettings take precedence over earlier
  909. // ways of setting things.
  910. if (Options & EOptionSpv) {
  911. shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
  912. : glslang::EShSourceGlsl,
  913. compUnit.stage, Client, ClientInputSemanticsVersion);
  914. shader->setEnvClient(Client, ClientVersion);
  915. shader->setEnvTarget(TargetLanguage, TargetVersion);
  916. if (targetHlslFunctionality1)
  917. shader->setEnvTargetHlslFunctionality1();
  918. }
  919. shaders.push_back(shader);
  920. const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
  921. DirStackFileIncluder includer;
  922. std::for_each(IncludeDirectoryList.rbegin(), IncludeDirectoryList.rend(), [&includer](const std::string& dir) {
  923. includer.pushExternalLocalDirectory(dir); });
  924. if (Options & EOptionOutputPreprocessed) {
  925. std::string str;
  926. if (shader->preprocess(&Resources, defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
  927. PutsIfNonEmpty(str.c_str());
  928. } else {
  929. CompileFailed = true;
  930. }
  931. StderrIfNonEmpty(shader->getInfoLog());
  932. StderrIfNonEmpty(shader->getInfoDebugLog());
  933. continue;
  934. }
  935. if (! shader->parse(&Resources, defaultVersion, false, messages, includer))
  936. CompileFailed = true;
  937. program.addShader(shader);
  938. if (! (Options & EOptionSuppressInfolog) &&
  939. ! (Options & EOptionMemoryLeakMode)) {
  940. PutsIfNonEmpty(compUnit.fileName[0].c_str());
  941. PutsIfNonEmpty(shader->getInfoLog());
  942. PutsIfNonEmpty(shader->getInfoDebugLog());
  943. }
  944. }
  945. //
  946. // Program-level processing...
  947. //
  948. // Link
  949. if (! (Options & EOptionOutputPreprocessed) && ! program.link(messages))
  950. LinkFailed = true;
  951. // Map IO
  952. if (Options & EOptionSpv) {
  953. if (!program.mapIO())
  954. LinkFailed = true;
  955. }
  956. // Report
  957. if (! (Options & EOptionSuppressInfolog) &&
  958. ! (Options & EOptionMemoryLeakMode)) {
  959. PutsIfNonEmpty(program.getInfoLog());
  960. PutsIfNonEmpty(program.getInfoDebugLog());
  961. }
  962. // Reflect
  963. if (Options & EOptionDumpReflection) {
  964. program.buildReflection(ReflectOptions);
  965. program.dumpReflection();
  966. }
  967. // Dump SPIR-V
  968. if (Options & EOptionSpv) {
  969. if (CompileFailed || LinkFailed)
  970. printf("SPIR-V is not generated for failed compile or link\n");
  971. else {
  972. for (int stage = 0; stage < EShLangCount; ++stage) {
  973. if (program.getIntermediate((EShLanguage)stage)) {
  974. std::vector<unsigned int> spirv;
  975. std::string warningsErrors;
  976. spv::SpvBuildLogger logger;
  977. glslang::SpvOptions spvOptions;
  978. if (Options & EOptionDebug)
  979. spvOptions.generateDebugInfo = true;
  980. spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
  981. spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
  982. spvOptions.disassemble = SpvToolsDisassembler;
  983. spvOptions.validate = SpvToolsValidate;
  984. glslang::GlslangToSpv(*program.getIntermediate((EShLanguage)stage), spirv, &logger, &spvOptions);
  985. // Dump the spv to a file or stdout, etc., but only if not doing
  986. // memory/perf testing, as it's not internal to programmatic use.
  987. if (! (Options & EOptionMemoryLeakMode)) {
  988. printf("%s", logger.getAllMessages().c_str());
  989. if (Options & EOptionOutputHexadecimal) {
  990. glslang::OutputSpvHex(spirv, GetBinaryName((EShLanguage)stage), variableName);
  991. } else {
  992. glslang::OutputSpvBin(spirv, GetBinaryName((EShLanguage)stage));
  993. }
  994. if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
  995. spv::Disassemble(std::cout, spirv);
  996. }
  997. }
  998. }
  999. }
  1000. }
  1001. // Free everything up, program has to go before the shaders
  1002. // because it might have merged stuff from the shaders, and
  1003. // the stuff from the shaders has to have its destructors called
  1004. // before the pools holding the memory in the shaders is freed.
  1005. delete &program;
  1006. while (shaders.size() > 0) {
  1007. delete shaders.back();
  1008. shaders.pop_back();
  1009. }
  1010. }
  1011. //
  1012. // Do file IO part of compile and link, handing off the pure
  1013. // API/programmatic mode to CompileAndLinkShaderUnits(), which can
  1014. // be put in a loop for testing memory footprint and performance.
  1015. //
  1016. // This is just for linking mode: meaning all the shaders will be put into the
  1017. // the same program linked together.
  1018. //
  1019. // This means there are a limited number of work items (not multi-threading mode)
  1020. // and that the point is testing at the linking level. Hence, to enable
  1021. // performance and memory testing, the actual compile/link can be put in
  1022. // a loop, independent of processing the work items and file IO.
  1023. //
  1024. void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
  1025. {
  1026. std::vector<ShaderCompUnit> compUnits;
  1027. // If this is using stdin, we can't really detect multiple different file
  1028. // units by input type. We need to assume that we're just being given one
  1029. // file of a certain type.
  1030. if ((Options & EOptionStdin) != 0) {
  1031. ShaderCompUnit compUnit(FindLanguage("stdin"));
  1032. std::istreambuf_iterator<char> begin(std::cin), end;
  1033. std::string tempString(begin, end);
  1034. char* fileText = strdup(tempString.c_str());
  1035. std::string fileName = "stdin";
  1036. compUnit.addString(fileName, fileText);
  1037. compUnits.push_back(compUnit);
  1038. } else {
  1039. // Transfer all the work items from to a simple list of
  1040. // of compilation units. (We don't care about the thread
  1041. // work-item distribution properties in this path, which
  1042. // is okay due to the limited number of shaders, know since
  1043. // they are all getting linked together.)
  1044. glslang::TWorkItem* workItem;
  1045. while (Worklist.remove(workItem)) {
  1046. ShaderCompUnit compUnit(FindLanguage(workItem->name));
  1047. char* fileText = ReadFileData(workItem->name.c_str());
  1048. if (fileText == nullptr)
  1049. usage();
  1050. compUnit.addString(workItem->name, fileText);
  1051. compUnits.push_back(compUnit);
  1052. }
  1053. }
  1054. // Actual call to programmatic processing of compile and link,
  1055. // in a loop for testing memory and performance. This part contains
  1056. // all the perf/memory that a programmatic consumer will care about.
  1057. for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
  1058. for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
  1059. CompileAndLinkShaderUnits(compUnits);
  1060. if (Options & EOptionMemoryLeakMode)
  1061. glslang::OS_DumpMemoryCounters();
  1062. }
  1063. // free memory from ReadFileData, which got stored in a const char*
  1064. // as the first string above
  1065. for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
  1066. FreeFileData(const_cast<char*>(it->text[0]));
  1067. }
  1068. int singleMain()
  1069. {
  1070. glslang::TWorklist workList;
  1071. std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
  1072. assert(item);
  1073. workList.add(item.get());
  1074. });
  1075. if (Options & EOptionDumpConfig) {
  1076. printf("%s", glslang::GetDefaultTBuiltInResourceString().c_str());
  1077. if (workList.empty())
  1078. return ESuccess;
  1079. }
  1080. if (Options & EOptionDumpBareVersion) {
  1081. printf("%d.%d.%d\n",
  1082. glslang::GetSpirvGeneratorVersion(), GLSLANG_MINOR_VERSION, GLSLANG_PATCH_LEVEL);
  1083. if (workList.empty())
  1084. return ESuccess;
  1085. } else if (Options & EOptionDumpVersions) {
  1086. printf("Glslang Version: %d.%d.%d\n",
  1087. glslang::GetSpirvGeneratorVersion(), GLSLANG_MINOR_VERSION, GLSLANG_PATCH_LEVEL);
  1088. printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
  1089. printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
  1090. std::string spirvVersion;
  1091. glslang::GetSpirvVersion(spirvVersion);
  1092. printf("SPIR-V Version %s\n", spirvVersion.c_str());
  1093. printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
  1094. printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
  1095. printf("SPIR-V Generator Version %d\n", glslang::GetSpirvGeneratorVersion());
  1096. printf("GL_KHR_vulkan_glsl version %d\n", 100);
  1097. printf("ARB_GL_gl_spirv version %d\n", 100);
  1098. if (workList.empty())
  1099. return ESuccess;
  1100. }
  1101. if (workList.empty() && ((Options & EOptionStdin) == 0)) {
  1102. usage();
  1103. }
  1104. if (Options & EOptionStdin) {
  1105. WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
  1106. workList.add(WorkItems.back().get());
  1107. }
  1108. ProcessConfigFile();
  1109. if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
  1110. Error("ERROR: HLSL requires SPIR-V code generation (or preprocessing only)");
  1111. //
  1112. // Two modes:
  1113. // 1) linking all arguments together, single-threaded, new C++ interface
  1114. // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
  1115. //
  1116. if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
  1117. glslang::InitializeProcess();
  1118. glslang::InitializeProcess(); // also test reference counting of users
  1119. glslang::InitializeProcess(); // also test reference counting of users
  1120. glslang::FinalizeProcess(); // also test reference counting of users
  1121. glslang::FinalizeProcess(); // also test reference counting of users
  1122. CompileAndLinkShaderFiles(workList);
  1123. glslang::FinalizeProcess();
  1124. } else {
  1125. ShInitialize();
  1126. ShInitialize(); // also test reference counting of users
  1127. ShFinalize(); // also test reference counting of users
  1128. bool printShaderNames = workList.size() > 1;
  1129. if (Options & EOptionMultiThreaded) {
  1130. std::array<std::thread, 16> threads;
  1131. for (unsigned int t = 0; t < threads.size(); ++t) {
  1132. threads[t] = std::thread(CompileShaders, std::ref(workList));
  1133. if (threads[t].get_id() == std::thread::id()) {
  1134. fprintf(stderr, "Failed to create thread\n");
  1135. return EFailThreadCreate;
  1136. }
  1137. }
  1138. std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
  1139. } else
  1140. CompileShaders(workList);
  1141. // Print out all the resulting infologs
  1142. for (size_t w = 0; w < WorkItems.size(); ++w) {
  1143. if (WorkItems[w]) {
  1144. if (printShaderNames || WorkItems[w]->results.size() > 0)
  1145. PutsIfNonEmpty(WorkItems[w]->name.c_str());
  1146. PutsIfNonEmpty(WorkItems[w]->results.c_str());
  1147. }
  1148. }
  1149. ShFinalize();
  1150. }
  1151. if (CompileFailed)
  1152. return EFailCompile;
  1153. if (LinkFailed)
  1154. return EFailLink;
  1155. return 0;
  1156. }
  1157. int C_DECL main(int argc, char* argv[])
  1158. {
  1159. ProcessArguments(WorkItems, argc, argv);
  1160. int ret = 0;
  1161. // Loop over the entire init/finalize cycle to watch memory changes
  1162. const int iterations = 1;
  1163. if (iterations > 1)
  1164. glslang::OS_DumpMemoryCounters();
  1165. for (int i = 0; i < iterations; ++i) {
  1166. ret = singleMain();
  1167. if (iterations > 1)
  1168. glslang::OS_DumpMemoryCounters();
  1169. }
  1170. return ret;
  1171. }
  1172. //
  1173. // Deduce the language from the filename. Files must end in one of the
  1174. // following extensions:
  1175. //
  1176. // .vert = vertex
  1177. // .tesc = tessellation control
  1178. // .tese = tessellation evaluation
  1179. // .geom = geometry
  1180. // .frag = fragment
  1181. // .comp = compute
  1182. // .rgen = ray generation
  1183. // .rint = ray intersection
  1184. // .rahit = ray any hit
  1185. // .rchit = ray closest hit
  1186. // .rmiss = ray miss
  1187. // .rcall = ray callable
  1188. // .mesh = mesh
  1189. // .task = task
  1190. // Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
  1191. // where <stage> is one of the stages listed above.
  1192. //
  1193. EShLanguage FindLanguage(const std::string& name, bool parseStageName)
  1194. {
  1195. std::string stageName;
  1196. if (shaderStageName)
  1197. stageName = shaderStageName;
  1198. else if (parseStageName) {
  1199. // Note: "first" extension means "first from the end", i.e.
  1200. // if the file is named foo.vert.glsl, then "glsl" is first,
  1201. // "vert" is second.
  1202. size_t firstExtStart = name.find_last_of(".");
  1203. bool hasFirstExt = firstExtStart != std::string::npos;
  1204. size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
  1205. bool hasSecondExt = secondExtStart != std::string::npos;
  1206. std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
  1207. bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
  1208. if (usesUnifiedExt && firstExt == "hlsl")
  1209. Options |= EOptionReadHlsl;
  1210. if (hasFirstExt && !usesUnifiedExt)
  1211. stageName = firstExt;
  1212. else if (usesUnifiedExt && hasSecondExt)
  1213. stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
  1214. else {
  1215. usage();
  1216. return EShLangVertex;
  1217. }
  1218. } else
  1219. stageName = name;
  1220. if (stageName == "vert")
  1221. return EShLangVertex;
  1222. else if (stageName == "tesc")
  1223. return EShLangTessControl;
  1224. else if (stageName == "tese")
  1225. return EShLangTessEvaluation;
  1226. else if (stageName == "geom")
  1227. return EShLangGeometry;
  1228. else if (stageName == "frag")
  1229. return EShLangFragment;
  1230. else if (stageName == "comp")
  1231. return EShLangCompute;
  1232. #ifdef NV_EXTENSIONS
  1233. else if (stageName == "rgen")
  1234. return EShLangRayGenNV;
  1235. else if (stageName == "rint")
  1236. return EShLangIntersectNV;
  1237. else if (stageName == "rahit")
  1238. return EShLangAnyHitNV;
  1239. else if (stageName == "rchit")
  1240. return EShLangClosestHitNV;
  1241. else if (stageName == "rmiss")
  1242. return EShLangMissNV;
  1243. else if (stageName == "rcall")
  1244. return EShLangCallableNV;
  1245. else if (stageName == "mesh")
  1246. return EShLangMeshNV;
  1247. else if (stageName == "task")
  1248. return EShLangTaskNV;
  1249. #endif
  1250. usage();
  1251. return EShLangVertex;
  1252. }
  1253. //
  1254. // Read a file's data into a string, and compile it using the old interface ShCompile,
  1255. // for non-linkable results.
  1256. //
  1257. void CompileFile(const char* fileName, ShHandle compiler)
  1258. {
  1259. int ret = 0;
  1260. char* shaderString;
  1261. if ((Options & EOptionStdin) != 0) {
  1262. std::istreambuf_iterator<char> begin(std::cin), end;
  1263. std::string tempString(begin, end);
  1264. shaderString = strdup(tempString.c_str());
  1265. } else {
  1266. shaderString = ReadFileData(fileName);
  1267. }
  1268. // move to length-based strings, rather than null-terminated strings
  1269. int* lengths = new int[1];
  1270. lengths[0] = (int)strlen(shaderString);
  1271. EShMessages messages = EShMsgDefault;
  1272. SetMessageOptions(messages);
  1273. if (UserPreamble.isSet())
  1274. Error("-D and -U options require -l (linking)\n");
  1275. for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
  1276. for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
  1277. // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1278. ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1279. // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
  1280. // "or should be l", "ine 1", "string 5\n", "float glo", "bal",
  1281. // ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
  1282. // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
  1283. // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1284. }
  1285. if (Options & EOptionMemoryLeakMode)
  1286. glslang::OS_DumpMemoryCounters();
  1287. }
  1288. delete [] lengths;
  1289. FreeFileData(shaderString);
  1290. if (ret == 0)
  1291. CompileFailed = true;
  1292. }
  1293. //
  1294. // print usage to stdout
  1295. //
  1296. void usage()
  1297. {
  1298. printf("Usage: glslangValidator [option]... [file]...\n"
  1299. "\n"
  1300. "'file' can end in .<stage> for auto-stage classification, where <stage> is:\n"
  1301. " .conf to provide a config file that replaces the default configuration\n"
  1302. " (see -c option below for generating a template)\n"
  1303. " .vert for a vertex shader\n"
  1304. " .tesc for a tessellation control shader\n"
  1305. " .tese for a tessellation evaluation shader\n"
  1306. " .geom for a geometry shader\n"
  1307. " .frag for a fragment shader\n"
  1308. " .comp for a compute shader\n"
  1309. #ifdef NV_EXTENSIONS
  1310. " .mesh for a mesh shader\n"
  1311. " .task for a task shader\n"
  1312. " .rgen for a ray generation shader\n"
  1313. " .rint for a ray intersection shader\n"
  1314. " .rahit for a ray any hit shader\n"
  1315. " .rchit for a ray closest hit shader\n"
  1316. " .rmiss for a ray miss shader\n"
  1317. " .rcall for a ray callable shader\n"
  1318. #endif
  1319. " .glsl for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes\n"
  1320. " .hlsl for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes\n"
  1321. "\n"
  1322. "Options:\n"
  1323. " -C cascading errors; risk crash from accumulation of error recoveries\n"
  1324. " -D input is HLSL (this is the default when any suffix is .hlsl)\n"
  1325. " -D<macro=def>\n"
  1326. " -D<macro> define a pre-processor macro\n"
  1327. " -E print pre-processed GLSL; cannot be used with -l;\n"
  1328. " errors will appear on stderr\n"
  1329. " -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
  1330. " default file name is <stage>.spv (-o overrides this);\n"
  1331. " 'ver', when present, is the version of the input semantics,\n"
  1332. " which will appear in #define GL_SPIRV ver;\n"
  1333. " '--client opengl100' is the same as -G100;\n"
  1334. " a '--target-env' for OpenGL will also imply '-G'\n"
  1335. " -H print human readable form of SPIR-V; turns on -V\n"
  1336. " -I<dir> add dir to the include search path; includer's directory\n"
  1337. " is searched first, followed by left-to-right order of -I\n"
  1338. " -Od disables optimization; may cause illegal SPIR-V for HLSL\n"
  1339. " -Os optimizes SPIR-V to minimize size\n"
  1340. " -S <stage> uses specified stage rather than parsing the file extension\n"
  1341. " choices for <stage> are vert, tesc, tese, geom, frag, or comp\n"
  1342. " -U<macro> undefine a pre-processor macro\n"
  1343. " -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
  1344. " default file name is <stage>.spv (-o overrides this)\n"
  1345. " 'ver', when present, is the version of the input semantics,\n"
  1346. " which will appear in #define VULKAN ver\n"
  1347. " '--client vulkan100' is the same as -V100\n"
  1348. " a '--target-env' for Vulkan will also imply '-V'\n"
  1349. " -c configuration dump;\n"
  1350. " creates the default configuration file (redirect to a .conf file)\n"
  1351. " -d default to desktop (#version 110) when there is no shader #version\n"
  1352. " (default is ES version 100)\n"
  1353. " -e <name> | --entry-point <name>\n"
  1354. " specify <name> as the entry-point function name\n"
  1355. " -f{hlsl_functionality1}\n"
  1356. " 'hlsl_functionality1' enables use of the\n"
  1357. " SPV_GOOGLE_hlsl_functionality1 extension\n"
  1358. " -g generate debug information\n"
  1359. " -h print this usage message\n"
  1360. " -i intermediate tree (glslang AST) is printed out\n"
  1361. " -l link all input files together to form a single module\n"
  1362. " -m memory leak mode\n"
  1363. " -o <file> save binary to <file>, requires a binary option (e.g., -V)\n"
  1364. " -q dump reflection query database\n"
  1365. " -r | --relaxed-errors"
  1366. " relaxed GLSL semantic error-checking mode\n"
  1367. " -s silence syntax and semantic error reporting\n"
  1368. " -t multi-threaded mode\n"
  1369. " -v | --version\n"
  1370. " print version strings\n"
  1371. " -w | --suppress-warnings\n"
  1372. " suppress GLSL warnings, except as required by \"#extension : warn\"\n"
  1373. " -x save binary output as text-based 32-bit hexadecimal numbers\n"
  1374. " -u<name>:<loc> specify a uniform location override for --aml\n"
  1375. " --uniform-base <base> set a base to use for generated uniform locations\n"
  1376. " --auto-map-bindings | --amb automatically bind uniform variables\n"
  1377. " without explicit bindings\n"
  1378. " --auto-map-locations | --aml automatically locate input/output lacking\n"
  1379. " 'location' (fragile, not cross stage)\n"
  1380. " --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
  1381. " --dump-builtin-symbols prints builtin symbol table prior each compile\n"
  1382. " -dumpfullversion | -dumpversion print bare major.minor.patchlevel\n"
  1383. " --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to\n"
  1384. " scalars\n"
  1385. " --hlsl-offsets allow block offsets to follow HLSL rules\n"
  1386. " works independently of source language\n"
  1387. " --hlsl-iomap perform IO mapping in HLSL register space\n"
  1388. " --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL\n"
  1389. " --hlsl-dx9-compatible interprets sampler declarations as a\n"
  1390. " texture/sampler combo like DirectX9 would.\n"
  1391. " --invert-y | --iy invert position.Y output in vertex shader\n"
  1392. " --keep-uncalled | --ku don't eliminate uncalled functions\n"
  1393. " --nan-clamp favor non-NaN operand in min, max, and clamp\n"
  1394. " --no-storage-format | --nsf use Unknown image format\n"
  1395. " --reflect-strict-array-suffix use strict array suffix rules when\n"
  1396. " reflecting\n"
  1397. " --reflect-basic-array-suffix arrays of basic types will have trailing [0]\n"
  1398. " --reflect-intermediate-io reflection includes inputs/outputs of linked\n"
  1399. " shaders rather than just vertex/fragment\n"
  1400. " --reflect-separate-buffers reflect buffer variables and blocks\n"
  1401. " separately to uniforms\n"
  1402. " --reflect-all-block-variables reflect all variables in blocks, whether\n"
  1403. " inactive or active\n"
  1404. " --reflect-unwrap-io-blocks unwrap input/output blocks the same as\n"
  1405. " uniform blocks\n"
  1406. " --resource-set-binding [stage] name set binding\n"
  1407. " set descriptor set and binding for\n"
  1408. " individual resources\n"
  1409. " --resource-set-binding [stage] set\n"
  1410. " set descriptor set for all resources\n"
  1411. " --rsb synonym for --resource-set-binding\n"
  1412. " --shift-image-binding [stage] num\n"
  1413. " base binding number for images (uav)\n"
  1414. " --shift-image-binding [stage] [num set]...\n"
  1415. " per-descriptor-set shift values\n"
  1416. " --sib synonym for --shift-image-binding\n"
  1417. " --shift-sampler-binding [stage] num\n"
  1418. " base binding number for samplers\n"
  1419. " --shift-sampler-binding [stage] [num set]...\n"
  1420. " per-descriptor-set shift values\n"
  1421. " --ssb synonym for --shift-sampler-binding\n"
  1422. " --shift-ssbo-binding [stage] num base binding number for SSBOs\n"
  1423. " --shift-ssbo-binding [stage] [num set]...\n"
  1424. " per-descriptor-set shift values\n"
  1425. " --sbb synonym for --shift-ssbo-binding\n"
  1426. " --shift-texture-binding [stage] num\n"
  1427. " base binding number for textures\n"
  1428. " --shift-texture-binding [stage] [num set]...\n"
  1429. " per-descriptor-set shift values\n"
  1430. " --stb synonym for --shift-texture-binding\n"
  1431. " --shift-uav-binding [stage] num base binding number for UAVs\n"
  1432. " --shift-uav-binding [stage] [num set]...\n"
  1433. " per-descriptor-set shift values\n"
  1434. " --suavb synonym for --shift-uav-binding\n"
  1435. " --shift-UBO-binding [stage] num base binding number for UBOs\n"
  1436. " --shift-UBO-binding [stage] [num set]...\n"
  1437. " per-descriptor-set shift values\n"
  1438. " --sub synonym for --shift-UBO-binding\n"
  1439. " --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding\n"
  1440. " --spirv-dis output standard-form disassembly; works only\n"
  1441. " when a SPIR-V generation option is also used\n"
  1442. " --spirv-val execute the SPIRV-Tools validator\n"
  1443. " --source-entrypoint <name> the given shader source function is\n"
  1444. " renamed to be the <name> given in -e\n"
  1445. " --sep synonym for --source-entrypoint\n"
  1446. " --stdin read from stdin instead of from a file;\n"
  1447. " requires providing the shader stage using -S\n"
  1448. " --target-env {vulkan1.0 | vulkan1.1 | opengl | \n"
  1449. " spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3}\n"
  1450. " set execution environment that emitted code\n"
  1451. " will execute in (versus source language\n"
  1452. " semantics selected by --client) defaults:\n"
  1453. " * 'vulkan1.0' under '--client vulkan<ver>'\n"
  1454. " * 'opengl' under '--client opengl<ver>'\n"
  1455. " * 'spirv1.0' under --target-env vulkan1.0\n"
  1456. " * 'spirv1.3' under --target-env vulkan1.1\n"
  1457. " multiple --targen-env can be specified.\n"
  1458. " --variable-name <name>\n"
  1459. " --vn <name> creates a C header file that contains a\n"
  1460. " uint32_t array named <name>\n"
  1461. " initialized with the shader binary code\n"
  1462. );
  1463. exit(EFailUsage);
  1464. }
  1465. #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
  1466. #include <errno.h>
  1467. int fopen_s(
  1468. FILE** pFile,
  1469. const char* filename,
  1470. const char* mode
  1471. )
  1472. {
  1473. if (!pFile || !filename || !mode) {
  1474. return EINVAL;
  1475. }
  1476. FILE* f = fopen(filename, mode);
  1477. if (! f) {
  1478. if (errno != 0) {
  1479. return errno;
  1480. } else {
  1481. return ENOENT;
  1482. }
  1483. }
  1484. *pFile = f;
  1485. return 0;
  1486. }
  1487. #endif
  1488. //
  1489. // Malloc a string of sufficient size and read a string into it.
  1490. //
  1491. char* ReadFileData(const char* fileName)
  1492. {
  1493. FILE *in = nullptr;
  1494. int errorCode = fopen_s(&in, fileName, "r");
  1495. if (errorCode || in == nullptr)
  1496. Error("unable to open input file");
  1497. int count = 0;
  1498. while (fgetc(in) != EOF)
  1499. count++;
  1500. fseek(in, 0, SEEK_SET);
  1501. char* return_data = (char*)malloc(count + 1); // freed in FreeFileData()
  1502. if ((int)fread(return_data, 1, count, in) != count) {
  1503. free(return_data);
  1504. Error("can't read input file");
  1505. }
  1506. return_data[count] = '\0';
  1507. fclose(in);
  1508. return return_data;
  1509. }
  1510. void FreeFileData(char* data)
  1511. {
  1512. free(data);
  1513. }
  1514. void InfoLogMsg(const char* msg, const char* name, const int num)
  1515. {
  1516. if (num >= 0 )
  1517. printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
  1518. else
  1519. printf("#### %s %s INFO LOG ####\n", msg, name);
  1520. }