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