StandAlone.cpp 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. //
  2. // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
  3. // Copyright (C) 2013-2016 LunarG, Inc.
  4. // Copyright (C) 2016-2020 Google, Inc.
  5. // Modifications Copyright(C) 2021 Advanced Micro Devices, Inc.All rights reserved.
  6. //
  7. // All rights reserved.
  8. //
  9. // Redistribution and use in source and binary forms, with or without
  10. // modification, are permitted provided that the following conditions
  11. // are met:
  12. //
  13. // Redistributions of source code must retain the above copyright
  14. // notice, this list of conditions and the following disclaimer.
  15. //
  16. // Redistributions in binary form must reproduce the above
  17. // copyright notice, this list of conditions and the following
  18. // disclaimer in the documentation and/or other materials provided
  19. // with the distribution.
  20. //
  21. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  22. // contributors may be used to endorse or promote products derived
  23. // from this software without specific prior written permission.
  24. //
  25. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  28. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  29. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  30. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  31. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  32. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  33. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  34. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  35. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  36. // POSSIBILITY OF SUCH DAMAGE.
  37. //
  38. // this only applies to the standalone wrapper, not the front end in general
  39. #ifndef _CRT_SECURE_NO_WARNINGS
  40. #define _CRT_SECURE_NO_WARNINGS
  41. #endif
  42. #include "glslang/Public/ResourceLimits.h"
  43. #include "Worklist.h"
  44. #include "DirStackFileIncluder.h"
  45. #include "./../glslang/Include/ShHandle.h"
  46. #include "./../glslang/Public/ShaderLang.h"
  47. #include "../glslang/MachineIndependent/localintermediate.h"
  48. #include "../SPIRV/GlslangToSpv.h"
  49. #include "../SPIRV/GLSL.std.450.h"
  50. #include "../SPIRV/doc.h"
  51. #include "../SPIRV/disassemble.h"
  52. #include <array>
  53. #include <atomic>
  54. #include <cctype>
  55. #include <cmath>
  56. #include <cstdlib>
  57. #include <cstring>
  58. #include <map>
  59. #include <memory>
  60. #include <set>
  61. #include <thread>
  62. #include "../glslang/OSDependent/osinclude.h"
  63. // Build-time generated includes
  64. #include "glslang/build_info.h"
  65. #include "glslang/glsl_intrinsic_header.h"
  66. extern "C" {
  67. GLSLANG_EXPORT void ShOutputHtml();
  68. }
  69. // Command-line options
  70. enum TOptions : uint64_t {
  71. EOptionNone = 0,
  72. EOptionIntermediate = (1ull << 0),
  73. EOptionSuppressInfolog = (1ull << 1),
  74. EOptionMemoryLeakMode = (1ull << 2),
  75. EOptionRelaxedErrors = (1ull << 3),
  76. EOptionGiveWarnings = (1ull << 4),
  77. EOptionLinkProgram = (1ull << 5),
  78. EOptionMultiThreaded = (1ull << 6),
  79. EOptionDumpConfig = (1ull << 7),
  80. EOptionDumpReflection = (1ull << 8),
  81. EOptionSuppressWarnings = (1ull << 9),
  82. EOptionDumpVersions = (1ull << 10),
  83. EOptionSpv = (1ull << 11),
  84. EOptionHumanReadableSpv = (1ull << 12),
  85. EOptionVulkanRules = (1ull << 13),
  86. EOptionDefaultDesktop = (1ull << 14),
  87. EOptionOutputPreprocessed = (1ull << 15),
  88. EOptionOutputHexadecimal = (1ull << 16),
  89. EOptionReadHlsl = (1ull << 17),
  90. EOptionCascadingErrors = (1ull << 18),
  91. EOptionAutoMapBindings = (1ull << 19),
  92. EOptionFlattenUniformArrays = (1ull << 20),
  93. EOptionNoStorageFormat = (1ull << 21),
  94. EOptionKeepUncalled = (1ull << 22),
  95. EOptionHlslOffsets = (1ull << 23),
  96. EOptionHlslIoMapping = (1ull << 24),
  97. EOptionAutoMapLocations = (1ull << 25),
  98. EOptionDebug = (1ull << 26),
  99. EOptionStdin = (1ull << 27),
  100. EOptionOptimizeDisable = (1ull << 28),
  101. EOptionOptimizeSize = (1ull << 29),
  102. EOptionInvertY = (1ull << 30),
  103. EOptionDumpBareVersion = (1ull << 31),
  104. EOptionCompileOnly = (1ull << 32),
  105. EOptionDisplayErrorColumn = (1ull << 33),
  106. };
  107. bool targetHlslFunctionality1 = false;
  108. bool SpvToolsDisassembler = false;
  109. bool SpvToolsValidate = false;
  110. bool NaNClamp = false;
  111. bool stripDebugInfo = false;
  112. bool emitNonSemanticShaderDebugInfo = false;
  113. bool emitNonSemanticShaderDebugSource = false;
  114. bool beQuiet = false;
  115. bool VulkanRulesRelaxed = false;
  116. bool autoSampledTextures = false;
  117. //
  118. // Return codes from main/exit().
  119. //
  120. enum TFailCode {
  121. ESuccess = 0,
  122. EFailUsage,
  123. EFailCompile,
  124. EFailLink,
  125. EFailCompilerCreate,
  126. EFailThreadCreate,
  127. EFailLinkerCreate
  128. };
  129. //
  130. // Forward declarations.
  131. //
  132. EShLanguage FindLanguage(const std::string& name, bool parseSuffix=true);
  133. void CompileFile(const char* fileName, ShHandle);
  134. void usage();
  135. char* ReadFileData(const char* fileName);
  136. void FreeFileData(char* data);
  137. void InfoLogMsg(const char* msg, const char* name, const int num);
  138. // Globally track if any compile or link failure.
  139. std::atomic<int8_t> CompileFailed{0};
  140. std::atomic<int8_t> LinkFailed{0};
  141. std::atomic<int8_t> CompileOrLinkFailed{0};
  142. // array of unique places to leave the shader names and infologs for the asynchronous compiles
  143. std::vector<std::unique_ptr<glslang::TWorkItem>> WorkItems;
  144. std::string ConfigFile;
  145. //
  146. // Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
  147. //
  148. void ProcessConfigFile()
  149. {
  150. if (ConfigFile.size() == 0)
  151. *GetResources() = *GetDefaultResources();
  152. else {
  153. char* configString = ReadFileData(ConfigFile.c_str());
  154. DecodeResourceLimits(GetResources(), configString);
  155. FreeFileData(configString);
  156. }
  157. }
  158. int ReflectOptions = EShReflectionDefault;
  159. std::underlying_type_t<TOptions> Options = EOptionNone;
  160. const char* ExecutableName = nullptr;
  161. const char* binaryFileName = nullptr;
  162. const char* depencyFileName = nullptr;
  163. const char* entryPointName = nullptr;
  164. const char* sourceEntryPointName = nullptr;
  165. const char* shaderStageName = nullptr;
  166. const char* variableName = nullptr;
  167. bool HlslEnable16BitTypes = false;
  168. bool HlslDX9compatible = false;
  169. bool HlslDxPositionW = false;
  170. bool EnhancedMsgs = false;
  171. bool AbsolutePath = false;
  172. bool DumpBuiltinSymbols = false;
  173. std::vector<std::string> IncludeDirectoryList;
  174. // Source environment
  175. // (source 'Client' is currently the same as target 'Client')
  176. int ClientInputSemanticsVersion = 100;
  177. // Target environment
  178. glslang::EShClient Client = glslang::EShClientNone; // will stay EShClientNone if only validating
  179. glslang::EShTargetClientVersion ClientVersion; // not valid until Client is set
  180. glslang::EShTargetLanguage TargetLanguage = glslang::EShTargetNone;
  181. glslang::EShTargetLanguageVersion TargetVersion; // not valid until TargetLanguage is set
  182. // GLSL version
  183. int GlslVersion = 0; // GLSL version specified on CLI, overrides #version in shader source
  184. std::vector<std::string> Processes; // what should be recorded by OpModuleProcessed, or equivalent
  185. // Per descriptor-set binding base data
  186. typedef std::map<unsigned int, unsigned int> TPerSetBaseBinding;
  187. std::vector<std::pair<std::string, int>> uniformLocationOverrides;
  188. int uniformBase = 0;
  189. std::array<std::array<unsigned int, EShLangCount>, glslang::EResCount> baseBinding;
  190. std::array<std::array<TPerSetBaseBinding, EShLangCount>, glslang::EResCount> baseBindingForSet;
  191. std::array<std::vector<std::string>, EShLangCount> baseResourceSetBinding;
  192. std::vector<std::pair<std::string, glslang::TBlockStorageClass>> blockStorageOverrides;
  193. bool setGlobalUniformBlock = false;
  194. std::string globalUniformName;
  195. unsigned int globalUniformBinding;
  196. unsigned int globalUniformSet;
  197. bool setGlobalBufferBlock = false;
  198. std::string atomicCounterBlockName;
  199. unsigned int atomicCounterBlockSet;
  200. // Add things like "#define ..." to a preamble to use in the beginning of the shader.
  201. class TPreamble {
  202. public:
  203. TPreamble() { }
  204. bool isSet() const { return text.size() > 0; }
  205. const char* get() const { return text.c_str(); }
  206. // #define...
  207. void addDef(std::string def)
  208. {
  209. text.append("#define ");
  210. fixLine(def);
  211. Processes.push_back("define-macro ");
  212. Processes.back().append(def);
  213. // The first "=" needs to turn into a space
  214. const size_t equal = def.find_first_of("=");
  215. if (equal != def.npos)
  216. def[equal] = ' ';
  217. text.append(def);
  218. text.append("\n");
  219. }
  220. // #undef...
  221. void addUndef(std::string undef)
  222. {
  223. text.append("#undef ");
  224. fixLine(undef);
  225. Processes.push_back("undef-macro ");
  226. Processes.back().append(undef);
  227. text.append(undef);
  228. text.append("\n");
  229. }
  230. void addText(std::string preambleText)
  231. {
  232. fixLine(preambleText);
  233. Processes.push_back("preamble-text");
  234. Processes.back().append(preambleText);
  235. text.append(preambleText);
  236. text.append("\n");
  237. }
  238. protected:
  239. void fixLine(std::string& line)
  240. {
  241. // Can't go past a newline in the line
  242. const size_t end = line.find_first_of("\n");
  243. if (end != line.npos)
  244. line = line.substr(0, end);
  245. }
  246. std::string text; // contents of preamble
  247. };
  248. // Track the user's #define and #undef from the command line.
  249. TPreamble UserPreamble;
  250. std::string PreambleString;
  251. //
  252. // Create the default name for saving a binary if -o is not provided.
  253. //
  254. const char* GetBinaryName(EShLanguage stage)
  255. {
  256. const char* name;
  257. if (binaryFileName == nullptr) {
  258. switch (stage) {
  259. case EShLangVertex: name = "vert.spv"; break;
  260. case EShLangTessControl: name = "tesc.spv"; break;
  261. case EShLangTessEvaluation: name = "tese.spv"; break;
  262. case EShLangGeometry: name = "geom.spv"; break;
  263. case EShLangFragment: name = "frag.spv"; break;
  264. case EShLangCompute: name = "comp.spv"; break;
  265. case EShLangRayGen: name = "rgen.spv"; break;
  266. case EShLangIntersect: name = "rint.spv"; break;
  267. case EShLangAnyHit: name = "rahit.spv"; break;
  268. case EShLangClosestHit: name = "rchit.spv"; break;
  269. case EShLangMiss: name = "rmiss.spv"; break;
  270. case EShLangCallable: name = "rcall.spv"; break;
  271. case EShLangMesh : name = "mesh.spv"; break;
  272. case EShLangTask : name = "task.spv"; break;
  273. default: name = "unknown"; break;
  274. }
  275. } else
  276. name = binaryFileName;
  277. return name;
  278. }
  279. //
  280. // *.conf => this is a config file that can set limits/resources
  281. //
  282. bool SetConfigFile(const std::string& name)
  283. {
  284. if (name.size() < 5)
  285. return false;
  286. if (name.compare(name.size() - 5, 5, ".conf") == 0) {
  287. ConfigFile = name;
  288. return true;
  289. }
  290. return false;
  291. }
  292. //
  293. // Give error and exit with failure code.
  294. //
  295. void Error(const char* message, const char* detail = nullptr)
  296. {
  297. fprintf(stderr, "%s: Error: ", ExecutableName);
  298. if (detail != nullptr)
  299. fprintf(stderr, "%s: ", detail);
  300. fprintf(stderr, "%s (use -h for usage)\n", message);
  301. exit(EFailUsage);
  302. }
  303. //
  304. // Process an optional binding base of one the forms:
  305. // --argname [stage] base // base for stage (if given) or all stages (if not)
  306. // --argname [stage] [base set]... // set/base pairs: set the base for given binding set.
  307. // Where stage is one of the forms accepted by FindLanguage, and base is an integer
  308. //
  309. void ProcessBindingBase(int& argc, char**& argv, glslang::TResourceType res)
  310. {
  311. if (argc < 2)
  312. usage();
  313. EShLanguage lang = EShLangCount;
  314. int singleBase = 0;
  315. TPerSetBaseBinding perSetBase;
  316. int arg = 1;
  317. // Parse stage, if given
  318. if (!isdigit(argv[arg][0])) {
  319. if (argc < 3) // this form needs one more argument
  320. usage();
  321. lang = FindLanguage(argv[arg++], false);
  322. }
  323. if ((argc - arg) >= 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
  324. // Parse a per-set binding base
  325. do {
  326. const int baseNum = atoi(argv[arg++]);
  327. const int setNum = atoi(argv[arg++]);
  328. perSetBase[setNum] = baseNum;
  329. } while ((argc - arg) >= 2 && isdigit(argv[arg + 0][0]) && isdigit(argv[arg + 1][0]));
  330. } else {
  331. // Parse single binding base
  332. singleBase = atoi(argv[arg++]);
  333. }
  334. argc -= (arg-1);
  335. argv += (arg-1);
  336. // Set one or all languages
  337. const int langMin = (lang < EShLangCount) ? lang+0 : 0;
  338. const int langMax = (lang < EShLangCount) ? lang+1 : EShLangCount;
  339. for (int lang = langMin; lang < langMax; ++lang) {
  340. if (!perSetBase.empty())
  341. baseBindingForSet[res][lang].insert(perSetBase.begin(), perSetBase.end());
  342. else
  343. baseBinding[res][lang] = singleBase;
  344. }
  345. }
  346. void ProcessResourceSetBindingBase(int& argc, char**& argv, std::array<std::vector<std::string>, EShLangCount>& base)
  347. {
  348. if (argc < 2)
  349. usage();
  350. if (!isdigit(argv[1][0])) {
  351. if (argc < 3) // this form needs one more argument
  352. usage();
  353. // Parse form: --argname stage [regname set base...], or:
  354. // --argname stage set
  355. const EShLanguage lang = FindLanguage(argv[1], false);
  356. argc--;
  357. argv++;
  358. while (argc > 1 && argv[1] != nullptr && argv[1][0] != '-') {
  359. base[lang].push_back(argv[1]);
  360. argc--;
  361. argv++;
  362. }
  363. // Must have one arg, or a multiple of three (for [regname set binding] triples)
  364. if (base[lang].size() != 1 && (base[lang].size() % 3) != 0)
  365. usage();
  366. } else {
  367. // Parse form: --argname set
  368. for (int lang=0; lang<EShLangCount; ++lang)
  369. base[lang].push_back(argv[1]);
  370. argc--;
  371. argv++;
  372. }
  373. }
  374. //
  375. // Process an optional binding base of one the forms:
  376. // --argname name {uniform|buffer|push_constant}
  377. void ProcessBlockStorage(int& argc, char**& argv, std::vector<std::pair<std::string, glslang::TBlockStorageClass>>& storage)
  378. {
  379. if (argc < 3)
  380. usage();
  381. glslang::TBlockStorageClass blockStorage = glslang::EbsNone;
  382. std::string strBacking(argv[2]);
  383. if (strBacking == "uniform")
  384. blockStorage = glslang::EbsUniform;
  385. else if (strBacking == "buffer")
  386. blockStorage = glslang::EbsStorageBuffer;
  387. else if (strBacking == "push_constant")
  388. blockStorage = glslang::EbsPushConstant;
  389. else {
  390. printf("%s: invalid block storage\n", strBacking.c_str());
  391. usage();
  392. }
  393. storage.push_back(std::make_pair(std::string(argv[1]), blockStorage));
  394. argc -= 2;
  395. argv += 2;
  396. }
  397. inline bool isNonDigit(char c) {
  398. // a non-digit character valid in a glsl identifier
  399. return (c == '_') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  400. }
  401. // whether string isa valid identifier to be used in glsl
  402. bool isValidIdentifier(const char* str) {
  403. std::string idn(str);
  404. if (idn.length() == 0) {
  405. return false;
  406. }
  407. if (idn.length() >= 3 && idn.substr(0, 3) == "gl_") {
  408. // identifiers startin with "gl_" are reserved
  409. return false;
  410. }
  411. if (!isNonDigit(idn[0])) {
  412. return false;
  413. }
  414. for (unsigned int i = 1; i < idn.length(); ++i) {
  415. if (!(isdigit(idn[i]) || isNonDigit(idn[i]))) {
  416. return false;
  417. }
  418. }
  419. return true;
  420. }
  421. // Process settings for either the global buffer block or global unfirom block
  422. // of the form:
  423. // --argname name set binding
  424. void ProcessGlobalBlockSettings(int& argc, char**& argv, std::string* name, unsigned int* set, unsigned int* binding)
  425. {
  426. if (argc < 4)
  427. usage();
  428. unsigned int curArg = 1;
  429. assert(name || set || binding);
  430. if (name) {
  431. if (!isValidIdentifier(argv[curArg])) {
  432. printf("%s: invalid identifier\n", argv[curArg]);
  433. usage();
  434. }
  435. *name = argv[curArg];
  436. curArg++;
  437. }
  438. if (set) {
  439. errno = 0;
  440. int setVal = static_cast<int>(::strtol(argv[curArg], nullptr, 10));
  441. if (errno || setVal < 0) {
  442. printf("%s: invalid set\n", argv[curArg]);
  443. usage();
  444. }
  445. *set = setVal;
  446. curArg++;
  447. }
  448. if (binding) {
  449. errno = 0;
  450. int bindingVal = static_cast<int>(::strtol(argv[curArg], nullptr, 10));
  451. if (errno || bindingVal < 0) {
  452. printf("%s: invalid binding\n", argv[curArg]);
  453. usage();
  454. }
  455. *binding = bindingVal;
  456. curArg++;
  457. }
  458. argc -= (curArg - 1);
  459. argv += (curArg - 1);
  460. }
  461. //
  462. // Do all command-line argument parsing. This includes building up the work-items
  463. // to be processed later, and saving all the command-line options.
  464. //
  465. // Does not return (it exits) if command-line is fatally flawed.
  466. //
  467. void ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>>& workItems, int argc, char* argv[])
  468. {
  469. for (int res = 0; res < glslang::EResCount; ++res)
  470. baseBinding[res].fill(0);
  471. ExecutableName = argv[0];
  472. workItems.reserve(argc);
  473. const auto bumpArg = [&]() {
  474. if (argc > 0) {
  475. argc--;
  476. argv++;
  477. }
  478. };
  479. // read a string directly attached to a single-letter option
  480. const auto getStringOperand = [&](const char* desc) {
  481. if (argv[0][2] == 0) {
  482. printf("%s must immediately follow option (no spaces)\n", desc);
  483. exit(EFailUsage);
  484. }
  485. return argv[0] + 2;
  486. };
  487. // read a number attached to a single-letter option
  488. const auto getAttachedNumber = [&](const char* desc) {
  489. int num = atoi(argv[0] + 2);
  490. if (num == 0) {
  491. printf("%s: expected attached non-0 number\n", desc);
  492. exit(EFailUsage);
  493. }
  494. return num;
  495. };
  496. // minimum needed (without overriding something else) to target Vulkan SPIR-V
  497. const auto setVulkanSpv = []() {
  498. if (Client == glslang::EShClientNone)
  499. ClientVersion = glslang::EShTargetVulkan_1_0;
  500. Client = glslang::EShClientVulkan;
  501. Options |= EOptionSpv;
  502. Options |= EOptionVulkanRules;
  503. Options |= EOptionLinkProgram;
  504. };
  505. // minimum needed (without overriding something else) to target OpenGL SPIR-V
  506. const auto setOpenGlSpv = []() {
  507. if (Client == glslang::EShClientNone)
  508. ClientVersion = glslang::EShTargetOpenGL_450;
  509. Client = glslang::EShClientOpenGL;
  510. Options |= EOptionSpv;
  511. Options |= EOptionLinkProgram;
  512. // undo a -H default to Vulkan
  513. Options &= ~EOptionVulkanRules;
  514. };
  515. const auto getUniformOverride = [getStringOperand]() {
  516. const char *arg = getStringOperand("-u<name>:<location>");
  517. const char *split = strchr(arg, ':');
  518. if (split == nullptr) {
  519. printf("%s: missing location\n", arg);
  520. exit(EFailUsage);
  521. }
  522. errno = 0;
  523. int location = static_cast<int>(::strtol(split + 1, nullptr, 10));
  524. if (errno) {
  525. printf("%s: invalid location\n", arg);
  526. exit(EFailUsage);
  527. }
  528. return std::make_pair(std::string(arg, split - arg), location);
  529. };
  530. for (bumpArg(); argc >= 1; bumpArg()) {
  531. if (argv[0][0] == '-') {
  532. switch (argv[0][1]) {
  533. case '-':
  534. {
  535. std::string lowerword(argv[0]+2);
  536. std::transform(lowerword.begin(), lowerword.end(), lowerword.begin(), ::tolower);
  537. // handle --word style options
  538. if (lowerword == "auto-map-bindings" || // synonyms
  539. lowerword == "auto-map-binding" ||
  540. lowerword == "amb") {
  541. Options |= EOptionAutoMapBindings;
  542. } else if (lowerword == "auto-map-locations" || // synonyms
  543. lowerword == "aml") {
  544. Options |= EOptionAutoMapLocations;
  545. } else if (lowerword == "uniform-base") {
  546. if (argc <= 1)
  547. Error("no <base> provided", lowerword.c_str());
  548. uniformBase = static_cast<int>(::strtol(argv[1], nullptr, 10));
  549. bumpArg();
  550. break;
  551. } else if (lowerword == "client") {
  552. if (argc > 1) {
  553. if (strcmp(argv[1], "vulkan100") == 0)
  554. setVulkanSpv();
  555. else if (strcmp(argv[1], "opengl100") == 0)
  556. setOpenGlSpv();
  557. else
  558. Error("expects vulkan100 or opengl100", lowerword.c_str());
  559. } else
  560. Error("expects vulkan100 or opengl100", lowerword.c_str());
  561. bumpArg();
  562. } else if (lowerword == "define-macro" ||
  563. lowerword == "d") {
  564. if (argc > 1)
  565. UserPreamble.addDef(argv[1]);
  566. else
  567. Error("expects <name[=def]>", argv[0]);
  568. bumpArg();
  569. } else if (lowerword == "dump-builtin-symbols") {
  570. DumpBuiltinSymbols = true;
  571. } else if (lowerword == "entry-point") {
  572. entryPointName = argv[1];
  573. if (argc <= 1)
  574. Error("no <name> provided", lowerword.c_str());
  575. bumpArg();
  576. } else if (lowerword == "flatten-uniform-arrays" || // synonyms
  577. lowerword == "flatten-uniform-array" ||
  578. lowerword == "fua") {
  579. Options |= EOptionFlattenUniformArrays;
  580. } else if (lowerword == "glsl-version") {
  581. if (argc > 1) {
  582. if (strcmp(argv[1], "100") == 0) {
  583. GlslVersion = 100;
  584. } else if (strcmp(argv[1], "110") == 0) {
  585. GlslVersion = 110;
  586. } else if (strcmp(argv[1], "120") == 0) {
  587. GlslVersion = 120;
  588. } else if (strcmp(argv[1], "130") == 0) {
  589. GlslVersion = 130;
  590. } else if (strcmp(argv[1], "140") == 0) {
  591. GlslVersion = 140;
  592. } else if (strcmp(argv[1], "150") == 0) {
  593. GlslVersion = 150;
  594. } else if (strcmp(argv[1], "300es") == 0) {
  595. GlslVersion = 300;
  596. } else if (strcmp(argv[1], "310es") == 0) {
  597. GlslVersion = 310;
  598. } else if (strcmp(argv[1], "320es") == 0) {
  599. GlslVersion = 320;
  600. } else if (strcmp(argv[1], "330") == 0) {
  601. GlslVersion = 330;
  602. } else if (strcmp(argv[1], "400") == 0) {
  603. GlslVersion = 400;
  604. } else if (strcmp(argv[1], "410") == 0) {
  605. GlslVersion = 410;
  606. } else if (strcmp(argv[1], "420") == 0) {
  607. GlslVersion = 420;
  608. } else if (strcmp(argv[1], "430") == 0) {
  609. GlslVersion = 430;
  610. } else if (strcmp(argv[1], "440") == 0) {
  611. GlslVersion = 440;
  612. } else if (strcmp(argv[1], "450") == 0) {
  613. GlslVersion = 450;
  614. } else if (strcmp(argv[1], "460") == 0) {
  615. GlslVersion = 460;
  616. } else
  617. Error("--glsl-version expected one of: 100, 110, 120, 130, 140, 150,\n"
  618. "300es, 310es, 320es, 330\n"
  619. "400, 410, 420, 430, 440, 450, 460");
  620. }
  621. bumpArg();
  622. } else if (lowerword == "hlsl-offsets") {
  623. Options |= EOptionHlslOffsets;
  624. } else if (lowerword == "hlsl-iomap" ||
  625. lowerword == "hlsl-iomapper" ||
  626. lowerword == "hlsl-iomapping") {
  627. Options |= EOptionHlslIoMapping;
  628. } else if (lowerword == "hlsl-enable-16bit-types") {
  629. HlslEnable16BitTypes = true;
  630. } else if (lowerword == "hlsl-dx9-compatible") {
  631. HlslDX9compatible = true;
  632. } else if (lowerword == "hlsl-dx-position-w") {
  633. HlslDxPositionW = true;
  634. } else if (lowerword == "enhanced-msgs") {
  635. EnhancedMsgs = true;
  636. } else if (lowerword == "absolute-path") {
  637. AbsolutePath = true;
  638. } else if (lowerword == "auto-sampled-textures") {
  639. autoSampledTextures = true;
  640. } else if (lowerword == "invert-y" || // synonyms
  641. lowerword == "iy") {
  642. Options |= EOptionInvertY;
  643. } else if (lowerword == "keep-uncalled" || // synonyms
  644. lowerword == "ku") {
  645. Options |= EOptionKeepUncalled;
  646. } else if (lowerword == "nan-clamp") {
  647. NaNClamp = true;
  648. } else if (lowerword == "no-storage-format" || // synonyms
  649. lowerword == "nsf") {
  650. Options |= EOptionNoStorageFormat;
  651. } else if (lowerword == "preamble-text" ||
  652. lowerword == "p") {
  653. if (argc > 1)
  654. UserPreamble.addText(argv[1]);
  655. else
  656. Error("expects <text>", argv[0]);
  657. bumpArg();
  658. } else if (lowerword == "relaxed-errors") {
  659. Options |= EOptionRelaxedErrors;
  660. } else if (lowerword == "reflect-strict-array-suffix") {
  661. ReflectOptions |= EShReflectionStrictArraySuffix;
  662. } else if (lowerword == "reflect-basic-array-suffix") {
  663. ReflectOptions |= EShReflectionBasicArraySuffix;
  664. } else if (lowerword == "reflect-intermediate-io") {
  665. ReflectOptions |= EShReflectionIntermediateIO;
  666. } else if (lowerword == "reflect-separate-buffers") {
  667. ReflectOptions |= EShReflectionSeparateBuffers;
  668. } else if (lowerword == "reflect-all-block-variables") {
  669. ReflectOptions |= EShReflectionAllBlockVariables;
  670. } else if (lowerword == "reflect-unwrap-io-blocks") {
  671. ReflectOptions |= EShReflectionUnwrapIOBlocks;
  672. } else if (lowerword == "reflect-all-io-variables") {
  673. ReflectOptions |= EShReflectionAllIOVariables;
  674. } else if (lowerword == "reflect-shared-std140-ubo") {
  675. ReflectOptions |= EShReflectionSharedStd140UBO;
  676. } else if (lowerword == "reflect-shared-std140-ssbo") {
  677. ReflectOptions |= EShReflectionSharedStd140SSBO;
  678. } else if (lowerword == "resource-set-bindings" || // synonyms
  679. lowerword == "resource-set-binding" ||
  680. lowerword == "rsb") {
  681. ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
  682. } else if (lowerword == "set-block-storage" ||
  683. lowerword == "sbs") {
  684. ProcessBlockStorage(argc, argv, blockStorageOverrides);
  685. } else if (lowerword == "set-atomic-counter-block" ||
  686. lowerword == "sacb") {
  687. ProcessGlobalBlockSettings(argc, argv, &atomicCounterBlockName, &atomicCounterBlockSet, nullptr);
  688. setGlobalBufferBlock = true;
  689. } else if (lowerword == "set-default-uniform-block" ||
  690. lowerword == "sdub") {
  691. ProcessGlobalBlockSettings(argc, argv, &globalUniformName, &globalUniformSet, &globalUniformBinding);
  692. setGlobalUniformBlock = true;
  693. } else if (lowerword == "shift-image-bindings" || // synonyms
  694. lowerword == "shift-image-binding" ||
  695. lowerword == "sib") {
  696. ProcessBindingBase(argc, argv, glslang::EResImage);
  697. } else if (lowerword == "shift-sampler-bindings" || // synonyms
  698. lowerword == "shift-sampler-binding" ||
  699. lowerword == "ssb") {
  700. ProcessBindingBase(argc, argv, glslang::EResSampler);
  701. } else if (lowerword == "shift-uav-bindings" || // synonyms
  702. lowerword == "shift-uav-binding" ||
  703. lowerword == "suavb") {
  704. ProcessBindingBase(argc, argv, glslang::EResUav);
  705. } else if (lowerword == "shift-texture-bindings" || // synonyms
  706. lowerword == "shift-texture-binding" ||
  707. lowerword == "stb") {
  708. ProcessBindingBase(argc, argv, glslang::EResTexture);
  709. } else if (lowerword == "shift-ubo-bindings" || // synonyms
  710. lowerword == "shift-ubo-binding" ||
  711. lowerword == "shift-cbuffer-bindings" ||
  712. lowerword == "shift-cbuffer-binding" ||
  713. lowerword == "sub" ||
  714. lowerword == "scb") {
  715. ProcessBindingBase(argc, argv, glslang::EResUbo);
  716. } else if (lowerword == "shift-ssbo-bindings" || // synonyms
  717. lowerword == "shift-ssbo-binding" ||
  718. lowerword == "sbb") {
  719. ProcessBindingBase(argc, argv, glslang::EResSsbo);
  720. } else if (lowerword == "source-entrypoint" || // synonyms
  721. lowerword == "sep") {
  722. if (argc <= 1)
  723. Error("no <entry-point> provided", lowerword.c_str());
  724. sourceEntryPointName = argv[1];
  725. bumpArg();
  726. break;
  727. } else if (lowerword == "spirv-dis") {
  728. SpvToolsDisassembler = true;
  729. } else if (lowerword == "spirv-val") {
  730. SpvToolsValidate = true;
  731. } else if (lowerword == "stdin") {
  732. Options |= EOptionStdin;
  733. shaderStageName = argv[1];
  734. } else if (lowerword == "suppress-warnings") {
  735. Options |= EOptionSuppressWarnings;
  736. } else if (lowerword == "target-env") {
  737. if (argc > 1) {
  738. if (strcmp(argv[1], "vulkan1.0") == 0) {
  739. setVulkanSpv();
  740. ClientVersion = glslang::EShTargetVulkan_1_0;
  741. } else if (strcmp(argv[1], "vulkan1.1") == 0) {
  742. setVulkanSpv();
  743. ClientVersion = glslang::EShTargetVulkan_1_1;
  744. } else if (strcmp(argv[1], "vulkan1.2") == 0) {
  745. setVulkanSpv();
  746. ClientVersion = glslang::EShTargetVulkan_1_2;
  747. } else if (strcmp(argv[1], "vulkan1.3") == 0) {
  748. setVulkanSpv();
  749. ClientVersion = glslang::EShTargetVulkan_1_3;
  750. } else if (strcmp(argv[1], "opengl") == 0) {
  751. setOpenGlSpv();
  752. ClientVersion = glslang::EShTargetOpenGL_450;
  753. } else if (strcmp(argv[1], "spirv1.0") == 0) {
  754. TargetLanguage = glslang::EShTargetSpv;
  755. TargetVersion = glslang::EShTargetSpv_1_0;
  756. } else if (strcmp(argv[1], "spirv1.1") == 0) {
  757. TargetLanguage = glslang::EShTargetSpv;
  758. TargetVersion = glslang::EShTargetSpv_1_1;
  759. } else if (strcmp(argv[1], "spirv1.2") == 0) {
  760. TargetLanguage = glslang::EShTargetSpv;
  761. TargetVersion = glslang::EShTargetSpv_1_2;
  762. } else if (strcmp(argv[1], "spirv1.3") == 0) {
  763. TargetLanguage = glslang::EShTargetSpv;
  764. TargetVersion = glslang::EShTargetSpv_1_3;
  765. } else if (strcmp(argv[1], "spirv1.4") == 0) {
  766. TargetLanguage = glslang::EShTargetSpv;
  767. TargetVersion = glslang::EShTargetSpv_1_4;
  768. } else if (strcmp(argv[1], "spirv1.5") == 0) {
  769. TargetLanguage = glslang::EShTargetSpv;
  770. TargetVersion = glslang::EShTargetSpv_1_5;
  771. } else if (strcmp(argv[1], "spirv1.6") == 0) {
  772. TargetLanguage = glslang::EShTargetSpv;
  773. TargetVersion = glslang::EShTargetSpv_1_6;
  774. } else
  775. Error("--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2,\n"
  776. "vulkan1.3, opengl, spirv1.0, spirv1.1, spirv1.2, spirv1.3,\n"
  777. "spirv1.4, spirv1.5 or spirv1.6");
  778. }
  779. bumpArg();
  780. } else if (lowerword == "undef-macro" ||
  781. lowerword == "u") {
  782. if (argc > 1)
  783. UserPreamble.addUndef(argv[1]);
  784. else
  785. Error("expects <name>", argv[0]);
  786. bumpArg();
  787. } else if (lowerword == "variable-name" || // synonyms
  788. lowerword == "vn") {
  789. Options |= EOptionOutputHexadecimal;
  790. if (argc <= 1)
  791. Error("no <C-variable-name> provided", lowerword.c_str());
  792. variableName = argv[1];
  793. bumpArg();
  794. break;
  795. } else if (lowerword == "quiet") {
  796. beQuiet = true;
  797. } else if (lowerword == "depfile") {
  798. if (argc <= 1)
  799. Error("no <depfile-name> provided", lowerword.c_str());
  800. depencyFileName = argv[1];
  801. bumpArg();
  802. } else if (lowerword == "version") {
  803. Options |= EOptionDumpVersions;
  804. } else if (lowerword == "no-link") {
  805. Options |= EOptionCompileOnly;
  806. } else if (lowerword == "error-column") {
  807. Options |= EOptionDisplayErrorColumn;
  808. } else if (lowerword == "help") {
  809. usage();
  810. break;
  811. } else {
  812. Error("unrecognized command-line option", argv[0]);
  813. }
  814. }
  815. break;
  816. case 'C':
  817. Options |= EOptionCascadingErrors;
  818. break;
  819. case 'D':
  820. if (argv[0][2] == 0)
  821. Options |= EOptionReadHlsl;
  822. else
  823. UserPreamble.addDef(getStringOperand("-D<name[=def]>"));
  824. break;
  825. case 'u':
  826. uniformLocationOverrides.push_back(getUniformOverride());
  827. break;
  828. case 'E':
  829. Options |= EOptionOutputPreprocessed;
  830. break;
  831. case 'G':
  832. // OpenGL client
  833. setOpenGlSpv();
  834. if (argv[0][2] != 0)
  835. ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
  836. if (ClientInputSemanticsVersion != 100)
  837. Error("unknown client version for -G, should be 100");
  838. break;
  839. case 'H':
  840. Options |= EOptionHumanReadableSpv;
  841. if ((Options & EOptionSpv) == 0) {
  842. // default to Vulkan
  843. setVulkanSpv();
  844. }
  845. break;
  846. case 'I':
  847. IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
  848. break;
  849. case 'O':
  850. if (argv[0][2] == 'd')
  851. Options |= EOptionOptimizeDisable;
  852. else if (argv[0][2] == 's')
  853. #if ENABLE_OPT
  854. Options |= EOptionOptimizeSize;
  855. #else
  856. Error("-Os not available; optimizer not linked");
  857. #endif
  858. else
  859. Error("unknown -O option");
  860. break;
  861. case 'P':
  862. UserPreamble.addText(getStringOperand("-P<text>"));
  863. break;
  864. case 'R':
  865. VulkanRulesRelaxed = true;
  866. break;
  867. case 'S':
  868. if (argc <= 1)
  869. Error("no <stage> specified for -S");
  870. shaderStageName = argv[1];
  871. bumpArg();
  872. break;
  873. case 'U':
  874. UserPreamble.addUndef(getStringOperand("-U<name>"));
  875. break;
  876. case 'V':
  877. setVulkanSpv();
  878. if (argv[0][2] != 0)
  879. ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
  880. if (ClientInputSemanticsVersion != 100)
  881. Error("unknown client version for -V, should be 100");
  882. break;
  883. case 'c':
  884. Options |= EOptionDumpConfig;
  885. break;
  886. case 'd':
  887. if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
  888. strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
  889. Options |= EOptionDumpBareVersion;
  890. else
  891. Options |= EOptionDefaultDesktop;
  892. break;
  893. case 'e':
  894. entryPointName = argv[1];
  895. if (argc <= 1)
  896. Error("no <name> provided for -e");
  897. bumpArg();
  898. break;
  899. case 'f':
  900. if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
  901. targetHlslFunctionality1 = true;
  902. else
  903. Error("-f: expected hlsl_functionality1");
  904. break;
  905. case 'g':
  906. // Override previous -g or -g0 argument
  907. stripDebugInfo = false;
  908. emitNonSemanticShaderDebugInfo = false;
  909. Options &= ~EOptionDebug;
  910. if (argv[0][2] == '0')
  911. stripDebugInfo = true;
  912. else {
  913. Options |= EOptionDebug;
  914. if (argv[0][2] == 'V') {
  915. emitNonSemanticShaderDebugInfo = true;
  916. if (argv[0][3] == 'S') {
  917. emitNonSemanticShaderDebugSource = true;
  918. } else {
  919. emitNonSemanticShaderDebugSource = false;
  920. }
  921. }
  922. }
  923. break;
  924. case 'h':
  925. usage();
  926. break;
  927. case 'i':
  928. Options |= EOptionIntermediate;
  929. break;
  930. case 'l':
  931. Options |= EOptionLinkProgram;
  932. break;
  933. case 'm':
  934. Options |= EOptionMemoryLeakMode;
  935. break;
  936. case 'o':
  937. if (argc <= 1)
  938. Error("no <file> provided for -o");
  939. binaryFileName = argv[1];
  940. bumpArg();
  941. break;
  942. case 'q':
  943. Options |= EOptionDumpReflection;
  944. break;
  945. case 'r':
  946. Options |= EOptionRelaxedErrors;
  947. break;
  948. case 's':
  949. Options |= EOptionSuppressInfolog;
  950. break;
  951. case 't':
  952. Options |= EOptionMultiThreaded;
  953. break;
  954. case 'v':
  955. Options |= EOptionDumpVersions;
  956. break;
  957. case 'w':
  958. Options |= EOptionSuppressWarnings;
  959. break;
  960. case 'x':
  961. Options |= EOptionOutputHexadecimal;
  962. break;
  963. default:
  964. Error("unrecognized command-line option", argv[0]);
  965. break;
  966. }
  967. } else {
  968. std::string name(argv[0]);
  969. if (! SetConfigFile(name)) {
  970. workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
  971. }
  972. }
  973. }
  974. // Make sure that -S is always specified if --stdin is specified
  975. if ((Options & EOptionStdin) && shaderStageName == nullptr)
  976. Error("must provide -S when --stdin is given");
  977. // Make sure that -E is not specified alongside linking (which includes SPV generation)
  978. // Or things that require linking
  979. if (Options & EOptionOutputPreprocessed) {
  980. if (Options & EOptionLinkProgram)
  981. Error("can't use -E when linking is selected");
  982. if (Options & EOptionDumpReflection)
  983. Error("reflection requires linking, which can't be used when -E when is selected");
  984. }
  985. // reflection requires linking
  986. if ((Options & EOptionDumpReflection) && !(Options & EOptionLinkProgram))
  987. Error("reflection requires -l for linking");
  988. // -o or -x makes no sense if there is no target binary
  989. if (binaryFileName && (Options & EOptionSpv) == 0)
  990. Error("no binary generation requested (e.g., -V)");
  991. if ((Options & EOptionFlattenUniformArrays) != 0 &&
  992. (Options & EOptionReadHlsl) == 0)
  993. Error("uniform array flattening only valid when compiling HLSL source.");
  994. if ((Options & EOptionReadHlsl) && (Client == glslang::EShClientOpenGL)) {
  995. Error("Using HLSL input under OpenGL semantics is not currently supported.");
  996. }
  997. // rationalize client and target language
  998. if (TargetLanguage == glslang::EShTargetNone) {
  999. switch (ClientVersion) {
  1000. case glslang::EShTargetVulkan_1_0:
  1001. TargetLanguage = glslang::EShTargetSpv;
  1002. TargetVersion = glslang::EShTargetSpv_1_0;
  1003. break;
  1004. case glslang::EShTargetVulkan_1_1:
  1005. TargetLanguage = glslang::EShTargetSpv;
  1006. TargetVersion = glslang::EShTargetSpv_1_3;
  1007. break;
  1008. case glslang::EShTargetVulkan_1_2:
  1009. TargetLanguage = glslang::EShTargetSpv;
  1010. TargetVersion = glslang::EShTargetSpv_1_5;
  1011. break;
  1012. case glslang::EShTargetVulkan_1_3:
  1013. TargetLanguage = glslang::EShTargetSpv;
  1014. TargetVersion = glslang::EShTargetSpv_1_6;
  1015. break;
  1016. case glslang::EShTargetOpenGL_450:
  1017. TargetLanguage = glslang::EShTargetSpv;
  1018. TargetVersion = glslang::EShTargetSpv_1_0;
  1019. break;
  1020. default:
  1021. break;
  1022. }
  1023. }
  1024. if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
  1025. Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
  1026. }
  1027. //
  1028. // Translate the meaningful subset of command-line options to parser-behavior options.
  1029. //
  1030. void SetMessageOptions(EShMessages& messages)
  1031. {
  1032. if (Options & EOptionRelaxedErrors)
  1033. messages = (EShMessages)(messages | EShMsgRelaxedErrors);
  1034. if (Options & EOptionIntermediate)
  1035. messages = (EShMessages)(messages | EShMsgAST);
  1036. if (Options & EOptionSuppressWarnings)
  1037. messages = (EShMessages)(messages | EShMsgSuppressWarnings);
  1038. if (Options & EOptionSpv)
  1039. messages = (EShMessages)(messages | EShMsgSpvRules);
  1040. if (Options & EOptionVulkanRules)
  1041. messages = (EShMessages)(messages | EShMsgVulkanRules);
  1042. if (Options & EOptionOutputPreprocessed)
  1043. messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
  1044. if (Options & EOptionReadHlsl)
  1045. messages = (EShMessages)(messages | EShMsgReadHlsl);
  1046. if (Options & EOptionCascadingErrors)
  1047. messages = (EShMessages)(messages | EShMsgCascadingErrors);
  1048. if (Options & EOptionKeepUncalled)
  1049. messages = (EShMessages)(messages | EShMsgKeepUncalled);
  1050. if (Options & EOptionHlslOffsets)
  1051. messages = (EShMessages)(messages | EShMsgHlslOffsets);
  1052. if (Options & EOptionDebug)
  1053. messages = (EShMessages)(messages | EShMsgDebugInfo);
  1054. if (HlslEnable16BitTypes)
  1055. messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
  1056. if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
  1057. messages = (EShMessages)(messages | EShMsgHlslLegalization);
  1058. if (HlslDX9compatible)
  1059. messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
  1060. if (DumpBuiltinSymbols)
  1061. messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
  1062. if (EnhancedMsgs)
  1063. messages = (EShMessages)(messages | EShMsgEnhanced);
  1064. if (AbsolutePath)
  1065. messages = (EShMessages)(messages | EShMsgAbsolutePath);
  1066. if (Options & EOptionDisplayErrorColumn)
  1067. messages = (EShMessages)(messages | EShMsgDisplayErrorColumn);
  1068. }
  1069. //
  1070. // Thread entry point, for non-linking asynchronous mode.
  1071. //
  1072. void CompileShaders(glslang::TWorklist& worklist)
  1073. {
  1074. if (Options & EOptionDebug)
  1075. Error("cannot generate debug information unless linking to generate code");
  1076. // NOTE: TWorkList::remove is thread-safe
  1077. glslang::TWorkItem* workItem;
  1078. if (Options & EOptionStdin) {
  1079. if (worklist.remove(workItem)) {
  1080. ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), 0);
  1081. if (compiler == nullptr)
  1082. return;
  1083. CompileFile("stdin", compiler);
  1084. if (! (Options & EOptionSuppressInfolog))
  1085. workItem->results = ShGetInfoLog(compiler);
  1086. ShDestruct(compiler);
  1087. }
  1088. } else {
  1089. while (worklist.remove(workItem)) {
  1090. ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), 0);
  1091. if (compiler == nullptr)
  1092. return;
  1093. CompileFile(workItem->name.c_str(), compiler);
  1094. if (! (Options & EOptionSuppressInfolog))
  1095. workItem->results = ShGetInfoLog(compiler);
  1096. ShDestruct(compiler);
  1097. }
  1098. }
  1099. }
  1100. // Outputs the given string, but only if it is non-null and non-empty.
  1101. // This prevents erroneous newlines from appearing.
  1102. void PutsIfNonEmpty(const char* str)
  1103. {
  1104. if (str && str[0]) {
  1105. puts(str);
  1106. }
  1107. }
  1108. // Outputs the given string to stderr, but only if it is non-null and non-empty.
  1109. // This prevents erroneous newlines from appearing.
  1110. void StderrIfNonEmpty(const char* str)
  1111. {
  1112. if (str && str[0])
  1113. fprintf(stderr, "%s\n", str);
  1114. }
  1115. // Simple bundling of what makes a compilation unit for ease in passing around,
  1116. // and separation of handling file IO versus API (programmatic) compilation.
  1117. struct ShaderCompUnit {
  1118. EShLanguage stage;
  1119. static const int maxCount = 1;
  1120. int count; // live number of strings/names
  1121. const char* text[maxCount]; // memory owned/managed externally
  1122. std::string fileName[maxCount]; // hold's the memory, but...
  1123. const char* fileNameList[maxCount]; // downstream interface wants pointers
  1124. ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
  1125. ShaderCompUnit(const ShaderCompUnit& rhs)
  1126. {
  1127. stage = rhs.stage;
  1128. count = rhs.count;
  1129. for (int i = 0; i < count; ++i) {
  1130. fileName[i] = rhs.fileName[i];
  1131. text[i] = rhs.text[i];
  1132. fileNameList[i] = rhs.fileName[i].c_str();
  1133. }
  1134. }
  1135. void addString(std::string& ifileName, const char* itext)
  1136. {
  1137. assert(count < maxCount);
  1138. fileName[count] = ifileName;
  1139. text[count] = itext;
  1140. fileNameList[count] = fileName[count].c_str();
  1141. ++count;
  1142. }
  1143. };
  1144. // Writes a string into a depfile, escaping some special characters following the Makefile rules.
  1145. static void writeEscapedDepString(std::ofstream& file, const std::string& str)
  1146. {
  1147. for (char c : str) {
  1148. switch (c) {
  1149. case ' ':
  1150. case ':':
  1151. case '#':
  1152. case '[':
  1153. case ']':
  1154. case '\\':
  1155. file << '\\';
  1156. break;
  1157. case '$':
  1158. file << '$';
  1159. break;
  1160. }
  1161. file << c;
  1162. }
  1163. }
  1164. // Writes a depfile similar to gcc -MMD foo.c
  1165. bool writeDepFile(std::string depfile, std::vector<std::string>& binaryFiles, const std::vector<std::string>& sources)
  1166. {
  1167. std::ofstream file(depfile);
  1168. if (file.fail())
  1169. return false;
  1170. for (auto binaryFile = binaryFiles.begin(); binaryFile != binaryFiles.end(); binaryFile++) {
  1171. writeEscapedDepString(file, *binaryFile);
  1172. file << ":";
  1173. for (auto sourceFile = sources.begin(); sourceFile != sources.end(); sourceFile++) {
  1174. file << " ";
  1175. writeEscapedDepString(file, *sourceFile);
  1176. }
  1177. file << std::endl;
  1178. }
  1179. return true;
  1180. }
  1181. //
  1182. // For linking mode: Will independently parse each compilation unit, but then put them
  1183. // in the same program and link them together, making at most one linked module per
  1184. // pipeline stage.
  1185. //
  1186. // Uses the new C++ interface instead of the old handle-based interface.
  1187. //
  1188. void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
  1189. {
  1190. // keep track of what to free
  1191. std::list<glslang::TShader*> shaders;
  1192. EShMessages messages = EShMsgDefault;
  1193. SetMessageOptions(messages);
  1194. DirStackFileIncluder includer;
  1195. std::for_each(IncludeDirectoryList.rbegin(), IncludeDirectoryList.rend(), [&includer](const std::string& dir) {
  1196. includer.pushExternalLocalDirectory(dir); });
  1197. std::vector<std::string> sources;
  1198. //
  1199. // Per-shader processing...
  1200. //
  1201. glslang::TProgram& program = *new glslang::TProgram;
  1202. const bool compileOnly = (Options & EOptionCompileOnly) != 0;
  1203. for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
  1204. const auto &compUnit = *it;
  1205. for (int i = 0; i < compUnit.count; i++) {
  1206. sources.push_back(compUnit.fileNameList[i]);
  1207. }
  1208. glslang::TShader* shader = new glslang::TShader(compUnit.stage);
  1209. shader->setStringsWithLengthsAndNames(compUnit.text, nullptr, compUnit.fileNameList, compUnit.count);
  1210. if (entryPointName)
  1211. shader->setEntryPoint(entryPointName);
  1212. if (sourceEntryPointName) {
  1213. if (entryPointName == nullptr)
  1214. printf("Warning: Changing source entry point name without setting an entry-point name.\n"
  1215. "Use '-e <name>'.\n");
  1216. shader->setSourceEntryPoint(sourceEntryPointName);
  1217. }
  1218. if (compileOnly)
  1219. shader->setCompileOnly();
  1220. shader->setOverrideVersion(GlslVersion);
  1221. std::string intrinsicString = getIntrinsic(compUnit.text, compUnit.count);
  1222. PreambleString = "";
  1223. if (UserPreamble.isSet())
  1224. PreambleString.append(UserPreamble.get());
  1225. if (!intrinsicString.empty())
  1226. PreambleString.append(intrinsicString);
  1227. shader->setPreamble(PreambleString.c_str());
  1228. shader->addProcesses(Processes);
  1229. // Set IO mapper binding shift values
  1230. for (int r = 0; r < glslang::EResCount; ++r) {
  1231. const glslang::TResourceType res = glslang::TResourceType(r);
  1232. // Set base bindings
  1233. shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
  1234. // Set bindings for particular resource sets
  1235. // TODO: use a range based for loop here, when available in all environments.
  1236. for (auto i = baseBindingForSet[res][compUnit.stage].begin();
  1237. i != baseBindingForSet[res][compUnit.stage].end(); ++i)
  1238. shader->setShiftBindingForSet(res, i->second, i->first);
  1239. }
  1240. shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
  1241. shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
  1242. if (autoSampledTextures)
  1243. shader->setTextureSamplerTransformMode(EShTexSampTransUpgradeTextureRemoveSampler);
  1244. if (Options & EOptionAutoMapBindings)
  1245. shader->setAutoMapBindings(true);
  1246. if (Options & EOptionAutoMapLocations)
  1247. shader->setAutoMapLocations(true);
  1248. for (auto& uniOverride : uniformLocationOverrides) {
  1249. shader->addUniformLocationOverride(uniOverride.first.c_str(),
  1250. uniOverride.second);
  1251. }
  1252. shader->setUniformLocationBase(uniformBase);
  1253. if (VulkanRulesRelaxed) {
  1254. for (auto& storageOverride : blockStorageOverrides) {
  1255. shader->addBlockStorageOverride(storageOverride.first.c_str(),
  1256. storageOverride.second);
  1257. }
  1258. if (setGlobalBufferBlock) {
  1259. shader->setAtomicCounterBlockName(atomicCounterBlockName.c_str());
  1260. shader->setAtomicCounterBlockSet(atomicCounterBlockSet);
  1261. }
  1262. if (setGlobalUniformBlock) {
  1263. shader->setGlobalUniformBlockName(globalUniformName.c_str());
  1264. shader->setGlobalUniformSet(globalUniformSet);
  1265. shader->setGlobalUniformBinding(globalUniformBinding);
  1266. }
  1267. }
  1268. shader->setNanMinMaxClamp(NaNClamp);
  1269. #ifdef ENABLE_HLSL
  1270. shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
  1271. if (Options & EOptionHlslIoMapping)
  1272. shader->setHlslIoMapping(true);
  1273. #endif
  1274. if (Options & EOptionInvertY)
  1275. shader->setInvertY(true);
  1276. if (HlslDxPositionW)
  1277. shader->setDxPositionW(true);
  1278. if (EnhancedMsgs)
  1279. shader->setEnhancedMsgs();
  1280. if (emitNonSemanticShaderDebugInfo)
  1281. shader->setDebugInfo(true);
  1282. // Set up the environment, some subsettings take precedence over earlier
  1283. // ways of setting things.
  1284. if (Options & EOptionSpv) {
  1285. shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
  1286. : glslang::EShSourceGlsl,
  1287. compUnit.stage, Client, ClientInputSemanticsVersion);
  1288. shader->setEnvClient(Client, ClientVersion);
  1289. shader->setEnvTarget(TargetLanguage, TargetVersion);
  1290. #ifdef ENABLE_HLSL
  1291. if (targetHlslFunctionality1)
  1292. shader->setEnvTargetHlslFunctionality1();
  1293. #endif
  1294. if (VulkanRulesRelaxed)
  1295. shader->setEnvInputVulkanRulesRelaxed();
  1296. }
  1297. shaders.push_back(shader);
  1298. const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
  1299. if (Options & EOptionOutputPreprocessed) {
  1300. std::string str;
  1301. if (shader->preprocess(GetResources(), defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
  1302. PutsIfNonEmpty(str.c_str());
  1303. } else {
  1304. CompileFailed = 1;
  1305. }
  1306. StderrIfNonEmpty(shader->getInfoLog());
  1307. StderrIfNonEmpty(shader->getInfoDebugLog());
  1308. continue;
  1309. }
  1310. if (! shader->parse(GetResources(), defaultVersion, false, messages, includer))
  1311. CompileFailed = 1;
  1312. if (!compileOnly)
  1313. program.addShader(shader);
  1314. if (! (Options & EOptionSuppressInfolog) &&
  1315. ! (Options & EOptionMemoryLeakMode)) {
  1316. if (!beQuiet)
  1317. PutsIfNonEmpty(compUnit.fileName[0].c_str());
  1318. PutsIfNonEmpty(shader->getInfoLog());
  1319. PutsIfNonEmpty(shader->getInfoDebugLog());
  1320. }
  1321. }
  1322. //
  1323. // Program-level processing...
  1324. //
  1325. if (!compileOnly) {
  1326. // Link
  1327. if (!(Options & EOptionOutputPreprocessed) && !program.link(messages))
  1328. LinkFailed = true;
  1329. // Map IO
  1330. if (Options & EOptionSpv) {
  1331. if (!program.mapIO())
  1332. LinkFailed = true;
  1333. }
  1334. // Report
  1335. if (!(Options & EOptionSuppressInfolog) && !(Options & EOptionMemoryLeakMode)) {
  1336. PutsIfNonEmpty(program.getInfoLog());
  1337. PutsIfNonEmpty(program.getInfoDebugLog());
  1338. }
  1339. // Reflect
  1340. if (Options & EOptionDumpReflection) {
  1341. program.buildReflection(ReflectOptions);
  1342. program.dumpReflection();
  1343. }
  1344. }
  1345. std::vector<std::string> outputFiles;
  1346. #ifdef ENABLE_SPIRV
  1347. // Dump SPIR-V
  1348. if (Options & EOptionSpv) {
  1349. CompileOrLinkFailed.fetch_or(CompileFailed);
  1350. CompileOrLinkFailed.fetch_or(LinkFailed);
  1351. if (static_cast<bool>(CompileOrLinkFailed.load()))
  1352. printf("SPIR-V is not generated for failed compile or link\n");
  1353. else {
  1354. std::vector<glslang::TIntermediate*> intermediates;
  1355. if (!compileOnly) {
  1356. for (int stage = 0; stage < EShLangCount; ++stage) {
  1357. if (auto* i = program.getIntermediate((EShLanguage)stage)) {
  1358. intermediates.emplace_back(i);
  1359. }
  1360. }
  1361. } else {
  1362. for (const auto* shader : shaders) {
  1363. if (auto* i = shader->getIntermediate()) {
  1364. intermediates.emplace_back(i);
  1365. }
  1366. }
  1367. }
  1368. for (auto* intermediate : intermediates) {
  1369. std::vector<unsigned int> spirv;
  1370. spv::SpvBuildLogger logger;
  1371. glslang::SpvOptions spvOptions;
  1372. if (Options & EOptionDebug) {
  1373. spvOptions.generateDebugInfo = true;
  1374. if (emitNonSemanticShaderDebugInfo) {
  1375. spvOptions.emitNonSemanticShaderDebugInfo = true;
  1376. if (emitNonSemanticShaderDebugSource) {
  1377. spvOptions.emitNonSemanticShaderDebugSource = true;
  1378. }
  1379. }
  1380. } else if (stripDebugInfo)
  1381. spvOptions.stripDebugInfo = true;
  1382. spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
  1383. spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
  1384. spvOptions.disassemble = SpvToolsDisassembler;
  1385. spvOptions.validate = SpvToolsValidate;
  1386. spvOptions.compileOnly = compileOnly;
  1387. glslang::GlslangToSpv(*intermediate, spirv, &logger, &spvOptions);
  1388. // Dump the spv to a file or stdout, etc., but only if not doing
  1389. // memory/perf testing, as it's not internal to programmatic use.
  1390. if (!(Options & EOptionMemoryLeakMode)) {
  1391. printf("%s", logger.getAllMessages().c_str());
  1392. const auto filename = GetBinaryName(intermediate->getStage());
  1393. if (Options & EOptionOutputHexadecimal) {
  1394. if (!glslang::OutputSpvHex(spirv, filename, variableName))
  1395. exit(EFailUsage);
  1396. } else {
  1397. if (!glslang::OutputSpvBin(spirv, filename))
  1398. exit(EFailUsage);
  1399. }
  1400. outputFiles.push_back(filename);
  1401. if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
  1402. spv::Disassemble(std::cout, spirv);
  1403. }
  1404. }
  1405. }
  1406. }
  1407. #endif
  1408. CompileOrLinkFailed.fetch_or(CompileFailed);
  1409. CompileOrLinkFailed.fetch_or(LinkFailed);
  1410. if (depencyFileName && !static_cast<bool>(CompileOrLinkFailed.load())) {
  1411. std::set<std::string> includedFiles = includer.getIncludedFiles();
  1412. sources.insert(sources.end(), includedFiles.begin(), includedFiles.end());
  1413. writeDepFile(depencyFileName, outputFiles, sources);
  1414. }
  1415. // Free everything up, program has to go before the shaders
  1416. // because it might have merged stuff from the shaders, and
  1417. // the stuff from the shaders has to have its destructors called
  1418. // before the pools holding the memory in the shaders is freed.
  1419. delete &program;
  1420. while (shaders.size() > 0) {
  1421. delete shaders.back();
  1422. shaders.pop_back();
  1423. }
  1424. }
  1425. //
  1426. // Do file IO part of compile and link, handing off the pure
  1427. // API/programmatic mode to CompileAndLinkShaderUnits(), which can
  1428. // be put in a loop for testing memory footprint and performance.
  1429. //
  1430. // This is just for linking mode: meaning all the shaders will be put into the
  1431. // the same program linked together.
  1432. //
  1433. // This means there are a limited number of work items (not multi-threading mode)
  1434. // and that the point is testing at the linking level. Hence, to enable
  1435. // performance and memory testing, the actual compile/link can be put in
  1436. // a loop, independent of processing the work items and file IO.
  1437. //
  1438. void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
  1439. {
  1440. std::vector<ShaderCompUnit> compUnits;
  1441. // If this is using stdin, we can't really detect multiple different file
  1442. // units by input type. We need to assume that we're just being given one
  1443. // file of a certain type.
  1444. if ((Options & EOptionStdin) != 0) {
  1445. ShaderCompUnit compUnit(FindLanguage("stdin"));
  1446. std::istreambuf_iterator<char> begin(std::cin), end;
  1447. std::string tempString(begin, end);
  1448. char* fileText = strdup(tempString.c_str());
  1449. std::string fileName = "stdin";
  1450. compUnit.addString(fileName, fileText);
  1451. compUnits.push_back(compUnit);
  1452. } else {
  1453. // Transfer all the work items from to a simple list of
  1454. // of compilation units. (We don't care about the thread
  1455. // work-item distribution properties in this path, which
  1456. // is okay due to the limited number of shaders, know since
  1457. // they are all getting linked together.)
  1458. glslang::TWorkItem* workItem;
  1459. while (Worklist.remove(workItem)) {
  1460. ShaderCompUnit compUnit(FindLanguage(workItem->name));
  1461. char* fileText = ReadFileData(workItem->name.c_str());
  1462. if (fileText == nullptr)
  1463. usage();
  1464. compUnit.addString(workItem->name, fileText);
  1465. compUnits.push_back(compUnit);
  1466. }
  1467. }
  1468. // Actual call to programmatic processing of compile and link,
  1469. // in a loop for testing memory and performance. This part contains
  1470. // all the perf/memory that a programmatic consumer will care about.
  1471. for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
  1472. for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
  1473. CompileAndLinkShaderUnits(compUnits);
  1474. if (Options & EOptionMemoryLeakMode)
  1475. glslang::OS_DumpMemoryCounters();
  1476. }
  1477. // free memory from ReadFileData, which got stored in a const char*
  1478. // as the first string above
  1479. for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
  1480. FreeFileData(const_cast<char*>(it->text[0]));
  1481. }
  1482. int singleMain()
  1483. {
  1484. glslang::TWorklist workList;
  1485. std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
  1486. assert(item);
  1487. workList.add(item.get());
  1488. });
  1489. if (Options & EOptionDumpConfig) {
  1490. printf("%s", GetDefaultTBuiltInResourceString().c_str());
  1491. if (workList.empty())
  1492. return ESuccess;
  1493. }
  1494. if (Options & EOptionDumpBareVersion) {
  1495. int spirvGeneratorVersion = 0;
  1496. #ifdef ENABLE_SPIRV
  1497. spirvGeneratorVersion = glslang::GetSpirvGeneratorVersion();
  1498. #endif
  1499. printf("%d:%d.%d.%d%s\n", spirvGeneratorVersion, GLSLANG_VERSION_MAJOR, GLSLANG_VERSION_MINOR,
  1500. GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
  1501. if (workList.empty())
  1502. return ESuccess;
  1503. } else if (Options & EOptionDumpVersions) {
  1504. int spirvGeneratorVersion = 0;
  1505. #ifdef ENABLE_SPIRV
  1506. spirvGeneratorVersion = glslang::GetSpirvGeneratorVersion();
  1507. #endif
  1508. printf("Glslang Version: %d:%d.%d.%d%s\n", spirvGeneratorVersion, GLSLANG_VERSION_MAJOR,
  1509. GLSLANG_VERSION_MINOR, GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
  1510. printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
  1511. printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
  1512. std::string spirvVersion;
  1513. #if ENABLE_SPIRV
  1514. glslang::GetSpirvVersion(spirvVersion);
  1515. #endif
  1516. printf("SPIR-V Version %s\n", spirvVersion.c_str());
  1517. printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
  1518. printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
  1519. printf("SPIR-V Generator Version %d\n", spirvGeneratorVersion);
  1520. printf("GL_KHR_vulkan_glsl version %d\n", 100);
  1521. printf("ARB_GL_gl_spirv version %d\n", 100);
  1522. if (workList.empty())
  1523. return ESuccess;
  1524. }
  1525. if (workList.empty() && ((Options & EOptionStdin) == 0)) {
  1526. usage();
  1527. }
  1528. if (Options & EOptionStdin) {
  1529. WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
  1530. workList.add(WorkItems.back().get());
  1531. }
  1532. ProcessConfigFile();
  1533. if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
  1534. Error("HLSL requires SPIR-V code generation (or preprocessing only)");
  1535. //
  1536. // Two modes:
  1537. // 1) linking all arguments together, single-threaded, new C++ interface
  1538. // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
  1539. //
  1540. if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
  1541. glslang::InitializeProcess();
  1542. glslang::InitializeProcess(); // also test reference counting of users
  1543. glslang::InitializeProcess(); // also test reference counting of users
  1544. glslang::FinalizeProcess(); // also test reference counting of users
  1545. glslang::FinalizeProcess(); // also test reference counting of users
  1546. CompileAndLinkShaderFiles(workList);
  1547. glslang::FinalizeProcess();
  1548. } else {
  1549. ShInitialize();
  1550. ShInitialize(); // also test reference counting of users
  1551. ShFinalize(); // also test reference counting of users
  1552. bool printShaderNames = workList.size() > 1;
  1553. if (Options & EOptionMultiThreaded) {
  1554. std::array<std::thread, 16> threads;
  1555. for (unsigned int t = 0; t < threads.size(); ++t) {
  1556. threads[t] = std::thread(CompileShaders, std::ref(workList));
  1557. if (threads[t].get_id() == std::thread::id()) {
  1558. fprintf(stderr, "Failed to create thread\n");
  1559. return EFailThreadCreate;
  1560. }
  1561. }
  1562. std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
  1563. } else
  1564. CompileShaders(workList);
  1565. // Print out all the resulting infologs
  1566. for (size_t w = 0; w < WorkItems.size(); ++w) {
  1567. if (WorkItems[w]) {
  1568. if (printShaderNames || WorkItems[w]->results.size() > 0)
  1569. PutsIfNonEmpty(WorkItems[w]->name.c_str());
  1570. PutsIfNonEmpty(WorkItems[w]->results.c_str());
  1571. }
  1572. }
  1573. ShFinalize();
  1574. }
  1575. if (CompileFailed.load())
  1576. return EFailCompile;
  1577. if (LinkFailed.load())
  1578. return EFailLink;
  1579. return 0;
  1580. }
  1581. int C_DECL main(int argc, char* argv[])
  1582. {
  1583. ProcessArguments(WorkItems, argc, argv);
  1584. int ret = 0;
  1585. // Loop over the entire init/finalize cycle to watch memory changes
  1586. const int iterations = 1;
  1587. if (iterations > 1)
  1588. glslang::OS_DumpMemoryCounters();
  1589. for (int i = 0; i < iterations; ++i) {
  1590. ret = singleMain();
  1591. if (iterations > 1)
  1592. glslang::OS_DumpMemoryCounters();
  1593. }
  1594. return ret;
  1595. }
  1596. //
  1597. // Deduce the language from the filename. Files must end in one of the
  1598. // following extensions:
  1599. //
  1600. // .vert = vertex
  1601. // .tesc = tessellation control
  1602. // .tese = tessellation evaluation
  1603. // .geom = geometry
  1604. // .frag = fragment
  1605. // .comp = compute
  1606. // .rgen = ray generation
  1607. // .rint = ray intersection
  1608. // .rahit = ray any hit
  1609. // .rchit = ray closest hit
  1610. // .rmiss = ray miss
  1611. // .rcall = ray callable
  1612. // .mesh = mesh
  1613. // .task = task
  1614. // Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
  1615. // where <stage> is one of the stages listed above.
  1616. //
  1617. EShLanguage FindLanguage(const std::string& name, bool parseStageName)
  1618. {
  1619. std::string stageName;
  1620. if (shaderStageName)
  1621. stageName = shaderStageName;
  1622. else if (parseStageName) {
  1623. // Note: "first" extension means "first from the end", i.e.
  1624. // if the file is named foo.vert.glsl, then "glsl" is first,
  1625. // "vert" is second.
  1626. size_t firstExtStart = name.find_last_of(".");
  1627. bool hasFirstExt = firstExtStart != std::string::npos;
  1628. size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
  1629. bool hasSecondExt = secondExtStart != std::string::npos;
  1630. std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
  1631. bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
  1632. if (usesUnifiedExt && firstExt == "hlsl")
  1633. Options |= EOptionReadHlsl;
  1634. if (hasFirstExt && !usesUnifiedExt)
  1635. stageName = firstExt;
  1636. else if (usesUnifiedExt && hasSecondExt)
  1637. stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
  1638. else {
  1639. usage();
  1640. return EShLangVertex;
  1641. }
  1642. } else
  1643. stageName = name;
  1644. if (stageName == "vert")
  1645. return EShLangVertex;
  1646. else if (stageName == "tesc")
  1647. return EShLangTessControl;
  1648. else if (stageName == "tese")
  1649. return EShLangTessEvaluation;
  1650. else if (stageName == "geom")
  1651. return EShLangGeometry;
  1652. else if (stageName == "frag")
  1653. return EShLangFragment;
  1654. else if (stageName == "comp")
  1655. return EShLangCompute;
  1656. else if (stageName == "rgen")
  1657. return EShLangRayGen;
  1658. else if (stageName == "rint")
  1659. return EShLangIntersect;
  1660. else if (stageName == "rahit")
  1661. return EShLangAnyHit;
  1662. else if (stageName == "rchit")
  1663. return EShLangClosestHit;
  1664. else if (stageName == "rmiss")
  1665. return EShLangMiss;
  1666. else if (stageName == "rcall")
  1667. return EShLangCallable;
  1668. else if (stageName == "mesh")
  1669. return EShLangMesh;
  1670. else if (stageName == "task")
  1671. return EShLangTask;
  1672. usage();
  1673. return EShLangVertex;
  1674. }
  1675. //
  1676. // Read a file's data into a string, and compile it using the old interface ShCompile,
  1677. // for non-linkable results.
  1678. //
  1679. void CompileFile(const char* fileName, ShHandle compiler)
  1680. {
  1681. int ret = 0;
  1682. char* shaderString;
  1683. if ((Options & EOptionStdin) != 0) {
  1684. std::istreambuf_iterator<char> begin(std::cin), end;
  1685. std::string tempString(begin, end);
  1686. shaderString = strdup(tempString.c_str());
  1687. } else {
  1688. shaderString = ReadFileData(fileName);
  1689. }
  1690. // move to length-based strings, rather than null-terminated strings
  1691. int* lengths = new int[1];
  1692. lengths[0] = (int)strlen(shaderString);
  1693. EShMessages messages = EShMsgDefault;
  1694. SetMessageOptions(messages);
  1695. if (UserPreamble.isSet())
  1696. Error("-D, -U and -P options require -l (linking)\n");
  1697. for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
  1698. for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
  1699. // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1700. ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, GetResources(), 0,
  1701. (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages, fileName);
  1702. // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
  1703. // "or should be l", "ine 1", "string 5\n", "float glo", "bal",
  1704. // ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
  1705. // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
  1706. // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1707. }
  1708. if (Options & EOptionMemoryLeakMode)
  1709. glslang::OS_DumpMemoryCounters();
  1710. }
  1711. delete [] lengths;
  1712. FreeFileData(shaderString);
  1713. if (ret == 0)
  1714. CompileFailed = true;
  1715. }
  1716. //
  1717. // print usage to stdout
  1718. //
  1719. void usage()
  1720. {
  1721. printf("Usage: glslang [option]... [file]...\n"
  1722. "\n"
  1723. "'file' can end in .<stage> for auto-stage classification, where <stage> is:\n"
  1724. " .conf to provide a config file that replaces the default configuration\n"
  1725. " (see -c option below for generating a template)\n"
  1726. " .vert for a vertex shader\n"
  1727. " .tesc for a tessellation control shader\n"
  1728. " .tese for a tessellation evaluation shader\n"
  1729. " .geom for a geometry shader\n"
  1730. " .frag for a fragment shader\n"
  1731. " .comp for a compute shader\n"
  1732. " .mesh for a mesh shader\n"
  1733. " .task for a task shader\n"
  1734. " .rgen for a ray generation shader\n"
  1735. " .rint for a ray intersection shader\n"
  1736. " .rahit for a ray any hit shader\n"
  1737. " .rchit for a ray closest hit shader\n"
  1738. " .rmiss for a ray miss shader\n"
  1739. " .rcall for a ray callable shader\n"
  1740. " .glsl for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes\n"
  1741. " .hlsl for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes\n"
  1742. "\n"
  1743. "Options:\n"
  1744. " -C cascading errors; risk crash from accumulation of error recoveries\n"
  1745. " -D input is HLSL (this is the default when any suffix is .hlsl)\n"
  1746. " -D<name[=def]> | --define-macro <name[=def]> | --D <name[=def]>\n"
  1747. " define a pre-processor macro\n"
  1748. " -E print pre-processed GLSL; cannot be used with -l;\n"
  1749. " errors will appear on stderr\n"
  1750. " -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
  1751. " default file name is <stage>.spv (-o overrides this);\n"
  1752. " 'ver', when present, is the version of the input semantics,\n"
  1753. " which will appear in #define GL_SPIRV ver;\n"
  1754. " '--client opengl100' is the same as -G100;\n"
  1755. " a '--target-env' for OpenGL will also imply '-G';\n"
  1756. " currently only supports GLSL\n"
  1757. " -H print human readable form of SPIR-V; turns on -V\n"
  1758. " -I<dir> add dir to the include search path; includer's directory\n"
  1759. " is searched first, followed by left-to-right order of -I\n"
  1760. " -Od disables optimization; may cause illegal SPIR-V for HLSL\n"
  1761. " -Os optimizes SPIR-V to minimize size\n"
  1762. " -P<text> | --preamble-text <text> | --P <text>\n"
  1763. " inject custom preamble text, which is treated as if it\n"
  1764. " appeared immediately after the version declaration (if any).\n"
  1765. " -R use relaxed verification rules for generating Vulkan SPIR-V,\n"
  1766. " allowing the use of default uniforms, atomic_uints, and\n"
  1767. " gl_VertexID and gl_InstanceID keywords.\n"
  1768. " -S <stage> uses specified stage rather than parsing the file extension\n"
  1769. " choices for <stage> are vert, tesc, tese, geom, frag, or comp\n"
  1770. " -U<name> | --undef-macro <name> | --U <name>\n"
  1771. " undefine a pre-processor macro\n"
  1772. " -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
  1773. " default file name is <stage>.spv (-o overrides this)\n"
  1774. " 'ver', when present, is the version of the input semantics,\n"
  1775. " which will appear in #define VULKAN ver\n"
  1776. " '--client vulkan100' is the same as -V100\n"
  1777. " a '--target-env' for Vulkan will also imply '-V'\n"
  1778. " -c configuration dump;\n"
  1779. " creates the default configuration file (redirect to a .conf file)\n"
  1780. " -d default to desktop (#version 110) when there is no shader #version\n"
  1781. " (default is ES version 100)\n"
  1782. " -e <name> | --entry-point <name>\n"
  1783. " specify <name> as the entry-point function name\n"
  1784. " -f{hlsl_functionality1}\n"
  1785. " 'hlsl_functionality1' enables use of the\n"
  1786. " SPV_GOOGLE_hlsl_functionality1 extension\n"
  1787. " -g generate debug information\n"
  1788. " -g0 strip debug information\n"
  1789. " -gV generate nonsemantic shader debug information\n"
  1790. " -gVS generate nonsemantic shader debug information with source\n"
  1791. " -h print this usage message\n"
  1792. " -i intermediate tree (glslang AST) is printed out\n"
  1793. " -l link all input files together to form a single module\n"
  1794. " -m memory leak mode\n"
  1795. " -o <file> save binary to <file>, requires a binary option (e.g., -V)\n"
  1796. " -q dump reflection query database; requires -l for linking\n"
  1797. " -r | --relaxed-errors"
  1798. " relaxed GLSL semantic error-checking mode\n"
  1799. " -s silence syntax and semantic error reporting\n"
  1800. " -t multi-threaded mode\n"
  1801. " -v | --version\n"
  1802. " print version strings\n"
  1803. " -w | --suppress-warnings\n"
  1804. " suppress GLSL warnings, except as required by \"#extension : warn\"\n"
  1805. " -x save binary output as text-based 32-bit hexadecimal numbers\n"
  1806. " -u<name>:<loc> specify a uniform location override for --aml\n"
  1807. " --uniform-base <base> set a base to use for generated uniform locations\n"
  1808. " --auto-map-bindings | --amb automatically bind uniform variables\n"
  1809. " without explicit bindings\n"
  1810. " --auto-map-locations | --aml automatically locate input/output lacking\n"
  1811. " 'location' (fragile, not cross stage)\n"
  1812. " --absolute-path Prints absolute path for messages\n"
  1813. " --auto-sampled-textures Removes sampler variables and converts\n"
  1814. " existing textures to sampled textures\n"
  1815. " --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
  1816. " --depfile <file> writes depfile for build systems\n"
  1817. " --dump-builtin-symbols prints builtin symbol table prior each compile\n"
  1818. " -dumpfullversion | -dumpversion print bare major.minor.patchlevel\n"
  1819. " --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to\n"
  1820. " scalars\n"
  1821. " --glsl-version {100 | 110 | 120 | 130 | 140 | 150 |\n"
  1822. " 300es | 310es | 320es | 330\n"
  1823. " 400 | 410 | 420 | 430 | 440 | 450 | 460}\n"
  1824. " set GLSL version, overrides #version\n"
  1825. " in shader sourcen\n"
  1826. " --hlsl-offsets allow block offsets to follow HLSL rules\n"
  1827. " works independently of source language\n"
  1828. " --hlsl-iomap perform IO mapping in HLSL register space\n"
  1829. " --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL\n"
  1830. " --hlsl-dx9-compatible interprets sampler declarations as a\n"
  1831. " texture/sampler combo like DirectX9 would,\n"
  1832. " and recognizes DirectX9-specific semantics\n"
  1833. " --hlsl-dx-position-w W component of SV_Position in HLSL fragment\n"
  1834. " shaders compatible with DirectX\n"
  1835. " --invert-y | --iy invert position.Y output in vertex shader\n"
  1836. " --enhanced-msgs print more readable error messages (GLSL only)\n"
  1837. " --error-column display the column of the error along the line\n"
  1838. " --keep-uncalled | --ku don't eliminate uncalled functions\n"
  1839. " --nan-clamp favor non-NaN operand in min, max, and clamp\n"
  1840. " --no-storage-format | --nsf use Unknown image format\n"
  1841. " --quiet do not print anything to stdout, unless\n"
  1842. " requested by another option\n"
  1843. " --reflect-strict-array-suffix use strict array suffix rules when\n"
  1844. " reflecting\n"
  1845. " --reflect-basic-array-suffix arrays of basic types will have trailing [0]\n"
  1846. " --reflect-intermediate-io reflection includes inputs/outputs of linked\n"
  1847. " shaders rather than just vertex/fragment\n"
  1848. " --reflect-separate-buffers reflect buffer variables and blocks\n"
  1849. " separately to uniforms\n"
  1850. " --reflect-all-block-variables reflect all variables in blocks, whether\n"
  1851. " inactive or active\n"
  1852. " --reflect-unwrap-io-blocks unwrap input/output blocks the same as\n"
  1853. " uniform blocks\n"
  1854. " --resource-set-binding [stage] name set binding\n"
  1855. " set descriptor set and binding for\n"
  1856. " individual resources\n"
  1857. " --resource-set-binding [stage] set\n"
  1858. " set descriptor set for all resources\n"
  1859. " --rsb synonym for --resource-set-binding\n"
  1860. " --set-block-backing name {uniform|buffer|push_constant}\n"
  1861. " changes the backing type of a uniform, buffer,\n"
  1862. " or push_constant block declared in\n"
  1863. " in the program, when using -R option.\n"
  1864. " This can be used to change the backing\n"
  1865. " for existing blocks as well as implicit ones\n"
  1866. " such as 'gl_DefaultUniformBlock'.\n"
  1867. " --sbs synonym for set-block-storage\n"
  1868. " --set-atomic-counter-block name set\n"
  1869. " set name, and descriptor set for\n"
  1870. " atomic counter blocks, with -R opt\n"
  1871. " --sacb synonym for set-atomic-counter-block\n"
  1872. " --set-default-uniform-block name set binding\n"
  1873. " set name, descriptor set, and binding for\n"
  1874. " global default-uniform-block, with -R opt\n"
  1875. " --sdub synonym for set-default-uniform-block\n"
  1876. " --shift-image-binding [stage] num\n"
  1877. " base binding number for images (uav)\n"
  1878. " --shift-image-binding [stage] [num set]...\n"
  1879. " per-descriptor-set shift values\n"
  1880. " --sib synonym for --shift-image-binding\n"
  1881. " --shift-sampler-binding [stage] num\n"
  1882. " base binding number for samplers\n"
  1883. " --shift-sampler-binding [stage] [num set]...\n"
  1884. " per-descriptor-set shift values\n"
  1885. " --ssb synonym for --shift-sampler-binding\n"
  1886. " --shift-ssbo-binding [stage] num base binding number for SSBOs\n"
  1887. " --shift-ssbo-binding [stage] [num set]...\n"
  1888. " per-descriptor-set shift values\n"
  1889. " --sbb synonym for --shift-ssbo-binding\n"
  1890. " --shift-texture-binding [stage] num\n"
  1891. " base binding number for textures\n"
  1892. " --shift-texture-binding [stage] [num set]...\n"
  1893. " per-descriptor-set shift values\n"
  1894. " --stb synonym for --shift-texture-binding\n"
  1895. " --shift-uav-binding [stage] num base binding number for UAVs\n"
  1896. " --shift-uav-binding [stage] [num set]...\n"
  1897. " per-descriptor-set shift values\n"
  1898. " --suavb synonym for --shift-uav-binding\n"
  1899. " --shift-UBO-binding [stage] num base binding number for UBOs\n"
  1900. " --shift-UBO-binding [stage] [num set]...\n"
  1901. " per-descriptor-set shift values\n"
  1902. " --sub synonym for --shift-UBO-binding\n"
  1903. " --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding\n"
  1904. " --spirv-dis output standard-form disassembly; works only\n"
  1905. " when a SPIR-V generation option is also used\n"
  1906. " --spirv-val execute the SPIRV-Tools validator\n"
  1907. " --source-entrypoint <name> the given shader source function is\n"
  1908. " renamed to be the <name> given in -e\n"
  1909. " --sep synonym for --source-entrypoint\n"
  1910. " --stdin read from stdin instead of from a file;\n"
  1911. " requires providing the shader stage using -S\n"
  1912. " --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | vulkan1.3 | opengl |\n"
  1913. " spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 |\n"
  1914. " spirv1.5 | spirv1.6}\n"
  1915. " Set the execution environment that the\n"
  1916. " generated code will be executed in.\n"
  1917. " Defaults to:\n"
  1918. " * vulkan1.0 under --client vulkan<ver>\n"
  1919. " * opengl under --client opengl<ver>\n"
  1920. " * spirv1.0 under --target-env vulkan1.0\n"
  1921. " * spirv1.3 under --target-env vulkan1.1\n"
  1922. " * spirv1.5 under --target-env vulkan1.2\n"
  1923. " * spirv1.6 under --target-env vulkan1.3\n"
  1924. " Multiple --target-env can be specified.\n"
  1925. " --variable-name <name>\n"
  1926. " --vn <name> creates a C header file that contains a\n"
  1927. " uint32_t array named <name>\n"
  1928. " initialized with the shader binary code\n"
  1929. " --no-link Only compile shader; do not link (GLSL-only)\n"
  1930. " NOTE: this option will set the export linkage\n"
  1931. " attribute on all functions\n");
  1932. exit(EFailUsage);
  1933. }
  1934. #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
  1935. #include <errno.h>
  1936. int fopen_s(
  1937. FILE** pFile,
  1938. const char* filename,
  1939. const char* mode
  1940. )
  1941. {
  1942. if (!pFile || !filename || !mode) {
  1943. return EINVAL;
  1944. }
  1945. FILE* f = fopen(filename, mode);
  1946. if (! f) {
  1947. if (errno != 0) {
  1948. return errno;
  1949. } else {
  1950. return ENOENT;
  1951. }
  1952. }
  1953. *pFile = f;
  1954. return 0;
  1955. }
  1956. #endif
  1957. //
  1958. // Malloc a string of sufficient size and read a string into it.
  1959. //
  1960. char* ReadFileData(const char* fileName)
  1961. {
  1962. FILE *in = nullptr;
  1963. int errorCode = fopen_s(&in, fileName, "r");
  1964. if (errorCode || in == nullptr)
  1965. Error("unable to open input file");
  1966. int count = 0;
  1967. while (fgetc(in) != EOF)
  1968. count++;
  1969. fseek(in, 0, SEEK_SET);
  1970. if (count > 3) {
  1971. unsigned char head[3];
  1972. if (fread(head, 1, 3, in) == 3) {
  1973. if (head[0] == 0xef && head[1] == 0xbb && head[2] == 0xbf) {
  1974. // skip BOM
  1975. count -= 3;
  1976. } else {
  1977. fseek(in, 0, SEEK_SET);
  1978. }
  1979. } else {
  1980. Error("can't read input file");
  1981. }
  1982. }
  1983. char* return_data = (char*)malloc(count + 1); // freed in FreeFileData()
  1984. if ((int)fread(return_data, 1, count, in) != count) {
  1985. free(return_data);
  1986. Error("can't read input file");
  1987. }
  1988. return_data[count] = '\0';
  1989. fclose(in);
  1990. return return_data;
  1991. }
  1992. void FreeFileData(char* data)
  1993. {
  1994. free(data);
  1995. }
  1996. void InfoLogMsg(const char* msg, const char* name, const int num)
  1997. {
  1998. if (num >= 0 )
  1999. printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
  2000. else
  2001. printf("#### %s %s INFO LOG ####\n", msg, name);
  2002. }