1 /*
2  * Mesa 3-D graphics library
3  *
4  * Copyright (C) 2004-2008  Brian Paul   All Rights Reserved.
5  * Copyright (C) 2009-2010  VMware, Inc.  All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included
15  * in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
21  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23  * OTHER DEALINGS IN THE SOFTWARE.
24  */
25 
26 /**
27  * \file shaderapi.c
28  * \author Brian Paul
29  *
30  * Implementation of GLSL-related API functions.
31  * The glUniform* functions are in uniforms.c
32  */
33 
34 
35 #include <errno.h>
36 #include <stdbool.h>
37 #include <c99_alloca.h>
38 
39 #include "main/glheader.h"
40 #include "main/context.h"
41 #include "draw_validate.h"
42 #include "main/enums.h"
43 #include "main/glspirv.h"
44 #include "main/hash.h"
45 #include "main/mtypes.h"
46 #include "main/pipelineobj.h"
47 #include "main/program_binary.h"
48 #include "main/shaderapi.h"
49 #include "main/shaderobj.h"
50 #include "main/state.h"
51 #include "main/transformfeedback.h"
52 #include "main/uniforms.h"
53 #include "compiler/glsl/builtin_functions.h"
54 #include "compiler/glsl/glsl_parser_extras.h"
55 #include "compiler/glsl/ir.h"
56 #include "compiler/glsl/ir_uniform.h"
57 #include "compiler/glsl/program.h"
58 #include "program/program.h"
59 #include "program/prog_print.h"
60 #include "program/prog_parameter.h"
61 #include "util/ralloc.h"
62 #include "util/hash_table.h"
63 #include "util/crc32.h"
64 #include "util/os_file.h"
65 #include "util/list.h"
66 #include "util/u_process.h"
67 #include "util/u_string.h"
68 #include "api_exec_decl.h"
69 
70 #include "state_tracker/st_context.h"
71 #include "state_tracker/st_program.h"
72 
73 #ifdef ENABLE_SHADER_CACHE
74 #if CUSTOM_SHADER_REPLACEMENT
75 #include "shader_replacement.h"
76 /* shader_replacement.h must declare a variable like this:
77 
78    struct _shader_replacement {
79       // process name. If null, only sha1 is used to match
80       const char *app;
81       // original glsl shader sha1
82       const char *sha1;
83       // shader stage
84       gl_shader_stage stage;
85       ... any other information ...
86    };
87    struct _shader_replacement shader_replacements[...];
88 
89    And a method to load a given replacement and return the new
90    glsl source:
91 
92    char* load_shader_replacement(struct _shader_replacement *repl);
93 
94    And a method to replace the shader without sha1 matching:
95 
96    char *try_direct_replace(const char *app, const char *source)
97 
98    shader_replacement.h can be generated at build time, or copied
99    from an external folder, or any other method.
100 */
101 #else
102 struct _shader_replacement {
103    const char *app;
104    const char *sha1;
105    gl_shader_stage stage;
106 };
107 struct _shader_replacement shader_replacements[0];
108 
try_direct_replace(const char * app,const char * source)109 static char *try_direct_replace(const char *app, const char *source)
110 {
111    return NULL;
112 }
113 
load_shader_replacement(struct _shader_replacement * repl)114 static char* load_shader_replacement(struct _shader_replacement *repl)
115 {
116    return NULL;
117 }
118 #endif
119 #endif
120 
121 /**
122  * Return mask of GLSL_x flags by examining the MESA_GLSL env var.
123  */
124 GLbitfield
_mesa_get_shader_flags(void)125 _mesa_get_shader_flags(void)
126 {
127    GLbitfield flags = 0x0;
128    const char *env = getenv("MESA_GLSL");
129 
130    if (env) {
131       if (strstr(env, "dump_on_error"))
132          flags |= GLSL_DUMP_ON_ERROR;
133 #ifndef CUSTOM_SHADER_REPLACEMENT
134       else if (strstr(env, "dump"))
135          flags |= GLSL_DUMP;
136       if (strstr(env, "log"))
137          flags |= GLSL_LOG;
138 #endif
139       if (strstr(env, "cache_fb"))
140          flags |= GLSL_CACHE_FALLBACK;
141       if (strstr(env, "cache_info"))
142          flags |= GLSL_CACHE_INFO;
143       if (strstr(env, "nopvert"))
144          flags |= GLSL_NOP_VERT;
145       if (strstr(env, "nopfrag"))
146          flags |= GLSL_NOP_FRAG;
147       if (strstr(env, "uniform"))
148          flags |= GLSL_UNIFORMS;
149       if (strstr(env, "useprog"))
150          flags |= GLSL_USE_PROG;
151       if (strstr(env, "errors"))
152          flags |= GLSL_REPORT_ERRORS;
153    }
154 
155    return flags;
156 }
157 
158 #define ANDROID_SHADER_CAPTURE 0
159 
160 #if ANDROID_SHADER_CAPTURE
161 #include "util/u_process.h"
162 #include <sys/stat.h>
163 #include <sys/types.h>
164 #endif
165 
166 /**
167  * Memoized version of getenv("MESA_SHADER_CAPTURE_PATH").
168  */
169 const char *
_mesa_get_shader_capture_path(void)170 _mesa_get_shader_capture_path(void)
171 {
172    static bool read_env_var = false;
173    static const char *path = NULL;
174 
175    if (!read_env_var) {
176       path = getenv("MESA_SHADER_CAPTURE_PATH");
177       read_env_var = true;
178 
179 #if ANDROID_SHADER_CAPTURE
180       if (!path) {
181          char *p;
182          asprintf(&p, "/data/shaders/%s", util_get_process_name());
183          mkdir(p, 0755);
184          path = p;
185       }
186 #endif
187    }
188 
189    return path;
190 }
191 
192 /**
193  * Initialize context's shader state.
194  */
195 void
_mesa_init_shader_state(struct gl_context * ctx)196 _mesa_init_shader_state(struct gl_context *ctx)
197 {
198    /* Device drivers may override these to control what kind of instructions
199     * are generated by the GLSL compiler.
200     */
201    struct gl_shader_compiler_options options;
202    gl_shader_stage sh;
203    int i;
204 
205    memset(&options, 0, sizeof(options));
206    options.MaxUnrollIterations = 32;
207    options.MaxIfDepth = UINT_MAX;
208 
209    for (sh = 0; sh < MESA_SHADER_STAGES; ++sh)
210       memcpy(&ctx->Const.ShaderCompilerOptions[sh], &options, sizeof(options));
211 
212    ctx->Shader.Flags = _mesa_get_shader_flags();
213 
214    if (ctx->Shader.Flags != 0)
215       ctx->Const.GenerateTemporaryNames = true;
216 
217    /* Extended for ARB_separate_shader_objects */
218    ctx->Shader.RefCount = 1;
219    ctx->TessCtrlProgram.patch_vertices = 3;
220    for (i = 0; i < 4; ++i)
221       ctx->TessCtrlProgram.patch_default_outer_level[i] = 1.0;
222    for (i = 0; i < 2; ++i)
223       ctx->TessCtrlProgram.patch_default_inner_level[i] = 1.0;
224 }
225 
226 
227 /**
228  * Free the per-context shader-related state.
229  */
230 void
_mesa_free_shader_state(struct gl_context * ctx)231 _mesa_free_shader_state(struct gl_context *ctx)
232 {
233    for (int i = 0; i < MESA_SHADER_STAGES; i++) {
234       _mesa_reference_program(ctx, &ctx->Shader.CurrentProgram[i], NULL);
235       _mesa_reference_shader_program(ctx,
236                                      &ctx->Shader.ReferencedPrograms[i],
237                                      NULL);
238       free(ctx->SubroutineIndex[i].IndexPtr);
239       ctx->SubroutineIndex[i].IndexPtr = NULL;
240    }
241    _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, NULL);
242 
243    /* Extended for ARB_separate_shader_objects */
244    _mesa_reference_pipeline_object(ctx, &ctx->_Shader, NULL);
245 
246    assert(ctx->Shader.RefCount == 1);
247 }
248 
249 
250 /**
251  * Copy string from <src> to <dst>, up to maxLength characters, returning
252  * length of <dst> in <length>.
253  * \param src  the strings source
254  * \param maxLength  max chars to copy
255  * \param length  returns number of chars copied
256  * \param dst  the string destination
257  */
258 void
_mesa_copy_string(GLchar * dst,GLsizei maxLength,GLsizei * length,const GLchar * src)259 _mesa_copy_string(GLchar *dst, GLsizei maxLength,
260                   GLsizei *length, const GLchar *src)
261 {
262    GLsizei len;
263    for (len = 0; len < maxLength - 1 && src && src[len]; len++)
264       dst[len] = src[len];
265    if (maxLength > 0)
266       dst[len] = 0;
267    if (length)
268       *length = len;
269 }
270 
271 
272 
273 /**
274  * Confirm that the a shader type is valid and supported by the implementation
275  *
276  * \param ctx   Current GL context
277  * \param type  Shader target
278  *
279  */
280 bool
_mesa_validate_shader_target(const struct gl_context * ctx,GLenum type)281 _mesa_validate_shader_target(const struct gl_context *ctx, GLenum type)
282 {
283    /* Note: when building built-in GLSL functions, this function may be
284     * invoked with ctx == NULL.  In that case, we can only validate that it's
285     * a shader target we recognize, not that it's supported in the current
286     * context.  But that's fine--we don't need any further validation than
287     * that when building built-in GLSL functions.
288     */
289 
290    switch (type) {
291    case GL_FRAGMENT_SHADER:
292       return ctx == NULL || ctx->Extensions.ARB_fragment_shader;
293    case GL_VERTEX_SHADER:
294       return ctx == NULL || ctx->Extensions.ARB_vertex_shader;
295    case GL_GEOMETRY_SHADER_ARB:
296       return ctx == NULL || _mesa_has_geometry_shaders(ctx);
297    case GL_TESS_CONTROL_SHADER:
298    case GL_TESS_EVALUATION_SHADER:
299       return ctx == NULL || _mesa_has_tessellation(ctx);
300    case GL_COMPUTE_SHADER:
301       return ctx == NULL || _mesa_has_compute_shaders(ctx);
302    default:
303       return false;
304    }
305 }
306 
307 
308 static GLboolean
is_program(struct gl_context * ctx,GLuint name)309 is_program(struct gl_context *ctx, GLuint name)
310 {
311    struct gl_shader_program *shProg = _mesa_lookup_shader_program(ctx, name);
312    return shProg ? GL_TRUE : GL_FALSE;
313 }
314 
315 
316 static GLboolean
is_shader(struct gl_context * ctx,GLuint name)317 is_shader(struct gl_context *ctx, GLuint name)
318 {
319    struct gl_shader *shader = _mesa_lookup_shader(ctx, name);
320    return shader ? GL_TRUE : GL_FALSE;
321 }
322 
323 
324 /**
325  * Attach shader to a shader program.
326  */
327 static void
attach_shader(struct gl_context * ctx,struct gl_shader_program * shProg,struct gl_shader * sh)328 attach_shader(struct gl_context *ctx, struct gl_shader_program *shProg,
329               struct gl_shader *sh)
330 {
331    GLuint n = shProg->NumShaders;
332 
333    shProg->Shaders = realloc(shProg->Shaders,
334                              (n + 1) * sizeof(struct gl_shader *));
335    if (!shProg->Shaders) {
336       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAttachShader");
337       return;
338    }
339 
340    /* append */
341    shProg->Shaders[n] = NULL; /* since realloc() didn't zero the new space */
342    _mesa_reference_shader(ctx, &shProg->Shaders[n], sh);
343    shProg->NumShaders++;
344 }
345 
346 static void
attach_shader_err(struct gl_context * ctx,GLuint program,GLuint shader,const char * caller)347 attach_shader_err(struct gl_context *ctx, GLuint program, GLuint shader,
348                   const char *caller)
349 {
350    struct gl_shader_program *shProg;
351    struct gl_shader *sh;
352    GLuint i, n;
353 
354    const bool same_type_disallowed = _mesa_is_gles(ctx);
355 
356    shProg = _mesa_lookup_shader_program_err(ctx, program, caller);
357    if (!shProg)
358       return;
359 
360    sh = _mesa_lookup_shader_err(ctx, shader, caller);
361    if (!sh) {
362       return;
363    }
364 
365    n = shProg->NumShaders;
366    for (i = 0; i < n; i++) {
367       if (shProg->Shaders[i] == sh) {
368          /* The shader is already attched to this program.  The
369           * GL_ARB_shader_objects spec says:
370           *
371           *     "The error INVALID_OPERATION is generated by AttachObjectARB
372           *     if <obj> is already attached to <containerObj>."
373           */
374          _mesa_error(ctx, GL_INVALID_OPERATION, "%s", caller);
375          return;
376       } else if (same_type_disallowed &&
377                  shProg->Shaders[i]->Stage == sh->Stage) {
378         /* Shader with the same type is already attached to this program,
379          * OpenGL ES 2.0 and 3.0 specs say:
380          *
381          *      "Multiple shader objects of the same type may not be attached
382          *      to a single program object. [...] The error INVALID_OPERATION
383          *      is generated if [...] another shader object of the same type
384          *      as shader is already attached to program."
385          */
386          _mesa_error(ctx, GL_INVALID_OPERATION, "%s", caller);
387          return;
388       }
389    }
390 
391    attach_shader(ctx, shProg, sh);
392 }
393 
394 static void
attach_shader_no_error(struct gl_context * ctx,GLuint program,GLuint shader)395 attach_shader_no_error(struct gl_context *ctx, GLuint program, GLuint shader)
396 {
397    struct gl_shader_program *shProg;
398    struct gl_shader *sh;
399 
400    shProg = _mesa_lookup_shader_program(ctx, program);
401    sh = _mesa_lookup_shader(ctx, shader);
402 
403    attach_shader(ctx, shProg, sh);
404 }
405 
406 static GLuint
create_shader(struct gl_context * ctx,GLenum type)407 create_shader(struct gl_context *ctx, GLenum type)
408 {
409    struct gl_shader *sh;
410    GLuint name;
411 
412    _mesa_HashLockMutex(ctx->Shared->ShaderObjects);
413    name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
414    sh = _mesa_new_shader(name, _mesa_shader_enum_to_shader_stage(type));
415    sh->Type = type;
416    _mesa_HashInsertLocked(ctx->Shared->ShaderObjects, name, sh, true);
417    _mesa_HashUnlockMutex(ctx->Shared->ShaderObjects);
418 
419    return name;
420 }
421 
422 
423 static GLuint
create_shader_err(struct gl_context * ctx,GLenum type,const char * caller)424 create_shader_err(struct gl_context *ctx, GLenum type, const char *caller)
425 {
426    if (!_mesa_validate_shader_target(ctx, type)) {
427       _mesa_error(ctx, GL_INVALID_ENUM, "%s(%s)",
428                   caller, _mesa_enum_to_string(type));
429       return 0;
430    }
431 
432    return create_shader(ctx, type);
433 }
434 
435 
436 static GLuint
create_shader_program(struct gl_context * ctx)437 create_shader_program(struct gl_context *ctx)
438 {
439    GLuint name;
440    struct gl_shader_program *shProg;
441 
442    _mesa_HashLockMutex(ctx->Shared->ShaderObjects);
443 
444    name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
445 
446    shProg = _mesa_new_shader_program(name);
447 
448    _mesa_HashInsertLocked(ctx->Shared->ShaderObjects, name, shProg, true);
449 
450    assert(shProg->RefCount == 1);
451 
452    _mesa_HashUnlockMutex(ctx->Shared->ShaderObjects);
453 
454    return name;
455 }
456 
457 
458 /**
459  * Delete a shader program.  Actually, just decrement the program's
460  * reference count and mark it as DeletePending.
461  * Used to implement glDeleteProgram() and glDeleteObjectARB().
462  */
463 static void
delete_shader_program(struct gl_context * ctx,GLuint name)464 delete_shader_program(struct gl_context *ctx, GLuint name)
465 {
466    /*
467     * NOTE: deleting shaders/programs works a bit differently than
468     * texture objects (and buffer objects, etc).  Shader/program
469     * handles/IDs exist in the hash table until the object is really
470     * deleted (refcount==0).  With texture objects, the handle/ID is
471     * removed from the hash table in glDeleteTextures() while the tex
472     * object itself might linger until its refcount goes to zero.
473     */
474    struct gl_shader_program *shProg;
475 
476    shProg = _mesa_lookup_shader_program_err(ctx, name, "glDeleteProgram");
477    if (!shProg)
478       return;
479 
480    if (!shProg->DeletePending) {
481       shProg->DeletePending = GL_TRUE;
482 
483       /* effectively, decr shProg's refcount */
484       _mesa_reference_shader_program(ctx, &shProg, NULL);
485    }
486 }
487 
488 
489 static void
delete_shader(struct gl_context * ctx,GLuint shader)490 delete_shader(struct gl_context *ctx, GLuint shader)
491 {
492    struct gl_shader *sh;
493 
494    sh = _mesa_lookup_shader_err(ctx, shader, "glDeleteShader");
495    if (!sh)
496       return;
497 
498    if (!sh->DeletePending) {
499       sh->DeletePending = GL_TRUE;
500 
501       /* effectively, decr sh's refcount */
502       _mesa_reference_shader(ctx, &sh, NULL);
503    }
504 }
505 
506 
507 static ALWAYS_INLINE void
detach_shader(struct gl_context * ctx,GLuint program,GLuint shader,bool no_error)508 detach_shader(struct gl_context *ctx, GLuint program, GLuint shader,
509               bool no_error)
510 {
511    struct gl_shader_program *shProg;
512    GLuint n;
513    GLuint i, j;
514 
515    if (!no_error) {
516       shProg = _mesa_lookup_shader_program_err(ctx, program, "glDetachShader");
517       if (!shProg)
518          return;
519    } else {
520       shProg = _mesa_lookup_shader_program(ctx, program);
521    }
522 
523    n = shProg->NumShaders;
524 
525    for (i = 0; i < n; i++) {
526       if (shProg->Shaders[i]->Name == shader) {
527          /* found it */
528          struct gl_shader **newList;
529 
530          /* release */
531          _mesa_reference_shader(ctx, &shProg->Shaders[i], NULL);
532 
533          /* alloc new, smaller array */
534          newList = malloc((n - 1) * sizeof(struct gl_shader *));
535          if (!newList) {
536             _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDetachShader");
537             return;
538          }
539          /* Copy old list entries to new list, skipping removed entry at [i] */
540          for (j = 0; j < i; j++) {
541             newList[j] = shProg->Shaders[j];
542          }
543          while (++i < n) {
544             newList[j++] = shProg->Shaders[i];
545          }
546 
547          /* Free old list and install new one */
548          free(shProg->Shaders);
549          shProg->Shaders = newList;
550          shProg->NumShaders = n - 1;
551 
552 #ifndef NDEBUG
553          /* sanity check - make sure the new list's entries are sensible */
554          for (j = 0; j < shProg->NumShaders; j++) {
555             assert(shProg->Shaders[j]->Stage == MESA_SHADER_VERTEX ||
556                    shProg->Shaders[j]->Stage == MESA_SHADER_TESS_CTRL ||
557                    shProg->Shaders[j]->Stage == MESA_SHADER_TESS_EVAL ||
558                    shProg->Shaders[j]->Stage == MESA_SHADER_GEOMETRY ||
559                    shProg->Shaders[j]->Stage == MESA_SHADER_FRAGMENT);
560             assert(shProg->Shaders[j]->RefCount > 0);
561          }
562 #endif
563 
564          return;
565       }
566    }
567 
568    /* not found */
569    if (!no_error) {
570       GLenum err;
571       if (is_shader(ctx, shader) || is_program(ctx, shader))
572          err = GL_INVALID_OPERATION;
573       else
574          err = GL_INVALID_VALUE;
575       _mesa_error(ctx, err, "glDetachShader(shader)");
576       return;
577    }
578 }
579 
580 
581 static void
detach_shader_error(struct gl_context * ctx,GLuint program,GLuint shader)582 detach_shader_error(struct gl_context *ctx, GLuint program, GLuint shader)
583 {
584    detach_shader(ctx, program, shader, false);
585 }
586 
587 
588 static void
detach_shader_no_error(struct gl_context * ctx,GLuint program,GLuint shader)589 detach_shader_no_error(struct gl_context *ctx, GLuint program, GLuint shader)
590 {
591    detach_shader(ctx, program, shader, true);
592 }
593 
594 
595 /**
596  * Return list of shaders attached to shader program.
597  * \param objOut  returns GLuint ids
598  * \param handleOut  returns GLhandleARB handles
599  */
600 static void
get_attached_shaders(struct gl_context * ctx,GLuint program,GLsizei maxCount,GLsizei * countOut,GLuint * objOut,GLhandleARB * handleOut)601 get_attached_shaders(struct gl_context *ctx, GLuint program, GLsizei maxCount,
602                      GLsizei *countOut, GLuint *objOut, GLhandleARB *handleOut)
603 {
604    struct gl_shader_program *shProg;
605 
606    if (maxCount < 0) {
607       _mesa_error(ctx, GL_INVALID_VALUE, "glGetAttachedShaders(maxCount < 0)");
608       return;
609    }
610 
611    shProg =
612       _mesa_lookup_shader_program_err(ctx, program, "glGetAttachedShaders");
613 
614    if (shProg) {
615       GLuint i;
616       for (i = 0; i < (GLuint) maxCount && i < shProg->NumShaders; i++) {
617          if (objOut) {
618             objOut[i] = shProg->Shaders[i]->Name;
619          }
620 
621          if (handleOut) {
622             handleOut[i] = (GLhandleARB) shProg->Shaders[i]->Name;
623          }
624       }
625       if (countOut) {
626          *countOut = i;
627       }
628    }
629 }
630 
631 /**
632  * glGetHandleARB() - return ID/name of currently bound shader program.
633  */
634 static GLuint
get_handle(struct gl_context * ctx,GLenum pname)635 get_handle(struct gl_context *ctx, GLenum pname)
636 {
637    if (pname == GL_PROGRAM_OBJECT_ARB) {
638       if (ctx->_Shader->ActiveProgram)
639          return ctx->_Shader->ActiveProgram->Name;
640       else
641          return 0;
642    }
643    else {
644       _mesa_error(ctx, GL_INVALID_ENUM, "glGetHandleARB");
645       return 0;
646    }
647 }
648 
649 
650 /**
651  * Check if a geometry shader query is valid at this time.  If not, report an
652  * error and return false.
653  *
654  * From GL 3.2 section 6.1.16 (Shader and Program Queries):
655  *
656  *     "If GEOMETRY_VERTICES_OUT, GEOMETRY_INPUT_TYPE, or GEOMETRY_OUTPUT_TYPE
657  *     are queried for a program which has not been linked successfully, or
658  *     which does not contain objects to form a geometry shader, then an
659  *     INVALID_OPERATION error is generated."
660  */
661 static bool
check_gs_query(struct gl_context * ctx,const struct gl_shader_program * shProg)662 check_gs_query(struct gl_context *ctx, const struct gl_shader_program *shProg)
663 {
664    if (shProg->data->LinkStatus &&
665        shProg->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
666       return true;
667    }
668 
669    _mesa_error(ctx, GL_INVALID_OPERATION,
670                "glGetProgramv(linked geometry shader required)");
671    return false;
672 }
673 
674 
675 /**
676  * Check if a tessellation control shader query is valid at this time.
677  * If not, report an error and return false.
678  *
679  * From GL 4.0 section 6.1.12 (Shader and Program Queries):
680  *
681  *     "If TESS_CONTROL_OUTPUT_VERTICES is queried for a program which has
682  *     not been linked successfully, or which does not contain objects to
683  *     form a tessellation control shader, then an INVALID_OPERATION error is
684  *     generated."
685  */
686 static bool
check_tcs_query(struct gl_context * ctx,const struct gl_shader_program * shProg)687 check_tcs_query(struct gl_context *ctx, const struct gl_shader_program *shProg)
688 {
689    if (shProg->data->LinkStatus &&
690        shProg->_LinkedShaders[MESA_SHADER_TESS_CTRL] != NULL) {
691       return true;
692    }
693 
694    _mesa_error(ctx, GL_INVALID_OPERATION,
695                "glGetProgramv(linked tessellation control shader required)");
696    return false;
697 }
698 
699 
700 /**
701  * Check if a tessellation evaluation shader query is valid at this time.
702  * If not, report an error and return false.
703  *
704  * From GL 4.0 section 6.1.12 (Shader and Program Queries):
705  *
706  *     "If any of the pname values in this paragraph are queried for a program
707  *     which has not been linked successfully, or which does not contain
708  *     objects to form a tessellation evaluation shader, then an
709  *     INVALID_OPERATION error is generated."
710  *
711  */
712 static bool
check_tes_query(struct gl_context * ctx,const struct gl_shader_program * shProg)713 check_tes_query(struct gl_context *ctx, const struct gl_shader_program *shProg)
714 {
715    if (shProg->data->LinkStatus &&
716        shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL] != NULL) {
717       return true;
718    }
719 
720    _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramv(linked tessellation "
721                "evaluation shader required)");
722    return false;
723 }
724 
725 static bool
get_shader_program_completion_status(struct gl_context * ctx,struct gl_shader_program * shprog)726 get_shader_program_completion_status(struct gl_context *ctx,
727                                      struct gl_shader_program *shprog)
728 {
729    struct pipe_screen *screen = ctx->screen;
730 
731    if (!screen->is_parallel_shader_compilation_finished)
732       return true;
733 
734    for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
735       struct gl_linked_shader *linked = shprog->_LinkedShaders[i];
736       void *sh = NULL;
737 
738       if (!linked || !linked->Program)
739          continue;
740 
741       if (linked->Program->variants)
742          sh = linked->Program->variants->driver_shader;
743 
744       unsigned type = pipe_shader_type_from_mesa(i);
745 
746       if (sh &&
747           !screen->is_parallel_shader_compilation_finished(screen, sh, type))
748          return false;
749    }
750    return true;
751 }
752 
753 /**
754  * glGetProgramiv() - get shader program state.
755  * Note that this is for GLSL shader programs, not ARB vertex/fragment
756  * programs (see glGetProgramivARB).
757  */
758 static void
get_programiv(struct gl_context * ctx,GLuint program,GLenum pname,GLint * params)759 get_programiv(struct gl_context *ctx, GLuint program, GLenum pname,
760               GLint *params)
761 {
762    struct gl_shader_program *shProg
763       = _mesa_lookup_shader_program_err(ctx, program, "glGetProgramiv(program)");
764 
765    /* Is transform feedback available in this context?
766     */
767    const bool has_xfb =
768       (ctx->API == API_OPENGL_COMPAT && ctx->Extensions.EXT_transform_feedback)
769       || ctx->API == API_OPENGL_CORE
770       || _mesa_is_gles3(ctx);
771 
772    /* True if geometry shaders (of the form that was adopted into GLSL 1.50
773     * and GL 3.2) are available in this context
774     */
775    const bool has_gs = _mesa_has_geometry_shaders(ctx);
776    const bool has_tess = _mesa_has_tessellation(ctx);
777 
778    /* Are uniform buffer objects available in this context?
779     */
780    const bool has_ubo =
781       (ctx->API == API_OPENGL_COMPAT &&
782        ctx->Extensions.ARB_uniform_buffer_object)
783       || ctx->API == API_OPENGL_CORE
784       || _mesa_is_gles3(ctx);
785 
786    if (!shProg) {
787       return;
788    }
789 
790    switch (pname) {
791    case GL_DELETE_STATUS:
792       *params = shProg->DeletePending;
793       return;
794    case GL_COMPLETION_STATUS_ARB:
795       *params = get_shader_program_completion_status(ctx, shProg);
796       return;
797    case GL_LINK_STATUS:
798       *params = shProg->data->LinkStatus ? GL_TRUE : GL_FALSE;
799       return;
800    case GL_VALIDATE_STATUS:
801       *params = shProg->data->Validated;
802       return;
803    case GL_INFO_LOG_LENGTH:
804       *params = (shProg->data->InfoLog && shProg->data->InfoLog[0] != '\0') ?
805          strlen(shProg->data->InfoLog) + 1 : 0;
806       return;
807    case GL_ATTACHED_SHADERS:
808       *params = shProg->NumShaders;
809       return;
810    case GL_ACTIVE_ATTRIBUTES:
811       *params = _mesa_count_active_attribs(shProg);
812       return;
813    case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
814       *params = _mesa_longest_attribute_name_length(shProg);
815       return;
816    case GL_ACTIVE_UNIFORMS: {
817       _mesa_get_program_interfaceiv(shProg, GL_UNIFORM, GL_ACTIVE_RESOURCES,
818                                     params);
819       return;
820    }
821    case GL_ACTIVE_UNIFORM_MAX_LENGTH: {
822       _mesa_get_program_interfaceiv(shProg, GL_UNIFORM, GL_MAX_NAME_LENGTH,
823                                     params);
824       return;
825    }
826    case GL_TRANSFORM_FEEDBACK_VARYINGS:
827       if (!has_xfb)
828          break;
829 
830       /* Check first if there are transform feedback varyings specified in the
831        * shader (ARB_enhanced_layouts). If there isn't any, return the number of
832        * varyings specified using the API.
833        */
834       if (shProg->last_vert_prog &&
835           shProg->last_vert_prog->sh.LinkedTransformFeedback->NumVarying > 0)
836          *params =
837             shProg->last_vert_prog->sh.LinkedTransformFeedback->NumVarying;
838       else
839          *params = shProg->TransformFeedback.NumVarying;
840       return;
841    case GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH: {
842       if (!has_xfb)
843          break;
844 
845       _mesa_get_program_interfaceiv(shProg, GL_TRANSFORM_FEEDBACK_VARYING,
846                                     GL_MAX_NAME_LENGTH, params);
847       return;
848    }
849    case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
850       if (!has_xfb)
851          break;
852       *params = shProg->TransformFeedback.BufferMode;
853       return;
854    case GL_GEOMETRY_VERTICES_OUT:
855       if (!has_gs)
856          break;
857       if (check_gs_query(ctx, shProg)) {
858          *params = shProg->_LinkedShaders[MESA_SHADER_GEOMETRY]->
859             Program->info.gs.vertices_out;
860       }
861       return;
862    case GL_GEOMETRY_SHADER_INVOCATIONS:
863       if (!has_gs ||
864           (_mesa_is_desktop_gl(ctx) && !ctx->Extensions.ARB_gpu_shader5)) {
865          break;
866       }
867       if (check_gs_query(ctx, shProg)) {
868          *params = shProg->_LinkedShaders[MESA_SHADER_GEOMETRY]->
869             Program->info.gs.invocations;
870       }
871       return;
872    case GL_GEOMETRY_INPUT_TYPE:
873       if (!has_gs)
874          break;
875       if (check_gs_query(ctx, shProg)) {
876          *params = shProg->_LinkedShaders[MESA_SHADER_GEOMETRY]->
877             Program->info.gs.input_primitive;
878       }
879       return;
880    case GL_GEOMETRY_OUTPUT_TYPE:
881       if (!has_gs)
882          break;
883       if (check_gs_query(ctx, shProg)) {
884          *params = shProg->_LinkedShaders[MESA_SHADER_GEOMETRY]->
885             Program->info.gs.output_primitive;
886       }
887       return;
888    case GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH: {
889       if (!has_ubo)
890          break;
891 
892       _mesa_get_program_interfaceiv(shProg, GL_UNIFORM_BLOCK,
893                                     GL_MAX_NAME_LENGTH, params);
894       return;
895    }
896    case GL_ACTIVE_UNIFORM_BLOCKS:
897       if (!has_ubo)
898          break;
899 
900       *params = shProg->data->NumUniformBlocks;
901       return;
902    case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
903       /* This enum isn't part of the OES extension for OpenGL ES 2.0.  It is
904        * only available with desktop OpenGL 3.0+ with the
905        * GL_ARB_get_program_binary extension or OpenGL ES 3.0.
906        *
907        * On desktop, we ignore the 3.0+ requirement because it is silly.
908        */
909       if (!_mesa_is_desktop_gl(ctx) && !_mesa_is_gles3(ctx))
910          break;
911 
912       *params = shProg->BinaryRetrievableHint;
913       return;
914    case GL_PROGRAM_BINARY_LENGTH:
915       if (ctx->Const.NumProgramBinaryFormats == 0 || !shProg->data->LinkStatus) {
916          *params = 0;
917       } else {
918          _mesa_get_program_binary_length(ctx, shProg, params);
919       }
920       return;
921    case GL_ACTIVE_ATOMIC_COUNTER_BUFFERS:
922       if (!ctx->Extensions.ARB_shader_atomic_counters && !_mesa_is_gles31(ctx))
923          break;
924 
925       *params = shProg->data->NumAtomicBuffers;
926       return;
927    case GL_COMPUTE_WORK_GROUP_SIZE: {
928       int i;
929       if (!_mesa_has_compute_shaders(ctx))
930          break;
931       if (!shProg->data->LinkStatus) {
932          _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramiv(program not "
933                      "linked)");
934          return;
935       }
936       if (shProg->_LinkedShaders[MESA_SHADER_COMPUTE] == NULL) {
937          _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramiv(no compute "
938                      "shaders)");
939          return;
940       }
941       for (i = 0; i < 3; i++)
942          params[i] = shProg->_LinkedShaders[MESA_SHADER_COMPUTE]->
943             Program->info.workgroup_size[i];
944       return;
945    }
946    case GL_PROGRAM_SEPARABLE:
947       /* If the program has not been linked, return initial value 0. */
948       *params = (shProg->data->LinkStatus == LINKING_FAILURE) ? 0 : shProg->SeparateShader;
949       return;
950 
951    /* ARB_tessellation_shader */
952    case GL_TESS_CONTROL_OUTPUT_VERTICES:
953       if (!has_tess)
954          break;
955       if (check_tcs_query(ctx, shProg)) {
956          *params = shProg->_LinkedShaders[MESA_SHADER_TESS_CTRL]->
957             Program->info.tess.tcs_vertices_out;
958       }
959       return;
960    case GL_TESS_GEN_MODE:
961       if (!has_tess)
962          break;
963       if (check_tes_query(ctx, shProg)) {
964          const struct gl_linked_shader *tes =
965             shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL];
966          switch (tes->Program->info.tess._primitive_mode) {
967          case TESS_PRIMITIVE_TRIANGLES:
968             *params = GL_TRIANGLES;
969             break;
970          case TESS_PRIMITIVE_QUADS:
971             *params = GL_QUADS;
972             break;
973          case TESS_PRIMITIVE_ISOLINES:
974             *params = GL_ISOLINES;
975             break;
976          case TESS_PRIMITIVE_UNSPECIFIED:
977             *params = 0;
978             break;
979          }
980       }
981       return;
982    case GL_TESS_GEN_SPACING:
983       if (!has_tess)
984          break;
985       if (check_tes_query(ctx, shProg)) {
986          const struct gl_linked_shader *tes =
987             shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL];
988          switch (tes->Program->info.tess.spacing) {
989          case TESS_SPACING_EQUAL:
990             *params = GL_EQUAL;
991             break;
992          case TESS_SPACING_FRACTIONAL_ODD:
993             *params = GL_FRACTIONAL_ODD;
994             break;
995          case TESS_SPACING_FRACTIONAL_EVEN:
996             *params = GL_FRACTIONAL_EVEN;
997             break;
998          case TESS_SPACING_UNSPECIFIED:
999             *params = 0;
1000             break;
1001          }
1002       }
1003       return;
1004    case GL_TESS_GEN_VERTEX_ORDER:
1005       if (!has_tess)
1006          break;
1007       if (check_tes_query(ctx, shProg)) {
1008          *params = shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL]->
1009             Program->info.tess.ccw ? GL_CCW : GL_CW;
1010          }
1011       return;
1012    case GL_TESS_GEN_POINT_MODE:
1013       if (!has_tess)
1014          break;
1015       if (check_tes_query(ctx, shProg)) {
1016          *params = shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL]->
1017             Program->info.tess.point_mode ? GL_TRUE : GL_FALSE;
1018       }
1019       return;
1020    default:
1021       break;
1022    }
1023 
1024    _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramiv(pname=%s)",
1025                _mesa_enum_to_string(pname));
1026 }
1027 
1028 
1029 /**
1030  * glGetShaderiv() - get GLSL shader state
1031  */
1032 static void
get_shaderiv(struct gl_context * ctx,GLuint name,GLenum pname,GLint * params)1033 get_shaderiv(struct gl_context *ctx, GLuint name, GLenum pname, GLint *params)
1034 {
1035    struct gl_shader *shader =
1036       _mesa_lookup_shader_err(ctx, name, "glGetShaderiv");
1037 
1038    if (!shader) {
1039       return;
1040    }
1041 
1042    switch (pname) {
1043    case GL_SHADER_TYPE:
1044       *params = shader->Type;
1045       break;
1046    case GL_DELETE_STATUS:
1047       *params = shader->DeletePending;
1048       break;
1049    case GL_COMPLETION_STATUS_ARB:
1050       /* _mesa_glsl_compile_shader is not offloaded to other threads. */
1051       *params = GL_TRUE;
1052       return;
1053    case GL_COMPILE_STATUS:
1054       *params = shader->CompileStatus ? GL_TRUE : GL_FALSE;
1055       break;
1056    case GL_INFO_LOG_LENGTH:
1057       *params = (shader->InfoLog && shader->InfoLog[0] != '\0') ?
1058          strlen(shader->InfoLog) + 1 : 0;
1059       break;
1060    case GL_SHADER_SOURCE_LENGTH:
1061       *params = shader->Source ? strlen((char *) shader->Source) + 1 : 0;
1062       break;
1063    case GL_SPIR_V_BINARY_ARB:
1064       *params = (shader->spirv_data != NULL);
1065       break;
1066    default:
1067       _mesa_error(ctx, GL_INVALID_ENUM, "glGetShaderiv(pname)");
1068       return;
1069    }
1070 }
1071 
1072 
1073 static void
get_program_info_log(struct gl_context * ctx,GLuint program,GLsizei bufSize,GLsizei * length,GLchar * infoLog)1074 get_program_info_log(struct gl_context *ctx, GLuint program, GLsizei bufSize,
1075                      GLsizei *length, GLchar *infoLog)
1076 {
1077    struct gl_shader_program *shProg;
1078 
1079    /* Section 2.5 GL Errors (page 18) of the OpenGL ES 3.0.4 spec and
1080     * section 2.3.1 (Errors) of the OpenGL 4.5 spec say:
1081     *
1082     *     "If a negative number is provided where an argument of type sizei or
1083     *     sizeiptr is specified, an INVALID_VALUE error is generated."
1084     */
1085    if (bufSize < 0) {
1086       _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramInfoLog(bufSize < 0)");
1087       return;
1088    }
1089 
1090    shProg = _mesa_lookup_shader_program_err(ctx, program,
1091                                             "glGetProgramInfoLog(program)");
1092    if (!shProg) {
1093       return;
1094    }
1095 
1096    _mesa_copy_string(infoLog, bufSize, length, shProg->data->InfoLog);
1097 }
1098 
1099 
1100 static void
get_shader_info_log(struct gl_context * ctx,GLuint shader,GLsizei bufSize,GLsizei * length,GLchar * infoLog)1101 get_shader_info_log(struct gl_context *ctx, GLuint shader, GLsizei bufSize,
1102                     GLsizei *length, GLchar *infoLog)
1103 {
1104    struct gl_shader *sh;
1105 
1106    /* Section 2.5 GL Errors (page 18) of the OpenGL ES 3.0.4 spec and
1107     * section 2.3.1 (Errors) of the OpenGL 4.5 spec say:
1108     *
1109     *     "If a negative number is provided where an argument of type sizei or
1110     *     sizeiptr is specified, an INVALID_VALUE error is generated."
1111     */
1112    if (bufSize < 0) {
1113       _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderInfoLog(bufSize < 0)");
1114       return;
1115    }
1116 
1117    sh = _mesa_lookup_shader_err(ctx, shader, "glGetShaderInfoLog(shader)");
1118    if (!sh) {
1119       return;
1120    }
1121 
1122    _mesa_copy_string(infoLog, bufSize, length, sh->InfoLog);
1123 }
1124 
1125 
1126 /**
1127  * Return shader source code.
1128  */
1129 static void
get_shader_source(struct gl_context * ctx,GLuint shader,GLsizei maxLength,GLsizei * length,GLchar * sourceOut)1130 get_shader_source(struct gl_context *ctx, GLuint shader, GLsizei maxLength,
1131                   GLsizei *length, GLchar *sourceOut)
1132 {
1133    struct gl_shader *sh;
1134 
1135    if (maxLength < 0) {
1136       _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderSource(bufSize < 0)");
1137       return;
1138    }
1139 
1140    sh = _mesa_lookup_shader_err(ctx, shader, "glGetShaderSource");
1141    if (!sh) {
1142       return;
1143    }
1144    _mesa_copy_string(sourceOut, maxLength, length, sh->Source);
1145 }
1146 
1147 
1148 /**
1149  * Set/replace shader source code.  A helper function used by
1150  * glShaderSource[ARB].
1151  */
1152 static void
set_shader_source(struct gl_shader * sh,const GLchar * source,const uint8_t original_sha1[SHA1_DIGEST_LENGTH])1153 set_shader_source(struct gl_shader *sh, const GLchar *source,
1154                   const uint8_t original_sha1[SHA1_DIGEST_LENGTH])
1155 {
1156    assert(sh);
1157 
1158    /* The GL_ARB_gl_spirv spec adds the following to the end of the description
1159     * of ShaderSource:
1160     *
1161     *   "If <shader> was previously associated with a SPIR-V module (via the
1162     *    ShaderBinary command), that association is broken. Upon successful
1163     *    completion of this command the SPIR_V_BINARY_ARB state of <shader>
1164     *    is set to FALSE."
1165     */
1166    _mesa_shader_spirv_data_reference(&sh->spirv_data, NULL);
1167 
1168    if (sh->CompileStatus == COMPILE_SKIPPED && !sh->FallbackSource) {
1169       /* If shader was previously compiled back-up the source in case of cache
1170        * fallback.
1171        */
1172       sh->FallbackSource = sh->Source;
1173       memcpy(sh->fallback_source_sha1, sh->source_sha1, SHA1_DIGEST_LENGTH);
1174       sh->Source = source;
1175    } else {
1176       /* free old shader source string and install new one */
1177       free((void *)sh->Source);
1178       sh->Source = source;
1179    }
1180 
1181    memcpy(sh->source_sha1, original_sha1, SHA1_DIGEST_LENGTH);
1182 }
1183 
1184 static void
ensure_builtin_types(struct gl_context * ctx)1185 ensure_builtin_types(struct gl_context *ctx)
1186 {
1187    if (!ctx->shader_builtin_ref) {
1188       _mesa_glsl_builtin_functions_init_or_ref();
1189       ctx->shader_builtin_ref = true;
1190    }
1191 }
1192 
1193 /**
1194  * Compile a shader.
1195  */
1196 void
_mesa_compile_shader(struct gl_context * ctx,struct gl_shader * sh)1197 _mesa_compile_shader(struct gl_context *ctx, struct gl_shader *sh)
1198 {
1199    if (!sh)
1200       return;
1201 
1202    /* The GL_ARB_gl_spirv spec says:
1203     *
1204     *    "Add a new error for the CompileShader command:
1205     *
1206     *      An INVALID_OPERATION error is generated if the SPIR_V_BINARY_ARB
1207     *      state of <shader> is TRUE."
1208     */
1209    if (sh->spirv_data) {
1210       _mesa_error(ctx, GL_INVALID_OPERATION, "glCompileShader(SPIR-V)");
1211       return;
1212    }
1213 
1214    if (!sh->Source) {
1215       /* If the user called glCompileShader without first calling
1216        * glShaderSource, we should fail to compile, but not raise a GL_ERROR.
1217        */
1218       sh->CompileStatus = COMPILE_FAILURE;
1219    } else {
1220       if (ctx->_Shader->Flags & GLSL_DUMP) {
1221          _mesa_log("GLSL source for %s shader %d:\n",
1222                  _mesa_shader_stage_to_string(sh->Stage), sh->Name);
1223          _mesa_log_direct(sh->Source);
1224       }
1225 
1226       ensure_builtin_types(ctx);
1227 
1228       /* this call will set the shader->CompileStatus field to indicate if
1229        * compilation was successful.
1230        */
1231       _mesa_glsl_compile_shader(ctx, sh, false, false, false);
1232 
1233       if (ctx->_Shader->Flags & GLSL_LOG) {
1234          _mesa_write_shader_to_file(sh);
1235       }
1236 
1237       if (ctx->_Shader->Flags & GLSL_DUMP) {
1238          if (sh->CompileStatus) {
1239             if (sh->ir) {
1240                _mesa_log("GLSL IR for shader %d:\n", sh->Name);
1241                _mesa_print_ir(_mesa_get_log_file(), sh->ir, NULL);
1242             } else {
1243                _mesa_log("No GLSL IR for shader %d (shader may be from "
1244                          "cache)\n", sh->Name);
1245             }
1246             _mesa_log("\n\n");
1247          } else {
1248             _mesa_log("GLSL shader %d failed to compile.\n", sh->Name);
1249          }
1250          if (sh->InfoLog && sh->InfoLog[0] != 0) {
1251             _mesa_log("GLSL shader %d info log:\n", sh->Name);
1252             _mesa_log("%s\n", sh->InfoLog);
1253          }
1254       }
1255    }
1256 
1257    if (!sh->CompileStatus) {
1258       if (ctx->_Shader->Flags & GLSL_DUMP_ON_ERROR) {
1259          _mesa_log("GLSL source for %s shader %d:\n",
1260                  _mesa_shader_stage_to_string(sh->Stage), sh->Name);
1261          _mesa_log("%s\n", sh->Source);
1262          _mesa_log("Info Log:\n%s\n", sh->InfoLog);
1263       }
1264 
1265       if (ctx->_Shader->Flags & GLSL_REPORT_ERRORS) {
1266          _mesa_debug(ctx, "Error compiling shader %u:\n%s\n",
1267                      sh->Name, sh->InfoLog);
1268       }
1269    }
1270 }
1271 
1272 
1273 struct update_programs_in_pipeline_params
1274 {
1275    struct gl_context *ctx;
1276    struct gl_shader_program *shProg;
1277 };
1278 
1279 static void
update_programs_in_pipeline(void * data,void * userData)1280 update_programs_in_pipeline(void *data, void *userData)
1281 {
1282    struct update_programs_in_pipeline_params *params =
1283       (struct update_programs_in_pipeline_params *) userData;
1284    struct gl_pipeline_object *obj = (struct gl_pipeline_object *) data;
1285 
1286    for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1287       if (obj->CurrentProgram[stage] &&
1288           obj->CurrentProgram[stage]->Id == params->shProg->Name) {
1289          struct gl_program *prog = params->shProg->_LinkedShaders[stage]->Program;
1290          _mesa_use_program(params->ctx, stage, params->shProg, prog, obj);
1291       }
1292    }
1293 }
1294 
1295 
1296 /**
1297  * Link a program's shaders.
1298  */
1299 static ALWAYS_INLINE void
link_program(struct gl_context * ctx,struct gl_shader_program * shProg,bool no_error)1300 link_program(struct gl_context *ctx, struct gl_shader_program *shProg,
1301              bool no_error)
1302 {
1303    if (!shProg)
1304       return;
1305 
1306    if (!no_error) {
1307       /* From the ARB_transform_feedback2 specification:
1308        * "The error INVALID_OPERATION is generated by LinkProgram if <program>
1309        * is the name of a program being used by one or more transform feedback
1310        * objects, even if the objects are not currently bound or are paused."
1311        */
1312       if (_mesa_transform_feedback_is_using_program(ctx, shProg)) {
1313          _mesa_error(ctx, GL_INVALID_OPERATION,
1314                      "glLinkProgram(transform feedback is using the program)");
1315          return;
1316       }
1317    }
1318 
1319    unsigned programs_in_use = 0;
1320    if (ctx->_Shader)
1321       for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1322          if (ctx->_Shader->CurrentProgram[stage] &&
1323              ctx->_Shader->CurrentProgram[stage]->Id == shProg->Name) {
1324             programs_in_use |= 1 << stage;
1325          }
1326       }
1327 
1328    ensure_builtin_types(ctx);
1329 
1330    FLUSH_VERTICES(ctx, 0, 0);
1331    _mesa_glsl_link_shader(ctx, shProg);
1332 
1333    /* From section 7.3 (Program Objects) of the OpenGL 4.5 spec:
1334     *
1335     *    "If LinkProgram or ProgramBinary successfully re-links a program
1336     *     object that is active for any shader stage, then the newly generated
1337     *     executable code will be installed as part of the current rendering
1338     *     state for all shader stages where the program is active.
1339     *     Additionally, the newly generated executable code is made part of
1340     *     the state of any program pipeline for all stages where the program
1341     *     is attached."
1342     */
1343    if (shProg->data->LinkStatus) {
1344       while (programs_in_use) {
1345          const int stage = u_bit_scan(&programs_in_use);
1346 
1347          struct gl_program *prog = NULL;
1348          if (shProg->_LinkedShaders[stage])
1349             prog = shProg->_LinkedShaders[stage]->Program;
1350 
1351          _mesa_use_program(ctx, stage, shProg, prog, ctx->_Shader);
1352       }
1353 
1354       if (ctx->Pipeline.Objects) {
1355          struct update_programs_in_pipeline_params params = {
1356             .ctx = ctx,
1357             .shProg = shProg
1358          };
1359          _mesa_HashWalk(ctx->Pipeline.Objects, update_programs_in_pipeline,
1360                         &params);
1361       }
1362    }
1363 
1364 #ifndef CUSTOM_SHADER_REPLACEMENT
1365    /* Capture .shader_test files. */
1366    const char *capture_path = _mesa_get_shader_capture_path();
1367    if (shProg->Name != 0 && shProg->Name != ~0 && capture_path != NULL) {
1368       /* Find an unused filename. */
1369       FILE *file = NULL;
1370       char *filename = NULL;
1371       for (unsigned i = 0;; i++) {
1372          if (i) {
1373             filename = ralloc_asprintf(NULL, "%s/%u-%u.shader_test",
1374                                        capture_path, shProg->Name, i);
1375          } else {
1376             filename = ralloc_asprintf(NULL, "%s/%u.shader_test",
1377                                        capture_path, shProg->Name);
1378          }
1379          file = os_file_create_unique(filename, 0644);
1380          if (file)
1381             break;
1382          /* If we are failing for another reason than "this filename already
1383           * exists", we are likely to fail again with another filename, so
1384           * let's just give up */
1385          if (errno != EEXIST)
1386             break;
1387          ralloc_free(filename);
1388       }
1389       if (file) {
1390          fprintf(file, "[require]\nGLSL%s >= %u.%02u\n",
1391                  shProg->IsES ? " ES" : "",
1392                  shProg->data->Version / 100, shProg->data->Version % 100);
1393          if (shProg->SeparateShader)
1394             fprintf(file, "GL_ARB_separate_shader_objects\nSSO ENABLED\n");
1395          fprintf(file, "\n");
1396 
1397          for (unsigned i = 0; i < shProg->NumShaders; i++) {
1398             fprintf(file, "[%s shader]\n%s\n",
1399                     _mesa_shader_stage_to_string(shProg->Shaders[i]->Stage),
1400                     shProg->Shaders[i]->Source);
1401          }
1402          fclose(file);
1403       } else {
1404          _mesa_warning(ctx, "Failed to open %s", filename);
1405       }
1406 
1407       ralloc_free(filename);
1408    }
1409 #endif
1410 
1411    if (shProg->data->LinkStatus == LINKING_FAILURE &&
1412        (ctx->_Shader->Flags & GLSL_REPORT_ERRORS)) {
1413       _mesa_debug(ctx, "Error linking program %u:\n%s\n",
1414                   shProg->Name, shProg->data->InfoLog);
1415    }
1416 
1417    _mesa_update_vertex_processing_mode(ctx);
1418    _mesa_update_valid_to_render_state(ctx);
1419 
1420    shProg->BinaryRetrievableHint = shProg->BinaryRetrievableHintPending;
1421 
1422    /* debug code */
1423    if (0) {
1424       GLuint i;
1425 
1426       printf("Link %u shaders in program %u: %s\n",
1427                    shProg->NumShaders, shProg->Name,
1428                    shProg->data->LinkStatus ? "Success" : "Failed");
1429 
1430       for (i = 0; i < shProg->NumShaders; i++) {
1431          printf(" shader %u, stage %u\n",
1432                       shProg->Shaders[i]->Name,
1433                       shProg->Shaders[i]->Stage);
1434       }
1435    }
1436 }
1437 
1438 
1439 static void
link_program_error(struct gl_context * ctx,struct gl_shader_program * shProg)1440 link_program_error(struct gl_context *ctx, struct gl_shader_program *shProg)
1441 {
1442    link_program(ctx, shProg, false);
1443 }
1444 
1445 
1446 static void
link_program_no_error(struct gl_context * ctx,struct gl_shader_program * shProg)1447 link_program_no_error(struct gl_context *ctx, struct gl_shader_program *shProg)
1448 {
1449    link_program(ctx, shProg, true);
1450 }
1451 
1452 
1453 void
_mesa_link_program(struct gl_context * ctx,struct gl_shader_program * shProg)1454 _mesa_link_program(struct gl_context *ctx, struct gl_shader_program *shProg)
1455 {
1456    link_program_error(ctx, shProg);
1457 }
1458 
1459 
1460 /**
1461  * Print basic shader info (for debug).
1462  */
1463 static void
print_shader_info(const struct gl_shader_program * shProg)1464 print_shader_info(const struct gl_shader_program *shProg)
1465 {
1466    GLuint i;
1467 
1468    printf("Mesa: glUseProgram(%u)\n", shProg->Name);
1469    for (i = 0; i < shProg->NumShaders; i++) {
1470       printf("  %s shader %u\n",
1471              _mesa_shader_stage_to_string(shProg->Shaders[i]->Stage),
1472              shProg->Shaders[i]->Name);
1473    }
1474    if (shProg->_LinkedShaders[MESA_SHADER_VERTEX])
1475       printf("  vert prog %u\n",
1476 	     shProg->_LinkedShaders[MESA_SHADER_VERTEX]->Program->Id);
1477    if (shProg->_LinkedShaders[MESA_SHADER_FRAGMENT])
1478       printf("  frag prog %u\n",
1479 	     shProg->_LinkedShaders[MESA_SHADER_FRAGMENT]->Program->Id);
1480    if (shProg->_LinkedShaders[MESA_SHADER_GEOMETRY])
1481       printf("  geom prog %u\n",
1482 	     shProg->_LinkedShaders[MESA_SHADER_GEOMETRY]->Program->Id);
1483    if (shProg->_LinkedShaders[MESA_SHADER_TESS_CTRL])
1484       printf("  tesc prog %u\n",
1485 	     shProg->_LinkedShaders[MESA_SHADER_TESS_CTRL]->Program->Id);
1486    if (shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL])
1487       printf("  tese prog %u\n",
1488 	     shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL]->Program->Id);
1489 }
1490 
1491 
1492 /**
1493  * Use the named shader program for subsequent glUniform calls
1494  */
1495 void
_mesa_active_program(struct gl_context * ctx,struct gl_shader_program * shProg,const char * caller)1496 _mesa_active_program(struct gl_context *ctx, struct gl_shader_program *shProg,
1497 		     const char *caller)
1498 {
1499    if ((shProg != NULL) && !shProg->data->LinkStatus) {
1500       _mesa_error(ctx, GL_INVALID_OPERATION,
1501 		  "%s(program %u not linked)", caller, shProg->Name);
1502       return;
1503    }
1504 
1505    if (ctx->Shader.ActiveProgram != shProg) {
1506       _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, shProg);
1507       _mesa_update_valid_to_render_state(ctx);
1508    }
1509 }
1510 
1511 
1512 /**
1513  * Use the named shader program for subsequent rendering.
1514  */
1515 void
_mesa_use_shader_program(struct gl_context * ctx,struct gl_shader_program * shProg)1516 _mesa_use_shader_program(struct gl_context *ctx,
1517                          struct gl_shader_program *shProg)
1518 {
1519    for (int i = 0; i < MESA_SHADER_STAGES; i++) {
1520       struct gl_program *new_prog = NULL;
1521       if (shProg && shProg->_LinkedShaders[i])
1522          new_prog = shProg->_LinkedShaders[i]->Program;
1523       _mesa_use_program(ctx, i, shProg, new_prog, &ctx->Shader);
1524    }
1525    _mesa_active_program(ctx, shProg, "glUseProgram");
1526 }
1527 
1528 
1529 /**
1530  * Do validation of the given shader program.
1531  * \param errMsg  returns error message if validation fails.
1532  * \return GL_TRUE if valid, GL_FALSE if invalid (and set errMsg)
1533  */
1534 static GLboolean
validate_shader_program(const struct gl_shader_program * shProg,char * errMsg)1535 validate_shader_program(const struct gl_shader_program *shProg,
1536                         char *errMsg)
1537 {
1538    if (!shProg->data->LinkStatus) {
1539       return GL_FALSE;
1540    }
1541 
1542    /* From the GL spec, a program is invalid if any of these are true:
1543 
1544      any two active samplers in the current program object are of
1545      different types, but refer to the same texture image unit,
1546 
1547      any active sampler in the current program object refers to a texture
1548      image unit where fixed-function fragment processing accesses a
1549      texture target that does not match the sampler type, or
1550 
1551      the sum of the number of active samplers in the program and the
1552      number of texture image units enabled for fixed-function fragment
1553      processing exceeds the combined limit on the total number of texture
1554      image units allowed.
1555    */
1556 
1557    /*
1558     * Check: any two active samplers in the current program object are of
1559     * different types, but refer to the same texture image unit,
1560     */
1561    if (!_mesa_sampler_uniforms_are_valid(shProg, errMsg, 100))
1562       return GL_FALSE;
1563 
1564    return GL_TRUE;
1565 }
1566 
1567 
1568 /**
1569  * Called via glValidateProgram()
1570  */
1571 static void
validate_program(struct gl_context * ctx,GLuint program)1572 validate_program(struct gl_context *ctx, GLuint program)
1573 {
1574    struct gl_shader_program *shProg;
1575    char errMsg[100] = "";
1576 
1577    shProg = _mesa_lookup_shader_program_err(ctx, program, "glValidateProgram");
1578    if (!shProg) {
1579       return;
1580    }
1581 
1582    shProg->data->Validated = validate_shader_program(shProg, errMsg);
1583    if (!shProg->data->Validated) {
1584       /* update info log */
1585       if (shProg->data->InfoLog) {
1586          ralloc_free(shProg->data->InfoLog);
1587       }
1588       shProg->data->InfoLog = ralloc_strdup(shProg->data, errMsg);
1589    }
1590 }
1591 
1592 
1593 void GLAPIENTRY
_mesa_AttachObjectARB_no_error(GLhandleARB program,GLhandleARB shader)1594 _mesa_AttachObjectARB_no_error(GLhandleARB program, GLhandleARB shader)
1595 {
1596    GET_CURRENT_CONTEXT(ctx);
1597    attach_shader_no_error(ctx, program, shader);
1598 }
1599 
1600 
1601 void GLAPIENTRY
_mesa_AttachObjectARB(GLhandleARB program,GLhandleARB shader)1602 _mesa_AttachObjectARB(GLhandleARB program, GLhandleARB shader)
1603 {
1604    GET_CURRENT_CONTEXT(ctx);
1605    attach_shader_err(ctx, program, shader, "glAttachObjectARB");
1606 }
1607 
1608 
1609 void GLAPIENTRY
_mesa_AttachShader_no_error(GLuint program,GLuint shader)1610 _mesa_AttachShader_no_error(GLuint program, GLuint shader)
1611 {
1612    GET_CURRENT_CONTEXT(ctx);
1613    attach_shader_no_error(ctx, program, shader);
1614 }
1615 
1616 
1617 void GLAPIENTRY
_mesa_AttachShader(GLuint program,GLuint shader)1618 _mesa_AttachShader(GLuint program, GLuint shader)
1619 {
1620    GET_CURRENT_CONTEXT(ctx);
1621    attach_shader_err(ctx, program, shader, "glAttachShader");
1622 }
1623 
1624 
1625 void GLAPIENTRY
_mesa_CompileShader(GLuint shaderObj)1626 _mesa_CompileShader(GLuint shaderObj)
1627 {
1628    GET_CURRENT_CONTEXT(ctx);
1629    if (MESA_VERBOSE & VERBOSE_API)
1630       _mesa_debug(ctx, "glCompileShader %u\n", shaderObj);
1631    _mesa_compile_shader(ctx, _mesa_lookup_shader_err(ctx, shaderObj,
1632                                                      "glCompileShader"));
1633 }
1634 
1635 
1636 GLuint GLAPIENTRY
_mesa_CreateShader_no_error(GLenum type)1637 _mesa_CreateShader_no_error(GLenum type)
1638 {
1639    GET_CURRENT_CONTEXT(ctx);
1640    return create_shader(ctx, type);
1641 }
1642 
1643 
1644 GLuint GLAPIENTRY
_mesa_CreateShader(GLenum type)1645 _mesa_CreateShader(GLenum type)
1646 {
1647    GET_CURRENT_CONTEXT(ctx);
1648 
1649    if (MESA_VERBOSE & VERBOSE_API)
1650       _mesa_debug(ctx, "glCreateShader %s\n", _mesa_enum_to_string(type));
1651 
1652    return create_shader_err(ctx, type, "glCreateShader");
1653 }
1654 
1655 
1656 GLhandleARB GLAPIENTRY
_mesa_CreateShaderObjectARB_no_error(GLenum type)1657 _mesa_CreateShaderObjectARB_no_error(GLenum type)
1658 {
1659    GET_CURRENT_CONTEXT(ctx);
1660    return create_shader(ctx, type);
1661 }
1662 
1663 
1664 GLhandleARB GLAPIENTRY
_mesa_CreateShaderObjectARB(GLenum type)1665 _mesa_CreateShaderObjectARB(GLenum type)
1666 {
1667    GET_CURRENT_CONTEXT(ctx);
1668    return create_shader_err(ctx, type, "glCreateShaderObjectARB");
1669 }
1670 
1671 
1672 GLuint GLAPIENTRY
_mesa_CreateProgram(void)1673 _mesa_CreateProgram(void)
1674 {
1675    GET_CURRENT_CONTEXT(ctx);
1676    if (MESA_VERBOSE & VERBOSE_API)
1677       _mesa_debug(ctx, "glCreateProgram\n");
1678    return create_shader_program(ctx);
1679 }
1680 
1681 
1682 GLhandleARB GLAPIENTRY
_mesa_CreateProgramObjectARB(void)1683 _mesa_CreateProgramObjectARB(void)
1684 {
1685    GET_CURRENT_CONTEXT(ctx);
1686    return create_shader_program(ctx);
1687 }
1688 
1689 
1690 void GLAPIENTRY
_mesa_DeleteObjectARB(GLhandleARB obj)1691 _mesa_DeleteObjectARB(GLhandleARB obj)
1692 {
1693    if (MESA_VERBOSE & VERBOSE_API) {
1694       GET_CURRENT_CONTEXT(ctx);
1695       _mesa_debug(ctx, "glDeleteObjectARB(%lu)\n", (unsigned long)obj);
1696    }
1697 
1698    if (obj) {
1699       GET_CURRENT_CONTEXT(ctx);
1700       FLUSH_VERTICES(ctx, 0, 0);
1701       if (is_program(ctx, obj)) {
1702          delete_shader_program(ctx, obj);
1703       }
1704       else if (is_shader(ctx, obj)) {
1705          delete_shader(ctx, obj);
1706       }
1707       else {
1708          /* error? */
1709       }
1710    }
1711 }
1712 
1713 
1714 void GLAPIENTRY
_mesa_DeleteProgram(GLuint name)1715 _mesa_DeleteProgram(GLuint name)
1716 {
1717    if (name) {
1718       GET_CURRENT_CONTEXT(ctx);
1719       FLUSH_VERTICES(ctx, 0, 0);
1720       delete_shader_program(ctx, name);
1721    }
1722 }
1723 
1724 
1725 void GLAPIENTRY
_mesa_DeleteShader(GLuint name)1726 _mesa_DeleteShader(GLuint name)
1727 {
1728    if (name) {
1729       GET_CURRENT_CONTEXT(ctx);
1730       FLUSH_VERTICES(ctx, 0, 0);
1731       delete_shader(ctx, name);
1732    }
1733 }
1734 
1735 
1736 void GLAPIENTRY
_mesa_DetachObjectARB_no_error(GLhandleARB program,GLhandleARB shader)1737 _mesa_DetachObjectARB_no_error(GLhandleARB program, GLhandleARB shader)
1738 {
1739    GET_CURRENT_CONTEXT(ctx);
1740    detach_shader_no_error(ctx, program, shader);
1741 }
1742 
1743 
1744 void GLAPIENTRY
_mesa_DetachObjectARB(GLhandleARB program,GLhandleARB shader)1745 _mesa_DetachObjectARB(GLhandleARB program, GLhandleARB shader)
1746 {
1747    GET_CURRENT_CONTEXT(ctx);
1748    detach_shader_error(ctx, program, shader);
1749 }
1750 
1751 
1752 void GLAPIENTRY
_mesa_DetachShader_no_error(GLuint program,GLuint shader)1753 _mesa_DetachShader_no_error(GLuint program, GLuint shader)
1754 {
1755    GET_CURRENT_CONTEXT(ctx);
1756    detach_shader_no_error(ctx, program, shader);
1757 }
1758 
1759 
1760 void GLAPIENTRY
_mesa_DetachShader(GLuint program,GLuint shader)1761 _mesa_DetachShader(GLuint program, GLuint shader)
1762 {
1763    GET_CURRENT_CONTEXT(ctx);
1764    detach_shader_error(ctx, program, shader);
1765 }
1766 
1767 
1768 void GLAPIENTRY
_mesa_GetAttachedObjectsARB(GLhandleARB container,GLsizei maxCount,GLsizei * count,GLhandleARB * obj)1769 _mesa_GetAttachedObjectsARB(GLhandleARB container, GLsizei maxCount,
1770                             GLsizei * count, GLhandleARB * obj)
1771 {
1772    GET_CURRENT_CONTEXT(ctx);
1773    get_attached_shaders(ctx, (GLuint)container, maxCount, count, NULL, obj);
1774 }
1775 
1776 
1777 void GLAPIENTRY
_mesa_GetAttachedShaders(GLuint program,GLsizei maxCount,GLsizei * count,GLuint * obj)1778 _mesa_GetAttachedShaders(GLuint program, GLsizei maxCount,
1779                          GLsizei *count, GLuint *obj)
1780 {
1781    GET_CURRENT_CONTEXT(ctx);
1782    get_attached_shaders(ctx, program, maxCount, count, obj, NULL);
1783 }
1784 
1785 
1786 void GLAPIENTRY
_mesa_GetInfoLogARB(GLhandleARB object,GLsizei maxLength,GLsizei * length,GLcharARB * infoLog)1787 _mesa_GetInfoLogARB(GLhandleARB object, GLsizei maxLength, GLsizei * length,
1788                     GLcharARB * infoLog)
1789 {
1790    GET_CURRENT_CONTEXT(ctx);
1791    if (is_program(ctx, object)) {
1792       get_program_info_log(ctx, object, maxLength, length, infoLog);
1793    }
1794    else if (is_shader(ctx, object)) {
1795       get_shader_info_log(ctx, object, maxLength, length, infoLog);
1796    }
1797    else {
1798       _mesa_error(ctx, GL_INVALID_OPERATION, "glGetInfoLogARB");
1799    }
1800 }
1801 
1802 
1803 void GLAPIENTRY
_mesa_GetObjectParameterivARB(GLhandleARB object,GLenum pname,GLint * params)1804 _mesa_GetObjectParameterivARB(GLhandleARB object, GLenum pname, GLint *params)
1805 {
1806    GET_CURRENT_CONTEXT(ctx);
1807    /* Implement in terms of GetProgramiv, GetShaderiv */
1808    if (is_program(ctx, object)) {
1809       if (pname == GL_OBJECT_TYPE_ARB) {
1810 	 *params = GL_PROGRAM_OBJECT_ARB;
1811       }
1812       else {
1813 	 get_programiv(ctx, object, pname, params);
1814       }
1815    }
1816    else if (is_shader(ctx, object)) {
1817       if (pname == GL_OBJECT_TYPE_ARB) {
1818 	 *params = GL_SHADER_OBJECT_ARB;
1819       }
1820       else {
1821 	 get_shaderiv(ctx, object, pname, params);
1822       }
1823    }
1824    else {
1825       _mesa_error(ctx, GL_INVALID_VALUE, "glGetObjectParameterivARB");
1826    }
1827 }
1828 
1829 
1830 void GLAPIENTRY
_mesa_GetObjectParameterfvARB(GLhandleARB object,GLenum pname,GLfloat * params)1831 _mesa_GetObjectParameterfvARB(GLhandleARB object, GLenum pname,
1832                               GLfloat *params)
1833 {
1834    GLint iparams[1] = {0};  /* XXX is one element enough? */
1835    _mesa_GetObjectParameterivARB(object, pname, iparams);
1836    params[0] = (GLfloat) iparams[0];
1837 }
1838 
1839 
1840 void GLAPIENTRY
_mesa_GetProgramiv(GLuint program,GLenum pname,GLint * params)1841 _mesa_GetProgramiv(GLuint program, GLenum pname, GLint *params)
1842 {
1843    GET_CURRENT_CONTEXT(ctx);
1844    get_programiv(ctx, program, pname, params);
1845 }
1846 
1847 
1848 void GLAPIENTRY
_mesa_GetShaderiv(GLuint shader,GLenum pname,GLint * params)1849 _mesa_GetShaderiv(GLuint shader, GLenum pname, GLint *params)
1850 {
1851    GET_CURRENT_CONTEXT(ctx);
1852    get_shaderiv(ctx, shader, pname, params);
1853 }
1854 
1855 
1856 void GLAPIENTRY
_mesa_GetProgramInfoLog(GLuint program,GLsizei bufSize,GLsizei * length,GLchar * infoLog)1857 _mesa_GetProgramInfoLog(GLuint program, GLsizei bufSize,
1858                         GLsizei *length, GLchar *infoLog)
1859 {
1860    GET_CURRENT_CONTEXT(ctx);
1861    get_program_info_log(ctx, program, bufSize, length, infoLog);
1862 }
1863 
1864 
1865 void GLAPIENTRY
_mesa_GetShaderInfoLog(GLuint shader,GLsizei bufSize,GLsizei * length,GLchar * infoLog)1866 _mesa_GetShaderInfoLog(GLuint shader, GLsizei bufSize,
1867                        GLsizei *length, GLchar *infoLog)
1868 {
1869    GET_CURRENT_CONTEXT(ctx);
1870    get_shader_info_log(ctx, shader, bufSize, length, infoLog);
1871 }
1872 
1873 
1874 void GLAPIENTRY
_mesa_GetShaderSource(GLuint shader,GLsizei maxLength,GLsizei * length,GLchar * sourceOut)1875 _mesa_GetShaderSource(GLuint shader, GLsizei maxLength,
1876                       GLsizei *length, GLchar *sourceOut)
1877 {
1878    GET_CURRENT_CONTEXT(ctx);
1879    get_shader_source(ctx, shader, maxLength, length, sourceOut);
1880 }
1881 
1882 
1883 GLhandleARB GLAPIENTRY
_mesa_GetHandleARB(GLenum pname)1884 _mesa_GetHandleARB(GLenum pname)
1885 {
1886    GET_CURRENT_CONTEXT(ctx);
1887    return get_handle(ctx, pname);
1888 }
1889 
1890 
1891 GLboolean GLAPIENTRY
_mesa_IsProgram(GLuint name)1892 _mesa_IsProgram(GLuint name)
1893 {
1894    GET_CURRENT_CONTEXT(ctx);
1895    return is_program(ctx, name);
1896 }
1897 
1898 
1899 GLboolean GLAPIENTRY
_mesa_IsShader(GLuint name)1900 _mesa_IsShader(GLuint name)
1901 {
1902    GET_CURRENT_CONTEXT(ctx);
1903    return is_shader(ctx, name);
1904 }
1905 
1906 
1907 void GLAPIENTRY
_mesa_LinkProgram_no_error(GLuint programObj)1908 _mesa_LinkProgram_no_error(GLuint programObj)
1909 {
1910    GET_CURRENT_CONTEXT(ctx);
1911 
1912    struct gl_shader_program *shProg =
1913       _mesa_lookup_shader_program(ctx, programObj);
1914    link_program_no_error(ctx, shProg);
1915 }
1916 
1917 
1918 void GLAPIENTRY
_mesa_LinkProgram(GLuint programObj)1919 _mesa_LinkProgram(GLuint programObj)
1920 {
1921    GET_CURRENT_CONTEXT(ctx);
1922 
1923    if (MESA_VERBOSE & VERBOSE_API)
1924       _mesa_debug(ctx, "glLinkProgram %u\n", programObj);
1925 
1926    struct gl_shader_program *shProg =
1927       _mesa_lookup_shader_program_err(ctx, programObj, "glLinkProgram");
1928    link_program_error(ctx, shProg);
1929 }
1930 
1931 #ifdef ENABLE_SHADER_CACHE
1932 
1933 /**
1934  * Construct a full path for shader replacement functionality using
1935  * following format:
1936  *
1937  * <path>/<stage prefix>_<CHECKSUM>.glsl
1938  * <path>/<stage prefix>_<CHECKSUM>.arb
1939  */
1940 static char *
construct_name(const gl_shader_stage stage,const char * sha,const char * source,const char * path)1941 construct_name(const gl_shader_stage stage, const char *sha,
1942                const char *source, const char *path)
1943 {
1944    static const char *types[] = {
1945       "VS", "TC", "TE", "GS", "FS", "CS",
1946    };
1947 
1948    const char *format = strncmp(source, "!!ARB", 5) ? "glsl" : "arb";
1949 
1950    return ralloc_asprintf(NULL, "%s/%s_%s.%s", path, types[stage], sha, format);
1951 }
1952 
1953 /**
1954  * Write given shader source to a file in MESA_SHADER_DUMP_PATH.
1955  */
1956 void
_mesa_dump_shader_source(const gl_shader_stage stage,const char * source,const uint8_t sha1[SHA1_DIGEST_LENGTH])1957 _mesa_dump_shader_source(const gl_shader_stage stage, const char *source,
1958                          const uint8_t sha1[SHA1_DIGEST_LENGTH])
1959 {
1960 #ifndef CUSTOM_SHADER_REPLACEMENT
1961    static bool path_exists = true;
1962    char *dump_path;
1963    FILE *f;
1964    char sha[64];
1965 
1966    if (!path_exists)
1967       return;
1968 
1969    dump_path = getenv("MESA_SHADER_DUMP_PATH");
1970    if (!dump_path) {
1971       path_exists = false;
1972       return;
1973    }
1974 
1975    _mesa_sha1_format(sha, sha1);
1976    char *name = construct_name(stage, sha, source, dump_path);
1977 
1978    f = fopen(name, "w");
1979    if (f) {
1980       fputs(source, f);
1981       fclose(f);
1982    } else {
1983       GET_CURRENT_CONTEXT(ctx);
1984       _mesa_warning(ctx, "could not open %s for dumping shader (%s)", name,
1985                     strerror(errno));
1986    }
1987    ralloc_free(name);
1988 #endif
1989 }
1990 
1991 /**
1992  * Read shader source code from a file.
1993  * Useful for debugging to override an app's shader.
1994  */
1995 GLcharARB *
_mesa_read_shader_source(const gl_shader_stage stage,const char * source,const uint8_t sha1[SHA1_DIGEST_LENGTH])1996 _mesa_read_shader_source(const gl_shader_stage stage, const char *source,
1997                          const uint8_t sha1[SHA1_DIGEST_LENGTH])
1998 {
1999    char *read_path;
2000    static bool path_exists = true;
2001    int len, shader_size = 0;
2002    GLcharARB *buffer;
2003    FILE *f;
2004    char sha[64];
2005 
2006    _mesa_sha1_format(sha, sha1);
2007 
2008    if (!debug_get_bool_option("MESA_NO_SHADER_REPLACEMENT", false)) {
2009       const char *process_name = util_get_process_name();
2010 
2011       char *new_source = try_direct_replace(process_name, source);
2012       if (new_source)
2013          return new_source;
2014 
2015       for (size_t i = 0; i < ARRAY_SIZE(shader_replacements); i++) {
2016          if (stage != shader_replacements[i].stage)
2017             continue;
2018 
2019          if (shader_replacements[i].app &&
2020              strcmp(process_name, shader_replacements[i].app) != 0)
2021             continue;
2022 
2023          if (memcmp(sha, shader_replacements[i].sha1, 40) != 0)
2024             continue;
2025 
2026          return load_shader_replacement(&shader_replacements[i]);
2027       }
2028    }
2029 
2030    if (!path_exists)
2031       return NULL;
2032 
2033    read_path = getenv("MESA_SHADER_READ_PATH");
2034    if (!read_path) {
2035       path_exists = false;
2036       return NULL;
2037    }
2038 
2039    char *name = construct_name(stage, sha, source, read_path);
2040    f = fopen(name, "r");
2041    ralloc_free(name);
2042    if (!f)
2043       return NULL;
2044 
2045    /* allocate enough room for the entire shader */
2046    fseek(f, 0, SEEK_END);
2047    shader_size = ftell(f);
2048    rewind(f);
2049    assert(shader_size);
2050 
2051    /* add one for terminating zero */
2052    shader_size++;
2053 
2054    buffer = malloc(shader_size);
2055    assert(buffer);
2056 
2057    len = fread(buffer, 1, shader_size, f);
2058    buffer[len] = 0;
2059 
2060    fclose(f);
2061 
2062    return buffer;
2063 }
2064 
2065 #endif /* ENABLE_SHADER_CACHE */
2066 
2067 /**
2068  * Called via glShaderSource() and glShaderSourceARB() API functions.
2069  * Basically, concatenate the source code strings into one long string
2070  * and pass it to _mesa_shader_source().
2071  */
2072 static ALWAYS_INLINE void
shader_source(struct gl_context * ctx,GLuint shaderObj,GLsizei count,const GLchar * const * string,const GLint * length,bool no_error)2073 shader_source(struct gl_context *ctx, GLuint shaderObj, GLsizei count,
2074               const GLchar *const *string, const GLint *length, bool no_error)
2075 {
2076    GLint *offsets;
2077    GLsizei i, totalLength;
2078    GLcharARB *source;
2079    struct gl_shader *sh;
2080 
2081    if (!no_error) {
2082       sh = _mesa_lookup_shader_err(ctx, shaderObj, "glShaderSourceARB");
2083       if (!sh)
2084          return;
2085 
2086       if (string == NULL || count < 0) {
2087          _mesa_error(ctx, GL_INVALID_VALUE, "glShaderSourceARB");
2088          return;
2089       }
2090    } else {
2091       sh = _mesa_lookup_shader(ctx, shaderObj);
2092    }
2093 
2094    /* Return silently the spec doesn't define this as an error */
2095    if (count == 0)
2096       return;
2097 
2098    /*
2099     * This array holds offsets of where the appropriate string ends, thus the
2100     * last element will be set to the total length of the source code.
2101     */
2102    offsets = calloc(count, sizeof(GLint));
2103    if (offsets == NULL) {
2104       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
2105       return;
2106    }
2107 
2108    for (i = 0; i < count; i++) {
2109       if (!no_error && string[i] == NULL) {
2110          free((GLvoid *) offsets);
2111          _mesa_error(ctx, GL_INVALID_OPERATION,
2112                      "glShaderSourceARB(null string)");
2113          return;
2114       }
2115       if (length == NULL || length[i] < 0)
2116          offsets[i] = strlen(string[i]);
2117       else
2118          offsets[i] = length[i];
2119       /* accumulate string lengths */
2120       if (i > 0)
2121          offsets[i] += offsets[i - 1];
2122    }
2123 
2124    /* Total length of source string is sum off all strings plus two.
2125     * One extra byte for terminating zero, another extra byte to silence
2126     * valgrind warnings in the parser/grammer code.
2127     */
2128    totalLength = offsets[count - 1] + 2;
2129    source = malloc(totalLength * sizeof(GLcharARB));
2130    if (source == NULL) {
2131       free((GLvoid *) offsets);
2132       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
2133       return;
2134    }
2135 
2136    for (i = 0; i < count; i++) {
2137       GLint start = (i > 0) ? offsets[i - 1] : 0;
2138       memcpy(source + start, string[i],
2139              (offsets[i] - start) * sizeof(GLcharARB));
2140    }
2141    source[totalLength - 1] = '\0';
2142    source[totalLength - 2] = '\0';
2143 
2144    /* Compute the original source sha1 before shader replacement. */
2145    uint8_t original_sha1[SHA1_DIGEST_LENGTH];
2146    _mesa_sha1_compute(source, strlen(source), original_sha1);
2147 
2148 #ifdef ENABLE_SHADER_CACHE
2149    GLcharARB *replacement;
2150 
2151    /* Dump original shader source to MESA_SHADER_DUMP_PATH and replace
2152     * if corresponding entry found from MESA_SHADER_READ_PATH.
2153     */
2154    _mesa_dump_shader_source(sh->Stage, source, original_sha1);
2155 
2156    replacement = _mesa_read_shader_source(sh->Stage, source, original_sha1);
2157    if (replacement) {
2158       free(source);
2159       source = replacement;
2160    }
2161 #endif /* ENABLE_SHADER_CACHE */
2162 
2163    set_shader_source(sh, source, original_sha1);
2164 
2165    free(offsets);
2166 }
2167 
2168 
2169 void GLAPIENTRY
_mesa_ShaderSource_no_error(GLuint shaderObj,GLsizei count,const GLchar * const * string,const GLint * length)2170 _mesa_ShaderSource_no_error(GLuint shaderObj, GLsizei count,
2171                             const GLchar *const *string, const GLint *length)
2172 {
2173    GET_CURRENT_CONTEXT(ctx);
2174    shader_source(ctx, shaderObj, count, string, length, true);
2175 }
2176 
2177 
2178 void GLAPIENTRY
_mesa_ShaderSource(GLuint shaderObj,GLsizei count,const GLchar * const * string,const GLint * length)2179 _mesa_ShaderSource(GLuint shaderObj, GLsizei count,
2180                    const GLchar *const *string, const GLint *length)
2181 {
2182    GET_CURRENT_CONTEXT(ctx);
2183    shader_source(ctx, shaderObj, count, string, length, false);
2184 }
2185 
2186 
2187 static ALWAYS_INLINE void
use_program(GLuint program,bool no_error)2188 use_program(GLuint program, bool no_error)
2189 {
2190    GET_CURRENT_CONTEXT(ctx);
2191    struct gl_shader_program *shProg = NULL;
2192 
2193    if (MESA_VERBOSE & VERBOSE_API)
2194       _mesa_debug(ctx, "glUseProgram %u\n", program);
2195 
2196    if (no_error) {
2197       if (program) {
2198          shProg = _mesa_lookup_shader_program(ctx, program);
2199       }
2200    } else {
2201       if (_mesa_is_xfb_active_and_unpaused(ctx)) {
2202          _mesa_error(ctx, GL_INVALID_OPERATION,
2203                      "glUseProgram(transform feedback active)");
2204          return;
2205       }
2206 
2207       if (program) {
2208          shProg =
2209             _mesa_lookup_shader_program_err(ctx, program, "glUseProgram");
2210          if (!shProg)
2211             return;
2212 
2213          if (!shProg->data->LinkStatus) {
2214             _mesa_error(ctx, GL_INVALID_OPERATION,
2215                         "glUseProgram(program %u not linked)", program);
2216             return;
2217          }
2218 
2219          /* debug code */
2220          if (ctx->_Shader->Flags & GLSL_USE_PROG) {
2221             print_shader_info(shProg);
2222          }
2223       }
2224    }
2225 
2226    /* The ARB_separate_shader_object spec says:
2227     *
2228     *     "The executable code for an individual shader stage is taken from
2229     *     the current program for that stage.  If there is a current program
2230     *     object established by UseProgram, that program is considered current
2231     *     for all stages.  Otherwise, if there is a bound program pipeline
2232     *     object (section 2.14.PPO), the program bound to the appropriate
2233     *     stage of the pipeline object is considered current."
2234     */
2235    if (shProg) {
2236       /* Attach shader state to the binding point */
2237       _mesa_reference_pipeline_object(ctx, &ctx->_Shader, &ctx->Shader);
2238       /* Update the program */
2239       _mesa_use_shader_program(ctx, shProg);
2240    } else {
2241       /* Must be done first: detach the progam */
2242       _mesa_use_shader_program(ctx, shProg);
2243       /* Unattach shader_state binding point */
2244       _mesa_reference_pipeline_object(ctx, &ctx->_Shader,
2245                                       ctx->Pipeline.Default);
2246       /* If a pipeline was bound, rebind it */
2247       if (ctx->Pipeline.Current) {
2248          if (no_error)
2249             _mesa_BindProgramPipeline_no_error(ctx->Pipeline.Current->Name);
2250          else
2251             _mesa_BindProgramPipeline(ctx->Pipeline.Current->Name);
2252       }
2253    }
2254 
2255    _mesa_update_vertex_processing_mode(ctx);
2256 }
2257 
2258 
2259 void GLAPIENTRY
_mesa_UseProgram_no_error(GLuint program)2260 _mesa_UseProgram_no_error(GLuint program)
2261 {
2262    use_program(program, true);
2263 }
2264 
2265 
2266 void GLAPIENTRY
_mesa_UseProgram(GLuint program)2267 _mesa_UseProgram(GLuint program)
2268 {
2269    use_program(program, false);
2270 }
2271 
2272 
2273 void GLAPIENTRY
_mesa_ValidateProgram(GLuint program)2274 _mesa_ValidateProgram(GLuint program)
2275 {
2276    GET_CURRENT_CONTEXT(ctx);
2277    validate_program(ctx, program);
2278 }
2279 
2280 
2281 /**
2282  * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
2283  */
2284 void GLAPIENTRY
_mesa_GetShaderPrecisionFormat(GLenum shadertype,GLenum precisiontype,GLint * range,GLint * precision)2285 _mesa_GetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype,
2286                                GLint* range, GLint* precision)
2287 {
2288    const struct gl_program_constants *limits;
2289    const struct gl_precision *p;
2290    GET_CURRENT_CONTEXT(ctx);
2291 
2292    switch (shadertype) {
2293    case GL_VERTEX_SHADER:
2294       limits = &ctx->Const.Program[MESA_SHADER_VERTEX];
2295       break;
2296    case GL_FRAGMENT_SHADER:
2297       limits = &ctx->Const.Program[MESA_SHADER_FRAGMENT];
2298       break;
2299    default:
2300       _mesa_error(ctx, GL_INVALID_ENUM,
2301                   "glGetShaderPrecisionFormat(shadertype)");
2302       return;
2303    }
2304 
2305    switch (precisiontype) {
2306    case GL_LOW_FLOAT:
2307       p = &limits->LowFloat;
2308       break;
2309    case GL_MEDIUM_FLOAT:
2310       p = &limits->MediumFloat;
2311       break;
2312    case GL_HIGH_FLOAT:
2313       p = &limits->HighFloat;
2314       break;
2315    case GL_LOW_INT:
2316       p = &limits->LowInt;
2317       break;
2318    case GL_MEDIUM_INT:
2319       p = &limits->MediumInt;
2320       break;
2321    case GL_HIGH_INT:
2322       p = &limits->HighInt;
2323       break;
2324    default:
2325       _mesa_error(ctx, GL_INVALID_ENUM,
2326                   "glGetShaderPrecisionFormat(precisiontype)");
2327       return;
2328    }
2329 
2330    range[0] = p->RangeMin;
2331    range[1] = p->RangeMax;
2332    precision[0] = p->Precision;
2333 }
2334 
2335 
2336 /**
2337  * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
2338  */
2339 void GLAPIENTRY
_mesa_ReleaseShaderCompiler(void)2340 _mesa_ReleaseShaderCompiler(void)
2341 {
2342    GET_CURRENT_CONTEXT(ctx);
2343 
2344    if (ctx->shader_builtin_ref) {
2345       _mesa_glsl_builtin_functions_decref();
2346       ctx->shader_builtin_ref = false;
2347    }
2348 }
2349 
2350 
2351 /**
2352  * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
2353  */
2354 void GLAPIENTRY
_mesa_ShaderBinary(GLint n,const GLuint * shaders,GLenum binaryformat,const void * binary,GLint length)2355 _mesa_ShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat,
2356                    const void* binary, GLint length)
2357 {
2358    GET_CURRENT_CONTEXT(ctx);
2359    struct gl_shader **sh;
2360 
2361    /* Page 68, section 7.2 'Shader Binaries" of the of the OpenGL ES 3.1, and
2362     * page 88 of the OpenGL 4.5 specs state:
2363     *
2364     *     "An INVALID_VALUE error is generated if count or length is negative.
2365     *      An INVALID_ENUM error is generated if binaryformat is not a supported
2366     *      format returned in SHADER_BINARY_FORMATS."
2367     */
2368    if (n < 0 || length < 0) {
2369       _mesa_error(ctx, GL_INVALID_VALUE, "glShaderBinary(count or length < 0)");
2370       return;
2371    }
2372 
2373    /* Get all shader objects at once so we can make the operation
2374     * all-or-nothing.
2375     */
2376    if (n > SIZE_MAX / sizeof(*sh)) {
2377       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderBinary(count)");
2378       return;
2379    }
2380 
2381    sh = alloca(sizeof(*sh) * (size_t)n);
2382    if (!sh) {
2383       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderBinary");
2384       return;
2385    }
2386 
2387    for (int i = 0; i < n; ++i) {
2388       sh[i] = _mesa_lookup_shader_err(ctx, shaders[i], "glShaderBinary");
2389       if (!sh[i])
2390          return;
2391    }
2392 
2393    if (binaryformat == GL_SHADER_BINARY_FORMAT_SPIR_V_ARB) {
2394       if (!ctx->Extensions.ARB_gl_spirv) {
2395          _mesa_error(ctx, GL_INVALID_OPERATION, "glShaderBinary(SPIR-V)");
2396       } else if (n > 0) {
2397          _mesa_spirv_shader_binary(ctx, (unsigned) n, sh, binary,
2398                                    (size_t) length);
2399       }
2400 
2401       return;
2402    }
2403 
2404    _mesa_error(ctx, GL_INVALID_ENUM, "glShaderBinary(format)");
2405 }
2406 
2407 
2408 void GLAPIENTRY
_mesa_GetProgramBinary(GLuint program,GLsizei bufSize,GLsizei * length,GLenum * binaryFormat,GLvoid * binary)2409 _mesa_GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei *length,
2410                        GLenum *binaryFormat, GLvoid *binary)
2411 {
2412    struct gl_shader_program *shProg;
2413    GLsizei length_dummy;
2414    GET_CURRENT_CONTEXT(ctx);
2415 
2416    if (bufSize < 0){
2417       _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramBinary(bufSize < 0)");
2418       return;
2419    }
2420 
2421    shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetProgramBinary");
2422    if (!shProg)
2423       return;
2424 
2425    /* The ARB_get_program_binary spec says:
2426     *
2427     *     "If <length> is NULL, then no length is returned."
2428     *
2429     * Ensure that length always points to valid storage to avoid multiple NULL
2430     * pointer checks below.
2431     */
2432    if (length == NULL)
2433       length = &length_dummy;
2434 
2435 
2436    /* The ARB_get_program_binary spec says:
2437     *
2438     *     "When a program object's LINK_STATUS is FALSE, its program binary
2439     *     length is zero, and a call to GetProgramBinary will generate an
2440     *     INVALID_OPERATION error.
2441     */
2442    if (!shProg->data->LinkStatus) {
2443       _mesa_error(ctx, GL_INVALID_OPERATION,
2444                   "glGetProgramBinary(program %u not linked)",
2445                   shProg->Name);
2446       *length = 0;
2447       return;
2448    }
2449 
2450    if (ctx->Const.NumProgramBinaryFormats == 0) {
2451       *length = 0;
2452       _mesa_error(ctx, GL_INVALID_OPERATION,
2453                   "glGetProgramBinary(driver supports zero binary formats)");
2454    } else {
2455       _mesa_get_program_binary(ctx, shProg, bufSize, length, binaryFormat,
2456                                binary);
2457       assert(*length == 0 || *binaryFormat == GL_PROGRAM_BINARY_FORMAT_MESA);
2458    }
2459 }
2460 
2461 void GLAPIENTRY
_mesa_ProgramBinary(GLuint program,GLenum binaryFormat,const GLvoid * binary,GLsizei length)2462 _mesa_ProgramBinary(GLuint program, GLenum binaryFormat,
2463                     const GLvoid *binary, GLsizei length)
2464 {
2465    struct gl_shader_program *shProg;
2466    GET_CURRENT_CONTEXT(ctx);
2467 
2468    shProg = _mesa_lookup_shader_program_err(ctx, program, "glProgramBinary");
2469    if (!shProg)
2470       return;
2471 
2472    _mesa_clear_shader_program_data(ctx, shProg);
2473    shProg->data = _mesa_create_shader_program_data();
2474 
2475    /* Section 2.3.1 (Errors) of the OpenGL 4.5 spec says:
2476     *
2477     *     "If a negative number is provided where an argument of type sizei or
2478     *     sizeiptr is specified, an INVALID_VALUE error is generated."
2479     */
2480    if (length < 0) {
2481       _mesa_error(ctx, GL_INVALID_VALUE, "glProgramBinary(length < 0)");
2482       return;
2483    }
2484 
2485    if (ctx->Const.NumProgramBinaryFormats == 0 ||
2486        binaryFormat != GL_PROGRAM_BINARY_FORMAT_MESA) {
2487       /* The ARB_get_program_binary spec says:
2488        *
2489        *     "<binaryFormat> and <binary> must be those returned by a previous
2490        *     call to GetProgramBinary, and <length> must be the length of the
2491        *     program binary as returned by GetProgramBinary or GetProgramiv with
2492        *     <pname> PROGRAM_BINARY_LENGTH. Loading the program binary will fail,
2493        *     setting the LINK_STATUS of <program> to FALSE, if these conditions
2494        *     are not met."
2495        *
2496        * Since any value of binaryFormat passed "is not one of those specified as
2497        * allowable for [this] command, an INVALID_ENUM error is generated."
2498        */
2499       shProg->data->LinkStatus = LINKING_FAILURE;
2500       _mesa_error(ctx, GL_INVALID_ENUM, "glProgramBinary");
2501    } else {
2502       _mesa_program_binary(ctx, shProg, binaryFormat, binary, length);
2503    }
2504 }
2505 
2506 
2507 static ALWAYS_INLINE void
program_parameteri(struct gl_context * ctx,struct gl_shader_program * shProg,GLuint pname,GLint value,bool no_error)2508 program_parameteri(struct gl_context *ctx, struct gl_shader_program *shProg,
2509                    GLuint pname, GLint value, bool no_error)
2510 {
2511    switch (pname) {
2512    case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
2513       /* This enum isn't part of the OES extension for OpenGL ES 2.0, but it
2514        * is part of OpenGL ES 3.0.  For the ES2 case, this function shouldn't
2515        * even be in the dispatch table, so we shouldn't need to expclicitly
2516        * check here.
2517        *
2518        * On desktop, we ignore the 3.0+ requirement because it is silly.
2519        */
2520 
2521       /* The ARB_get_program_binary extension spec says:
2522        *
2523        *     "An INVALID_VALUE error is generated if the <value> argument to
2524        *     ProgramParameteri is not TRUE or FALSE."
2525        */
2526       if (!no_error && value != GL_TRUE && value != GL_FALSE) {
2527          goto invalid_value;
2528       }
2529 
2530       /* No need to notify the driver.  Any changes will actually take effect
2531        * the next time the shader is linked.
2532        *
2533        * The ARB_get_program_binary extension spec says:
2534        *
2535        *     "To indicate that a program binary is likely to be retrieved,
2536        *     ProgramParameteri should be called with <pname>
2537        *     PROGRAM_BINARY_RETRIEVABLE_HINT and <value> TRUE. This setting
2538        *     will not be in effect until the next time LinkProgram or
2539        *     ProgramBinary has been called successfully."
2540        *
2541        * The resolution of issue 9 in the extension spec also says:
2542        *
2543        *     "The application may use the PROGRAM_BINARY_RETRIEVABLE_HINT hint
2544        *     to indicate to the GL implementation that this program will
2545        *     likely be saved with GetProgramBinary at some point. This will
2546        *     give the GL implementation the opportunity to track any state
2547        *     changes made to the program before being saved such that when it
2548        *     is loaded again a recompile can be avoided."
2549        */
2550       shProg->BinaryRetrievableHintPending = value;
2551       return;
2552 
2553    case GL_PROGRAM_SEPARABLE:
2554       /* Spec imply that the behavior is the same as ARB_get_program_binary
2555        * Chapter 7.3 Program Objects
2556        */
2557       if (!no_error && value != GL_TRUE && value != GL_FALSE) {
2558          goto invalid_value;
2559       }
2560       shProg->SeparateShader = value;
2561       return;
2562 
2563    default:
2564       if (!no_error) {
2565          _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameteri(pname=%s)",
2566                      _mesa_enum_to_string(pname));
2567       }
2568       return;
2569    }
2570 
2571 invalid_value:
2572    _mesa_error(ctx, GL_INVALID_VALUE,
2573                "glProgramParameteri(pname=%s, value=%d): "
2574                "value must be 0 or 1.",
2575                _mesa_enum_to_string(pname),
2576                value);
2577 }
2578 
2579 
2580 void GLAPIENTRY
_mesa_ProgramParameteri_no_error(GLuint program,GLenum pname,GLint value)2581 _mesa_ProgramParameteri_no_error(GLuint program, GLenum pname, GLint value)
2582 {
2583    GET_CURRENT_CONTEXT(ctx);
2584 
2585    struct gl_shader_program *shProg = _mesa_lookup_shader_program(ctx, program);
2586    program_parameteri(ctx, shProg, pname, value, true);
2587 }
2588 
2589 
2590 void GLAPIENTRY
_mesa_ProgramParameteri(GLuint program,GLenum pname,GLint value)2591 _mesa_ProgramParameteri(GLuint program, GLenum pname, GLint value)
2592 {
2593    struct gl_shader_program *shProg;
2594    GET_CURRENT_CONTEXT(ctx);
2595 
2596    shProg = _mesa_lookup_shader_program_err(ctx, program,
2597                                             "glProgramParameteri");
2598    if (!shProg)
2599       return;
2600 
2601    program_parameteri(ctx, shProg, pname, value, false);
2602 }
2603 
2604 
2605 void
_mesa_use_program(struct gl_context * ctx,gl_shader_stage stage,struct gl_shader_program * shProg,struct gl_program * prog,struct gl_pipeline_object * shTarget)2606 _mesa_use_program(struct gl_context *ctx, gl_shader_stage stage,
2607                   struct gl_shader_program *shProg, struct gl_program *prog,
2608                   struct gl_pipeline_object *shTarget)
2609 {
2610    struct gl_program **target;
2611 
2612    target = &shTarget->CurrentProgram[stage];
2613    if (prog) {
2614       _mesa_program_init_subroutine_defaults(ctx, prog);
2615    }
2616 
2617    if (*target != prog) {
2618       /* Program is current, flush it */
2619       if (shTarget == ctx->_Shader) {
2620          FLUSH_VERTICES(ctx, _NEW_PROGRAM | _NEW_PROGRAM_CONSTANTS, 0);
2621       }
2622 
2623       _mesa_reference_shader_program(ctx,
2624                                      &shTarget->ReferencedPrograms[stage],
2625                                      shProg);
2626       _mesa_reference_program(ctx, target, prog);
2627       _mesa_update_allow_draw_out_of_order(ctx);
2628       _mesa_update_valid_to_render_state(ctx);
2629       if (stage == MESA_SHADER_VERTEX)
2630          _mesa_update_vertex_processing_mode(ctx);
2631       return;
2632    }
2633 
2634 }
2635 
2636 
2637 /**
2638  * Copy program-specific data generated by linking from the gl_shader_program
2639  * object to the gl_program object referred to by the gl_linked_shader.
2640  *
2641  * This function expects _mesa_reference_program() to have been previously
2642  * called setting the gl_linked_shaders program reference.
2643  */
2644 void
_mesa_copy_linked_program_data(const struct gl_shader_program * src,struct gl_linked_shader * dst_sh)2645 _mesa_copy_linked_program_data(const struct gl_shader_program *src,
2646                                struct gl_linked_shader *dst_sh)
2647 {
2648    assert(dst_sh->Program);
2649 
2650    struct gl_program *dst = dst_sh->Program;
2651 
2652    dst->info.separate_shader = src->SeparateShader;
2653 
2654    switch (dst_sh->Stage) {
2655    case MESA_SHADER_GEOMETRY: {
2656       dst->info.gs.vertices_in = src->Geom.VerticesIn;
2657       dst->info.gs.uses_end_primitive = src->Geom.UsesEndPrimitive;
2658       dst->info.gs.active_stream_mask = src->Geom.ActiveStreamMask;
2659       break;
2660    }
2661    case MESA_SHADER_FRAGMENT: {
2662       dst->info.fs.depth_layout = src->FragDepthLayout;
2663       break;
2664    }
2665    case MESA_SHADER_COMPUTE: {
2666       dst->info.shared_size = src->Comp.SharedSize;
2667       break;
2668    }
2669    default:
2670       break;
2671    }
2672 }
2673 
2674 /**
2675  * ARB_separate_shader_objects: Compile & Link Program
2676  */
2677 GLuint GLAPIENTRY
_mesa_CreateShaderProgramv(GLenum type,GLsizei count,const GLchar * const * strings)2678 _mesa_CreateShaderProgramv(GLenum type, GLsizei count,
2679                            const GLchar* const *strings)
2680 {
2681    GET_CURRENT_CONTEXT(ctx);
2682 
2683    const GLuint shader = create_shader_err(ctx, type, "glCreateShaderProgramv");
2684    GLuint program = 0;
2685 
2686    /*
2687     * According to OpenGL 4.5 and OpenGL ES 3.1 standards, section 7.3:
2688     * GL_INVALID_VALUE should be generated if count < 0
2689     */
2690    if (count < 0) {
2691       _mesa_error(ctx, GL_INVALID_VALUE, "glCreateShaderProgram (count < 0)");
2692       return program;
2693    }
2694 
2695    if (shader) {
2696       struct gl_shader *sh = _mesa_lookup_shader(ctx, shader);
2697 
2698       _mesa_ShaderSource(shader, count, strings, NULL);
2699       _mesa_compile_shader(ctx, sh);
2700 
2701       program = create_shader_program(ctx);
2702       if (program) {
2703 	 struct gl_shader_program *shProg;
2704 	 GLint compiled = GL_FALSE;
2705 
2706 	 shProg = _mesa_lookup_shader_program(ctx, program);
2707 
2708 	 shProg->SeparateShader = GL_TRUE;
2709 
2710 	 get_shaderiv(ctx, shader, GL_COMPILE_STATUS, &compiled);
2711 	 if (compiled) {
2712 	    attach_shader_err(ctx, program, shader, "glCreateShaderProgramv");
2713 	    _mesa_link_program(ctx, shProg);
2714 	    detach_shader_error(ctx, program, shader);
2715 
2716 #if 0
2717 	    /* Possibly... */
2718 	    if (active-user-defined-varyings-in-linked-program) {
2719 	       append-error-to-info-log;
2720                shProg->data->LinkStatus = LINKING_FAILURE;
2721 	    }
2722 #endif
2723 	 }
2724          if (sh->InfoLog)
2725             ralloc_strcat(&shProg->data->InfoLog, sh->InfoLog);
2726       }
2727 
2728       delete_shader(ctx, shader);
2729    }
2730 
2731    return program;
2732 }
2733 
2734 
2735 static void
set_patch_vertices(struct gl_context * ctx,GLint value)2736 set_patch_vertices(struct gl_context *ctx, GLint value)
2737 {
2738    if (ctx->TessCtrlProgram.patch_vertices != value) {
2739       FLUSH_VERTICES(ctx, 0, GL_CURRENT_BIT);
2740       ctx->NewDriverState |= ST_NEW_TESS_STATE;
2741       ctx->TessCtrlProgram.patch_vertices = value;
2742    }
2743 }
2744 
2745 /**
2746  * For GL_ARB_tessellation_shader
2747  */
2748 void GLAPIENTRY
_mesa_PatchParameteri_no_error(GLenum pname,GLint value)2749 _mesa_PatchParameteri_no_error(GLenum pname, GLint value)
2750 {
2751    GET_CURRENT_CONTEXT(ctx);
2752 
2753    set_patch_vertices(ctx, value);
2754 }
2755 
2756 
2757 extern void GLAPIENTRY
_mesa_PatchParameteri(GLenum pname,GLint value)2758 _mesa_PatchParameteri(GLenum pname, GLint value)
2759 {
2760    GET_CURRENT_CONTEXT(ctx);
2761 
2762    if (!_mesa_has_tessellation(ctx)) {
2763       _mesa_error(ctx, GL_INVALID_OPERATION, "glPatchParameteri");
2764       return;
2765    }
2766 
2767    if (pname != GL_PATCH_VERTICES) {
2768       _mesa_error(ctx, GL_INVALID_ENUM, "glPatchParameteri");
2769       return;
2770    }
2771 
2772    if (value <= 0 || value > ctx->Const.MaxPatchVertices) {
2773       _mesa_error(ctx, GL_INVALID_VALUE, "glPatchParameteri");
2774       return;
2775    }
2776 
2777    set_patch_vertices(ctx, value);
2778 }
2779 
2780 
2781 extern void GLAPIENTRY
_mesa_PatchParameterfv(GLenum pname,const GLfloat * values)2782 _mesa_PatchParameterfv(GLenum pname, const GLfloat *values)
2783 {
2784    GET_CURRENT_CONTEXT(ctx);
2785 
2786    if (!_mesa_has_tessellation(ctx)) {
2787       _mesa_error(ctx, GL_INVALID_OPERATION, "glPatchParameterfv");
2788       return;
2789    }
2790 
2791    switch(pname) {
2792    case GL_PATCH_DEFAULT_OUTER_LEVEL:
2793       FLUSH_VERTICES(ctx, 0, 0);
2794       memcpy(ctx->TessCtrlProgram.patch_default_outer_level, values,
2795              4 * sizeof(GLfloat));
2796       ctx->NewDriverState |= ST_NEW_TESS_STATE;
2797       return;
2798    case GL_PATCH_DEFAULT_INNER_LEVEL:
2799       FLUSH_VERTICES(ctx, 0, 0);
2800       memcpy(ctx->TessCtrlProgram.patch_default_inner_level, values,
2801              2 * sizeof(GLfloat));
2802       ctx->NewDriverState |= ST_NEW_TESS_STATE;
2803       return;
2804    default:
2805       _mesa_error(ctx, GL_INVALID_ENUM, "glPatchParameterfv");
2806       return;
2807    }
2808 }
2809 
2810 /**
2811  * ARB_shader_subroutine
2812  */
2813 GLint GLAPIENTRY
_mesa_GetSubroutineUniformLocation(GLuint program,GLenum shadertype,const GLchar * name)2814 _mesa_GetSubroutineUniformLocation(GLuint program, GLenum shadertype,
2815                                    const GLchar *name)
2816 {
2817    GET_CURRENT_CONTEXT(ctx);
2818    const char *api_name = "glGetSubroutineUniformLocation";
2819    struct gl_shader_program *shProg;
2820    GLenum resource_type;
2821    gl_shader_stage stage;
2822 
2823    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2824       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2825       return -1;
2826    }
2827 
2828    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2829    if (!shProg)
2830       return -1;
2831 
2832    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2833    if (!shProg->_LinkedShaders[stage]) {
2834       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2835       return -1;
2836    }
2837 
2838    resource_type = _mesa_shader_stage_to_subroutine_uniform(stage);
2839    return _mesa_program_resource_location(shProg, resource_type, name);
2840 }
2841 
2842 GLuint GLAPIENTRY
_mesa_GetSubroutineIndex(GLuint program,GLenum shadertype,const GLchar * name)2843 _mesa_GetSubroutineIndex(GLuint program, GLenum shadertype,
2844                          const GLchar *name)
2845 {
2846    GET_CURRENT_CONTEXT(ctx);
2847    const char *api_name = "glGetSubroutineIndex";
2848    struct gl_shader_program *shProg;
2849    struct gl_program_resource *res;
2850    GLenum resource_type;
2851    gl_shader_stage stage;
2852 
2853    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2854       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2855       return -1;
2856    }
2857 
2858    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2859    if (!shProg)
2860       return -1;
2861 
2862    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2863    if (!shProg->_LinkedShaders[stage]) {
2864       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2865       return -1;
2866    }
2867 
2868    resource_type = _mesa_shader_stage_to_subroutine(stage);
2869    res = _mesa_program_resource_find_name(shProg, resource_type, name, NULL);
2870    if (!res) {
2871      return -1;
2872    }
2873 
2874    return _mesa_program_resource_index(shProg, res);
2875 }
2876 
2877 
2878 GLvoid GLAPIENTRY
_mesa_GetActiveSubroutineUniformiv(GLuint program,GLenum shadertype,GLuint index,GLenum pname,GLint * values)2879 _mesa_GetActiveSubroutineUniformiv(GLuint program, GLenum shadertype,
2880                                    GLuint index, GLenum pname, GLint *values)
2881 {
2882    GET_CURRENT_CONTEXT(ctx);
2883    const char *api_name = "glGetActiveSubroutineUniformiv";
2884    struct gl_shader_program *shProg;
2885    struct gl_linked_shader *sh;
2886    gl_shader_stage stage;
2887    struct gl_program_resource *res;
2888    const struct gl_uniform_storage *uni;
2889    GLenum resource_type;
2890    int count, i, j;
2891 
2892    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2893       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2894       return;
2895    }
2896 
2897    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2898    if (!shProg)
2899       return;
2900 
2901    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2902    resource_type = _mesa_shader_stage_to_subroutine_uniform(stage);
2903 
2904    sh = shProg->_LinkedShaders[stage];
2905    if (!sh) {
2906       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2907       return;
2908    }
2909 
2910    struct gl_program *p = shProg->_LinkedShaders[stage]->Program;
2911    if (index >= p->sh.NumSubroutineUniforms) {
2912       _mesa_error(ctx, GL_INVALID_VALUE, "%s: invalid index greater than GL_ACTIVE_SUBROUTINE_UNIFORMS", api_name);
2913       return;
2914    }
2915 
2916    switch (pname) {
2917    case GL_NUM_COMPATIBLE_SUBROUTINES: {
2918       res = _mesa_program_resource_find_index(shProg, resource_type, index);
2919       if (res) {
2920          uni = res->Data;
2921          values[0] = uni->num_compatible_subroutines;
2922       }
2923       break;
2924    }
2925    case GL_COMPATIBLE_SUBROUTINES: {
2926       res = _mesa_program_resource_find_index(shProg, resource_type, index);
2927       if (res) {
2928          uni = res->Data;
2929          count = 0;
2930          for (i = 0; i < p->sh.NumSubroutineFunctions; i++) {
2931             struct gl_subroutine_function *fn = &p->sh.SubroutineFunctions[i];
2932             for (j = 0; j < fn->num_compat_types; j++) {
2933                if (fn->types[j] == uni->type) {
2934                   values[count++] = i;
2935                   break;
2936                }
2937             }
2938          }
2939       }
2940       break;
2941    }
2942    case GL_UNIFORM_SIZE:
2943       res = _mesa_program_resource_find_index(shProg, resource_type, index);
2944       if (res) {
2945          uni = res->Data;
2946          values[0] = uni->array_elements ? uni->array_elements : 1;
2947       }
2948       break;
2949    case GL_UNIFORM_NAME_LENGTH:
2950       res = _mesa_program_resource_find_index(shProg, resource_type, index);
2951       if (res) {
2952          values[0] = _mesa_program_resource_name_length(res) + 1
2953             + ((_mesa_program_resource_array_size(res) != 0) ? 3 : 0);
2954       }
2955       break;
2956    default:
2957       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2958       return;
2959    }
2960 }
2961 
2962 
2963 GLvoid GLAPIENTRY
_mesa_GetActiveSubroutineUniformName(GLuint program,GLenum shadertype,GLuint index,GLsizei bufsize,GLsizei * length,GLchar * name)2964 _mesa_GetActiveSubroutineUniformName(GLuint program, GLenum shadertype,
2965                                      GLuint index, GLsizei bufsize,
2966                                      GLsizei *length, GLchar *name)
2967 {
2968    GET_CURRENT_CONTEXT(ctx);
2969    const char *api_name = "glGetActiveSubroutineUniformName";
2970    struct gl_shader_program *shProg;
2971    GLenum resource_type;
2972    gl_shader_stage stage;
2973 
2974    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2975       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2976       return;
2977    }
2978 
2979    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2980    if (!shProg)
2981       return;
2982 
2983    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2984    if (!shProg->_LinkedShaders[stage]) {
2985       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2986       return;
2987    }
2988 
2989    resource_type = _mesa_shader_stage_to_subroutine_uniform(stage);
2990    /* get program resource name */
2991    _mesa_get_program_resource_name(shProg, resource_type,
2992                                    index, bufsize,
2993                                    length, name, false, api_name);
2994 }
2995 
2996 
2997 GLvoid GLAPIENTRY
_mesa_GetActiveSubroutineName(GLuint program,GLenum shadertype,GLuint index,GLsizei bufsize,GLsizei * length,GLchar * name)2998 _mesa_GetActiveSubroutineName(GLuint program, GLenum shadertype,
2999                               GLuint index, GLsizei bufsize,
3000                               GLsizei *length, GLchar *name)
3001 {
3002    GET_CURRENT_CONTEXT(ctx);
3003    const char *api_name = "glGetActiveSubroutineName";
3004    struct gl_shader_program *shProg;
3005    GLenum resource_type;
3006    gl_shader_stage stage;
3007 
3008    if (!_mesa_validate_shader_target(ctx, shadertype)) {
3009       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3010       return;
3011    }
3012 
3013    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
3014    if (!shProg)
3015       return;
3016 
3017    stage = _mesa_shader_enum_to_shader_stage(shadertype);
3018    if (!shProg->_LinkedShaders[stage]) {
3019       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3020       return;
3021    }
3022    resource_type = _mesa_shader_stage_to_subroutine(stage);
3023    _mesa_get_program_resource_name(shProg, resource_type,
3024                                    index, bufsize,
3025                                    length, name, false, api_name);
3026 }
3027 
3028 GLvoid GLAPIENTRY
_mesa_UniformSubroutinesuiv(GLenum shadertype,GLsizei count,const GLuint * indices)3029 _mesa_UniformSubroutinesuiv(GLenum shadertype, GLsizei count,
3030                             const GLuint *indices)
3031 {
3032    GET_CURRENT_CONTEXT(ctx);
3033    const char *api_name = "glUniformSubroutinesuiv";
3034    gl_shader_stage stage;
3035    int i;
3036 
3037    if (!_mesa_validate_shader_target(ctx, shadertype)) {
3038       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3039       return;
3040    }
3041 
3042    stage = _mesa_shader_enum_to_shader_stage(shadertype);
3043    struct gl_program *p = ctx->_Shader->CurrentProgram[stage];
3044    if (!p) {
3045       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3046       return;
3047    }
3048 
3049    if (count != p->sh.NumSubroutineUniformRemapTable) {
3050       _mesa_error(ctx, GL_INVALID_VALUE, "%s", api_name);
3051       return;
3052    }
3053 
3054    i = 0;
3055    bool flushed = false;
3056    do {
3057       struct gl_uniform_storage *uni = p->sh.SubroutineUniformRemapTable[i];
3058       if (uni == NULL) {
3059          i++;
3060          continue;
3061       }
3062 
3063       if (!flushed) {
3064          _mesa_flush_vertices_for_uniforms(ctx, uni);
3065          flushed = true;
3066       }
3067 
3068       int uni_count = uni->array_elements ? uni->array_elements : 1;
3069       int j, k, f;
3070 
3071       for (j = i; j < i + uni_count; j++) {
3072          struct gl_subroutine_function *subfn = NULL;
3073          if (indices[j] > p->sh.MaxSubroutineFunctionIndex) {
3074             _mesa_error(ctx, GL_INVALID_VALUE, "%s", api_name);
3075             return;
3076          }
3077 
3078          for (f = 0; f < p->sh.NumSubroutineFunctions; f++) {
3079             if (p->sh.SubroutineFunctions[f].index == indices[j])
3080                subfn = &p->sh.SubroutineFunctions[f];
3081          }
3082 
3083          if (!subfn) {
3084             continue;
3085          }
3086 
3087          for (k = 0; k < subfn->num_compat_types; k++) {
3088             if (subfn->types[k] == uni->type)
3089                break;
3090          }
3091          if (k == subfn->num_compat_types) {
3092             _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3093             return;
3094          }
3095 
3096          ctx->SubroutineIndex[p->info.stage].IndexPtr[j] = indices[j];
3097       }
3098       i += uni_count;
3099    } while(i < count);
3100 }
3101 
3102 
3103 GLvoid GLAPIENTRY
_mesa_GetUniformSubroutineuiv(GLenum shadertype,GLint location,GLuint * params)3104 _mesa_GetUniformSubroutineuiv(GLenum shadertype, GLint location,
3105                               GLuint *params)
3106 {
3107    GET_CURRENT_CONTEXT(ctx);
3108    const char *api_name = "glGetUniformSubroutineuiv";
3109    gl_shader_stage stage;
3110 
3111    if (!_mesa_validate_shader_target(ctx, shadertype)) {
3112       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3113       return;
3114    }
3115 
3116    stage = _mesa_shader_enum_to_shader_stage(shadertype);
3117    struct gl_program *p = ctx->_Shader->CurrentProgram[stage];
3118    if (!p) {
3119       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3120       return;
3121    }
3122 
3123    if (location >= p->sh.NumSubroutineUniformRemapTable) {
3124       _mesa_error(ctx, GL_INVALID_VALUE, "%s", api_name);
3125       return;
3126    }
3127 
3128    *params = ctx->SubroutineIndex[p->info.stage].IndexPtr[location];
3129 }
3130 
3131 
3132 GLvoid GLAPIENTRY
_mesa_GetProgramStageiv(GLuint program,GLenum shadertype,GLenum pname,GLint * values)3133 _mesa_GetProgramStageiv(GLuint program, GLenum shadertype,
3134                         GLenum pname, GLint *values)
3135 {
3136    GET_CURRENT_CONTEXT(ctx);
3137    const char *api_name = "glGetProgramStageiv";
3138    struct gl_shader_program *shProg;
3139    struct gl_linked_shader *sh;
3140    gl_shader_stage stage;
3141 
3142    if (!_mesa_validate_shader_target(ctx, shadertype)) {
3143       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3144       return;
3145    }
3146 
3147    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
3148    if (!shProg)
3149       return;
3150 
3151    stage = _mesa_shader_enum_to_shader_stage(shadertype);
3152    sh = shProg->_LinkedShaders[stage];
3153 
3154    /* ARB_shader_subroutine doesn't ask the program to be linked, or list any
3155     * INVALID_OPERATION in the case of not be linked.
3156     *
3157     * And for some pnames, like GL_ACTIVE_SUBROUTINE_UNIFORMS, you can ask the
3158     * same info using other specs (ARB_program_interface_query), without the
3159     * need of the program to be linked, being the value for that case 0.
3160     *
3161     * But at the same time, some other methods require the program to be
3162     * linked for pname related to locations, so it would be inconsistent to
3163     * not do the same here. So we are:
3164     *   * Return GL_INVALID_OPERATION if not linked only for locations.
3165     *   * Setting a default value of 0, to be returned if not linked.
3166     */
3167    if (!sh) {
3168       values[0] = 0;
3169       if (pname == GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS) {
3170          _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
3171       }
3172       return;
3173    }
3174 
3175    struct gl_program *p = sh->Program;
3176    switch (pname) {
3177    case GL_ACTIVE_SUBROUTINES:
3178       values[0] = p->sh.NumSubroutineFunctions;
3179       break;
3180    case GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS:
3181       values[0] = p->sh.NumSubroutineUniformRemapTable;
3182       break;
3183    case GL_ACTIVE_SUBROUTINE_UNIFORMS:
3184       values[0] = p->sh.NumSubroutineUniforms;
3185       break;
3186    case GL_ACTIVE_SUBROUTINE_MAX_LENGTH:
3187    {
3188       unsigned i;
3189       GLint max_len = 0;
3190       GLenum resource_type;
3191       struct gl_program_resource *res;
3192 
3193       resource_type = _mesa_shader_stage_to_subroutine(stage);
3194       for (i = 0; i < p->sh.NumSubroutineFunctions; i++) {
3195          res = _mesa_program_resource_find_index(shProg, resource_type, i);
3196          if (res) {
3197             const GLint len = _mesa_program_resource_name_length(res) + 1;
3198             if (len > max_len)
3199                max_len = len;
3200          }
3201       }
3202       values[0] = max_len;
3203       break;
3204    }
3205    case GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH:
3206    {
3207       unsigned i;
3208       GLint max_len = 0;
3209       GLenum resource_type;
3210       struct gl_program_resource *res;
3211 
3212       resource_type = _mesa_shader_stage_to_subroutine_uniform(stage);
3213       for (i = 0; i < p->sh.NumSubroutineUniformRemapTable; i++) {
3214          res = _mesa_program_resource_find_index(shProg, resource_type, i);
3215          if (res) {
3216             const GLint len = _mesa_program_resource_name_length(res) + 1
3217                + ((_mesa_program_resource_array_size(res) != 0) ? 3 : 0);
3218 
3219             if (len > max_len)
3220                max_len = len;
3221          }
3222       }
3223       values[0] = max_len;
3224       break;
3225    }
3226    default:
3227       _mesa_error(ctx, GL_INVALID_ENUM, "%s", api_name);
3228       values[0] = -1;
3229       break;
3230    }
3231 }
3232 
3233 /* This is simple list entry that will be used to hold a list of string
3234  * tokens of a parsed shader include path.
3235  */
3236 struct sh_incl_path_entry
3237 {
3238    struct list_head list;
3239 
3240    char *path;
3241 };
3242 
3243 /* Nodes of the shader include tree */
3244 struct sh_incl_path_ht_entry
3245 {
3246    struct hash_table *path;
3247    char *shader_source;
3248 };
3249 
3250 struct shader_includes {
3251    /* Array to hold include paths given to glCompileShaderIncludeARB() */
3252    struct sh_incl_path_entry **include_paths;
3253    size_t num_include_paths;
3254    size_t relative_path_cursor;
3255 
3256    /* Root hash table holding the shader include tree */
3257    struct hash_table *shader_include_tree;
3258 };
3259 
3260 void
_mesa_init_shader_includes(struct gl_shared_state * shared)3261 _mesa_init_shader_includes(struct gl_shared_state *shared)
3262 {
3263    shared->ShaderIncludes = calloc(1, sizeof(struct shader_includes));
3264    shared->ShaderIncludes->shader_include_tree =
3265       _mesa_hash_table_create(NULL, _mesa_hash_string,
3266                               _mesa_key_string_equal);
3267 }
3268 
3269 size_t
_mesa_get_shader_include_cursor(struct gl_shared_state * shared)3270 _mesa_get_shader_include_cursor(struct gl_shared_state *shared)
3271 {
3272    return shared->ShaderIncludes->relative_path_cursor;
3273 }
3274 
3275 void
_mesa_set_shader_include_cursor(struct gl_shared_state * shared,size_t cursor)3276 _mesa_set_shader_include_cursor(struct gl_shared_state *shared, size_t cursor)
3277 {
3278    shared->ShaderIncludes->relative_path_cursor = cursor;
3279 }
3280 
3281 static void
destroy_shader_include(struct hash_entry * entry)3282 destroy_shader_include(struct hash_entry *entry)
3283 {
3284    struct sh_incl_path_ht_entry *sh_incl_ht_entry =
3285       (struct sh_incl_path_ht_entry *) entry->data;
3286 
3287    _mesa_hash_table_destroy(sh_incl_ht_entry->path, destroy_shader_include);
3288    free(sh_incl_ht_entry->shader_source);
3289    free(sh_incl_ht_entry);
3290 }
3291 
3292 void
_mesa_destroy_shader_includes(struct gl_shared_state * shared)3293 _mesa_destroy_shader_includes(struct gl_shared_state *shared)
3294 {
3295    _mesa_hash_table_destroy(shared->ShaderIncludes->shader_include_tree,
3296                             destroy_shader_include);
3297    free(shared->ShaderIncludes);
3298 }
3299 
3300 static bool
valid_path_format(const char * str,bool relative_path)3301 valid_path_format(const char *str, bool relative_path)
3302 {
3303    int i = 0;
3304 
3305    if (!str[i] || (!relative_path && str[i] != '/'))
3306       return false;
3307 
3308    i++;
3309 
3310    while (str[i]) {
3311       const char c = str[i++];
3312       if (('A' <= c && c <= 'Z') ||
3313           ('a' <= c && c <= 'z') ||
3314           ('0' <= c && c <= '9'))
3315          continue;
3316 
3317       if (c == '/') {
3318          if (str[i - 2] == '/')
3319             return false;
3320 
3321          continue;
3322       }
3323 
3324       if (strchr("^. _+*%[](){}|&~=!:;,?-", c) == NULL)
3325          return false;
3326   }
3327 
3328   if (str[i - 1] == '/')
3329      return false;
3330 
3331   return true;
3332 }
3333 
3334 
3335 static bool
validate_and_tokenise_sh_incl(struct gl_context * ctx,void * mem_ctx,struct sh_incl_path_entry ** path_list,char * full_path,bool error_check)3336 validate_and_tokenise_sh_incl(struct gl_context *ctx,
3337                               void *mem_ctx,
3338                               struct sh_incl_path_entry **path_list,
3339                               char *full_path, bool error_check)
3340 {
3341    bool relative_path = ctx->Shared->ShaderIncludes->num_include_paths;
3342 
3343    if (!valid_path_format(full_path, relative_path)) {
3344       if (error_check) {
3345          _mesa_error(ctx, GL_INVALID_VALUE,
3346                      "glNamedStringARB(invalid name %s)", full_path);
3347       }
3348       return false;
3349    }
3350 
3351    char *save_ptr = NULL;
3352    char *path_str = strtok_r(full_path, "/", &save_ptr);
3353 
3354    *path_list = rzalloc(mem_ctx, struct sh_incl_path_entry);
3355    struct sh_incl_path_entry * list = *path_list;
3356    list_inithead(&list->list);
3357 
3358    while (path_str != NULL) {
3359       if (strlen(path_str) == 0) {
3360          if (error_check) {
3361             _mesa_error(ctx, GL_INVALID_VALUE,
3362                         "glNamedStringARB(invalid name %s)", full_path);
3363          }
3364 
3365          return false;
3366       }
3367 
3368       if (strcmp(path_str, ".") == 0) {
3369          /* Do nothing */
3370       } else if (strcmp(path_str, "..") == 0) {
3371          list_del(list->list.prev);
3372       } else {
3373          struct sh_incl_path_entry *path =
3374             rzalloc(mem_ctx, struct sh_incl_path_entry);
3375 
3376          path->path = strdup(path_str);
3377          list_addtail(&path->list, &list->list);
3378       }
3379 
3380       path_str = strtok_r(NULL, "/", &save_ptr);
3381    }
3382 
3383    return true;
3384 }
3385 
3386 static struct sh_incl_path_ht_entry *
lookup_shader_include(struct gl_context * ctx,char * path,bool error_check)3387 lookup_shader_include(struct gl_context *ctx, char *path,
3388                       bool error_check)
3389 {
3390    void *mem_ctx = ralloc_context(NULL);
3391    struct sh_incl_path_entry *path_list;
3392 
3393    if (!validate_and_tokenise_sh_incl(ctx, mem_ctx, &path_list, path,
3394                                       error_check)) {
3395       ralloc_free(mem_ctx);
3396       return NULL;
3397    }
3398 
3399    struct sh_incl_path_ht_entry *sh_incl_ht_entry = NULL;
3400    struct hash_table *path_ht =
3401       ctx->Shared->ShaderIncludes->shader_include_tree;
3402 
3403    size_t count = ctx->Shared->ShaderIncludes->num_include_paths;
3404    bool relative_path = path[0] != '/';
3405 
3406    size_t i = ctx->Shared->ShaderIncludes->relative_path_cursor;
3407    bool use_cursor = ctx->Shared->ShaderIncludes->relative_path_cursor;
3408 
3409    do {
3410       struct sh_incl_path_entry *entry;
3411 
3412       if (relative_path) {
3413 next_relative_path:
3414          {
3415             struct sh_incl_path_entry *rel_path_list =
3416                ctx->Shared->ShaderIncludes->include_paths[i];
3417             LIST_FOR_EACH_ENTRY(entry, &rel_path_list->list, list) {
3418                struct hash_entry *ht_entry =
3419                   _mesa_hash_table_search(path_ht, entry->path);
3420 
3421                if (!ht_entry) {
3422                   /* Reset search path and skip to the next include path */
3423                   path_ht = ctx->Shared->ShaderIncludes->shader_include_tree;
3424                   sh_incl_ht_entry = NULL;
3425                   if (use_cursor) {
3426                      i = 0;
3427                      use_cursor = false;
3428 
3429                      goto next_relative_path;
3430                   }
3431                   i++;
3432                   if (i < count)
3433                      goto next_relative_path;
3434                   else
3435                      break;
3436                } else {
3437                   sh_incl_ht_entry =
3438                     (struct sh_incl_path_ht_entry *) ht_entry->data;
3439                }
3440 
3441                path_ht = sh_incl_ht_entry->path;
3442             }
3443          }
3444       }
3445 
3446       LIST_FOR_EACH_ENTRY(entry, &path_list->list, list) {
3447          struct hash_entry *ht_entry =
3448             _mesa_hash_table_search(path_ht, entry->path);
3449 
3450          if (!ht_entry) {
3451             /* Reset search path and skip to the next include path */
3452             path_ht = ctx->Shared->ShaderIncludes->shader_include_tree;
3453             sh_incl_ht_entry = NULL;
3454             if (use_cursor) {
3455                i = 0;
3456                use_cursor = false;
3457 
3458                break;
3459             }
3460             i++;
3461             break;
3462          } else {
3463 
3464             sh_incl_ht_entry =
3465                (struct sh_incl_path_ht_entry *) ht_entry->data;
3466          }
3467 
3468          path_ht = sh_incl_ht_entry->path;
3469       }
3470 
3471       if (i < count &&
3472           (sh_incl_ht_entry == NULL || !sh_incl_ht_entry->shader_source))
3473          continue;
3474 
3475       /* If we get here then we have found a matching path or exahusted our
3476        * relative search paths.
3477        */
3478       ctx->Shared->ShaderIncludes->relative_path_cursor = i;
3479       break;
3480    } while (i < count);
3481 
3482    ralloc_free(mem_ctx);
3483 
3484    return sh_incl_ht_entry;
3485 }
3486 
3487 const char *
_mesa_lookup_shader_include(struct gl_context * ctx,char * path,bool error_check)3488 _mesa_lookup_shader_include(struct gl_context *ctx, char *path,
3489                             bool error_check)
3490 {
3491    struct sh_incl_path_ht_entry *shader_include =
3492       lookup_shader_include(ctx, path, error_check);
3493 
3494    return shader_include ? shader_include->shader_source : NULL;
3495 }
3496 
3497 static char *
copy_string(struct gl_context * ctx,const char * str,int str_len,const char * caller)3498 copy_string(struct gl_context *ctx, const char *str, int str_len,
3499             const char *caller)
3500 {
3501    if (!str) {
3502       _mesa_error(ctx, GL_INVALID_VALUE, "%s(NULL string)", caller);
3503       return NULL;
3504    }
3505 
3506    char *cp;
3507    if (str_len == -1)
3508       cp = strdup(str);
3509    else {
3510       cp = calloc(sizeof(char), str_len + 1);
3511       memcpy(cp, str, str_len);
3512    }
3513 
3514    return cp;
3515 }
3516 
3517 GLvoid GLAPIENTRY
_mesa_NamedStringARB(GLenum type,GLint namelen,const GLchar * name,GLint stringlen,const GLchar * string)3518 _mesa_NamedStringARB(GLenum type, GLint namelen, const GLchar *name,
3519                      GLint stringlen, const GLchar *string)
3520 {
3521    GET_CURRENT_CONTEXT(ctx);
3522    const char *caller = "glNamedStringARB";
3523 
3524    if (type != GL_SHADER_INCLUDE_ARB) {
3525       _mesa_error(ctx, GL_INVALID_VALUE, "%s(invalid type)", caller);
3526       return;
3527    }
3528 
3529    char *name_cp = copy_string(ctx, name, namelen, caller);
3530    char *string_cp = copy_string(ctx, string, stringlen, caller);
3531    if (!name_cp || !string_cp) {
3532       free(string_cp);
3533       free(name_cp);
3534       return;
3535    }
3536 
3537    void *mem_ctx = ralloc_context(NULL);
3538    struct sh_incl_path_entry *path_list;
3539 
3540    if (!validate_and_tokenise_sh_incl(ctx, mem_ctx, &path_list, name_cp,
3541                                       true)) {
3542       free(string_cp);
3543       free(name_cp);
3544       ralloc_free(mem_ctx);
3545       return;
3546    }
3547 
3548    simple_mtx_lock(&ctx->Shared->ShaderIncludeMutex);
3549 
3550    struct hash_table *path_ht =
3551       ctx->Shared->ShaderIncludes->shader_include_tree;
3552 
3553    struct sh_incl_path_entry *entry;
3554    LIST_FOR_EACH_ENTRY(entry, &path_list->list, list) {
3555       struct hash_entry *ht_entry =
3556          _mesa_hash_table_search(path_ht, entry->path);
3557 
3558       struct sh_incl_path_ht_entry *sh_incl_ht_entry;
3559       if (!ht_entry) {
3560          sh_incl_ht_entry = calloc(1, sizeof(struct sh_incl_path_ht_entry));
3561          sh_incl_ht_entry->path =
3562             _mesa_hash_table_create(NULL, _mesa_hash_string,
3563                                     _mesa_key_string_equal);
3564          _mesa_hash_table_insert(path_ht, entry->path, sh_incl_ht_entry);
3565       } else {
3566          sh_incl_ht_entry = (struct sh_incl_path_ht_entry *) ht_entry->data;
3567       }
3568 
3569       path_ht = sh_incl_ht_entry->path;
3570 
3571       if (list_last_entry(&path_list->list, struct sh_incl_path_entry, list) == entry) {
3572          free(sh_incl_ht_entry->shader_source);
3573          sh_incl_ht_entry->shader_source = string_cp;
3574       }
3575    }
3576 
3577    simple_mtx_unlock(&ctx->Shared->ShaderIncludeMutex);
3578 
3579    free(name_cp);
3580    ralloc_free(mem_ctx);
3581 }
3582 
3583 GLvoid GLAPIENTRY
_mesa_DeleteNamedStringARB(GLint namelen,const GLchar * name)3584 _mesa_DeleteNamedStringARB(GLint namelen, const GLchar *name)
3585 {
3586    GET_CURRENT_CONTEXT(ctx);
3587    const char *caller = "glDeleteNamedStringARB";
3588 
3589    char *name_cp = copy_string(ctx, name, namelen, caller);
3590    if (!name_cp)
3591       return;
3592 
3593    struct sh_incl_path_ht_entry *shader_include =
3594       lookup_shader_include(ctx, name_cp, true);
3595 
3596    if (!shader_include) {
3597       _mesa_error(ctx, GL_INVALID_OPERATION,
3598                   "%s(no string associated with path %s)", caller, name_cp);
3599       free(name_cp);
3600       return;
3601    }
3602 
3603    simple_mtx_lock(&ctx->Shared->ShaderIncludeMutex);
3604 
3605    free(shader_include->shader_source);
3606    shader_include->shader_source = NULL;
3607 
3608    simple_mtx_unlock(&ctx->Shared->ShaderIncludeMutex);
3609 
3610    free(name_cp);
3611 }
3612 
3613 GLvoid GLAPIENTRY
_mesa_CompileShaderIncludeARB(GLuint shader,GLsizei count,const GLchar * const * path,const GLint * length)3614 _mesa_CompileShaderIncludeARB(GLuint shader, GLsizei count,
3615                               const GLchar* const *path, const GLint *length)
3616 {
3617    GET_CURRENT_CONTEXT(ctx);
3618    const char *caller = "glCompileShaderIncludeARB";
3619 
3620    if (count > 0 && path == NULL) {
3621       _mesa_error(ctx, GL_INVALID_VALUE, "%s(count > 0 && path == NULL)",
3622                   caller);
3623       return;
3624    }
3625 
3626    void *mem_ctx = ralloc_context(NULL);
3627 
3628    simple_mtx_lock(&ctx->Shared->ShaderIncludeMutex);
3629 
3630    ctx->Shared->ShaderIncludes->include_paths =
3631       ralloc_array_size(mem_ctx, sizeof(struct sh_incl_path_entry *), count);
3632 
3633    for (size_t i = 0; i < count; i++) {
3634       char *path_cp = copy_string(ctx, path[i], length ? length[i] : -1,
3635                                   caller);
3636       if (!path_cp) {
3637          goto exit;
3638       }
3639 
3640       struct sh_incl_path_entry *path_list;
3641 
3642       if (!validate_and_tokenise_sh_incl(ctx, mem_ctx, &path_list, path_cp,
3643                                          true)) {
3644          free(path_cp);
3645          goto exit;
3646       }
3647 
3648       ctx->Shared->ShaderIncludes->include_paths[i] = path_list;
3649 
3650       free(path_cp);
3651    }
3652 
3653    /* We must set this *after* all calls to validate_and_tokenise_sh_incl()
3654     * are done as we use this to decide if we need to check the start of the
3655     * path for a '/'
3656     */
3657    ctx->Shared->ShaderIncludes->num_include_paths = count;
3658 
3659    struct gl_shader *sh = _mesa_lookup_shader(ctx, shader);
3660    if (!sh) {
3661       _mesa_error(ctx, GL_INVALID_OPERATION, "%s(shader)", caller);
3662       goto exit;
3663    }
3664 
3665    _mesa_compile_shader(ctx, sh);
3666 
3667 exit:
3668    ctx->Shared->ShaderIncludes->num_include_paths = 0;
3669    ctx->Shared->ShaderIncludes->relative_path_cursor = 0;
3670    ctx->Shared->ShaderIncludes->include_paths = NULL;
3671 
3672    simple_mtx_unlock(&ctx->Shared->ShaderIncludeMutex);
3673 
3674    ralloc_free(mem_ctx);
3675 }
3676 
3677 GLboolean GLAPIENTRY
_mesa_IsNamedStringARB(GLint namelen,const GLchar * name)3678 _mesa_IsNamedStringARB(GLint namelen, const GLchar *name)
3679 {
3680    GET_CURRENT_CONTEXT(ctx);
3681 
3682    if (!name)
3683       return false;
3684 
3685    char *name_cp = copy_string(ctx, name, namelen, "");
3686 
3687    const char *source = _mesa_lookup_shader_include(ctx, name_cp, false);
3688    free(name_cp);
3689 
3690    if (!source)
3691       return false;
3692 
3693    return true;
3694 }
3695 
3696 GLvoid GLAPIENTRY
_mesa_GetNamedStringARB(GLint namelen,const GLchar * name,GLsizei bufSize,GLint * stringlen,GLchar * string)3697 _mesa_GetNamedStringARB(GLint namelen, const GLchar *name, GLsizei bufSize,
3698                         GLint *stringlen, GLchar *string)
3699 {
3700    GET_CURRENT_CONTEXT(ctx);
3701    const char *caller = "glGetNamedStringARB";
3702 
3703    char *name_cp = copy_string(ctx, name, namelen, caller);
3704    if (!name_cp)
3705       return;
3706 
3707    const char *source = _mesa_lookup_shader_include(ctx, name_cp, true);
3708    if (!source) {
3709       _mesa_error(ctx, GL_INVALID_OPERATION,
3710                   "%s(no string associated with path %s)", caller, name_cp);
3711       free(name_cp);
3712       return;
3713    }
3714 
3715    size_t size = MIN2(strlen(source), bufSize - 1);
3716    memcpy(string, source, size);
3717    string[size] = '\0';
3718 
3719    *stringlen = size;
3720 
3721    free(name_cp);
3722 }
3723 
3724 GLvoid GLAPIENTRY
_mesa_GetNamedStringivARB(GLint namelen,const GLchar * name,GLenum pname,GLint * params)3725 _mesa_GetNamedStringivARB(GLint namelen, const GLchar *name,
3726                           GLenum pname, GLint *params)
3727 {
3728    GET_CURRENT_CONTEXT(ctx);
3729    const char *caller = "glGetNamedStringivARB";
3730 
3731    char *name_cp = copy_string(ctx, name, namelen, caller);
3732    if (!name_cp)
3733       return;
3734 
3735    const char *source = _mesa_lookup_shader_include(ctx, name_cp, true);
3736    if (!source) {
3737       _mesa_error(ctx, GL_INVALID_OPERATION,
3738                   "%s(no string associated with path %s)", caller, name_cp);
3739       free(name_cp);
3740       return;
3741    }
3742 
3743    switch (pname) {
3744    case GL_NAMED_STRING_LENGTH_ARB:
3745       *params = strlen(source) + 1;
3746       break;
3747    case GL_NAMED_STRING_TYPE_ARB:
3748       *params = GL_SHADER_INCLUDE_ARB;
3749       break;
3750    default:
3751       _mesa_error(ctx, GL_INVALID_ENUM, "%s(pname)", caller);
3752       break;
3753    }
3754 
3755    free(name_cp);
3756 }
3757 
3758 static int
find_compat_subroutine(struct gl_program * p,const struct glsl_type * type)3759 find_compat_subroutine(struct gl_program *p, const struct glsl_type *type)
3760 {
3761    int i, j;
3762 
3763    for (i = 0; i < p->sh.NumSubroutineFunctions; i++) {
3764       struct gl_subroutine_function *fn = &p->sh.SubroutineFunctions[i];
3765       for (j = 0; j < fn->num_compat_types; j++) {
3766          if (fn->types[j] == type)
3767             return i;
3768       }
3769    }
3770    return 0;
3771 }
3772 
3773 static void
_mesa_shader_write_subroutine_index(struct gl_context * ctx,struct gl_program * p)3774 _mesa_shader_write_subroutine_index(struct gl_context *ctx,
3775                                     struct gl_program *p)
3776 {
3777    int i, j;
3778 
3779    if (p->sh.NumSubroutineUniformRemapTable == 0)
3780       return;
3781 
3782    i = 0;
3783    do {
3784       struct gl_uniform_storage *uni = p->sh.SubroutineUniformRemapTable[i];
3785       int uni_count;
3786       int val;
3787 
3788       if (!uni) {
3789          i++;
3790          continue;
3791       }
3792 
3793       uni_count = uni->array_elements ? uni->array_elements : 1;
3794       for (j = 0; j < uni_count; j++) {
3795          val = ctx->SubroutineIndex[p->info.stage].IndexPtr[i + j];
3796          memcpy(&uni->storage[j], &val, sizeof(int));
3797       }
3798 
3799       _mesa_propagate_uniforms_to_driver_storage(uni, 0, uni_count);
3800       i += uni_count;
3801    } while(i < p->sh.NumSubroutineUniformRemapTable);
3802 }
3803 
3804 void
_mesa_shader_write_subroutine_indices(struct gl_context * ctx,gl_shader_stage stage)3805 _mesa_shader_write_subroutine_indices(struct gl_context *ctx,
3806                                       gl_shader_stage stage)
3807 {
3808    if (ctx->_Shader->CurrentProgram[stage])
3809       _mesa_shader_write_subroutine_index(ctx,
3810                                           ctx->_Shader->CurrentProgram[stage]);
3811 }
3812 
3813 void
_mesa_program_init_subroutine_defaults(struct gl_context * ctx,struct gl_program * p)3814 _mesa_program_init_subroutine_defaults(struct gl_context *ctx,
3815                                        struct gl_program *p)
3816 {
3817    assert(p);
3818 
3819    struct gl_subroutine_index_binding *binding = &ctx->SubroutineIndex[p->info.stage];
3820    if (binding->NumIndex != p->sh.NumSubroutineUniformRemapTable) {
3821       binding->IndexPtr = realloc(binding->IndexPtr,
3822                                   p->sh.NumSubroutineUniformRemapTable * (sizeof(GLuint)));
3823       binding->NumIndex = p->sh.NumSubroutineUniformRemapTable;
3824    }
3825 
3826    for (int i = 0; i < p->sh.NumSubroutineUniformRemapTable; i++) {
3827       struct gl_uniform_storage *uni = p->sh.SubroutineUniformRemapTable[i];
3828 
3829       if (!uni)
3830          continue;
3831 
3832       binding->IndexPtr[i] = find_compat_subroutine(p, uni->type);
3833    }
3834 }
3835