OSDN Git Service

mesa: Add MESA_SHADER_CAPTURE_PATH for writing .shader_test files.
[android-x86/external-mesa.git] / src / mesa / main / shaderapi.c
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  * XXX things to do:
35  * 1. Check that the right error code is generated for all _mesa_error() calls.
36  * 2. Insert FLUSH_VERTICES calls in various places
37  */
38
39
40 #include <stdbool.h>
41 #include "main/glheader.h"
42 #include "main/context.h"
43 #include "main/dispatch.h"
44 #include "main/enums.h"
45 #include "main/hash.h"
46 #include "main/mtypes.h"
47 #include "main/pipelineobj.h"
48 #include "main/shaderapi.h"
49 #include "main/shaderobj.h"
50 #include "main/transformfeedback.h"
51 #include "main/uniforms.h"
52 #include "compiler/glsl/glsl_parser_extras.h"
53 #include "compiler/glsl/ir.h"
54 #include "compiler/glsl/ir_uniform.h"
55 #include "compiler/glsl/program.h"
56 #include "program/program.h"
57 #include "program/prog_print.h"
58 #include "program/prog_parameter.h"
59 #include "util/ralloc.h"
60 #include "util/hash_table.h"
61 #include "util/mesa-sha1.h"
62
63
64 /**
65  * Return mask of GLSL_x flags by examining the MESA_GLSL env var.
66  */
67 GLbitfield
68 _mesa_get_shader_flags(void)
69 {
70    GLbitfield flags = 0x0;
71    const char *env = getenv("MESA_GLSL");
72
73    if (env) {
74       if (strstr(env, "dump_on_error"))
75          flags |= GLSL_DUMP_ON_ERROR;
76       else if (strstr(env, "dump"))
77          flags |= GLSL_DUMP;
78       if (strstr(env, "log"))
79          flags |= GLSL_LOG;
80       if (strstr(env, "nopvert"))
81          flags |= GLSL_NOP_VERT;
82       if (strstr(env, "nopfrag"))
83          flags |= GLSL_NOP_FRAG;
84       if (strstr(env, "nopt"))
85          flags |= GLSL_NO_OPT;
86       else if (strstr(env, "opt"))
87          flags |= GLSL_OPT;
88       if (strstr(env, "uniform"))
89          flags |= GLSL_UNIFORMS;
90       if (strstr(env, "useprog"))
91          flags |= GLSL_USE_PROG;
92       if (strstr(env, "errors"))
93          flags |= GLSL_REPORT_ERRORS;
94    }
95
96    return flags;
97 }
98
99 /**
100  * Memoized version of getenv("MESA_SHADER_CAPTURE_PATH").
101  */
102 const char *
103 _mesa_get_shader_capture_path(void)
104 {
105    static bool read_env_var = false;
106    static const char *path = NULL;
107
108    if (!read_env_var) {
109       path = getenv("MESA_SHADER_CAPTURE_PATH");
110       read_env_var = true;
111       if (path &&
112           strlen(path) > PATH_MAX - strlen("/fp-4294967295.shader_test")) {
113          GET_CURRENT_CONTEXT(ctx);
114          _mesa_warning(ctx, "MESA_SHADER_CAPTURE_PATH too long; ignoring "
115                             "request to capture shaders");
116          path = NULL;
117       }
118    }
119
120    return path;
121 }
122
123 /**
124  * Initialize context's shader state.
125  */
126 void
127 _mesa_init_shader_state(struct gl_context *ctx)
128 {
129    /* Device drivers may override these to control what kind of instructions
130     * are generated by the GLSL compiler.
131     */
132    struct gl_shader_compiler_options options;
133    gl_shader_stage sh;
134    int i;
135
136    memset(&options, 0, sizeof(options));
137    options.MaxUnrollIterations = 32;
138    options.MaxIfDepth = UINT_MAX;
139
140    for (sh = 0; sh < MESA_SHADER_STAGES; ++sh)
141       memcpy(&ctx->Const.ShaderCompilerOptions[sh], &options, sizeof(options));
142
143    ctx->Shader.Flags = _mesa_get_shader_flags();
144
145    if (ctx->Shader.Flags != 0)
146       ctx->Const.GenerateTemporaryNames = true;
147
148    /* Extended for ARB_separate_shader_objects */
149    ctx->Shader.RefCount = 1;
150    mtx_init(&ctx->Shader.Mutex, mtx_plain);
151
152    ctx->TessCtrlProgram.patch_vertices = 3;
153    for (i = 0; i < 4; ++i)
154       ctx->TessCtrlProgram.patch_default_outer_level[i] = 1.0;
155    for (i = 0; i < 2; ++i)
156       ctx->TessCtrlProgram.patch_default_inner_level[i] = 1.0;
157 }
158
159
160 /**
161  * Free the per-context shader-related state.
162  */
163 void
164 _mesa_free_shader_state(struct gl_context *ctx)
165 {
166    int i;
167    for (i = 0; i < MESA_SHADER_STAGES; i++) {
168       _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentProgram[i],
169                                      NULL);
170    }
171    _mesa_reference_shader_program(ctx, &ctx->Shader._CurrentFragmentProgram,
172                                   NULL);
173    _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, NULL);
174
175    /* Extended for ARB_separate_shader_objects */
176    _mesa_reference_pipeline_object(ctx, &ctx->_Shader, NULL);
177
178    assert(ctx->Shader.RefCount == 1);
179    mtx_destroy(&ctx->Shader.Mutex);
180 }
181
182
183 /**
184  * Copy string from <src> to <dst>, up to maxLength characters, returning
185  * length of <dst> in <length>.
186  * \param src  the strings source
187  * \param maxLength  max chars to copy
188  * \param length  returns number of chars copied
189  * \param dst  the string destination
190  */
191 void
192 _mesa_copy_string(GLchar *dst, GLsizei maxLength,
193                   GLsizei *length, const GLchar *src)
194 {
195    GLsizei len;
196    for (len = 0; len < maxLength - 1 && src && src[len]; len++)
197       dst[len] = src[len];
198    if (maxLength > 0)
199       dst[len] = 0;
200    if (length)
201       *length = len;
202 }
203
204
205
206 /**
207  * Confirm that the a shader type is valid and supported by the implementation
208  *
209  * \param ctx   Current GL context
210  * \param type  Shader target
211  *
212  */
213 bool
214 _mesa_validate_shader_target(const struct gl_context *ctx, GLenum type)
215 {
216    /* Note: when building built-in GLSL functions, this function may be
217     * invoked with ctx == NULL.  In that case, we can only validate that it's
218     * a shader target we recognize, not that it's supported in the current
219     * context.  But that's fine--we don't need any further validation than
220     * that when building built-in GLSL functions.
221     */
222
223    switch (type) {
224    case GL_FRAGMENT_SHADER:
225       return ctx == NULL || ctx->Extensions.ARB_fragment_shader;
226    case GL_VERTEX_SHADER:
227       return ctx == NULL || ctx->Extensions.ARB_vertex_shader;
228    case GL_GEOMETRY_SHADER_ARB:
229       return ctx == NULL || _mesa_has_geometry_shaders(ctx);
230    case GL_TESS_CONTROL_SHADER:
231    case GL_TESS_EVALUATION_SHADER:
232       return ctx == NULL || _mesa_has_tessellation(ctx);
233    case GL_COMPUTE_SHADER:
234       return ctx == NULL || _mesa_has_compute_shaders(ctx);
235    default:
236       return false;
237    }
238 }
239
240
241 static GLboolean
242 is_program(struct gl_context *ctx, GLuint name)
243 {
244    struct gl_shader_program *shProg = _mesa_lookup_shader_program(ctx, name);
245    return shProg ? GL_TRUE : GL_FALSE;
246 }
247
248
249 static GLboolean
250 is_shader(struct gl_context *ctx, GLuint name)
251 {
252    struct gl_shader *shader = _mesa_lookup_shader(ctx, name);
253    return shader ? GL_TRUE : GL_FALSE;
254 }
255
256
257 /**
258  * Attach shader to a shader program.
259  */
260 static void
261 attach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
262 {
263    struct gl_shader_program *shProg;
264    struct gl_shader *sh;
265    GLuint i, n;
266
267    const bool same_type_disallowed = _mesa_is_gles(ctx);
268
269    shProg = _mesa_lookup_shader_program_err(ctx, program, "glAttachShader");
270    if (!shProg)
271       return;
272
273    sh = _mesa_lookup_shader_err(ctx, shader, "glAttachShader");
274    if (!sh) {
275       return;
276    }
277
278    n = shProg->NumShaders;
279    for (i = 0; i < n; i++) {
280       if (shProg->Shaders[i] == sh) {
281          /* The shader is already attched to this program.  The
282           * GL_ARB_shader_objects spec says:
283           *
284           *     "The error INVALID_OPERATION is generated by AttachObjectARB
285           *     if <obj> is already attached to <containerObj>."
286           */
287          _mesa_error(ctx, GL_INVALID_OPERATION, "glAttachShader");
288          return;
289       } else if (same_type_disallowed &&
290                  shProg->Shaders[i]->Type == sh->Type) {
291         /* Shader with the same type is already attached to this program,
292          * OpenGL ES 2.0 and 3.0 specs say:
293          *
294          *      "Multiple shader objects of the same type may not be attached
295          *      to a single program object. [...] The error INVALID_OPERATION
296          *      is generated if [...] another shader object of the same type
297          *      as shader is already attached to program."
298          */
299          _mesa_error(ctx, GL_INVALID_OPERATION, "glAttachShader");
300          return;
301       }
302    }
303
304    /* grow list */
305    shProg->Shaders = realloc(shProg->Shaders,
306                              (n + 1) * sizeof(struct gl_shader *));
307    if (!shProg->Shaders) {
308       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAttachShader");
309       return;
310    }
311
312    /* append */
313    shProg->Shaders[n] = NULL; /* since realloc() didn't zero the new space */
314    _mesa_reference_shader(ctx, &shProg->Shaders[n], sh);
315    shProg->NumShaders++;
316 }
317
318
319 static GLuint
320 create_shader(struct gl_context *ctx, GLenum type)
321 {
322    struct gl_shader *sh;
323    GLuint name;
324
325    if (!_mesa_validate_shader_target(ctx, type)) {
326       _mesa_error(ctx, GL_INVALID_ENUM, "CreateShader(%s)",
327                   _mesa_enum_to_string(type));
328       return 0;
329    }
330
331    _mesa_HashLockMutex(ctx->Shared->ShaderObjects);
332    name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
333    sh = ctx->Driver.NewShader(ctx, name, type);
334    _mesa_HashInsertLocked(ctx->Shared->ShaderObjects, name, sh);
335    _mesa_HashUnlockMutex(ctx->Shared->ShaderObjects);
336
337    return name;
338 }
339
340
341 static GLuint
342 create_shader_program(struct gl_context *ctx)
343 {
344    GLuint name;
345    struct gl_shader_program *shProg;
346
347    _mesa_HashLockMutex(ctx->Shared->ShaderObjects);
348
349    name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
350
351    shProg = _mesa_new_shader_program(name);
352
353    _mesa_HashInsertLocked(ctx->Shared->ShaderObjects, name, shProg);
354
355    assert(shProg->RefCount == 1);
356
357    _mesa_HashUnlockMutex(ctx->Shared->ShaderObjects);
358
359    return name;
360 }
361
362
363 /**
364  * Delete a shader program.  Actually, just decrement the program's
365  * reference count and mark it as DeletePending.
366  * Used to implement glDeleteProgram() and glDeleteObjectARB().
367  */
368 static void
369 delete_shader_program(struct gl_context *ctx, GLuint name)
370 {
371    /*
372     * NOTE: deleting shaders/programs works a bit differently than
373     * texture objects (and buffer objects, etc).  Shader/program
374     * handles/IDs exist in the hash table until the object is really
375     * deleted (refcount==0).  With texture objects, the handle/ID is
376     * removed from the hash table in glDeleteTextures() while the tex
377     * object itself might linger until its refcount goes to zero.
378     */
379    struct gl_shader_program *shProg;
380
381    shProg = _mesa_lookup_shader_program_err(ctx, name, "glDeleteProgram");
382    if (!shProg)
383       return;
384
385    if (!shProg->DeletePending) {
386       shProg->DeletePending = GL_TRUE;
387
388       /* effectively, decr shProg's refcount */
389       _mesa_reference_shader_program(ctx, &shProg, NULL);
390    }
391 }
392
393
394 static void
395 delete_shader(struct gl_context *ctx, GLuint shader)
396 {
397    struct gl_shader *sh;
398
399    sh = _mesa_lookup_shader_err(ctx, shader, "glDeleteShader");
400    if (!sh)
401       return;
402
403    if (!sh->DeletePending) {
404       sh->DeletePending = GL_TRUE;
405
406       /* effectively, decr sh's refcount */
407       _mesa_reference_shader(ctx, &sh, NULL);
408    }
409 }
410
411
412 static void
413 detach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
414 {
415    struct gl_shader_program *shProg;
416    GLuint n;
417    GLuint i, j;
418
419    shProg = _mesa_lookup_shader_program_err(ctx, program, "glDetachShader");
420    if (!shProg)
421       return;
422
423    n = shProg->NumShaders;
424
425    for (i = 0; i < n; i++) {
426       if (shProg->Shaders[i]->Name == shader) {
427          /* found it */
428          struct gl_shader **newList;
429
430          /* release */
431          _mesa_reference_shader(ctx, &shProg->Shaders[i], NULL);
432
433          /* alloc new, smaller array */
434          newList = malloc((n - 1) * sizeof(struct gl_shader *));
435          if (!newList) {
436             _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDetachShader");
437             return;
438          }
439          /* Copy old list entries to new list, skipping removed entry at [i] */
440          for (j = 0; j < i; j++) {
441             newList[j] = shProg->Shaders[j];
442          }
443          while (++i < n) {
444             newList[j++] = shProg->Shaders[i];
445          }
446
447          /* Free old list and install new one */
448          free(shProg->Shaders);
449          shProg->Shaders = newList;
450          shProg->NumShaders = n - 1;
451
452 #ifdef DEBUG
453          /* sanity check - make sure the new list's entries are sensible */
454          for (j = 0; j < shProg->NumShaders; j++) {
455             assert(shProg->Shaders[j]->Type == GL_VERTEX_SHADER ||
456                    shProg->Shaders[j]->Type == GL_TESS_CONTROL_SHADER ||
457                    shProg->Shaders[j]->Type == GL_TESS_EVALUATION_SHADER ||
458                    shProg->Shaders[j]->Type == GL_GEOMETRY_SHADER ||
459                    shProg->Shaders[j]->Type == GL_FRAGMENT_SHADER);
460             assert(shProg->Shaders[j]->RefCount > 0);
461          }
462 #endif
463
464          return;
465       }
466    }
467
468    /* not found */
469    {
470       GLenum err;
471       if (is_shader(ctx, shader) || is_program(ctx, shader))
472          err = GL_INVALID_OPERATION;
473       else
474          err = GL_INVALID_VALUE;
475       _mesa_error(ctx, err, "glDetachShader(shader)");
476       return;
477    }
478 }
479
480
481 /**
482  * Return list of shaders attached to shader program.
483  */
484 static void
485 get_attached_shaders(struct gl_context *ctx, GLuint program, GLsizei maxCount,
486                      GLsizei *count, GLuint *obj)
487 {
488    struct gl_shader_program *shProg;
489
490    if (maxCount < 0) {
491       _mesa_error(ctx, GL_INVALID_VALUE, "glGetAttachedShaders(maxCount < 0)");
492       return;
493    }
494
495    shProg =
496       _mesa_lookup_shader_program_err(ctx, program, "glGetAttachedShaders");
497
498    if (shProg) {
499       GLuint i;
500       for (i = 0; i < (GLuint) maxCount && i < shProg->NumShaders; i++) {
501          obj[i] = shProg->Shaders[i]->Name;
502       }
503       if (count)
504          *count = i;
505    }
506 }
507
508
509 /**
510  * glGetHandleARB() - return ID/name of currently bound shader program.
511  */
512 static GLuint
513 get_handle(struct gl_context *ctx, GLenum pname)
514 {
515    if (pname == GL_PROGRAM_OBJECT_ARB) {
516       if (ctx->_Shader->ActiveProgram)
517          return ctx->_Shader->ActiveProgram->Name;
518       else
519          return 0;
520    }
521    else {
522       _mesa_error(ctx, GL_INVALID_ENUM, "glGetHandleARB");
523       return 0;
524    }
525 }
526
527
528 /**
529  * Check if a geometry shader query is valid at this time.  If not, report an
530  * error and return false.
531  *
532  * From GL 3.2 section 6.1.16 (Shader and Program Queries):
533  *
534  *     "If GEOMETRY_VERTICES_OUT, GEOMETRY_INPUT_TYPE, or GEOMETRY_OUTPUT_TYPE
535  *     are queried for a program which has not been linked successfully, or
536  *     which does not contain objects to form a geometry shader, then an
537  *     INVALID_OPERATION error is generated."
538  */
539 static bool
540 check_gs_query(struct gl_context *ctx, const struct gl_shader_program *shProg)
541 {
542    if (shProg->LinkStatus &&
543        shProg->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
544       return true;
545    }
546
547    _mesa_error(ctx, GL_INVALID_OPERATION,
548                "glGetProgramv(linked geometry shader required)");
549    return false;
550 }
551
552
553 /**
554  * Check if a tessellation control shader query is valid at this time.
555  * If not, report an error and return false.
556  *
557  * From GL 4.0 section 6.1.12 (Shader and Program Queries):
558  *
559  *     "If TESS_CONTROL_OUTPUT_VERTICES is queried for a program which has
560  *     not been linked successfully, or which does not contain objects to
561  *     form a tessellation control shader, then an INVALID_OPERATION error is
562  *     generated."
563  */
564 static bool
565 check_tcs_query(struct gl_context *ctx, const struct gl_shader_program *shProg)
566 {
567    if (shProg->LinkStatus &&
568        shProg->_LinkedShaders[MESA_SHADER_TESS_CTRL] != NULL) {
569       return true;
570    }
571
572    _mesa_error(ctx, GL_INVALID_OPERATION,
573                "glGetProgramv(linked tessellation control shader required)");
574    return false;
575 }
576
577
578 /**
579  * Check if a tessellation evaluation shader query is valid at this time.
580  * If not, report an error and return false.
581  *
582  * From GL 4.0 section 6.1.12 (Shader and Program Queries):
583  *
584  *     "If any of the pname values in this paragraph are queried for a program
585  *     which has not been linked successfully, or which does not contain
586  *     objects to form a tessellation evaluation shader, then an
587  *     INVALID_OPERATION error is generated."
588  *
589  */
590 static bool
591 check_tes_query(struct gl_context *ctx, const struct gl_shader_program *shProg)
592 {
593    if (shProg->LinkStatus &&
594        shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL] != NULL) {
595       return true;
596    }
597
598    _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramv(linked tessellation "
599                "evaluation shader required)");
600    return false;
601 }
602
603
604 /**
605  * glGetProgramiv() - get shader program state.
606  * Note that this is for GLSL shader programs, not ARB vertex/fragment
607  * programs (see glGetProgramivARB).
608  */
609 static void
610 get_programiv(struct gl_context *ctx, GLuint program, GLenum pname,
611               GLint *params)
612 {
613    struct gl_shader_program *shProg
614       = _mesa_lookup_shader_program_err(ctx, program, "glGetProgramiv(program)");
615
616    /* Is transform feedback available in this context?
617     */
618    const bool has_xfb =
619       (ctx->API == API_OPENGL_COMPAT && ctx->Extensions.EXT_transform_feedback)
620       || ctx->API == API_OPENGL_CORE
621       || _mesa_is_gles3(ctx);
622
623    /* True if geometry shaders (of the form that was adopted into GLSL 1.50
624     * and GL 3.2) are available in this context
625     */
626    const bool has_core_gs = _mesa_has_geometry_shaders(ctx);
627    const bool has_tess = _mesa_has_tessellation(ctx);
628
629    /* Are uniform buffer objects available in this context?
630     */
631    const bool has_ubo =
632       (ctx->API == API_OPENGL_COMPAT &&
633        ctx->Extensions.ARB_uniform_buffer_object)
634       || ctx->API == API_OPENGL_CORE
635       || _mesa_is_gles3(ctx);
636
637    if (!shProg) {
638       return;
639    }
640
641    switch (pname) {
642    case GL_DELETE_STATUS:
643       *params = shProg->DeletePending;
644       return;
645    case GL_LINK_STATUS:
646       *params = shProg->LinkStatus;
647       return;
648    case GL_VALIDATE_STATUS:
649       *params = shProg->Validated;
650       return;
651    case GL_INFO_LOG_LENGTH:
652       *params = shProg->InfoLog ? strlen(shProg->InfoLog) + 1 : 0;
653       return;
654    case GL_ATTACHED_SHADERS:
655       *params = shProg->NumShaders;
656       return;
657    case GL_ACTIVE_ATTRIBUTES:
658       *params = _mesa_count_active_attribs(shProg);
659       return;
660    case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
661       *params = _mesa_longest_attribute_name_length(shProg);
662       return;
663    case GL_ACTIVE_UNIFORMS: {
664       unsigned i;
665       const unsigned num_uniforms =
666          shProg->NumUniformStorage - shProg->NumHiddenUniforms;
667       for (*params = 0, i = 0; i < num_uniforms; i++) {
668          if (!shProg->UniformStorage[i].is_shader_storage)
669             (*params)++;
670       }
671       return;
672    }
673    case GL_ACTIVE_UNIFORM_MAX_LENGTH: {
674       unsigned i;
675       GLint max_len = 0;
676       const unsigned num_uniforms =
677          shProg->NumUniformStorage - shProg->NumHiddenUniforms;
678
679       for (i = 0; i < num_uniforms; i++) {
680          if (shProg->UniformStorage[i].is_shader_storage)
681             continue;
682
683          /* Add one for the terminating NUL character for a non-array, and
684           * 4 for the "[0]" and the NUL for an array.
685           */
686          const GLint len = strlen(shProg->UniformStorage[i].name) + 1 +
687              ((shProg->UniformStorage[i].array_elements != 0) ? 3 : 0);
688
689          if (len > max_len)
690             max_len = len;
691       }
692
693       *params = max_len;
694       return;
695    }
696    case GL_TRANSFORM_FEEDBACK_VARYINGS:
697       if (!has_xfb)
698          break;
699       *params = shProg->TransformFeedback.NumVarying;
700       return;
701    case GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH: {
702       unsigned i;
703       GLint max_len = 0;
704       if (!has_xfb)
705          break;
706
707       for (i = 0; i < shProg->TransformFeedback.NumVarying; i++) {
708          /* Add one for the terminating NUL character.
709           */
710          const GLint len =
711             strlen(shProg->TransformFeedback.VaryingNames[i]) + 1;
712
713          if (len > max_len)
714             max_len = len;
715       }
716
717       *params = max_len;
718       return;
719    }
720    case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
721       if (!has_xfb)
722          break;
723       *params = shProg->TransformFeedback.BufferMode;
724       return;
725    case GL_GEOMETRY_VERTICES_OUT:
726       if (!has_core_gs)
727          break;
728       if (check_gs_query(ctx, shProg))
729          *params = shProg->Geom.VerticesOut;
730       return;
731    case GL_GEOMETRY_SHADER_INVOCATIONS:
732       if (!has_core_gs || !ctx->Extensions.ARB_gpu_shader5)
733          break;
734       if (check_gs_query(ctx, shProg))
735          *params = shProg->Geom.Invocations;
736       return;
737    case GL_GEOMETRY_INPUT_TYPE:
738       if (!has_core_gs)
739          break;
740       if (check_gs_query(ctx, shProg))
741          *params = shProg->Geom.InputType;
742       return;
743    case GL_GEOMETRY_OUTPUT_TYPE:
744       if (!has_core_gs)
745          break;
746       if (check_gs_query(ctx, shProg))
747          *params = shProg->Geom.OutputType;
748       return;
749    case GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH: {
750       unsigned i;
751       GLint max_len = 0;
752
753       if (!has_ubo)
754          break;
755
756       for (i = 0; i < shProg->NumUniformBlocks; i++) {
757          /* Add one for the terminating NUL character.
758           */
759          const GLint len = strlen(shProg->UniformBlocks[i].Name) + 1;
760
761          if (len > max_len)
762             max_len = len;
763       }
764
765       *params = max_len;
766       return;
767    }
768    case GL_ACTIVE_UNIFORM_BLOCKS:
769       if (!has_ubo)
770          break;
771
772       *params = shProg->NumUniformBlocks;
773       return;
774    case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
775       /* This enum isn't part of the OES extension for OpenGL ES 2.0.  It is
776        * only available with desktop OpenGL 3.0+ with the
777        * GL_ARB_get_program_binary extension or OpenGL ES 3.0.
778        *
779        * On desktop, we ignore the 3.0+ requirement because it is silly.
780        */
781       if (!_mesa_is_desktop_gl(ctx) && !_mesa_is_gles3(ctx))
782          break;
783
784       *params = shProg->BinaryRetreivableHint;
785       return;
786    case GL_PROGRAM_BINARY_LENGTH:
787       *params = 0;
788       return;
789    case GL_ACTIVE_ATOMIC_COUNTER_BUFFERS:
790       if (!ctx->Extensions.ARB_shader_atomic_counters)
791          break;
792
793       *params = shProg->NumAtomicBuffers;
794       return;
795    case GL_COMPUTE_WORK_GROUP_SIZE: {
796       int i;
797       if (!_mesa_has_compute_shaders(ctx))
798          break;
799       if (!shProg->LinkStatus) {
800          _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramiv(program not "
801                      "linked)");
802          return;
803       }
804       if (shProg->_LinkedShaders[MESA_SHADER_COMPUTE] == NULL) {
805          _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramiv(no compute "
806                      "shaders)");
807          return;
808       }
809       for (i = 0; i < 3; i++)
810          params[i] = shProg->Comp.LocalSize[i];
811       return;
812    }
813    case GL_PROGRAM_SEPARABLE:
814       /* If the program has not been linked, return initial value 0. */
815       *params = (shProg->LinkStatus == GL_FALSE) ? 0 : shProg->SeparateShader;
816       return;
817
818    /* ARB_tessellation_shader */
819    case GL_TESS_CONTROL_OUTPUT_VERTICES:
820       if (!has_tess)
821          break;
822       if (check_tcs_query(ctx, shProg))
823          *params = shProg->TessCtrl.VerticesOut;
824       return;
825    case GL_TESS_GEN_MODE:
826       if (!has_tess)
827          break;
828       if (check_tes_query(ctx, shProg))
829          *params = shProg->TessEval.PrimitiveMode;
830       return;
831    case GL_TESS_GEN_SPACING:
832       if (!has_tess)
833          break;
834       if (check_tes_query(ctx, shProg))
835          *params = shProg->TessEval.Spacing;
836       return;
837    case GL_TESS_GEN_VERTEX_ORDER:
838       if (!has_tess)
839          break;
840       if (check_tes_query(ctx, shProg))
841          *params = shProg->TessEval.VertexOrder;
842       return;
843    case GL_TESS_GEN_POINT_MODE:
844       if (!has_tess)
845          break;
846       if (check_tes_query(ctx, shProg))
847          *params = shProg->TessEval.PointMode;
848       return;
849    default:
850       break;
851    }
852
853    _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramiv(pname=%s)",
854                _mesa_enum_to_string(pname));
855 }
856
857
858 /**
859  * glGetShaderiv() - get GLSL shader state
860  */
861 static void
862 get_shaderiv(struct gl_context *ctx, GLuint name, GLenum pname, GLint *params)
863 {
864    struct gl_shader *shader =
865       _mesa_lookup_shader_err(ctx, name, "glGetShaderiv");
866
867    if (!shader) {
868       return;
869    }
870
871    switch (pname) {
872    case GL_SHADER_TYPE:
873       *params = shader->Type;
874       break;
875    case GL_DELETE_STATUS:
876       *params = shader->DeletePending;
877       break;
878    case GL_COMPILE_STATUS:
879       *params = shader->CompileStatus;
880       break;
881    case GL_INFO_LOG_LENGTH:
882       *params = shader->InfoLog ? strlen(shader->InfoLog) + 1 : 0;
883       break;
884    case GL_SHADER_SOURCE_LENGTH:
885       *params = shader->Source ? strlen((char *) shader->Source) + 1 : 0;
886       break;
887    default:
888       _mesa_error(ctx, GL_INVALID_ENUM, "glGetShaderiv(pname)");
889       return;
890    }
891 }
892
893
894 static void
895 get_program_info_log(struct gl_context *ctx, GLuint program, GLsizei bufSize,
896                      GLsizei *length, GLchar *infoLog)
897 {
898    struct gl_shader_program *shProg;
899
900    /* Section 2.5 GL Errors (page 18) of the OpenGL ES 3.0.4 spec and
901     * section 2.3.1 (Errors) of the OpenGL 4.5 spec say:
902     *
903     *     "If a negative number is provided where an argument of type sizei or
904     *     sizeiptr is specified, an INVALID_VALUE error is generated."
905     */
906    if (bufSize < 0) {
907       _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramInfoLog(bufSize < 0)");
908       return;
909    }
910
911    shProg = _mesa_lookup_shader_program_err(ctx, program,
912                                             "glGetProgramInfoLog(program)");
913    if (!shProg) {
914       return;
915    }
916
917    _mesa_copy_string(infoLog, bufSize, length, shProg->InfoLog);
918 }
919
920
921 static void
922 get_shader_info_log(struct gl_context *ctx, GLuint shader, GLsizei bufSize,
923                     GLsizei *length, GLchar *infoLog)
924 {
925    struct gl_shader *sh;
926
927    /* Section 2.5 GL Errors (page 18) of the OpenGL ES 3.0.4 spec and
928     * section 2.3.1 (Errors) of the OpenGL 4.5 spec say:
929     *
930     *     "If a negative number is provided where an argument of type sizei or
931     *     sizeiptr is specified, an INVALID_VALUE error is generated."
932     */
933    if (bufSize < 0) {
934       _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderInfoLog(bufSize < 0)");
935       return;
936    }
937
938    sh = _mesa_lookup_shader_err(ctx, shader, "glGetShaderInfoLog(shader)");
939    if (!sh) {
940       return;
941    }
942
943    _mesa_copy_string(infoLog, bufSize, length, sh->InfoLog);
944 }
945
946
947 /**
948  * Return shader source code.
949  */
950 static void
951 get_shader_source(struct gl_context *ctx, GLuint shader, GLsizei maxLength,
952                   GLsizei *length, GLchar *sourceOut)
953 {
954    struct gl_shader *sh;
955
956    if (maxLength < 0) {
957       _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderSource(bufSize < 0)");
958       return;
959    }
960
961    sh = _mesa_lookup_shader_err(ctx, shader, "glGetShaderSource");
962    if (!sh) {
963       return;
964    }
965    _mesa_copy_string(sourceOut, maxLength, length, sh->Source);
966 }
967
968
969 /**
970  * Set/replace shader source code.  A helper function used by
971  * glShaderSource[ARB].
972  */
973 static void
974 shader_source(struct gl_shader *sh, const GLchar *source)
975 {
976    assert(sh);
977
978    /* free old shader source string and install new one */
979    free((void *)sh->Source);
980    sh->Source = source;
981 #ifdef DEBUG
982    sh->SourceChecksum = _mesa_str_checksum(sh->Source);
983 #endif
984 }
985
986
987 /**
988  * Compile a shader.
989  */
990 void
991 _mesa_compile_shader(struct gl_context *ctx, struct gl_shader *sh)
992 {
993    if (!sh)
994       return;
995
996    if (!sh->Source) {
997       /* If the user called glCompileShader without first calling
998        * glShaderSource, we should fail to compile, but not raise a GL_ERROR.
999        */
1000       sh->CompileStatus = GL_FALSE;
1001    } else {
1002       if (ctx->_Shader->Flags & GLSL_DUMP) {
1003          _mesa_log("GLSL source for %s shader %d:\n",
1004                  _mesa_shader_stage_to_string(sh->Stage), sh->Name);
1005          _mesa_log("%s\n", sh->Source);
1006       }
1007
1008       /* this call will set the shader->CompileStatus field to indicate if
1009        * compilation was successful.
1010        */
1011       _mesa_glsl_compile_shader(ctx, sh, false, false);
1012
1013       if (ctx->_Shader->Flags & GLSL_LOG) {
1014          _mesa_write_shader_to_file(sh);
1015       }
1016
1017       if (ctx->_Shader->Flags & GLSL_DUMP) {
1018          if (sh->CompileStatus) {
1019             _mesa_log("GLSL IR for shader %d:\n", sh->Name);
1020             _mesa_print_ir(_mesa_get_log_file(), sh->ir, NULL);
1021             _mesa_log("\n\n");
1022          } else {
1023             _mesa_log("GLSL shader %d failed to compile.\n", sh->Name);
1024          }
1025          if (sh->InfoLog && sh->InfoLog[0] != 0) {
1026             _mesa_log("GLSL shader %d info log:\n", sh->Name);
1027             _mesa_log("%s\n", sh->InfoLog);
1028          }
1029       }
1030    }
1031
1032    if (!sh->CompileStatus) {
1033       if (ctx->_Shader->Flags & GLSL_DUMP_ON_ERROR) {
1034          _mesa_log("GLSL source for %s shader %d:\n",
1035                  _mesa_shader_stage_to_string(sh->Stage), sh->Name);
1036          _mesa_log("%s\n", sh->Source);
1037          _mesa_log("Info Log:\n%s\n", sh->InfoLog);
1038       }
1039
1040       if (ctx->_Shader->Flags & GLSL_REPORT_ERRORS) {
1041          _mesa_debug(ctx, "Error compiling shader %u:\n%s\n",
1042                      sh->Name, sh->InfoLog);
1043       }
1044    }
1045 }
1046
1047
1048 /**
1049  * Link a program's shaders.
1050  */
1051 void
1052 _mesa_link_program(struct gl_context *ctx, struct gl_shader_program *shProg)
1053 {
1054    if (!shProg)
1055       return;
1056
1057    /* From the ARB_transform_feedback2 specification:
1058     * "The error INVALID_OPERATION is generated by LinkProgram if <program> is
1059     *  the name of a program being used by one or more transform feedback
1060     *  objects, even if the objects are not currently bound or are paused."
1061     */
1062    if (_mesa_transform_feedback_is_using_program(ctx, shProg)) {
1063       _mesa_error(ctx, GL_INVALID_OPERATION,
1064                   "glLinkProgram(transform feedback is using the program)");
1065       return;
1066    }
1067
1068    FLUSH_VERTICES(ctx, _NEW_PROGRAM);
1069
1070    _mesa_glsl_link_shader(ctx, shProg);
1071
1072    /* Capture .shader_test files. */
1073    const char *capture_path = _mesa_get_shader_capture_path();
1074    if (shProg->Name != 0 && capture_path != NULL) {
1075       FILE *file;
1076       char filename[PATH_MAX];
1077
1078       _mesa_snprintf(filename, sizeof(filename), "%s/%u.shader_test",
1079                      capture_path, shProg->Name);
1080
1081       file = fopen(filename, "w");
1082       if (file) {
1083          fprintf(file, "[require]\nGLSL%s >= %u.%02u\n",
1084                  shProg->IsES ? " ES" : "",
1085                  shProg->Version / 100, shProg->Version % 100);
1086          if (shProg->SeparateShader)
1087             fprintf(file, "GL_ARB_separate_shader_objects\nSSO ENABLED\n");
1088          fprintf(file, "\n");
1089
1090          for (unsigned i = 0; i < shProg->NumShaders; i++) {
1091             fprintf(file, "[%s shader]\n%s\n",
1092                     _mesa_shader_stage_to_string(shProg->Shaders[i]->Stage),
1093                     shProg->Shaders[i]->Source);
1094          }
1095          fclose(file);
1096       } else {
1097          _mesa_warning(ctx, "Failed to open %s", filename);
1098       }
1099    }
1100
1101    if (shProg->LinkStatus == GL_FALSE &&
1102        (ctx->_Shader->Flags & GLSL_REPORT_ERRORS)) {
1103       _mesa_debug(ctx, "Error linking program %u:\n%s\n",
1104                   shProg->Name, shProg->InfoLog);
1105    }
1106
1107    /* debug code */
1108    if (0) {
1109       GLuint i;
1110
1111       printf("Link %u shaders in program %u: %s\n",
1112                    shProg->NumShaders, shProg->Name,
1113                    shProg->LinkStatus ? "Success" : "Failed");
1114
1115       for (i = 0; i < shProg->NumShaders; i++) {
1116          printf(" shader %u, type 0x%x\n",
1117                       shProg->Shaders[i]->Name,
1118                       shProg->Shaders[i]->Type);
1119       }
1120    }
1121 }
1122
1123
1124 /**
1125  * Print basic shader info (for debug).
1126  */
1127 static void
1128 print_shader_info(const struct gl_shader_program *shProg)
1129 {
1130    GLuint i;
1131
1132    printf("Mesa: glUseProgram(%u)\n", shProg->Name);
1133    for (i = 0; i < shProg->NumShaders; i++) {
1134       printf("  %s shader %u, checksum %u\n",
1135              _mesa_shader_stage_to_string(shProg->Shaders[i]->Stage),
1136              shProg->Shaders[i]->Name,
1137              shProg->Shaders[i]->SourceChecksum);
1138    }
1139    if (shProg->_LinkedShaders[MESA_SHADER_VERTEX])
1140       printf("  vert prog %u\n",
1141              shProg->_LinkedShaders[MESA_SHADER_VERTEX]->Program->Id);
1142    if (shProg->_LinkedShaders[MESA_SHADER_FRAGMENT])
1143       printf("  frag prog %u\n",
1144              shProg->_LinkedShaders[MESA_SHADER_FRAGMENT]->Program->Id);
1145    if (shProg->_LinkedShaders[MESA_SHADER_GEOMETRY])
1146       printf("  geom prog %u\n",
1147              shProg->_LinkedShaders[MESA_SHADER_GEOMETRY]->Program->Id);
1148    if (shProg->_LinkedShaders[MESA_SHADER_TESS_CTRL])
1149       printf("  tesc prog %u\n",
1150              shProg->_LinkedShaders[MESA_SHADER_TESS_CTRL]->Program->Id);
1151    if (shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL])
1152       printf("  tese prog %u\n",
1153              shProg->_LinkedShaders[MESA_SHADER_TESS_EVAL]->Program->Id);
1154 }
1155
1156
1157 /**
1158  * Use the named shader program for subsequent glUniform calls
1159  */
1160 void
1161 _mesa_active_program(struct gl_context *ctx, struct gl_shader_program *shProg,
1162                      const char *caller)
1163 {
1164    if ((shProg != NULL) && !shProg->LinkStatus) {
1165       _mesa_error(ctx, GL_INVALID_OPERATION,
1166                   "%s(program %u not linked)", caller, shProg->Name);
1167       return;
1168    }
1169
1170    if (ctx->Shader.ActiveProgram != shProg) {
1171       _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, shProg);
1172    }
1173 }
1174
1175
1176 static void
1177 use_shader_program(struct gl_context *ctx, gl_shader_stage stage,
1178                    struct gl_shader_program *shProg,
1179                    struct gl_pipeline_object *shTarget)
1180 {
1181    struct gl_shader_program **target;
1182
1183    target = &shTarget->CurrentProgram[stage];
1184    if ((shProg != NULL) && (shProg->_LinkedShaders[stage] == NULL))
1185       shProg = NULL;
1186
1187    if (shProg)
1188       _mesa_shader_program_init_subroutine_defaults(shProg);
1189
1190    if (*target != shProg) {
1191       /* Program is current, flush it */
1192       if (shTarget == ctx->_Shader) {
1193          FLUSH_VERTICES(ctx, _NEW_PROGRAM | _NEW_PROGRAM_CONSTANTS);
1194       }
1195
1196       /* If the shader is also bound as the current rendering shader, unbind
1197        * it from that binding point as well.  This ensures that the correct
1198        * semantics of glDeleteProgram are maintained.
1199        */
1200       switch (stage) {
1201       case MESA_SHADER_VERTEX:
1202       case MESA_SHADER_TESS_CTRL:
1203       case MESA_SHADER_TESS_EVAL:
1204       case MESA_SHADER_GEOMETRY:
1205       case MESA_SHADER_COMPUTE:
1206          /* Empty for now. */
1207          break;
1208       case MESA_SHADER_FRAGMENT:
1209          if (*target == ctx->_Shader->_CurrentFragmentProgram) {
1210             _mesa_reference_shader_program(ctx,
1211                                            &ctx->_Shader->_CurrentFragmentProgram,
1212                                            NULL);
1213          }
1214          break;
1215       }
1216
1217       _mesa_reference_shader_program(ctx, target, shProg);
1218       return;
1219    }
1220 }
1221
1222
1223 /**
1224  * Use the named shader program for subsequent rendering.
1225  */
1226 void
1227 _mesa_use_program(struct gl_context *ctx, struct gl_shader_program *shProg)
1228 {
1229    int i;
1230    for (i = 0; i < MESA_SHADER_STAGES; i++)
1231       use_shader_program(ctx, i, shProg, &ctx->Shader);
1232    _mesa_active_program(ctx, shProg, "glUseProgram");
1233
1234    if (ctx->Driver.UseProgram)
1235       ctx->Driver.UseProgram(ctx, shProg);
1236 }
1237
1238
1239 /**
1240  * Do validation of the given shader program.
1241  * \param errMsg  returns error message if validation fails.
1242  * \return GL_TRUE if valid, GL_FALSE if invalid (and set errMsg)
1243  */
1244 static GLboolean
1245 validate_shader_program(const struct gl_shader_program *shProg,
1246                         char *errMsg)
1247 {
1248    if (!shProg->LinkStatus) {
1249       return GL_FALSE;
1250    }
1251
1252    /* From the GL spec, a program is invalid if any of these are true:
1253
1254      any two active samplers in the current program object are of
1255      different types, but refer to the same texture image unit,
1256
1257      any active sampler in the current program object refers to a texture
1258      image unit where fixed-function fragment processing accesses a
1259      texture target that does not match the sampler type, or
1260
1261      the sum of the number of active samplers in the program and the
1262      number of texture image units enabled for fixed-function fragment
1263      processing exceeds the combined limit on the total number of texture
1264      image units allowed.
1265    */
1266
1267    /*
1268     * Check: any two active samplers in the current program object are of
1269     * different types, but refer to the same texture image unit,
1270     */
1271    if (!_mesa_sampler_uniforms_are_valid(shProg, errMsg, 100))
1272       return GL_FALSE;
1273
1274    return GL_TRUE;
1275 }
1276
1277
1278 /**
1279  * Called via glValidateProgram()
1280  */
1281 static void
1282 validate_program(struct gl_context *ctx, GLuint program)
1283 {
1284    struct gl_shader_program *shProg;
1285    char errMsg[100] = "";
1286
1287    shProg = _mesa_lookup_shader_program_err(ctx, program, "glValidateProgram");
1288    if (!shProg) {
1289       return;
1290    }
1291
1292    shProg->Validated = validate_shader_program(shProg, errMsg);
1293    if (!shProg->Validated) {
1294       /* update info log */
1295       if (shProg->InfoLog) {
1296          ralloc_free(shProg->InfoLog);
1297       }
1298       shProg->InfoLog = ralloc_strdup(shProg, errMsg);
1299    }
1300 }
1301
1302
1303
1304 void GLAPIENTRY
1305 _mesa_AttachObjectARB(GLhandleARB program, GLhandleARB shader)
1306 {
1307    GET_CURRENT_CONTEXT(ctx);
1308    attach_shader(ctx, program, shader);
1309 }
1310
1311
1312 void GLAPIENTRY
1313 _mesa_AttachShader(GLuint program, GLuint shader)
1314 {
1315    GET_CURRENT_CONTEXT(ctx);
1316    attach_shader(ctx, program, shader);
1317 }
1318
1319
1320 void GLAPIENTRY
1321 _mesa_CompileShader(GLuint shaderObj)
1322 {
1323    GET_CURRENT_CONTEXT(ctx);
1324    if (MESA_VERBOSE & VERBOSE_API)
1325       _mesa_debug(ctx, "glCompileShader %u\n", shaderObj);
1326    _mesa_compile_shader(ctx, _mesa_lookup_shader_err(ctx, shaderObj,
1327                                                      "glCompileShader"));
1328 }
1329
1330
1331 GLuint GLAPIENTRY
1332 _mesa_CreateShader(GLenum type)
1333 {
1334    GET_CURRENT_CONTEXT(ctx);
1335    if (MESA_VERBOSE & VERBOSE_API)
1336       _mesa_debug(ctx, "glCreateShader %s\n", _mesa_enum_to_string(type));
1337    return create_shader(ctx, type);
1338 }
1339
1340
1341 GLhandleARB GLAPIENTRY
1342 _mesa_CreateShaderObjectARB(GLenum type)
1343 {
1344    GET_CURRENT_CONTEXT(ctx);
1345    return create_shader(ctx, type);
1346 }
1347
1348
1349 GLuint GLAPIENTRY
1350 _mesa_CreateProgram(void)
1351 {
1352    GET_CURRENT_CONTEXT(ctx);
1353    if (MESA_VERBOSE & VERBOSE_API)
1354       _mesa_debug(ctx, "glCreateProgram\n");
1355    return create_shader_program(ctx);
1356 }
1357
1358
1359 GLhandleARB GLAPIENTRY
1360 _mesa_CreateProgramObjectARB(void)
1361 {
1362    GET_CURRENT_CONTEXT(ctx);
1363    return create_shader_program(ctx);
1364 }
1365
1366
1367 void GLAPIENTRY
1368 _mesa_DeleteObjectARB(GLhandleARB obj)
1369 {
1370    if (MESA_VERBOSE & VERBOSE_API) {
1371       GET_CURRENT_CONTEXT(ctx);
1372       _mesa_debug(ctx, "glDeleteObjectARB(%lu)\n", (unsigned long)obj);
1373    }
1374
1375    if (obj) {
1376       GET_CURRENT_CONTEXT(ctx);
1377       FLUSH_VERTICES(ctx, 0);
1378       if (is_program(ctx, obj)) {
1379          delete_shader_program(ctx, obj);
1380       }
1381       else if (is_shader(ctx, obj)) {
1382          delete_shader(ctx, obj);
1383       }
1384       else {
1385          /* error? */
1386       }
1387    }
1388 }
1389
1390
1391 void GLAPIENTRY
1392 _mesa_DeleteProgram(GLuint name)
1393 {
1394    if (name) {
1395       GET_CURRENT_CONTEXT(ctx);
1396       FLUSH_VERTICES(ctx, 0);
1397       delete_shader_program(ctx, name);
1398    }
1399 }
1400
1401
1402 void GLAPIENTRY
1403 _mesa_DeleteShader(GLuint name)
1404 {
1405    if (name) {
1406       GET_CURRENT_CONTEXT(ctx);
1407       FLUSH_VERTICES(ctx, 0);
1408       delete_shader(ctx, name);
1409    }
1410 }
1411
1412
1413 void GLAPIENTRY
1414 _mesa_DetachObjectARB(GLhandleARB program, GLhandleARB shader)
1415 {
1416    GET_CURRENT_CONTEXT(ctx);
1417    detach_shader(ctx, program, shader);
1418 }
1419
1420
1421 void GLAPIENTRY
1422 _mesa_DetachShader(GLuint program, GLuint shader)
1423 {
1424    GET_CURRENT_CONTEXT(ctx);
1425    detach_shader(ctx, program, shader);
1426 }
1427
1428
1429 void GLAPIENTRY
1430 _mesa_GetAttachedObjectsARB(GLhandleARB container, GLsizei maxCount,
1431                             GLsizei * count, GLhandleARB * obj)
1432 {
1433    GET_CURRENT_CONTEXT(ctx);
1434    get_attached_shaders(ctx, container, maxCount, count, obj);
1435 }
1436
1437
1438 void GLAPIENTRY
1439 _mesa_GetAttachedShaders(GLuint program, GLsizei maxCount,
1440                          GLsizei *count, GLuint *obj)
1441 {
1442    GET_CURRENT_CONTEXT(ctx);
1443    get_attached_shaders(ctx, program, maxCount, count, obj);
1444 }
1445
1446
1447 void GLAPIENTRY
1448 _mesa_GetInfoLogARB(GLhandleARB object, GLsizei maxLength, GLsizei * length,
1449                     GLcharARB * infoLog)
1450 {
1451    GET_CURRENT_CONTEXT(ctx);
1452    if (is_program(ctx, object)) {
1453       get_program_info_log(ctx, object, maxLength, length, infoLog);
1454    }
1455    else if (is_shader(ctx, object)) {
1456       get_shader_info_log(ctx, object, maxLength, length, infoLog);
1457    }
1458    else {
1459       _mesa_error(ctx, GL_INVALID_OPERATION, "glGetInfoLogARB");
1460    }
1461 }
1462
1463
1464 void GLAPIENTRY
1465 _mesa_GetObjectParameterivARB(GLhandleARB object, GLenum pname, GLint *params)
1466 {
1467    GET_CURRENT_CONTEXT(ctx);
1468    /* Implement in terms of GetProgramiv, GetShaderiv */
1469    if (is_program(ctx, object)) {
1470       if (pname == GL_OBJECT_TYPE_ARB) {
1471          *params = GL_PROGRAM_OBJECT_ARB;
1472       }
1473       else {
1474          get_programiv(ctx, object, pname, params);
1475       }
1476    }
1477    else if (is_shader(ctx, object)) {
1478       if (pname == GL_OBJECT_TYPE_ARB) {
1479          *params = GL_SHADER_OBJECT_ARB;
1480       }
1481       else {
1482          get_shaderiv(ctx, object, pname, params);
1483       }
1484    }
1485    else {
1486       _mesa_error(ctx, GL_INVALID_VALUE, "glGetObjectParameterivARB");
1487    }
1488 }
1489
1490
1491 void GLAPIENTRY
1492 _mesa_GetObjectParameterfvARB(GLhandleARB object, GLenum pname,
1493                               GLfloat *params)
1494 {
1495    GLint iparams[1] = {0};  /* XXX is one element enough? */
1496    _mesa_GetObjectParameterivARB(object, pname, iparams);
1497    params[0] = (GLfloat) iparams[0];
1498 }
1499
1500
1501 void GLAPIENTRY
1502 _mesa_GetProgramiv(GLuint program, GLenum pname, GLint *params)
1503 {
1504    GET_CURRENT_CONTEXT(ctx);
1505    get_programiv(ctx, program, pname, params);
1506 }
1507
1508
1509 void GLAPIENTRY
1510 _mesa_GetShaderiv(GLuint shader, GLenum pname, GLint *params)
1511 {
1512    GET_CURRENT_CONTEXT(ctx);
1513    get_shaderiv(ctx, shader, pname, params);
1514 }
1515
1516
1517 void GLAPIENTRY
1518 _mesa_GetProgramInfoLog(GLuint program, GLsizei bufSize,
1519                         GLsizei *length, GLchar *infoLog)
1520 {
1521    GET_CURRENT_CONTEXT(ctx);
1522    get_program_info_log(ctx, program, bufSize, length, infoLog);
1523 }
1524
1525
1526 void GLAPIENTRY
1527 _mesa_GetShaderInfoLog(GLuint shader, GLsizei bufSize,
1528                        GLsizei *length, GLchar *infoLog)
1529 {
1530    GET_CURRENT_CONTEXT(ctx);
1531    get_shader_info_log(ctx, shader, bufSize, length, infoLog);
1532 }
1533
1534
1535 void GLAPIENTRY
1536 _mesa_GetShaderSource(GLuint shader, GLsizei maxLength,
1537                       GLsizei *length, GLchar *sourceOut)
1538 {
1539    GET_CURRENT_CONTEXT(ctx);
1540    get_shader_source(ctx, shader, maxLength, length, sourceOut);
1541 }
1542
1543
1544 GLhandleARB GLAPIENTRY
1545 _mesa_GetHandleARB(GLenum pname)
1546 {
1547    GET_CURRENT_CONTEXT(ctx);
1548    return get_handle(ctx, pname);
1549 }
1550
1551
1552 GLboolean GLAPIENTRY
1553 _mesa_IsProgram(GLuint name)
1554 {
1555    GET_CURRENT_CONTEXT(ctx);
1556    return is_program(ctx, name);
1557 }
1558
1559
1560 GLboolean GLAPIENTRY
1561 _mesa_IsShader(GLuint name)
1562 {
1563    GET_CURRENT_CONTEXT(ctx);
1564    return is_shader(ctx, name);
1565 }
1566
1567
1568 void GLAPIENTRY
1569 _mesa_LinkProgram(GLuint programObj)
1570 {
1571    GET_CURRENT_CONTEXT(ctx);
1572    if (MESA_VERBOSE & VERBOSE_API)
1573       _mesa_debug(ctx, "glLinkProgram %u\n", programObj);
1574    _mesa_link_program(ctx, _mesa_lookup_shader_program_err(ctx, programObj,
1575                                                            "glLinkProgram"));
1576 }
1577
1578 #if defined(HAVE_SHA1)
1579 /**
1580  * Generate a SHA-1 hash value string for given source string.
1581  */
1582 static void
1583 generate_sha1(const char *source, char sha_str[64])
1584 {
1585    unsigned char sha[20];
1586    _mesa_sha1_compute(source, strlen(source), sha);
1587    _mesa_sha1_format(sha_str, sha);
1588 }
1589
1590 /**
1591  * Construct a full path for shader replacement functionality using
1592  * following format:
1593  *
1594  * <path>/<stage prefix>_<CHECKSUM>.glsl
1595  */
1596 static void
1597 construct_name(const gl_shader_stage stage, const char *source,
1598                const char *path, char *name, unsigned length)
1599 {
1600    char sha[64];
1601    static const char *types[] = {
1602       "VS", "TC", "TE", "GS", "FS", "CS",
1603    };
1604
1605    generate_sha1(source, sha);
1606    _mesa_snprintf(name, length, "%s/%s_%s.glsl", path, types[stage],
1607                   sha);
1608 }
1609
1610 /**
1611  * Write given shader source to a file in MESA_SHADER_DUMP_PATH.
1612  */
1613 static void
1614 dump_shader(const gl_shader_stage stage, const char *source)
1615 {
1616    char name[PATH_MAX];
1617    static bool path_exists = true;
1618    char *dump_path;
1619    FILE *f;
1620
1621    if (!path_exists)
1622       return;
1623
1624    dump_path = getenv("MESA_SHADER_DUMP_PATH");
1625    if (!dump_path) {
1626       path_exists = false;
1627       return;
1628    }
1629
1630    construct_name(stage, source, dump_path, name, PATH_MAX);
1631
1632    f = fopen(name, "w");
1633    if (f) {
1634       fputs(source, f);
1635       fclose(f);
1636    } else {
1637       GET_CURRENT_CONTEXT(ctx);
1638       _mesa_warning(ctx, "could not open %s for dumping shader (%s)", name,
1639                     strerror(errno));
1640    }
1641 }
1642
1643 /**
1644  * Read shader source code from a file.
1645  * Useful for debugging to override an app's shader.
1646  */
1647 static GLcharARB *
1648 read_shader(const gl_shader_stage stage, const char *source)
1649 {
1650    char name[PATH_MAX];
1651    char *read_path;
1652    static bool path_exists = true;
1653    int len, shader_size = 0;
1654    GLcharARB *buffer;
1655    FILE *f;
1656
1657    if (!path_exists)
1658       return NULL;
1659
1660    read_path = getenv("MESA_SHADER_READ_PATH");
1661    if (!read_path) {
1662       path_exists = false;
1663       return NULL;
1664    }
1665
1666    construct_name(stage, source, read_path, name, PATH_MAX);
1667
1668    f = fopen(name, "r");
1669    if (!f)
1670       return NULL;
1671
1672    /* allocate enough room for the entire shader */
1673    fseek(f, 0, SEEK_END);
1674    shader_size = ftell(f);
1675    rewind(f);
1676    assert(shader_size);
1677
1678    /* add one for terminating zero */
1679    shader_size++;
1680
1681    buffer = malloc(shader_size);
1682    assert(buffer);
1683
1684    len = fread(buffer, 1, shader_size, f);
1685    buffer[len] = 0;
1686
1687    fclose(f);
1688
1689    return buffer;
1690 }
1691 #endif /* HAVE_SHA1 */
1692
1693 /**
1694  * Called via glShaderSource() and glShaderSourceARB() API functions.
1695  * Basically, concatenate the source code strings into one long string
1696  * and pass it to _mesa_shader_source().
1697  */
1698 void GLAPIENTRY
1699 _mesa_ShaderSource(GLuint shaderObj, GLsizei count,
1700                    const GLchar * const * string, const GLint * length)
1701 {
1702    GET_CURRENT_CONTEXT(ctx);
1703    GLint *offsets;
1704    GLsizei i, totalLength;
1705    GLcharARB *source;
1706    struct gl_shader *sh;
1707
1708 #if defined(HAVE_SHA1)
1709    GLcharARB *replacement;
1710 #endif /* HAVE_SHA1 */
1711
1712    sh = _mesa_lookup_shader_err(ctx, shaderObj, "glShaderSourceARB");
1713    if (!sh)
1714       return;
1715
1716    if (string == NULL) {
1717       _mesa_error(ctx, GL_INVALID_VALUE, "glShaderSourceARB");
1718       return;
1719    }
1720
1721    /*
1722     * This array holds offsets of where the appropriate string ends, thus the
1723     * last element will be set to the total length of the source code.
1724     */
1725    offsets = malloc(count * sizeof(GLint));
1726    if (offsets == NULL) {
1727       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
1728       return;
1729    }
1730
1731    for (i = 0; i < count; i++) {
1732       if (string[i] == NULL) {
1733          free((GLvoid *) offsets);
1734          _mesa_error(ctx, GL_INVALID_OPERATION,
1735                      "glShaderSourceARB(null string)");
1736          return;
1737       }
1738       if (length == NULL || length[i] < 0)
1739          offsets[i] = strlen(string[i]);
1740       else
1741          offsets[i] = length[i];
1742       /* accumulate string lengths */
1743       if (i > 0)
1744          offsets[i] += offsets[i - 1];
1745    }
1746
1747    /* Total length of source string is sum off all strings plus two.
1748     * One extra byte for terminating zero, another extra byte to silence
1749     * valgrind warnings in the parser/grammer code.
1750     */
1751    totalLength = offsets[count - 1] + 2;
1752    source = malloc(totalLength * sizeof(GLcharARB));
1753    if (source == NULL) {
1754       free((GLvoid *) offsets);
1755       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
1756       return;
1757    }
1758
1759    for (i = 0; i < count; i++) {
1760       GLint start = (i > 0) ? offsets[i - 1] : 0;
1761       memcpy(source + start, string[i],
1762              (offsets[i] - start) * sizeof(GLcharARB));
1763    }
1764    source[totalLength - 1] = '\0';
1765    source[totalLength - 2] = '\0';
1766
1767 #if defined(HAVE_SHA1)
1768    /* Dump original shader source to MESA_SHADER_DUMP_PATH and replace
1769     * if corresponding entry found from MESA_SHADER_READ_PATH.
1770     */
1771    dump_shader(sh->Stage, source);
1772
1773    replacement = read_shader(sh->Stage, source);
1774    if (replacement) {
1775       free(source);
1776       source = replacement;
1777    }
1778 #endif /* HAVE_SHA1 */
1779
1780    shader_source(sh, source);
1781
1782    free(offsets);
1783 }
1784
1785
1786 void GLAPIENTRY
1787 _mesa_UseProgram(GLuint program)
1788 {
1789    GET_CURRENT_CONTEXT(ctx);
1790    struct gl_shader_program *shProg;
1791
1792    if (MESA_VERBOSE & VERBOSE_API)
1793       _mesa_debug(ctx, "glUseProgram %u\n", program);
1794
1795    if (_mesa_is_xfb_active_and_unpaused(ctx)) {
1796       _mesa_error(ctx, GL_INVALID_OPERATION,
1797                   "glUseProgram(transform feedback active)");
1798       return;
1799    }
1800
1801    if (program) {
1802       shProg = _mesa_lookup_shader_program_err(ctx, program, "glUseProgram");
1803       if (!shProg) {
1804          return;
1805       }
1806       if (!shProg->LinkStatus) {
1807          _mesa_error(ctx, GL_INVALID_OPERATION,
1808                      "glUseProgram(program %u not linked)", program);
1809          return;
1810       }
1811
1812       /* debug code */
1813       if (ctx->_Shader->Flags & GLSL_USE_PROG) {
1814          print_shader_info(shProg);
1815       }
1816    }
1817    else {
1818       shProg = NULL;
1819    }
1820
1821    /* The ARB_separate_shader_object spec says:
1822     *
1823     *     "The executable code for an individual shader stage is taken from
1824     *     the current program for that stage.  If there is a current program
1825     *     object established by UseProgram, that program is considered current
1826     *     for all stages.  Otherwise, if there is a bound program pipeline
1827     *     object (section 2.14.PPO), the program bound to the appropriate
1828     *     stage of the pipeline object is considered current."
1829     */
1830    if (program) {
1831       /* Attach shader state to the binding point */
1832       _mesa_reference_pipeline_object(ctx, &ctx->_Shader, &ctx->Shader);
1833       /* Update the program */
1834       _mesa_use_program(ctx, shProg);
1835    } else {
1836       /* Must be done first: detach the progam */
1837       _mesa_use_program(ctx, shProg);
1838       /* Unattach shader_state binding point */
1839       _mesa_reference_pipeline_object(ctx, &ctx->_Shader, ctx->Pipeline.Default);
1840       /* If a pipeline was bound, rebind it */
1841       if (ctx->Pipeline.Current) {
1842          _mesa_BindProgramPipeline(ctx->Pipeline.Current->Name);
1843       }
1844    }
1845 }
1846
1847
1848 void GLAPIENTRY
1849 _mesa_ValidateProgram(GLuint program)
1850 {
1851    GET_CURRENT_CONTEXT(ctx);
1852    validate_program(ctx, program);
1853 }
1854
1855
1856 /**
1857  * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1858  */
1859 void GLAPIENTRY
1860 _mesa_GetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype,
1861                                GLint* range, GLint* precision)
1862 {
1863    const struct gl_program_constants *limits;
1864    const struct gl_precision *p;
1865    GET_CURRENT_CONTEXT(ctx);
1866
1867    switch (shadertype) {
1868    case GL_VERTEX_SHADER:
1869       limits = &ctx->Const.Program[MESA_SHADER_VERTEX];
1870       break;
1871    case GL_FRAGMENT_SHADER:
1872       limits = &ctx->Const.Program[MESA_SHADER_FRAGMENT];
1873       break;
1874    default:
1875       _mesa_error(ctx, GL_INVALID_ENUM,
1876                   "glGetShaderPrecisionFormat(shadertype)");
1877       return;
1878    }
1879
1880    switch (precisiontype) {
1881    case GL_LOW_FLOAT:
1882       p = &limits->LowFloat;
1883       break;
1884    case GL_MEDIUM_FLOAT:
1885       p = &limits->MediumFloat;
1886       break;
1887    case GL_HIGH_FLOAT:
1888       p = &limits->HighFloat;
1889       break;
1890    case GL_LOW_INT:
1891       p = &limits->LowInt;
1892       break;
1893    case GL_MEDIUM_INT:
1894       p = &limits->MediumInt;
1895       break;
1896    case GL_HIGH_INT:
1897       p = &limits->HighInt;
1898       break;
1899    default:
1900       _mesa_error(ctx, GL_INVALID_ENUM,
1901                   "glGetShaderPrecisionFormat(precisiontype)");
1902       return;
1903    }
1904
1905    range[0] = p->RangeMin;
1906    range[1] = p->RangeMax;
1907    precision[0] = p->Precision;
1908 }
1909
1910
1911 /**
1912  * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1913  */
1914 void GLAPIENTRY
1915 _mesa_ReleaseShaderCompiler(void)
1916 {
1917    _mesa_destroy_shader_compiler_caches();
1918 }
1919
1920
1921 /**
1922  * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1923  */
1924 void GLAPIENTRY
1925 _mesa_ShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat,
1926                    const void* binary, GLint length)
1927 {
1928    GET_CURRENT_CONTEXT(ctx);
1929    (void) shaders;
1930    (void) binaryformat;
1931    (void) binary;
1932
1933    /* Page 68, section 7.2 'Shader Binaries" of the of the OpenGL ES 3.1, and
1934     * page 88 of the OpenGL 4.5 specs state:
1935     *
1936     *     "An INVALID_VALUE error is generated if count or length is negative.
1937     *      An INVALID_ENUM error is generated if binaryformat is not a supported
1938     *      format returned in SHADER_BINARY_FORMATS."
1939     */
1940    if (n < 0 || length < 0) {
1941       _mesa_error(ctx, GL_INVALID_VALUE, "glShaderBinary(count or length < 0)");
1942       return;
1943    }
1944
1945    _mesa_error(ctx, GL_INVALID_ENUM, "glShaderBinary(format)");
1946 }
1947
1948
1949 void GLAPIENTRY
1950 _mesa_GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei *length,
1951                        GLenum *binaryFormat, GLvoid *binary)
1952 {
1953    struct gl_shader_program *shProg;
1954    GLsizei length_dummy;
1955    GET_CURRENT_CONTEXT(ctx);
1956
1957    if (bufSize < 0){
1958       _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramBinary(bufSize < 0)");
1959       return;
1960    }
1961
1962    shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetProgramBinary");
1963    if (!shProg)
1964       return;
1965
1966    /* The ARB_get_program_binary spec says:
1967     *
1968     *     "If <length> is NULL, then no length is returned."
1969     *
1970     * Ensure that length always points to valid storage to avoid multiple NULL
1971     * pointer checks below.
1972     */
1973    if (length == NULL)
1974       length = &length_dummy;
1975
1976
1977    /* The ARB_get_program_binary spec says:
1978     *
1979     *     "When a program object's LINK_STATUS is FALSE, its program binary
1980     *     length is zero, and a call to GetProgramBinary will generate an
1981     *     INVALID_OPERATION error.
1982     */
1983    if (!shProg->LinkStatus) {
1984       _mesa_error(ctx, GL_INVALID_OPERATION,
1985                   "glGetProgramBinary(program %u not linked)",
1986                   shProg->Name);
1987       *length = 0;
1988       return;
1989    }
1990
1991    *length = 0;
1992    _mesa_error(ctx, GL_INVALID_OPERATION,
1993                "glGetProgramBinary(driver supports zero binary formats)");
1994
1995    (void) binaryFormat;
1996    (void) binary;
1997 }
1998
1999 void GLAPIENTRY
2000 _mesa_ProgramBinary(GLuint program, GLenum binaryFormat,
2001                     const GLvoid *binary, GLsizei length)
2002 {
2003    struct gl_shader_program *shProg;
2004    GET_CURRENT_CONTEXT(ctx);
2005
2006    shProg = _mesa_lookup_shader_program_err(ctx, program, "glProgramBinary");
2007    if (!shProg)
2008       return;
2009
2010    (void) binaryFormat;
2011    (void) binary;
2012
2013    /* Section 2.3.1 (Errors) of the OpenGL 4.5 spec says:
2014     *
2015     *     "If a negative number is provided where an argument of type sizei or
2016     *     sizeiptr is specified, an INVALID_VALUE error is generated."
2017     */
2018    if (length < 0) {
2019       _mesa_error(ctx, GL_INVALID_VALUE, "glProgramBinary(length < 0)");
2020       return;
2021    }
2022
2023    /* The ARB_get_program_binary spec says:
2024     *
2025     *     "<binaryFormat> and <binary> must be those returned by a previous
2026     *     call to GetProgramBinary, and <length> must be the length of the
2027     *     program binary as returned by GetProgramBinary or GetProgramiv with
2028     *     <pname> PROGRAM_BINARY_LENGTH. Loading the program binary will fail,
2029     *     setting the LINK_STATUS of <program> to FALSE, if these conditions
2030     *     are not met."
2031     *
2032     * Since any value of binaryFormat passed "is not one of those specified as
2033     * allowable for [this] command, an INVALID_ENUM error is generated."
2034     */
2035    shProg->LinkStatus = GL_FALSE;
2036    _mesa_error(ctx, GL_INVALID_ENUM, "glProgramBinary");
2037 }
2038
2039
2040 void GLAPIENTRY
2041 _mesa_ProgramParameteri(GLuint program, GLenum pname, GLint value)
2042 {
2043    struct gl_shader_program *shProg;
2044    GET_CURRENT_CONTEXT(ctx);
2045
2046    shProg = _mesa_lookup_shader_program_err(ctx, program,
2047                                             "glProgramParameteri");
2048    if (!shProg)
2049       return;
2050
2051    switch (pname) {
2052    case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
2053       /* This enum isn't part of the OES extension for OpenGL ES 2.0, but it
2054        * is part of OpenGL ES 3.0.  For the ES2 case, this function shouldn't
2055        * even be in the dispatch table, so we shouldn't need to expclicitly
2056        * check here.
2057        *
2058        * On desktop, we ignore the 3.0+ requirement because it is silly.
2059        */
2060
2061       /* The ARB_get_program_binary extension spec says:
2062        *
2063        *     "An INVALID_VALUE error is generated if the <value> argument to
2064        *     ProgramParameteri is not TRUE or FALSE."
2065        */
2066       if (value != GL_TRUE && value != GL_FALSE) {
2067          goto invalid_value;
2068       }
2069
2070       /* No need to notify the driver.  Any changes will actually take effect
2071        * the next time the shader is linked.
2072        *
2073        * The ARB_get_program_binary extension spec says:
2074        *
2075        *     "To indicate that a program binary is likely to be retrieved,
2076        *     ProgramParameteri should be called with <pname>
2077        *     PROGRAM_BINARY_RETRIEVABLE_HINT and <value> TRUE. This setting
2078        *     will not be in effect until the next time LinkProgram or
2079        *     ProgramBinary has been called successfully."
2080        *
2081        * The resloution of issue 9 in the extension spec also says:
2082        *
2083        *     "The application may use the PROGRAM_BINARY_RETRIEVABLE_HINT hint
2084        *     to indicate to the GL implementation that this program will
2085        *     likely be saved with GetProgramBinary at some point. This will
2086        *     give the GL implementation the opportunity to track any state
2087        *     changes made to the program before being saved such that when it
2088        *     is loaded again a recompile can be avoided."
2089        */
2090       shProg->BinaryRetreivableHint = value;
2091       return;
2092
2093    case GL_PROGRAM_SEPARABLE:
2094       /* Spec imply that the behavior is the same as ARB_get_program_binary
2095        * Chapter 7.3 Program Objects
2096        */
2097       if (value != GL_TRUE && value != GL_FALSE) {
2098          goto invalid_value;
2099       }
2100       shProg->SeparateShader = value;
2101       return;
2102
2103    default:
2104       _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameteri(pname=%s)",
2105                   _mesa_enum_to_string(pname));
2106       return;
2107    }
2108
2109 invalid_value:
2110    _mesa_error(ctx, GL_INVALID_VALUE,
2111                "glProgramParameteri(pname=%s, value=%d): "
2112                "value must be 0 or 1.",
2113                _mesa_enum_to_string(pname),
2114                value);
2115 }
2116
2117
2118 void
2119 _mesa_use_shader_program(struct gl_context *ctx, GLenum type,
2120                          struct gl_shader_program *shProg,
2121                          struct gl_pipeline_object *shTarget)
2122 {
2123    gl_shader_stage stage = _mesa_shader_enum_to_shader_stage(type);
2124    use_shader_program(ctx, stage, shProg, shTarget);
2125
2126    if (ctx->Driver.UseProgram)
2127       ctx->Driver.UseProgram(ctx, shProg);
2128 }
2129
2130
2131 /**
2132  * Copy program-specific data generated by linking from the gl_shader_program
2133  * object to a specific gl_program object.
2134  */
2135 void
2136 _mesa_copy_linked_program_data(gl_shader_stage type,
2137                                const struct gl_shader_program *src,
2138                                struct gl_program *dst)
2139 {
2140    switch (type) {
2141    case MESA_SHADER_VERTEX:
2142       dst->ClipDistanceArraySize = src->Vert.ClipDistanceArraySize;
2143       dst->CullDistanceArraySize = src->Vert.CullDistanceArraySize;
2144       break;
2145    case MESA_SHADER_TESS_CTRL: {
2146       struct gl_tess_ctrl_program *dst_tcp =
2147          (struct gl_tess_ctrl_program *) dst;
2148       dst_tcp->VerticesOut = src->TessCtrl.VerticesOut;
2149       break;
2150    }
2151    case MESA_SHADER_TESS_EVAL: {
2152       struct gl_tess_eval_program *dst_tep =
2153          (struct gl_tess_eval_program *) dst;
2154       dst_tep->PrimitiveMode = src->TessEval.PrimitiveMode;
2155       dst_tep->Spacing = src->TessEval.Spacing;
2156       dst_tep->VertexOrder = src->TessEval.VertexOrder;
2157       dst_tep->PointMode = src->TessEval.PointMode;
2158       dst->ClipDistanceArraySize = src->TessEval.ClipDistanceArraySize;
2159       dst->CullDistanceArraySize = src->TessEval.CullDistanceArraySize;
2160       break;
2161    }
2162    case MESA_SHADER_GEOMETRY: {
2163       struct gl_geometry_program *dst_gp = (struct gl_geometry_program *) dst;
2164       dst_gp->VerticesIn = src->Geom.VerticesIn;
2165       dst_gp->VerticesOut = src->Geom.VerticesOut;
2166       dst_gp->Invocations = src->Geom.Invocations;
2167       dst_gp->InputType = src->Geom.InputType;
2168       dst_gp->OutputType = src->Geom.OutputType;
2169       dst->ClipDistanceArraySize = src->Geom.ClipDistanceArraySize;
2170       dst->CullDistanceArraySize = src->Geom.CullDistanceArraySize;
2171       dst_gp->UsesEndPrimitive = src->Geom.UsesEndPrimitive;
2172       dst_gp->UsesStreams = src->Geom.UsesStreams;
2173       break;
2174    }
2175    case MESA_SHADER_FRAGMENT: {
2176       struct gl_fragment_program *dst_fp = (struct gl_fragment_program *) dst;
2177       dst_fp->FragDepthLayout = src->FragDepthLayout;
2178       break;
2179    }
2180    case MESA_SHADER_COMPUTE: {
2181       struct gl_compute_program *dst_cp = (struct gl_compute_program *) dst;
2182       int i;
2183       for (i = 0; i < 3; i++)
2184          dst_cp->LocalSize[i] = src->Comp.LocalSize[i];
2185       dst_cp->SharedSize = src->Comp.SharedSize;
2186       break;
2187    }
2188    default:
2189       break;
2190    }
2191 }
2192
2193 /**
2194  * ARB_separate_shader_objects: Compile & Link Program
2195  */
2196 GLuint GLAPIENTRY
2197 _mesa_CreateShaderProgramv(GLenum type, GLsizei count,
2198                            const GLchar* const *strings)
2199 {
2200    GET_CURRENT_CONTEXT(ctx);
2201
2202    const GLuint shader = create_shader(ctx, type);
2203    GLuint program = 0;
2204
2205    /*
2206     * According to OpenGL 4.5 and OpenGL ES 3.1 standards, section 7.3:
2207     * GL_INVALID_VALUE should be generated if count < 0
2208     */
2209    if (count < 0) {
2210       _mesa_error(ctx, GL_INVALID_VALUE, "glCreateShaderProgram (count < 0)");
2211       return program;
2212    }
2213
2214    if (shader) {
2215       struct gl_shader *sh = _mesa_lookup_shader(ctx, shader);
2216
2217       _mesa_ShaderSource(shader, count, strings, NULL);
2218       _mesa_compile_shader(ctx, sh);
2219
2220       program = create_shader_program(ctx);
2221       if (program) {
2222          struct gl_shader_program *shProg;
2223          GLint compiled = GL_FALSE;
2224
2225          shProg = _mesa_lookup_shader_program(ctx, program);
2226
2227          shProg->SeparateShader = GL_TRUE;
2228
2229          get_shaderiv(ctx, shader, GL_COMPILE_STATUS, &compiled);
2230          if (compiled) {
2231             attach_shader(ctx, program, shader);
2232             _mesa_link_program(ctx, shProg);
2233             detach_shader(ctx, program, shader);
2234
2235 #if 0
2236             /* Possibly... */
2237             if (active-user-defined-varyings-in-linked-program) {
2238                append-error-to-info-log;
2239                shProg->LinkStatus = GL_FALSE;
2240             }
2241 #endif
2242          }
2243          if (sh->InfoLog)
2244             ralloc_strcat(&shProg->InfoLog, sh->InfoLog);
2245       }
2246
2247       delete_shader(ctx, shader);
2248    }
2249
2250    return program;
2251 }
2252
2253
2254 /**
2255  * For GL_ARB_tessellation_shader
2256  */
2257 extern void GLAPIENTRY
2258 _mesa_PatchParameteri(GLenum pname, GLint value)
2259 {
2260    GET_CURRENT_CONTEXT(ctx);
2261
2262    if (!_mesa_has_tessellation(ctx)) {
2263       _mesa_error(ctx, GL_INVALID_OPERATION, "glPatchParameteri");
2264       return;
2265    }
2266
2267    if (pname != GL_PATCH_VERTICES) {
2268       _mesa_error(ctx, GL_INVALID_ENUM, "glPatchParameteri");
2269       return;
2270    }
2271
2272    if (value <= 0 || value > ctx->Const.MaxPatchVertices) {
2273       _mesa_error(ctx, GL_INVALID_VALUE, "glPatchParameteri");
2274       return;
2275    }
2276
2277    ctx->TessCtrlProgram.patch_vertices = value;
2278 }
2279
2280
2281 extern void GLAPIENTRY
2282 _mesa_PatchParameterfv(GLenum pname, const GLfloat *values)
2283 {
2284    GET_CURRENT_CONTEXT(ctx);
2285
2286    if (!_mesa_has_tessellation(ctx)) {
2287       _mesa_error(ctx, GL_INVALID_OPERATION, "glPatchParameterfv");
2288       return;
2289    }
2290
2291    switch(pname) {
2292    case GL_PATCH_DEFAULT_OUTER_LEVEL:
2293       FLUSH_VERTICES(ctx, 0);
2294       memcpy(ctx->TessCtrlProgram.patch_default_outer_level, values,
2295              4 * sizeof(GLfloat));
2296       ctx->NewDriverState |= ctx->DriverFlags.NewDefaultTessLevels;
2297       return;
2298    case GL_PATCH_DEFAULT_INNER_LEVEL:
2299       FLUSH_VERTICES(ctx, 0);
2300       memcpy(ctx->TessCtrlProgram.patch_default_inner_level, values,
2301              2 * sizeof(GLfloat));
2302       ctx->NewDriverState |= ctx->DriverFlags.NewDefaultTessLevels;
2303       return;
2304    default:
2305       _mesa_error(ctx, GL_INVALID_ENUM, "glPatchParameterfv");
2306       return;
2307    }
2308 }
2309
2310 /**
2311  * ARB_shader_subroutine
2312  */
2313 GLint GLAPIENTRY
2314 _mesa_GetSubroutineUniformLocation(GLuint program, GLenum shadertype,
2315                                    const GLchar *name)
2316 {
2317    GET_CURRENT_CONTEXT(ctx);
2318    const char *api_name = "glGetSubroutineUniformLocation";
2319    struct gl_shader_program *shProg;
2320    GLenum resource_type;
2321    gl_shader_stage stage;
2322
2323    if (!_mesa_has_shader_subroutine(ctx)) {
2324       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2325       return -1;
2326    }
2327
2328    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2329       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2330       return -1;
2331    }
2332
2333    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2334    if (!shProg)
2335       return -1;
2336
2337    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2338    if (!shProg->_LinkedShaders[stage]) {
2339       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2340       return -1;
2341    }
2342
2343    resource_type = _mesa_shader_stage_to_subroutine_uniform(stage);
2344    return _mesa_program_resource_location(shProg, resource_type, name);
2345 }
2346
2347 GLuint GLAPIENTRY
2348 _mesa_GetSubroutineIndex(GLuint program, GLenum shadertype,
2349                          const GLchar *name)
2350 {
2351    GET_CURRENT_CONTEXT(ctx);
2352    const char *api_name = "glGetSubroutineIndex";
2353    struct gl_shader_program *shProg;
2354    struct gl_program_resource *res;
2355    GLenum resource_type;
2356    gl_shader_stage stage;
2357
2358    if (!_mesa_has_shader_subroutine(ctx)) {
2359       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2360       return -1;
2361    }
2362
2363    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2364       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2365       return -1;
2366    }
2367
2368    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2369    if (!shProg)
2370       return -1;
2371
2372    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2373    if (!shProg->_LinkedShaders[stage]) {
2374       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2375       return -1;
2376    }
2377
2378    resource_type = _mesa_shader_stage_to_subroutine(stage);
2379    res = _mesa_program_resource_find_name(shProg, resource_type, name, NULL);
2380    if (!res) {
2381      return -1;
2382    }
2383
2384    return _mesa_program_resource_index(shProg, res);
2385 }
2386
2387
2388 GLvoid GLAPIENTRY
2389 _mesa_GetActiveSubroutineUniformiv(GLuint program, GLenum shadertype,
2390                                    GLuint index, GLenum pname, GLint *values)
2391 {
2392    GET_CURRENT_CONTEXT(ctx);
2393    const char *api_name = "glGetActiveSubroutineUniformiv";
2394    struct gl_shader_program *shProg;
2395    struct gl_shader *sh;
2396    gl_shader_stage stage;
2397    struct gl_program_resource *res;
2398    const struct gl_uniform_storage *uni;
2399    GLenum resource_type;
2400    int count, i, j;
2401
2402    if (!_mesa_has_shader_subroutine(ctx)) {
2403       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2404       return;
2405    }
2406
2407    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2408       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2409       return;
2410    }
2411
2412    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2413    if (!shProg)
2414       return;
2415
2416    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2417    resource_type = _mesa_shader_stage_to_subroutine_uniform(stage);
2418
2419    sh = shProg->_LinkedShaders[stage];
2420    if (!sh) {
2421       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2422       return;
2423    }
2424
2425    if (index >= sh->NumSubroutineUniforms) {
2426       _mesa_error(ctx, GL_INVALID_VALUE, "%s: invalid index greater than GL_ACTIVE_SUBROUTINE_UNIFORMS", api_name);
2427       return;
2428    }
2429
2430    switch (pname) {
2431    case GL_NUM_COMPATIBLE_SUBROUTINES: {
2432       res = _mesa_program_resource_find_index(shProg, resource_type, index);
2433       if (res) {
2434          uni = res->Data;
2435          values[0] = uni->num_compatible_subroutines;
2436       }
2437       break;
2438    }
2439    case GL_COMPATIBLE_SUBROUTINES: {
2440       res = _mesa_program_resource_find_index(shProg, resource_type, index);
2441       if (res) {
2442          uni = res->Data;
2443          count = 0;
2444          for (i = 0; i < sh->NumSubroutineFunctions; i++) {
2445             struct gl_subroutine_function *fn = &sh->SubroutineFunctions[i];
2446             for (j = 0; j < fn->num_compat_types; j++) {
2447                if (fn->types[j] == uni->type) {
2448                   values[count++] = i;
2449                   break;
2450                }
2451             }
2452          }
2453       }
2454       break;
2455    }
2456    case GL_UNIFORM_SIZE:
2457       res = _mesa_program_resource_find_index(shProg, resource_type, index);
2458       if (res) {
2459          uni = res->Data;
2460          values[0] = uni->array_elements ? uni->array_elements : 1;
2461       }
2462       break;
2463    case GL_UNIFORM_NAME_LENGTH:
2464       res = _mesa_program_resource_find_index(shProg, resource_type, index);
2465       if (res) {
2466          values[0] = strlen(_mesa_program_resource_name(res)) + 1
2467             + ((_mesa_program_resource_array_size(res) != 0) ? 3 : 0);
2468       }
2469       break;
2470    default:
2471       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2472       return;
2473    }
2474 }
2475
2476
2477 GLvoid GLAPIENTRY
2478 _mesa_GetActiveSubroutineUniformName(GLuint program, GLenum shadertype,
2479                                      GLuint index, GLsizei bufsize,
2480                                      GLsizei *length, GLchar *name)
2481 {
2482    GET_CURRENT_CONTEXT(ctx);
2483    const char *api_name = "glGetActiveSubroutineUniformName";
2484    struct gl_shader_program *shProg;
2485    GLenum resource_type;
2486    gl_shader_stage stage;
2487
2488    if (!_mesa_has_shader_subroutine(ctx)) {
2489       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2490       return;
2491    }
2492
2493    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2494       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2495       return;
2496    }
2497
2498    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2499    if (!shProg)
2500       return;
2501
2502    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2503    if (!shProg->_LinkedShaders[stage]) {
2504       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2505       return;
2506    }
2507
2508    resource_type = _mesa_shader_stage_to_subroutine_uniform(stage);
2509    /* get program resource name */
2510    _mesa_get_program_resource_name(shProg, resource_type,
2511                                    index, bufsize,
2512                                    length, name, api_name);
2513 }
2514
2515
2516 GLvoid GLAPIENTRY
2517 _mesa_GetActiveSubroutineName(GLuint program, GLenum shadertype,
2518                               GLuint index, GLsizei bufsize,
2519                               GLsizei *length, GLchar *name)
2520 {
2521    GET_CURRENT_CONTEXT(ctx);
2522    const char *api_name = "glGetActiveSubroutineName";
2523    struct gl_shader_program *shProg;
2524    GLenum resource_type;
2525    gl_shader_stage stage;
2526
2527    if (!_mesa_has_shader_subroutine(ctx)) {
2528       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2529       return;
2530    }
2531
2532    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2533       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2534       return;
2535    }
2536
2537    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2538    if (!shProg)
2539       return;
2540
2541    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2542    if (!shProg->_LinkedShaders[stage]) {
2543       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2544       return;
2545    }
2546    resource_type = _mesa_shader_stage_to_subroutine(stage);
2547    _mesa_get_program_resource_name(shProg, resource_type,
2548                                    index, bufsize,
2549                                    length, name, api_name);
2550 }
2551
2552
2553 GLvoid GLAPIENTRY
2554 _mesa_UniformSubroutinesuiv(GLenum shadertype, GLsizei count,
2555                             const GLuint *indices)
2556 {
2557    GET_CURRENT_CONTEXT(ctx);
2558    const char *api_name = "glUniformSubroutinesuiv";
2559    struct gl_shader_program *shProg;
2560    struct gl_shader *sh;
2561    gl_shader_stage stage;
2562    int i;
2563
2564    if (!_mesa_has_shader_subroutine(ctx)) {
2565       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2566       return;
2567    }
2568
2569    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2570       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2571       return;
2572    }
2573
2574    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2575    shProg = ctx->_Shader->CurrentProgram[stage];
2576    if (!shProg) {
2577       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2578       return;
2579    }
2580
2581    sh = shProg->_LinkedShaders[stage];
2582    if (!sh) {
2583       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2584       return;
2585    }
2586
2587    if (count != sh->NumSubroutineUniformRemapTable) {
2588       _mesa_error(ctx, GL_INVALID_VALUE, "%s", api_name);
2589       return;
2590    }
2591
2592    i = 0;
2593    do {
2594       struct gl_uniform_storage *uni = sh->SubroutineUniformRemapTable[i];
2595       if (uni == NULL) {
2596          i++;
2597          continue;
2598       }
2599
2600       int uni_count = uni->array_elements ? uni->array_elements : 1;
2601       int j, k, f;
2602
2603       for (j = i; j < i + uni_count; j++) {
2604          struct gl_subroutine_function *subfn = NULL;
2605          if (indices[j] > sh->MaxSubroutineFunctionIndex) {
2606             _mesa_error(ctx, GL_INVALID_VALUE, "%s", api_name);
2607             return;
2608          }
2609
2610          for (f = 0; f < sh->NumSubroutineFunctions; f++) {
2611             if (sh->SubroutineFunctions[f].index == indices[j])
2612                subfn = &sh->SubroutineFunctions[f];
2613          }
2614
2615          if (!subfn) {
2616             continue;
2617          }
2618
2619          for (k = 0; k < subfn->num_compat_types; k++) {
2620             if (subfn->types[k] == uni->type)
2621                break;
2622          }
2623          if (k == subfn->num_compat_types) {
2624             _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2625             return;
2626          }
2627       }
2628       i += uni_count;
2629    } while(i < count);
2630
2631    FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
2632    i = 0;
2633    do {
2634       struct gl_uniform_storage *uni = sh->SubroutineUniformRemapTable[i];
2635       if (uni == NULL) {
2636          i++;
2637          continue;
2638       }
2639
2640       int uni_count = uni->array_elements ? uni->array_elements : 1;
2641
2642       memcpy(&uni->storage[0], &indices[i],
2643              sizeof(GLuint) * uni_count);
2644
2645       _mesa_propagate_uniforms_to_driver_storage(uni, 0, uni_count);
2646       i += uni_count;
2647    } while(i < count);
2648 }
2649
2650
2651 GLvoid GLAPIENTRY
2652 _mesa_GetUniformSubroutineuiv(GLenum shadertype, GLint location,
2653                               GLuint *params)
2654 {
2655    GET_CURRENT_CONTEXT(ctx);
2656    const char *api_name = "glGetUniformSubroutineuiv";
2657    struct gl_shader_program *shProg;
2658    struct gl_shader *sh;
2659    gl_shader_stage stage;
2660
2661    if (!_mesa_has_shader_subroutine(ctx)) {
2662       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2663       return;
2664    }
2665
2666    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2667       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2668       return;
2669    }
2670
2671    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2672    shProg = ctx->_Shader->CurrentProgram[stage];
2673    if (!shProg) {
2674       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2675       return;
2676    }
2677
2678    sh = shProg->_LinkedShaders[stage];
2679    if (!sh) {
2680       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2681       return;
2682    }
2683
2684    if (location >= sh->NumSubroutineUniformRemapTable) {
2685       _mesa_error(ctx, GL_INVALID_VALUE, "%s", api_name);
2686       return;
2687    }
2688
2689    {
2690       struct gl_uniform_storage *uni = sh->SubroutineUniformRemapTable[location];
2691       int offset = location - uni->opaque[stage].index;
2692       memcpy(params, &uni->storage[offset],
2693              sizeof(GLuint));
2694    }
2695 }
2696
2697
2698 GLvoid GLAPIENTRY
2699 _mesa_GetProgramStageiv(GLuint program, GLenum shadertype,
2700                         GLenum pname, GLint *values)
2701 {
2702    GET_CURRENT_CONTEXT(ctx);
2703    const char *api_name = "glGetProgramStageiv";
2704    struct gl_shader_program *shProg;
2705    struct gl_shader *sh;
2706    gl_shader_stage stage;
2707
2708    if (!_mesa_has_shader_subroutine(ctx)) {
2709       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2710       return;
2711    }
2712
2713    if (!_mesa_validate_shader_target(ctx, shadertype)) {
2714       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2715       return;
2716    }
2717
2718    shProg = _mesa_lookup_shader_program_err(ctx, program, api_name);
2719    if (!shProg)
2720       return;
2721
2722    stage = _mesa_shader_enum_to_shader_stage(shadertype);
2723    sh = shProg->_LinkedShaders[stage];
2724    if (!sh) {
2725       _mesa_error(ctx, GL_INVALID_OPERATION, "%s", api_name);
2726       return;
2727    }
2728
2729    switch (pname) {
2730    case GL_ACTIVE_SUBROUTINES:
2731       values[0] = sh->NumSubroutineFunctions;
2732       break;
2733    case GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS:
2734       values[0] = sh->NumSubroutineUniformRemapTable;
2735       break;
2736    case GL_ACTIVE_SUBROUTINE_UNIFORMS:
2737       values[0] = sh->NumSubroutineUniforms;
2738       break;
2739    case GL_ACTIVE_SUBROUTINE_MAX_LENGTH:
2740    {
2741       unsigned i;
2742       GLint max_len = 0;
2743       GLenum resource_type;
2744       struct gl_program_resource *res;
2745
2746       resource_type = _mesa_shader_stage_to_subroutine(stage);
2747       for (i = 0; i < sh->NumSubroutineFunctions; i++) {
2748          res = _mesa_program_resource_find_index(shProg, resource_type, i);
2749          if (res) {
2750             const GLint len = strlen(_mesa_program_resource_name(res)) + 1;
2751             if (len > max_len)
2752                max_len = len;
2753          }
2754       }
2755       values[0] = max_len;
2756       break;
2757    }
2758    case GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH:
2759    {
2760       unsigned i;
2761       GLint max_len = 0;
2762       GLenum resource_type;
2763       struct gl_program_resource *res;
2764
2765       resource_type = _mesa_shader_stage_to_subroutine_uniform(stage);
2766       for (i = 0; i < sh->NumSubroutineUniformRemapTable; i++) {
2767          res = _mesa_program_resource_find_index(shProg, resource_type, i);
2768          if (res) {
2769             const GLint len = strlen(_mesa_program_resource_name(res)) + 1
2770                + ((_mesa_program_resource_array_size(res) != 0) ? 3 : 0);
2771
2772             if (len > max_len)
2773                max_len = len;
2774          }
2775       }
2776       values[0] = max_len;
2777       break;
2778    }
2779    default:
2780       _mesa_error(ctx, GL_INVALID_ENUM, "%s", api_name);
2781       values[0] = -1;
2782       break;
2783    }
2784 }
2785
2786 static int
2787 find_compat_subroutine(struct gl_shader *sh, const struct glsl_type *type)
2788 {
2789    int i, j;
2790
2791    for (i = 0; i < sh->NumSubroutineFunctions; i++) {
2792       struct gl_subroutine_function *fn = &sh->SubroutineFunctions[i];
2793       for (j = 0; j < fn->num_compat_types; j++) {
2794          if (fn->types[j] == type)
2795             return i;
2796       }
2797    }
2798    return 0;
2799 }
2800
2801 static void
2802 _mesa_shader_init_subroutine_defaults(struct gl_shader *sh)
2803 {
2804    int i, j;
2805
2806    for (i = 0; i < sh->NumSubroutineUniformRemapTable; i++) {
2807       struct gl_uniform_storage *uni = sh->SubroutineUniformRemapTable[i];
2808       int uni_count;
2809       int val;
2810
2811       if (!uni)
2812          continue;
2813       uni_count = uni->array_elements ? uni->array_elements : 1;
2814       val = find_compat_subroutine(sh, uni->type);
2815
2816       for (j = 0; j < uni_count; j++)
2817          memcpy(&uni->storage[j], &val, sizeof(int));
2818
2819       _mesa_propagate_uniforms_to_driver_storage(uni, 0, uni_count);
2820    }
2821 }
2822
2823 void
2824 _mesa_shader_program_init_subroutine_defaults(struct gl_shader_program *shProg)
2825 {
2826    int i;
2827
2828    if (!shProg)
2829       return;
2830
2831    for (i = 0; i < MESA_SHADER_STAGES; i++) {
2832       if (!shProg->_LinkedShaders[i])
2833          continue;
2834
2835       _mesa_shader_init_subroutine_defaults(shProg->_LinkedShaders[i]);
2836    }
2837 }