mesa: Returns a GL_INVALID_VALUE error on several APIs when buffer size is negative
[mesa.git] / src / mesa / main / shaderapi.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2004-2008 Brian Paul All Rights Reserved.
5 * Copyright (C) 2009-2010 VMware, Inc. All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
21 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 * OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26 /**
27 * \file shaderapi.c
28 * \author Brian Paul
29 *
30 * Implementation of GLSL-related API functions.
31 * The glUniform* functions are in uniforms.c
32 *
33 *
34 * XXX things to do:
35 * 1. Check that the right error code is generated for all _mesa_error() calls.
36 * 2. Insert FLUSH_VERTICES calls in various places
37 */
38
39
40 #include "main/glheader.h"
41 #include "main/context.h"
42 #include "main/dispatch.h"
43 #include "main/enums.h"
44 #include "main/hash.h"
45 #include "main/mtypes.h"
46 #include "main/pipelineobj.h"
47 #include "main/shaderapi.h"
48 #include "main/shaderobj.h"
49 #include "main/transformfeedback.h"
50 #include "main/uniforms.h"
51 #include "program/program.h"
52 #include "program/prog_print.h"
53 #include "program/prog_parameter.h"
54 #include "util/ralloc.h"
55 #include "util/hash_table.h"
56 #include <stdbool.h>
57 #include "../glsl/glsl_parser_extras.h"
58 #include "../glsl/ir.h"
59 #include "../glsl/ir_uniform.h"
60 #include "../glsl/program.h"
61
62 /** Define this to enable shader substitution (see below) */
63 #define SHADER_SUBST 0
64
65
66 /**
67 * Return mask of GLSL_x flags by examining the MESA_GLSL env var.
68 */
69 GLbitfield
70 _mesa_get_shader_flags(void)
71 {
72 GLbitfield flags = 0x0;
73 const char *env = getenv("MESA_GLSL");
74
75 if (env) {
76 if (strstr(env, "dump_on_error"))
77 flags |= GLSL_DUMP_ON_ERROR;
78 else if (strstr(env, "dump"))
79 flags |= GLSL_DUMP;
80 if (strstr(env, "log"))
81 flags |= GLSL_LOG;
82 if (strstr(env, "nopvert"))
83 flags |= GLSL_NOP_VERT;
84 if (strstr(env, "nopfrag"))
85 flags |= GLSL_NOP_FRAG;
86 if (strstr(env, "nopt"))
87 flags |= GLSL_NO_OPT;
88 else if (strstr(env, "opt"))
89 flags |= GLSL_OPT;
90 if (strstr(env, "uniform"))
91 flags |= GLSL_UNIFORMS;
92 if (strstr(env, "useprog"))
93 flags |= GLSL_USE_PROG;
94 if (strstr(env, "errors"))
95 flags |= GLSL_REPORT_ERRORS;
96 }
97
98 return flags;
99 }
100
101
102 /**
103 * Initialize context's shader state.
104 */
105 void
106 _mesa_init_shader_state(struct gl_context *ctx)
107 {
108 /* Device drivers may override these to control what kind of instructions
109 * are generated by the GLSL compiler.
110 */
111 struct gl_shader_compiler_options options;
112 gl_shader_stage sh;
113
114 memset(&options, 0, sizeof(options));
115 options.MaxUnrollIterations = 32;
116 options.MaxIfDepth = UINT_MAX;
117
118 /* Default pragma settings */
119 options.DefaultPragmas.Optimize = GL_TRUE;
120
121 for (sh = 0; sh < MESA_SHADER_STAGES; ++sh)
122 memcpy(&ctx->Const.ShaderCompilerOptions[sh], &options, sizeof(options));
123
124 ctx->Shader.Flags = _mesa_get_shader_flags();
125
126 if (ctx->Shader.Flags != 0)
127 ctx->Const.GenerateTemporaryNames = true;
128
129 /* Extended for ARB_separate_shader_objects */
130 ctx->Shader.RefCount = 1;
131 mtx_init(&ctx->Shader.Mutex, mtx_plain);
132 }
133
134
135 /**
136 * Free the per-context shader-related state.
137 */
138 void
139 _mesa_free_shader_state(struct gl_context *ctx)
140 {
141 int i;
142 for (i = 0; i < MESA_SHADER_STAGES; i++) {
143 _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentProgram[i],
144 NULL);
145 }
146 _mesa_reference_shader_program(ctx, &ctx->Shader._CurrentFragmentProgram,
147 NULL);
148 _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, NULL);
149
150 /* Extended for ARB_separate_shader_objects */
151 _mesa_reference_pipeline_object(ctx, &ctx->_Shader, NULL);
152
153 assert(ctx->Shader.RefCount == 1);
154 mtx_destroy(&ctx->Shader.Mutex);
155 }
156
157
158 /**
159 * Copy string from <src> to <dst>, up to maxLength characters, returning
160 * length of <dst> in <length>.
161 * \param src the strings source
162 * \param maxLength max chars to copy
163 * \param length returns number of chars copied
164 * \param dst the string destination
165 */
166 void
167 _mesa_copy_string(GLchar *dst, GLsizei maxLength,
168 GLsizei *length, const GLchar *src)
169 {
170 GLsizei len;
171 for (len = 0; len < maxLength - 1 && src && src[len]; len++)
172 dst[len] = src[len];
173 if (maxLength > 0)
174 dst[len] = 0;
175 if (length)
176 *length = len;
177 }
178
179
180
181 /**
182 * Confirm that the a shader type is valid and supported by the implementation
183 *
184 * \param ctx Current GL context
185 * \param type Shader target
186 *
187 */
188 bool
189 _mesa_validate_shader_target(const struct gl_context *ctx, GLenum type)
190 {
191 /* Note: when building built-in GLSL functions, this function may be
192 * invoked with ctx == NULL. In that case, we can only validate that it's
193 * a shader target we recognize, not that it's supported in the current
194 * context. But that's fine--we don't need any further validation than
195 * that when building built-in GLSL functions.
196 */
197
198 switch (type) {
199 case GL_FRAGMENT_SHADER:
200 return ctx == NULL || ctx->Extensions.ARB_fragment_shader;
201 case GL_VERTEX_SHADER:
202 return ctx == NULL || ctx->Extensions.ARB_vertex_shader;
203 case GL_GEOMETRY_SHADER_ARB:
204 return ctx == NULL || _mesa_has_geometry_shaders(ctx);
205 case GL_COMPUTE_SHADER:
206 return ctx == NULL || ctx->Extensions.ARB_compute_shader;
207 default:
208 return false;
209 }
210 }
211
212
213 static GLboolean
214 is_program(struct gl_context *ctx, GLuint name)
215 {
216 struct gl_shader_program *shProg = _mesa_lookup_shader_program(ctx, name);
217 return shProg ? GL_TRUE : GL_FALSE;
218 }
219
220
221 static GLboolean
222 is_shader(struct gl_context *ctx, GLuint name)
223 {
224 struct gl_shader *shader = _mesa_lookup_shader(ctx, name);
225 return shader ? GL_TRUE : GL_FALSE;
226 }
227
228
229 /**
230 * Attach shader to a shader program.
231 */
232 static void
233 attach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
234 {
235 struct gl_shader_program *shProg;
236 struct gl_shader *sh;
237 GLuint i, n;
238
239 const bool same_type_disallowed = _mesa_is_gles(ctx);
240
241 shProg = _mesa_lookup_shader_program_err(ctx, program, "glAttachShader");
242 if (!shProg)
243 return;
244
245 sh = _mesa_lookup_shader_err(ctx, shader, "glAttachShader");
246 if (!sh) {
247 return;
248 }
249
250 n = shProg->NumShaders;
251 for (i = 0; i < n; i++) {
252 if (shProg->Shaders[i] == sh) {
253 /* The shader is already attched to this program. The
254 * GL_ARB_shader_objects spec says:
255 *
256 * "The error INVALID_OPERATION is generated by AttachObjectARB
257 * if <obj> is already attached to <containerObj>."
258 */
259 _mesa_error(ctx, GL_INVALID_OPERATION, "glAttachShader");
260 return;
261 } else if (same_type_disallowed &&
262 shProg->Shaders[i]->Type == sh->Type) {
263 /* Shader with the same type is already attached to this program,
264 * OpenGL ES 2.0 and 3.0 specs say:
265 *
266 * "Multiple shader objects of the same type may not be attached
267 * to a single program object. [...] The error INVALID_OPERATION
268 * is generated if [...] another shader object of the same type
269 * as shader is already attached to program."
270 */
271 _mesa_error(ctx, GL_INVALID_OPERATION, "glAttachShader");
272 return;
273 }
274 }
275
276 /* grow list */
277 shProg->Shaders = realloc(shProg->Shaders,
278 (n + 1) * sizeof(struct gl_shader *));
279 if (!shProg->Shaders) {
280 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAttachShader");
281 return;
282 }
283
284 /* append */
285 shProg->Shaders[n] = NULL; /* since realloc() didn't zero the new space */
286 _mesa_reference_shader(ctx, &shProg->Shaders[n], sh);
287 shProg->NumShaders++;
288 }
289
290
291 static GLuint
292 create_shader(struct gl_context *ctx, GLenum type)
293 {
294 struct gl_shader *sh;
295 GLuint name;
296
297 if (!_mesa_validate_shader_target(ctx, type)) {
298 _mesa_error(ctx, GL_INVALID_ENUM, "CreateShader(type)");
299 return 0;
300 }
301
302 name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
303 sh = ctx->Driver.NewShader(ctx, name, type);
304 _mesa_HashInsert(ctx->Shared->ShaderObjects, name, sh);
305
306 return name;
307 }
308
309
310 static GLuint
311 create_shader_program(struct gl_context *ctx)
312 {
313 GLuint name;
314 struct gl_shader_program *shProg;
315
316 name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
317
318 shProg = ctx->Driver.NewShaderProgram(name);
319
320 _mesa_HashInsert(ctx->Shared->ShaderObjects, name, shProg);
321
322 assert(shProg->RefCount == 1);
323
324 return name;
325 }
326
327
328 /**
329 * Delete a shader program. Actually, just decrement the program's
330 * reference count and mark it as DeletePending.
331 * Used to implement glDeleteProgram() and glDeleteObjectARB().
332 */
333 static void
334 delete_shader_program(struct gl_context *ctx, GLuint name)
335 {
336 /*
337 * NOTE: deleting shaders/programs works a bit differently than
338 * texture objects (and buffer objects, etc). Shader/program
339 * handles/IDs exist in the hash table until the object is really
340 * deleted (refcount==0). With texture objects, the handle/ID is
341 * removed from the hash table in glDeleteTextures() while the tex
342 * object itself might linger until its refcount goes to zero.
343 */
344 struct gl_shader_program *shProg;
345
346 shProg = _mesa_lookup_shader_program_err(ctx, name, "glDeleteProgram");
347 if (!shProg)
348 return;
349
350 if (!shProg->DeletePending) {
351 shProg->DeletePending = GL_TRUE;
352
353 /* effectively, decr shProg's refcount */
354 _mesa_reference_shader_program(ctx, &shProg, NULL);
355 }
356 }
357
358
359 static void
360 delete_shader(struct gl_context *ctx, GLuint shader)
361 {
362 struct gl_shader *sh;
363
364 sh = _mesa_lookup_shader_err(ctx, shader, "glDeleteShader");
365 if (!sh)
366 return;
367
368 if (!sh->DeletePending) {
369 sh->DeletePending = GL_TRUE;
370
371 /* effectively, decr sh's refcount */
372 _mesa_reference_shader(ctx, &sh, NULL);
373 }
374 }
375
376
377 static void
378 detach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
379 {
380 struct gl_shader_program *shProg;
381 GLuint n;
382 GLuint i, j;
383
384 shProg = _mesa_lookup_shader_program_err(ctx, program, "glDetachShader");
385 if (!shProg)
386 return;
387
388 n = shProg->NumShaders;
389
390 for (i = 0; i < n; i++) {
391 if (shProg->Shaders[i]->Name == shader) {
392 /* found it */
393 struct gl_shader **newList;
394
395 /* release */
396 _mesa_reference_shader(ctx, &shProg->Shaders[i], NULL);
397
398 /* alloc new, smaller array */
399 newList = malloc((n - 1) * sizeof(struct gl_shader *));
400 if (!newList) {
401 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDetachShader");
402 return;
403 }
404 /* Copy old list entries to new list, skipping removed entry at [i] */
405 for (j = 0; j < i; j++) {
406 newList[j] = shProg->Shaders[j];
407 }
408 while (++i < n) {
409 newList[j++] = shProg->Shaders[i];
410 }
411
412 /* Free old list and install new one */
413 free(shProg->Shaders);
414 shProg->Shaders = newList;
415 shProg->NumShaders = n - 1;
416
417 #ifdef DEBUG
418 /* sanity check - make sure the new list's entries are sensible */
419 for (j = 0; j < shProg->NumShaders; j++) {
420 assert(shProg->Shaders[j]->Type == GL_VERTEX_SHADER ||
421 shProg->Shaders[j]->Type == GL_GEOMETRY_SHADER ||
422 shProg->Shaders[j]->Type == GL_FRAGMENT_SHADER);
423 assert(shProg->Shaders[j]->RefCount > 0);
424 }
425 #endif
426
427 return;
428 }
429 }
430
431 /* not found */
432 {
433 GLenum err;
434 if (is_shader(ctx, shader) || is_program(ctx, shader))
435 err = GL_INVALID_OPERATION;
436 else
437 err = GL_INVALID_VALUE;
438 _mesa_error(ctx, err, "glDetachShader(shader)");
439 return;
440 }
441 }
442
443
444 /**
445 * Return list of shaders attached to shader program.
446 */
447 static void
448 get_attached_shaders(struct gl_context *ctx, GLuint program, GLsizei maxCount,
449 GLsizei *count, GLuint *obj)
450 {
451 struct gl_shader_program *shProg;
452
453 if (maxCount < 0) {
454 _mesa_error(ctx, GL_INVALID_VALUE, "glGetAttachedShaders(maxCount < 0)");
455 return;
456 }
457
458 shProg =
459 _mesa_lookup_shader_program_err(ctx, program, "glGetAttachedShaders");
460
461 if (shProg) {
462 GLuint i;
463 for (i = 0; i < (GLuint) maxCount && i < shProg->NumShaders; i++) {
464 obj[i] = shProg->Shaders[i]->Name;
465 }
466 if (count)
467 *count = i;
468 }
469 }
470
471
472 /**
473 * glGetHandleARB() - return ID/name of currently bound shader program.
474 */
475 static GLuint
476 get_handle(struct gl_context *ctx, GLenum pname)
477 {
478 if (pname == GL_PROGRAM_OBJECT_ARB) {
479 if (ctx->_Shader->ActiveProgram)
480 return ctx->_Shader->ActiveProgram->Name;
481 else
482 return 0;
483 }
484 else {
485 _mesa_error(ctx, GL_INVALID_ENUM, "glGetHandleARB");
486 return 0;
487 }
488 }
489
490
491 /**
492 * Check if a geometry shader query is valid at this time. If not, report an
493 * error and return false.
494 *
495 * From GL 3.2 section 6.1.16 (Shader and Program Queries):
496 *
497 * "If GEOMETRY_VERTICES_OUT, GEOMETRY_INPUT_TYPE, or GEOMETRY_OUTPUT_TYPE
498 * are queried for a program which has not been linked successfully, or
499 * which does not contain objects to form a geometry shader, then an
500 * INVALID_OPERATION error is generated."
501 */
502 static bool
503 check_gs_query(struct gl_context *ctx, const struct gl_shader_program *shProg)
504 {
505 if (shProg->LinkStatus &&
506 shProg->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
507 return true;
508 }
509
510 _mesa_error(ctx, GL_INVALID_OPERATION,
511 "glGetProgramv(linked geometry shader required)");
512 return false;
513 }
514
515
516 /**
517 * glGetProgramiv() - get shader program state.
518 * Note that this is for GLSL shader programs, not ARB vertex/fragment
519 * programs (see glGetProgramivARB).
520 */
521 static void
522 get_programiv(struct gl_context *ctx, GLuint program, GLenum pname,
523 GLint *params)
524 {
525 struct gl_shader_program *shProg
526 = _mesa_lookup_shader_program(ctx, program);
527
528 /* Is transform feedback available in this context?
529 */
530 const bool has_xfb =
531 (ctx->API == API_OPENGL_COMPAT && ctx->Extensions.EXT_transform_feedback)
532 || ctx->API == API_OPENGL_CORE
533 || _mesa_is_gles3(ctx);
534
535 /* True if geometry shaders (of the form that was adopted into GLSL 1.50
536 * and GL 3.2) are available in this context
537 */
538 const bool has_core_gs = _mesa_is_desktop_gl(ctx) && ctx->Version >= 32;
539
540 /* Are uniform buffer objects available in this context?
541 */
542 const bool has_ubo =
543 (ctx->API == API_OPENGL_COMPAT &&
544 ctx->Extensions.ARB_uniform_buffer_object)
545 || ctx->API == API_OPENGL_CORE
546 || _mesa_is_gles3(ctx);
547
548 if (!shProg) {
549 _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramiv(program)");
550 return;
551 }
552
553 switch (pname) {
554 case GL_DELETE_STATUS:
555 *params = shProg->DeletePending;
556 return;
557 case GL_LINK_STATUS:
558 *params = shProg->LinkStatus;
559 return;
560 case GL_VALIDATE_STATUS:
561 *params = shProg->Validated;
562 return;
563 case GL_INFO_LOG_LENGTH:
564 *params = shProg->InfoLog ? strlen(shProg->InfoLog) + 1 : 0;
565 return;
566 case GL_ATTACHED_SHADERS:
567 *params = shProg->NumShaders;
568 return;
569 case GL_ACTIVE_ATTRIBUTES:
570 *params = _mesa_count_active_attribs(shProg);
571 return;
572 case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
573 *params = _mesa_longest_attribute_name_length(shProg);
574 return;
575 case GL_ACTIVE_UNIFORMS:
576 *params = shProg->NumUserUniformStorage - shProg->NumHiddenUniforms;
577 return;
578 case GL_ACTIVE_UNIFORM_MAX_LENGTH: {
579 unsigned i;
580 GLint max_len = 0;
581 const unsigned num_uniforms =
582 shProg->NumUserUniformStorage - shProg->NumHiddenUniforms;
583
584 for (i = 0; i < num_uniforms; i++) {
585 /* Add one for the terminating NUL character for a non-array, and
586 * 4 for the "[0]" and the NUL for an array.
587 */
588 const GLint len = strlen(shProg->UniformStorage[i].name) + 1 +
589 ((shProg->UniformStorage[i].array_elements != 0) ? 3 : 0);
590
591 if (len > max_len)
592 max_len = len;
593 }
594
595 *params = max_len;
596 return;
597 }
598 case GL_TRANSFORM_FEEDBACK_VARYINGS:
599 if (!has_xfb)
600 break;
601 *params = shProg->TransformFeedback.NumVarying;
602 return;
603 case GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH: {
604 unsigned i;
605 GLint max_len = 0;
606 if (!has_xfb)
607 break;
608
609 for (i = 0; i < shProg->TransformFeedback.NumVarying; i++) {
610 /* Add one for the terminating NUL character.
611 */
612 const GLint len =
613 strlen(shProg->TransformFeedback.VaryingNames[i]) + 1;
614
615 if (len > max_len)
616 max_len = len;
617 }
618
619 *params = max_len;
620 return;
621 }
622 case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
623 if (!has_xfb)
624 break;
625 *params = shProg->TransformFeedback.BufferMode;
626 return;
627 case GL_GEOMETRY_VERTICES_OUT:
628 if (!has_core_gs)
629 break;
630 if (check_gs_query(ctx, shProg))
631 *params = shProg->Geom.VerticesOut;
632 return;
633 case GL_GEOMETRY_SHADER_INVOCATIONS:
634 if (!has_core_gs || !ctx->Extensions.ARB_gpu_shader5)
635 break;
636 if (check_gs_query(ctx, shProg))
637 *params = shProg->Geom.Invocations;
638 return;
639 case GL_GEOMETRY_INPUT_TYPE:
640 if (!has_core_gs)
641 break;
642 if (check_gs_query(ctx, shProg))
643 *params = shProg->Geom.InputType;
644 return;
645 case GL_GEOMETRY_OUTPUT_TYPE:
646 if (!has_core_gs)
647 break;
648 if (check_gs_query(ctx, shProg))
649 *params = shProg->Geom.OutputType;
650 return;
651 case GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH: {
652 unsigned i;
653 GLint max_len = 0;
654
655 if (!has_ubo)
656 break;
657
658 for (i = 0; i < shProg->NumUniformBlocks; i++) {
659 /* Add one for the terminating NUL character.
660 */
661 const GLint len = strlen(shProg->UniformBlocks[i].Name) + 1;
662
663 if (len > max_len)
664 max_len = len;
665 }
666
667 *params = max_len;
668 return;
669 }
670 case GL_ACTIVE_UNIFORM_BLOCKS:
671 if (!has_ubo)
672 break;
673
674 *params = shProg->NumUniformBlocks;
675 return;
676 case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
677 /* This enum isn't part of the OES extension for OpenGL ES 2.0. It is
678 * only available with desktop OpenGL 3.0+ with the
679 * GL_ARB_get_program_binary extension or OpenGL ES 3.0.
680 *
681 * On desktop, we ignore the 3.0+ requirement because it is silly.
682 */
683 if (!_mesa_is_desktop_gl(ctx) && !_mesa_is_gles3(ctx))
684 break;
685
686 *params = shProg->BinaryRetreivableHint;
687 return;
688 case GL_PROGRAM_BINARY_LENGTH:
689 *params = 0;
690 return;
691 case GL_ACTIVE_ATOMIC_COUNTER_BUFFERS:
692 if (!ctx->Extensions.ARB_shader_atomic_counters)
693 break;
694
695 *params = shProg->NumAtomicBuffers;
696 return;
697 case GL_COMPUTE_WORK_GROUP_SIZE: {
698 int i;
699 if (!_mesa_is_desktop_gl(ctx) || !ctx->Extensions.ARB_compute_shader)
700 break;
701 if (!shProg->LinkStatus) {
702 _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramiv(program not "
703 "linked)");
704 return;
705 }
706 if (shProg->_LinkedShaders[MESA_SHADER_COMPUTE] == NULL) {
707 _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramiv(no compute "
708 "shaders)");
709 return;
710 }
711 for (i = 0; i < 3; i++)
712 params[i] = shProg->Comp.LocalSize[i];
713 return;
714 }
715 case GL_PROGRAM_SEPARABLE:
716 *params = shProg->SeparateShader;
717 return;
718 default:
719 break;
720 }
721
722 _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramiv(pname=%s)",
723 _mesa_lookup_enum_by_nr(pname));
724 }
725
726
727 /**
728 * glGetShaderiv() - get GLSL shader state
729 */
730 static void
731 get_shaderiv(struct gl_context *ctx, GLuint name, GLenum pname, GLint *params)
732 {
733 struct gl_shader *shader =
734 _mesa_lookup_shader_err(ctx, name, "glGetShaderiv");
735
736 if (!shader) {
737 return;
738 }
739
740 switch (pname) {
741 case GL_SHADER_TYPE:
742 *params = shader->Type;
743 break;
744 case GL_DELETE_STATUS:
745 *params = shader->DeletePending;
746 break;
747 case GL_COMPILE_STATUS:
748 *params = shader->CompileStatus;
749 break;
750 case GL_INFO_LOG_LENGTH:
751 *params = shader->InfoLog ? strlen(shader->InfoLog) + 1 : 0;
752 break;
753 case GL_SHADER_SOURCE_LENGTH:
754 *params = shader->Source ? strlen((char *) shader->Source) + 1 : 0;
755 break;
756 default:
757 _mesa_error(ctx, GL_INVALID_ENUM, "glGetShaderiv(pname)");
758 return;
759 }
760 }
761
762
763 static void
764 get_program_info_log(struct gl_context *ctx, GLuint program, GLsizei bufSize,
765 GLsizei *length, GLchar *infoLog)
766 {
767 struct gl_shader_program *shProg = _mesa_lookup_shader_program(ctx, program);
768 if (!shProg) {
769 _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramInfoLog(program)");
770 return;
771 }
772 _mesa_copy_string(infoLog, bufSize, length, shProg->InfoLog);
773 }
774
775
776 static void
777 get_shader_info_log(struct gl_context *ctx, GLuint shader, GLsizei bufSize,
778 GLsizei *length, GLchar *infoLog)
779 {
780 struct gl_shader *sh = _mesa_lookup_shader(ctx, shader);
781 if (!sh) {
782 _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderInfoLog(shader)");
783 return;
784 }
785 _mesa_copy_string(infoLog, bufSize, length, sh->InfoLog);
786 }
787
788
789 /**
790 * Return shader source code.
791 */
792 static void
793 get_shader_source(struct gl_context *ctx, GLuint shader, GLsizei maxLength,
794 GLsizei *length, GLchar *sourceOut)
795 {
796 struct gl_shader *sh;
797
798 if (maxLength < 0) {
799 _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderSource(bufSize < 0)");
800 return;
801 }
802
803 sh = _mesa_lookup_shader_err(ctx, shader, "glGetShaderSource");
804 if (!sh) {
805 return;
806 }
807 _mesa_copy_string(sourceOut, maxLength, length, sh->Source);
808 }
809
810
811 /**
812 * Set/replace shader source code. A helper function used by
813 * glShaderSource[ARB].
814 */
815 static void
816 shader_source(struct gl_context *ctx, GLuint shader, const GLchar *source)
817 {
818 struct gl_shader *sh;
819
820 sh = _mesa_lookup_shader_err(ctx, shader, "glShaderSource");
821 if (!sh)
822 return;
823
824 /* free old shader source string and install new one */
825 free((void *)sh->Source);
826 sh->Source = source;
827 sh->CompileStatus = GL_FALSE;
828 #ifdef DEBUG
829 sh->SourceChecksum = _mesa_str_checksum(sh->Source);
830 #endif
831 }
832
833
834 /**
835 * Compile a shader.
836 */
837 static void
838 compile_shader(struct gl_context *ctx, GLuint shaderObj)
839 {
840 struct gl_shader *sh;
841 struct gl_shader_compiler_options *options;
842
843 sh = _mesa_lookup_shader_err(ctx, shaderObj, "glCompileShader");
844 if (!sh)
845 return;
846
847 options = &ctx->Const.ShaderCompilerOptions[sh->Stage];
848
849 /* set default pragma state for shader */
850 sh->Pragmas = options->DefaultPragmas;
851
852 if (!sh->Source) {
853 /* If the user called glCompileShader without first calling
854 * glShaderSource, we should fail to compile, but not raise a GL_ERROR.
855 */
856 sh->CompileStatus = GL_FALSE;
857 } else {
858 if (ctx->_Shader->Flags & GLSL_DUMP) {
859 fprintf(stderr, "GLSL source for %s shader %d:\n",
860 _mesa_shader_stage_to_string(sh->Stage), sh->Name);
861 fprintf(stderr, "%s\n", sh->Source);
862 fflush(stderr);
863 }
864
865 /* this call will set the shader->CompileStatus field to indicate if
866 * compilation was successful.
867 */
868 _mesa_glsl_compile_shader(ctx, sh, false, false);
869
870 if (ctx->_Shader->Flags & GLSL_LOG) {
871 _mesa_write_shader_to_file(sh);
872 }
873
874 if (ctx->_Shader->Flags & GLSL_DUMP) {
875 if (sh->CompileStatus) {
876 fprintf(stderr, "GLSL IR for shader %d:\n", sh->Name);
877 _mesa_print_ir(stderr, sh->ir, NULL);
878 fprintf(stderr, "\n\n");
879 } else {
880 fprintf(stderr, "GLSL shader %d failed to compile.\n", sh->Name);
881 }
882 if (sh->InfoLog && sh->InfoLog[0] != 0) {
883 fprintf(stderr, "GLSL shader %d info log:\n", sh->Name);
884 fprintf(stderr, "%s\n", sh->InfoLog);
885 }
886 fflush(stderr);
887 }
888 }
889
890 if (!sh->CompileStatus) {
891 if (ctx->_Shader->Flags & GLSL_DUMP_ON_ERROR) {
892 fprintf(stderr, "GLSL source for %s shader %d:\n",
893 _mesa_shader_stage_to_string(sh->Stage), sh->Name);
894 fprintf(stderr, "%s\n", sh->Source);
895 fprintf(stderr, "Info Log:\n%s\n", sh->InfoLog);
896 fflush(stderr);
897 }
898
899 if (ctx->_Shader->Flags & GLSL_REPORT_ERRORS) {
900 _mesa_debug(ctx, "Error compiling shader %u:\n%s\n",
901 sh->Name, sh->InfoLog);
902 }
903 }
904 }
905
906
907 /**
908 * Link a program's shaders.
909 */
910 static void
911 link_program(struct gl_context *ctx, GLuint program)
912 {
913 struct gl_shader_program *shProg;
914
915 shProg = _mesa_lookup_shader_program_err(ctx, program, "glLinkProgram");
916 if (!shProg)
917 return;
918
919 /* From the ARB_transform_feedback2 specification:
920 * "The error INVALID_OPERATION is generated by LinkProgram if <program> is
921 * the name of a program being used by one or more transform feedback
922 * objects, even if the objects are not currently bound or are paused."
923 */
924 if (_mesa_transform_feedback_is_using_program(ctx, shProg)) {
925 _mesa_error(ctx, GL_INVALID_OPERATION,
926 "glLinkProgram(transform feedback is using the program)");
927 return;
928 }
929
930 FLUSH_VERTICES(ctx, _NEW_PROGRAM);
931
932 _mesa_glsl_link_shader(ctx, shProg);
933
934 if (shProg->LinkStatus == GL_FALSE &&
935 (ctx->_Shader->Flags & GLSL_REPORT_ERRORS)) {
936 _mesa_debug(ctx, "Error linking program %u:\n%s\n",
937 shProg->Name, shProg->InfoLog);
938 }
939
940 /* debug code */
941 if (0) {
942 GLuint i;
943
944 printf("Link %u shaders in program %u: %s\n",
945 shProg->NumShaders, shProg->Name,
946 shProg->LinkStatus ? "Success" : "Failed");
947
948 for (i = 0; i < shProg->NumShaders; i++) {
949 printf(" shader %u, type 0x%x\n",
950 shProg->Shaders[i]->Name,
951 shProg->Shaders[i]->Type);
952 }
953 }
954 }
955
956
957 /**
958 * Print basic shader info (for debug).
959 */
960 static void
961 print_shader_info(const struct gl_shader_program *shProg)
962 {
963 GLuint i;
964
965 printf("Mesa: glUseProgram(%u)\n", shProg->Name);
966 for (i = 0; i < shProg->NumShaders; i++) {
967 printf(" %s shader %u, checksum %u\n",
968 _mesa_shader_stage_to_string(shProg->Shaders[i]->Stage),
969 shProg->Shaders[i]->Name,
970 shProg->Shaders[i]->SourceChecksum);
971 }
972 if (shProg->_LinkedShaders[MESA_SHADER_VERTEX])
973 printf(" vert prog %u\n",
974 shProg->_LinkedShaders[MESA_SHADER_VERTEX]->Program->Id);
975 if (shProg->_LinkedShaders[MESA_SHADER_FRAGMENT])
976 printf(" frag prog %u\n",
977 shProg->_LinkedShaders[MESA_SHADER_FRAGMENT]->Program->Id);
978 if (shProg->_LinkedShaders[MESA_SHADER_GEOMETRY])
979 printf(" geom prog %u\n",
980 shProg->_LinkedShaders[MESA_SHADER_GEOMETRY]->Program->Id);
981 }
982
983
984 /**
985 * Use the named shader program for subsequent glUniform calls
986 */
987 void
988 _mesa_active_program(struct gl_context *ctx, struct gl_shader_program *shProg,
989 const char *caller)
990 {
991 if ((shProg != NULL) && !shProg->LinkStatus) {
992 _mesa_error(ctx, GL_INVALID_OPERATION,
993 "%s(program %u not linked)", caller, shProg->Name);
994 return;
995 }
996
997 if (ctx->Shader.ActiveProgram != shProg) {
998 _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, shProg);
999 }
1000 }
1001
1002
1003 static void
1004 use_shader_program(struct gl_context *ctx, GLenum type,
1005 struct gl_shader_program *shProg,
1006 struct gl_pipeline_object *shTarget)
1007 {
1008 struct gl_shader_program **target;
1009 gl_shader_stage stage = _mesa_shader_enum_to_shader_stage(type);
1010
1011 target = &shTarget->CurrentProgram[stage];
1012 if ((shProg == NULL) || (shProg->_LinkedShaders[stage] == NULL))
1013 shProg = NULL;
1014
1015 if (*target != shProg) {
1016 /* Program is current, flush it */
1017 if (shTarget == ctx->_Shader) {
1018 FLUSH_VERTICES(ctx, _NEW_PROGRAM | _NEW_PROGRAM_CONSTANTS);
1019 }
1020
1021 /* If the shader is also bound as the current rendering shader, unbind
1022 * it from that binding point as well. This ensures that the correct
1023 * semantics of glDeleteProgram are maintained.
1024 */
1025 switch (type) {
1026 case GL_VERTEX_SHADER:
1027 /* Empty for now. */
1028 break;
1029 case GL_GEOMETRY_SHADER_ARB:
1030 /* Empty for now. */
1031 break;
1032 case GL_COMPUTE_SHADER:
1033 /* Empty for now. */
1034 break;
1035 case GL_FRAGMENT_SHADER:
1036 if (*target == ctx->_Shader->_CurrentFragmentProgram) {
1037 _mesa_reference_shader_program(ctx,
1038 &ctx->_Shader->_CurrentFragmentProgram,
1039 NULL);
1040 }
1041 break;
1042 }
1043
1044 _mesa_reference_shader_program(ctx, target, shProg);
1045 return;
1046 }
1047 }
1048
1049
1050 /**
1051 * Use the named shader program for subsequent rendering.
1052 */
1053 void
1054 _mesa_use_program(struct gl_context *ctx, struct gl_shader_program *shProg)
1055 {
1056 use_shader_program(ctx, GL_VERTEX_SHADER, shProg, &ctx->Shader);
1057 use_shader_program(ctx, GL_GEOMETRY_SHADER_ARB, shProg, &ctx->Shader);
1058 use_shader_program(ctx, GL_FRAGMENT_SHADER, shProg, &ctx->Shader);
1059 use_shader_program(ctx, GL_COMPUTE_SHADER, shProg, &ctx->Shader);
1060 _mesa_active_program(ctx, shProg, "glUseProgram");
1061
1062 if (ctx->Driver.UseProgram)
1063 ctx->Driver.UseProgram(ctx, shProg);
1064 }
1065
1066
1067 /**
1068 * Do validation of the given shader program.
1069 * \param errMsg returns error message if validation fails.
1070 * \return GL_TRUE if valid, GL_FALSE if invalid (and set errMsg)
1071 */
1072 static GLboolean
1073 validate_shader_program(const struct gl_shader_program *shProg,
1074 char *errMsg)
1075 {
1076 if (!shProg->LinkStatus) {
1077 return GL_FALSE;
1078 }
1079
1080 /* From the GL spec, a program is invalid if any of these are true:
1081
1082 any two active samplers in the current program object are of
1083 different types, but refer to the same texture image unit,
1084
1085 any active sampler in the current program object refers to a texture
1086 image unit where fixed-function fragment processing accesses a
1087 texture target that does not match the sampler type, or
1088
1089 the sum of the number of active samplers in the program and the
1090 number of texture image units enabled for fixed-function fragment
1091 processing exceeds the combined limit on the total number of texture
1092 image units allowed.
1093 */
1094
1095 /*
1096 * Check: any two active samplers in the current program object are of
1097 * different types, but refer to the same texture image unit,
1098 */
1099 if (!_mesa_sampler_uniforms_are_valid(shProg, errMsg, 100))
1100 return GL_FALSE;
1101
1102 return GL_TRUE;
1103 }
1104
1105
1106 /**
1107 * Called via glValidateProgram()
1108 */
1109 static void
1110 validate_program(struct gl_context *ctx, GLuint program)
1111 {
1112 struct gl_shader_program *shProg;
1113 char errMsg[100] = "";
1114
1115 shProg = _mesa_lookup_shader_program_err(ctx, program, "glValidateProgram");
1116 if (!shProg) {
1117 return;
1118 }
1119
1120 shProg->Validated = validate_shader_program(shProg, errMsg);
1121 if (!shProg->Validated) {
1122 /* update info log */
1123 if (shProg->InfoLog) {
1124 ralloc_free(shProg->InfoLog);
1125 }
1126 shProg->InfoLog = ralloc_strdup(shProg, errMsg);
1127 }
1128 }
1129
1130
1131
1132 void GLAPIENTRY
1133 _mesa_AttachObjectARB(GLhandleARB program, GLhandleARB shader)
1134 {
1135 GET_CURRENT_CONTEXT(ctx);
1136 attach_shader(ctx, program, shader);
1137 }
1138
1139
1140 void GLAPIENTRY
1141 _mesa_AttachShader(GLuint program, GLuint shader)
1142 {
1143 GET_CURRENT_CONTEXT(ctx);
1144 attach_shader(ctx, program, shader);
1145 }
1146
1147
1148 void GLAPIENTRY
1149 _mesa_CompileShader(GLhandleARB shaderObj)
1150 {
1151 GET_CURRENT_CONTEXT(ctx);
1152 if (MESA_VERBOSE & VERBOSE_API)
1153 _mesa_debug(ctx, "glCompileShader %u\n", shaderObj);
1154 compile_shader(ctx, shaderObj);
1155 }
1156
1157
1158 GLuint GLAPIENTRY
1159 _mesa_CreateShader(GLenum type)
1160 {
1161 GET_CURRENT_CONTEXT(ctx);
1162 if (MESA_VERBOSE & VERBOSE_API)
1163 _mesa_debug(ctx, "glCreateShader %s\n", _mesa_lookup_enum_by_nr(type));
1164 return create_shader(ctx, type);
1165 }
1166
1167
1168 GLhandleARB GLAPIENTRY
1169 _mesa_CreateShaderObjectARB(GLenum type)
1170 {
1171 GET_CURRENT_CONTEXT(ctx);
1172 return create_shader(ctx, type);
1173 }
1174
1175
1176 GLuint GLAPIENTRY
1177 _mesa_CreateProgram(void)
1178 {
1179 GET_CURRENT_CONTEXT(ctx);
1180 if (MESA_VERBOSE & VERBOSE_API)
1181 _mesa_debug(ctx, "glCreateProgram\n");
1182 return create_shader_program(ctx);
1183 }
1184
1185
1186 GLhandleARB GLAPIENTRY
1187 _mesa_CreateProgramObjectARB(void)
1188 {
1189 GET_CURRENT_CONTEXT(ctx);
1190 return create_shader_program(ctx);
1191 }
1192
1193
1194 void GLAPIENTRY
1195 _mesa_DeleteObjectARB(GLhandleARB obj)
1196 {
1197 if (MESA_VERBOSE & VERBOSE_API) {
1198 GET_CURRENT_CONTEXT(ctx);
1199 _mesa_debug(ctx, "glDeleteObjectARB(%u)\n", obj);
1200 }
1201
1202 if (obj) {
1203 GET_CURRENT_CONTEXT(ctx);
1204 FLUSH_VERTICES(ctx, 0);
1205 if (is_program(ctx, obj)) {
1206 delete_shader_program(ctx, obj);
1207 }
1208 else if (is_shader(ctx, obj)) {
1209 delete_shader(ctx, obj);
1210 }
1211 else {
1212 /* error? */
1213 }
1214 }
1215 }
1216
1217
1218 void GLAPIENTRY
1219 _mesa_DeleteProgram(GLuint name)
1220 {
1221 if (name) {
1222 GET_CURRENT_CONTEXT(ctx);
1223 FLUSH_VERTICES(ctx, 0);
1224 delete_shader_program(ctx, name);
1225 }
1226 }
1227
1228
1229 void GLAPIENTRY
1230 _mesa_DeleteShader(GLuint name)
1231 {
1232 if (name) {
1233 GET_CURRENT_CONTEXT(ctx);
1234 FLUSH_VERTICES(ctx, 0);
1235 delete_shader(ctx, name);
1236 }
1237 }
1238
1239
1240 void GLAPIENTRY
1241 _mesa_DetachObjectARB(GLhandleARB program, GLhandleARB shader)
1242 {
1243 GET_CURRENT_CONTEXT(ctx);
1244 detach_shader(ctx, program, shader);
1245 }
1246
1247
1248 void GLAPIENTRY
1249 _mesa_DetachShader(GLuint program, GLuint shader)
1250 {
1251 GET_CURRENT_CONTEXT(ctx);
1252 detach_shader(ctx, program, shader);
1253 }
1254
1255
1256 void GLAPIENTRY
1257 _mesa_GetAttachedObjectsARB(GLhandleARB container, GLsizei maxCount,
1258 GLsizei * count, GLhandleARB * obj)
1259 {
1260 GET_CURRENT_CONTEXT(ctx);
1261 get_attached_shaders(ctx, container, maxCount, count, obj);
1262 }
1263
1264
1265 void GLAPIENTRY
1266 _mesa_GetAttachedShaders(GLuint program, GLsizei maxCount,
1267 GLsizei *count, GLuint *obj)
1268 {
1269 GET_CURRENT_CONTEXT(ctx);
1270 get_attached_shaders(ctx, program, maxCount, count, obj);
1271 }
1272
1273
1274 void GLAPIENTRY
1275 _mesa_GetInfoLogARB(GLhandleARB object, GLsizei maxLength, GLsizei * length,
1276 GLcharARB * infoLog)
1277 {
1278 GET_CURRENT_CONTEXT(ctx);
1279 if (is_program(ctx, object)) {
1280 get_program_info_log(ctx, object, maxLength, length, infoLog);
1281 }
1282 else if (is_shader(ctx, object)) {
1283 get_shader_info_log(ctx, object, maxLength, length, infoLog);
1284 }
1285 else {
1286 _mesa_error(ctx, GL_INVALID_OPERATION, "glGetInfoLogARB");
1287 }
1288 }
1289
1290
1291 void GLAPIENTRY
1292 _mesa_GetObjectParameterivARB(GLhandleARB object, GLenum pname, GLint *params)
1293 {
1294 GET_CURRENT_CONTEXT(ctx);
1295 /* Implement in terms of GetProgramiv, GetShaderiv */
1296 if (is_program(ctx, object)) {
1297 if (pname == GL_OBJECT_TYPE_ARB) {
1298 *params = GL_PROGRAM_OBJECT_ARB;
1299 }
1300 else {
1301 get_programiv(ctx, object, pname, params);
1302 }
1303 }
1304 else if (is_shader(ctx, object)) {
1305 if (pname == GL_OBJECT_TYPE_ARB) {
1306 *params = GL_SHADER_OBJECT_ARB;
1307 }
1308 else {
1309 get_shaderiv(ctx, object, pname, params);
1310 }
1311 }
1312 else {
1313 _mesa_error(ctx, GL_INVALID_VALUE, "glGetObjectParameterivARB");
1314 }
1315 }
1316
1317
1318 void GLAPIENTRY
1319 _mesa_GetObjectParameterfvARB(GLhandleARB object, GLenum pname,
1320 GLfloat *params)
1321 {
1322 GLint iparams[1]; /* XXX is one element enough? */
1323 _mesa_GetObjectParameterivARB(object, pname, iparams);
1324 params[0] = (GLfloat) iparams[0];
1325 }
1326
1327
1328 void GLAPIENTRY
1329 _mesa_GetProgramiv(GLuint program, GLenum pname, GLint *params)
1330 {
1331 GET_CURRENT_CONTEXT(ctx);
1332 get_programiv(ctx, program, pname, params);
1333 }
1334
1335
1336 void GLAPIENTRY
1337 _mesa_GetShaderiv(GLuint shader, GLenum pname, GLint *params)
1338 {
1339 GET_CURRENT_CONTEXT(ctx);
1340 get_shaderiv(ctx, shader, pname, params);
1341 }
1342
1343
1344 void GLAPIENTRY
1345 _mesa_GetProgramInfoLog(GLuint program, GLsizei bufSize,
1346 GLsizei *length, GLchar *infoLog)
1347 {
1348 GET_CURRENT_CONTEXT(ctx);
1349 get_program_info_log(ctx, program, bufSize, length, infoLog);
1350 }
1351
1352
1353 void GLAPIENTRY
1354 _mesa_GetShaderInfoLog(GLuint shader, GLsizei bufSize,
1355 GLsizei *length, GLchar *infoLog)
1356 {
1357 GET_CURRENT_CONTEXT(ctx);
1358 get_shader_info_log(ctx, shader, bufSize, length, infoLog);
1359 }
1360
1361
1362 void GLAPIENTRY
1363 _mesa_GetShaderSource(GLhandleARB shader, GLsizei maxLength,
1364 GLsizei *length, GLcharARB *sourceOut)
1365 {
1366 GET_CURRENT_CONTEXT(ctx);
1367 get_shader_source(ctx, shader, maxLength, length, sourceOut);
1368 }
1369
1370
1371 GLhandleARB GLAPIENTRY
1372 _mesa_GetHandleARB(GLenum pname)
1373 {
1374 GET_CURRENT_CONTEXT(ctx);
1375 return get_handle(ctx, pname);
1376 }
1377
1378
1379 GLboolean GLAPIENTRY
1380 _mesa_IsProgram(GLuint name)
1381 {
1382 GET_CURRENT_CONTEXT(ctx);
1383 return is_program(ctx, name);
1384 }
1385
1386
1387 GLboolean GLAPIENTRY
1388 _mesa_IsShader(GLuint name)
1389 {
1390 GET_CURRENT_CONTEXT(ctx);
1391 return is_shader(ctx, name);
1392 }
1393
1394
1395 void GLAPIENTRY
1396 _mesa_LinkProgram(GLhandleARB programObj)
1397 {
1398 GET_CURRENT_CONTEXT(ctx);
1399 link_program(ctx, programObj);
1400 }
1401
1402
1403
1404 /**
1405 * Read shader source code from a file.
1406 * Useful for debugging to override an app's shader.
1407 */
1408 static GLcharARB *
1409 read_shader(const char *fname)
1410 {
1411 int shader_size = 0;
1412 FILE *f = fopen(fname, "r");
1413 GLcharARB *buffer, *shader;
1414 int len;
1415
1416 if (!f) {
1417 return NULL;
1418 }
1419
1420 /* allocate enough room for the entire shader */
1421 fseek(f, 0, SEEK_END);
1422 shader_size = ftell(f);
1423 rewind(f);
1424 assert(shader_size);
1425
1426 /* add one for terminating zero */
1427 shader_size++;
1428
1429 buffer = malloc(shader_size);
1430 assert(buffer);
1431
1432 len = fread(buffer, 1, shader_size, f);
1433 buffer[len] = 0;
1434
1435 fclose(f);
1436
1437 shader = _mesa_strdup(buffer);
1438 free(buffer);
1439
1440 return shader;
1441 }
1442
1443
1444 /**
1445 * Called via glShaderSource() and glShaderSourceARB() API functions.
1446 * Basically, concatenate the source code strings into one long string
1447 * and pass it to _mesa_shader_source().
1448 */
1449 void GLAPIENTRY
1450 _mesa_ShaderSource(GLhandleARB shaderObj, GLsizei count,
1451 const GLcharARB * const * string, const GLint * length)
1452 {
1453 GET_CURRENT_CONTEXT(ctx);
1454 GLint *offsets;
1455 GLsizei i, totalLength;
1456 GLcharARB *source;
1457 GLuint checksum;
1458
1459 if (!shaderObj || string == NULL) {
1460 _mesa_error(ctx, GL_INVALID_VALUE, "glShaderSourceARB");
1461 return;
1462 }
1463
1464 /*
1465 * This array holds offsets of where the appropriate string ends, thus the
1466 * last element will be set to the total length of the source code.
1467 */
1468 offsets = malloc(count * sizeof(GLint));
1469 if (offsets == NULL) {
1470 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
1471 return;
1472 }
1473
1474 for (i = 0; i < count; i++) {
1475 if (string[i] == NULL) {
1476 free((GLvoid *) offsets);
1477 _mesa_error(ctx, GL_INVALID_OPERATION,
1478 "glShaderSourceARB(null string)");
1479 return;
1480 }
1481 if (length == NULL || length[i] < 0)
1482 offsets[i] = strlen(string[i]);
1483 else
1484 offsets[i] = length[i];
1485 /* accumulate string lengths */
1486 if (i > 0)
1487 offsets[i] += offsets[i - 1];
1488 }
1489
1490 /* Total length of source string is sum off all strings plus two.
1491 * One extra byte for terminating zero, another extra byte to silence
1492 * valgrind warnings in the parser/grammer code.
1493 */
1494 totalLength = offsets[count - 1] + 2;
1495 source = malloc(totalLength * sizeof(GLcharARB));
1496 if (source == NULL) {
1497 free((GLvoid *) offsets);
1498 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
1499 return;
1500 }
1501
1502 for (i = 0; i < count; i++) {
1503 GLint start = (i > 0) ? offsets[i - 1] : 0;
1504 memcpy(source + start, string[i],
1505 (offsets[i] - start) * sizeof(GLcharARB));
1506 }
1507 source[totalLength - 1] = '\0';
1508 source[totalLength - 2] = '\0';
1509
1510 if (SHADER_SUBST) {
1511 /* Compute the shader's source code checksum then try to open a file
1512 * named newshader_<CHECKSUM>. If it exists, use it in place of the
1513 * original shader source code. For debugging.
1514 */
1515 char filename[100];
1516 GLcharARB *newSource;
1517
1518 checksum = _mesa_str_checksum(source);
1519
1520 _mesa_snprintf(filename, sizeof(filename), "newshader_%d", checksum);
1521
1522 newSource = read_shader(filename);
1523 if (newSource) {
1524 fprintf(stderr, "Mesa: Replacing shader %u chksum=%d with %s\n",
1525 shaderObj, checksum, filename);
1526 free(source);
1527 source = newSource;
1528 }
1529 }
1530
1531 shader_source(ctx, shaderObj, source);
1532
1533 if (SHADER_SUBST) {
1534 struct gl_shader *sh = _mesa_lookup_shader(ctx, shaderObj);
1535 if (sh)
1536 sh->SourceChecksum = checksum; /* save original checksum */
1537 }
1538
1539 free(offsets);
1540 }
1541
1542
1543 void GLAPIENTRY
1544 _mesa_UseProgram(GLhandleARB program)
1545 {
1546 GET_CURRENT_CONTEXT(ctx);
1547 struct gl_shader_program *shProg;
1548
1549 if (_mesa_is_xfb_active_and_unpaused(ctx)) {
1550 _mesa_error(ctx, GL_INVALID_OPERATION,
1551 "glUseProgram(transform feedback active)");
1552 return;
1553 }
1554
1555 if (program) {
1556 shProg = _mesa_lookup_shader_program_err(ctx, program, "glUseProgram");
1557 if (!shProg) {
1558 return;
1559 }
1560 if (!shProg->LinkStatus) {
1561 _mesa_error(ctx, GL_INVALID_OPERATION,
1562 "glUseProgram(program %u not linked)", program);
1563 return;
1564 }
1565
1566 /* debug code */
1567 if (ctx->_Shader->Flags & GLSL_USE_PROG) {
1568 print_shader_info(shProg);
1569 }
1570 }
1571 else {
1572 shProg = NULL;
1573 }
1574
1575 /* The ARB_separate_shader_object spec says:
1576 *
1577 * "The executable code for an individual shader stage is taken from
1578 * the current program for that stage. If there is a current program
1579 * object established by UseProgram, that program is considered current
1580 * for all stages. Otherwise, if there is a bound program pipeline
1581 * object (section 2.14.PPO), the program bound to the appropriate
1582 * stage of the pipeline object is considered current."
1583 */
1584 if (program) {
1585 /* Attach shader state to the binding point */
1586 _mesa_reference_pipeline_object(ctx, &ctx->_Shader, &ctx->Shader);
1587 /* Update the program */
1588 _mesa_use_program(ctx, shProg);
1589 } else {
1590 /* Must be done first: detach the progam */
1591 _mesa_use_program(ctx, shProg);
1592 /* Unattach shader_state binding point */
1593 _mesa_reference_pipeline_object(ctx, &ctx->_Shader, ctx->Pipeline.Default);
1594 /* If a pipeline was bound, rebind it */
1595 if (ctx->Pipeline.Current) {
1596 _mesa_BindProgramPipeline(ctx->Pipeline.Current->Name);
1597 }
1598 }
1599 }
1600
1601
1602 void GLAPIENTRY
1603 _mesa_ValidateProgram(GLhandleARB program)
1604 {
1605 GET_CURRENT_CONTEXT(ctx);
1606 validate_program(ctx, program);
1607 }
1608
1609
1610 /**
1611 * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1612 */
1613 void GLAPIENTRY
1614 _mesa_GetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype,
1615 GLint* range, GLint* precision)
1616 {
1617 const struct gl_program_constants *limits;
1618 const struct gl_precision *p;
1619 GET_CURRENT_CONTEXT(ctx);
1620
1621 switch (shadertype) {
1622 case GL_VERTEX_SHADER:
1623 limits = &ctx->Const.Program[MESA_SHADER_VERTEX];
1624 break;
1625 case GL_FRAGMENT_SHADER:
1626 limits = &ctx->Const.Program[MESA_SHADER_FRAGMENT];
1627 break;
1628 default:
1629 _mesa_error(ctx, GL_INVALID_ENUM,
1630 "glGetShaderPrecisionFormat(shadertype)");
1631 return;
1632 }
1633
1634 switch (precisiontype) {
1635 case GL_LOW_FLOAT:
1636 p = &limits->LowFloat;
1637 break;
1638 case GL_MEDIUM_FLOAT:
1639 p = &limits->MediumFloat;
1640 break;
1641 case GL_HIGH_FLOAT:
1642 p = &limits->HighFloat;
1643 break;
1644 case GL_LOW_INT:
1645 p = &limits->LowInt;
1646 break;
1647 case GL_MEDIUM_INT:
1648 p = &limits->MediumInt;
1649 break;
1650 case GL_HIGH_INT:
1651 p = &limits->HighInt;
1652 break;
1653 default:
1654 _mesa_error(ctx, GL_INVALID_ENUM,
1655 "glGetShaderPrecisionFormat(precisiontype)");
1656 return;
1657 }
1658
1659 range[0] = p->RangeMin;
1660 range[1] = p->RangeMax;
1661 precision[0] = p->Precision;
1662 }
1663
1664
1665 /**
1666 * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1667 */
1668 void GLAPIENTRY
1669 _mesa_ReleaseShaderCompiler(void)
1670 {
1671 _mesa_destroy_shader_compiler_caches();
1672 }
1673
1674
1675 /**
1676 * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1677 */
1678 void GLAPIENTRY
1679 _mesa_ShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat,
1680 const void* binary, GLint length)
1681 {
1682 GET_CURRENT_CONTEXT(ctx);
1683 (void) n;
1684 (void) shaders;
1685 (void) binaryformat;
1686 (void) binary;
1687 (void) length;
1688 _mesa_error(ctx, GL_INVALID_OPERATION, "glShaderBinary");
1689 }
1690
1691
1692 void GLAPIENTRY
1693 _mesa_GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei *length,
1694 GLenum *binaryFormat, GLvoid *binary)
1695 {
1696 struct gl_shader_program *shProg;
1697 GLsizei length_dummy;
1698 GET_CURRENT_CONTEXT(ctx);
1699
1700 if (bufSize < 0){
1701 _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramBinary(bufSize < 0)");
1702 return;
1703 }
1704
1705 shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetProgramBinary");
1706 if (!shProg)
1707 return;
1708
1709 /* The ARB_get_program_binary spec says:
1710 *
1711 * "If <length> is NULL, then no length is returned."
1712 *
1713 * Ensure that length always points to valid storage to avoid multiple NULL
1714 * pointer checks below.
1715 */
1716 if (length != NULL)
1717 length = &length_dummy;
1718
1719
1720 /* The ARB_get_program_binary spec says:
1721 *
1722 * "When a program object's LINK_STATUS is FALSE, its program binary
1723 * length is zero, and a call to GetProgramBinary will generate an
1724 * INVALID_OPERATION error.
1725 */
1726 if (!shProg->LinkStatus) {
1727 _mesa_error(ctx, GL_INVALID_OPERATION,
1728 "glGetProgramBinary(program %u not linked)",
1729 shProg->Name);
1730 *length = 0;
1731 return;
1732 }
1733
1734 *length = 0;
1735 _mesa_error(ctx, GL_INVALID_OPERATION,
1736 "glGetProgramBinary(driver supports zero binary formats)");
1737
1738 (void) binaryFormat;
1739 (void) binary;
1740 }
1741
1742 void GLAPIENTRY
1743 _mesa_ProgramBinary(GLuint program, GLenum binaryFormat,
1744 const GLvoid *binary, GLsizei length)
1745 {
1746 struct gl_shader_program *shProg;
1747 GET_CURRENT_CONTEXT(ctx);
1748
1749 shProg = _mesa_lookup_shader_program_err(ctx, program, "glProgramBinary");
1750 if (!shProg)
1751 return;
1752
1753 (void) binaryFormat;
1754 (void) binary;
1755
1756 /* Section 2.3.1 (Errors) of the OpenGL 4.5 spec says:
1757 *
1758 * "If a negative number is provided where an argument of type sizei or
1759 * sizeiptr is specified, an INVALID_VALUE error is generated."
1760 */
1761 if (length < 0) {
1762 _mesa_error(ctx, GL_INVALID_VALUE, "glProgramBinary(length < 0)");
1763 return;
1764 }
1765
1766 /* The ARB_get_program_binary spec says:
1767 *
1768 * "<binaryFormat> and <binary> must be those returned by a previous
1769 * call to GetProgramBinary, and <length> must be the length of the
1770 * program binary as returned by GetProgramBinary or GetProgramiv with
1771 * <pname> PROGRAM_BINARY_LENGTH. Loading the program binary will fail,
1772 * setting the LINK_STATUS of <program> to FALSE, if these conditions
1773 * are not met."
1774 *
1775 * Since any value of binaryFormat passed "is not one of those specified as
1776 * allowable for [this] command, an INVALID_ENUM error is generated."
1777 */
1778 shProg->LinkStatus = GL_FALSE;
1779 _mesa_error(ctx, GL_INVALID_ENUM, "glProgramBinary");
1780 }
1781
1782
1783 void GLAPIENTRY
1784 _mesa_ProgramParameteri(GLuint program, GLenum pname, GLint value)
1785 {
1786 struct gl_shader_program *shProg;
1787 GET_CURRENT_CONTEXT(ctx);
1788
1789 shProg = _mesa_lookup_shader_program_err(ctx, program,
1790 "glProgramParameteri");
1791 if (!shProg)
1792 return;
1793
1794 switch (pname) {
1795 case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
1796 /* This enum isn't part of the OES extension for OpenGL ES 2.0, but it
1797 * is part of OpenGL ES 3.0. For the ES2 case, this function shouldn't
1798 * even be in the dispatch table, so we shouldn't need to expclicitly
1799 * check here.
1800 *
1801 * On desktop, we ignore the 3.0+ requirement because it is silly.
1802 */
1803
1804 /* The ARB_get_program_binary extension spec says:
1805 *
1806 * "An INVALID_VALUE error is generated if the <value> argument to
1807 * ProgramParameteri is not TRUE or FALSE."
1808 */
1809 if (value != GL_TRUE && value != GL_FALSE) {
1810 goto invalid_value;
1811 }
1812
1813 /* No need to notify the driver. Any changes will actually take effect
1814 * the next time the shader is linked.
1815 *
1816 * The ARB_get_program_binary extension spec says:
1817 *
1818 * "To indicate that a program binary is likely to be retrieved,
1819 * ProgramParameteri should be called with <pname>
1820 * PROGRAM_BINARY_RETRIEVABLE_HINT and <value> TRUE. This setting
1821 * will not be in effect until the next time LinkProgram or
1822 * ProgramBinary has been called successfully."
1823 *
1824 * The resloution of issue 9 in the extension spec also says:
1825 *
1826 * "The application may use the PROGRAM_BINARY_RETRIEVABLE_HINT hint
1827 * to indicate to the GL implementation that this program will
1828 * likely be saved with GetProgramBinary at some point. This will
1829 * give the GL implementation the opportunity to track any state
1830 * changes made to the program before being saved such that when it
1831 * is loaded again a recompile can be avoided."
1832 */
1833 shProg->BinaryRetreivableHint = value;
1834 return;
1835
1836 case GL_PROGRAM_SEPARABLE:
1837 /* Spec imply that the behavior is the same as ARB_get_program_binary
1838 * Chapter 7.3 Program Objects
1839 */
1840 if (value != GL_TRUE && value != GL_FALSE) {
1841 goto invalid_value;
1842 }
1843 shProg->SeparateShader = value;
1844 return;
1845
1846 default:
1847 _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameteri(pname=%s)",
1848 _mesa_lookup_enum_by_nr(pname));
1849 return;
1850 }
1851
1852 invalid_value:
1853 _mesa_error(ctx, GL_INVALID_VALUE,
1854 "glProgramParameteri(pname=%s, value=%d): "
1855 "value must be 0 or 1.",
1856 _mesa_lookup_enum_by_nr(pname),
1857 value);
1858 }
1859
1860
1861 void
1862 _mesa_use_shader_program(struct gl_context *ctx, GLenum type,
1863 struct gl_shader_program *shProg,
1864 struct gl_pipeline_object *shTarget)
1865 {
1866 use_shader_program(ctx, type, shProg, shTarget);
1867
1868 if (ctx->Driver.UseProgram)
1869 ctx->Driver.UseProgram(ctx, shProg);
1870 }
1871
1872
1873 static GLuint
1874 _mesa_create_shader_program(struct gl_context* ctx, GLboolean separate,
1875 GLenum type, GLsizei count, const GLchar* const *strings)
1876 {
1877 const GLuint shader = create_shader(ctx, type);
1878 GLuint program = 0;
1879
1880 if (shader) {
1881 _mesa_ShaderSource(shader, count, strings, NULL);
1882
1883 compile_shader(ctx, shader);
1884
1885 program = create_shader_program(ctx);
1886 if (program) {
1887 struct gl_shader_program *shProg;
1888 struct gl_shader *sh;
1889 GLint compiled = GL_FALSE;
1890
1891 shProg = _mesa_lookup_shader_program(ctx, program);
1892 sh = _mesa_lookup_shader(ctx, shader);
1893
1894 shProg->SeparateShader = separate;
1895
1896 get_shaderiv(ctx, shader, GL_COMPILE_STATUS, &compiled);
1897 if (compiled) {
1898 attach_shader(ctx, program, shader);
1899 link_program(ctx, program);
1900 detach_shader(ctx, program, shader);
1901
1902 #if 0
1903 /* Possibly... */
1904 if (active-user-defined-varyings-in-linked-program) {
1905 append-error-to-info-log;
1906 shProg->LinkStatus = GL_FALSE;
1907 }
1908 #endif
1909 }
1910
1911 ralloc_strcat(&shProg->InfoLog, sh->InfoLog);
1912 }
1913
1914 delete_shader(ctx, shader);
1915 }
1916
1917 return program;
1918 }
1919
1920
1921 /**
1922 * Copy program-specific data generated by linking from the gl_shader_program
1923 * object to a specific gl_program object.
1924 */
1925 void
1926 _mesa_copy_linked_program_data(gl_shader_stage type,
1927 const struct gl_shader_program *src,
1928 struct gl_program *dst)
1929 {
1930 switch (type) {
1931 case MESA_SHADER_VERTEX:
1932 dst->UsesClipDistanceOut = src->Vert.UsesClipDistance;
1933 break;
1934 case MESA_SHADER_GEOMETRY: {
1935 struct gl_geometry_program *dst_gp = (struct gl_geometry_program *) dst;
1936 dst_gp->VerticesIn = src->Geom.VerticesIn;
1937 dst_gp->VerticesOut = src->Geom.VerticesOut;
1938 dst_gp->Invocations = src->Geom.Invocations;
1939 dst_gp->InputType = src->Geom.InputType;
1940 dst_gp->OutputType = src->Geom.OutputType;
1941 dst->UsesClipDistanceOut = src->Geom.UsesClipDistance;
1942 dst_gp->UsesEndPrimitive = src->Geom.UsesEndPrimitive;
1943 dst_gp->UsesStreams = src->Geom.UsesStreams;
1944 }
1945 break;
1946 case MESA_SHADER_FRAGMENT: {
1947 struct gl_fragment_program *dst_fp = (struct gl_fragment_program *) dst;
1948 dst_fp->FragDepthLayout = src->FragDepthLayout;
1949 }
1950 break;
1951 case MESA_SHADER_COMPUTE: {
1952 struct gl_compute_program *dst_cp = (struct gl_compute_program *) dst;
1953 int i;
1954 for (i = 0; i < 3; i++)
1955 dst_cp->LocalSize[i] = src->Comp.LocalSize[i];
1956 }
1957 break;
1958 default:
1959 break;
1960 }
1961 }
1962
1963 /**
1964 * ARB_separate_shader_objects: Compile & Link Program
1965 */
1966 GLuint GLAPIENTRY
1967 _mesa_CreateShaderProgramv(GLenum type, GLsizei count,
1968 const GLchar* const *strings)
1969 {
1970 GET_CURRENT_CONTEXT(ctx);
1971
1972 return _mesa_create_shader_program(ctx, GL_TRUE, type, count, strings);
1973 }