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