OSDN Git Service

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