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