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