mesa: Use correct enum conversion function.
[mesa.git] / src / mesa / main / errors.c
1 /**
2 * \file errors.c
3 * Mesa debugging and error handling functions.
4 */
5
6 /*
7 * Mesa 3-D graphics library
8 *
9 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
10 *
11 * Permission is hereby granted, free of charge, to any person obtaining a
12 * copy of this software and associated documentation files (the "Software"),
13 * to deal in the Software without restriction, including without limitation
14 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15 * and/or sell copies of the Software, and to permit persons to whom the
16 * Software is furnished to do so, subject to the following conditions:
17 *
18 * The above copyright notice and this permission notice shall be included
19 * in all copies or substantial portions of the Software.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
25 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
26 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27 * OTHER DEALINGS IN THE SOFTWARE.
28 */
29
30
31 #include "errors.h"
32 #include "enums.h"
33 #include "imports.h"
34 #include "context.h"
35 #include "dispatch.h"
36 #include "hash.h"
37 #include "mtypes.h"
38 #include "version.h"
39 #include "hash_table.h"
40 #include "glapi/glthread.h"
41
42 #define MESSAGE_LOG 1
43 #define MESSAGE_LOG_ARB 2
44
45 _glthread_DECLARE_STATIC_MUTEX(DynamicIDMutex);
46 static GLuint NextDynamicID = 1;
47
48 struct gl_debug_severity
49 {
50 struct simple_node link;
51 GLuint ID;
52 };
53
54 static char out_of_memory[] = "Debugging error: out of memory";
55
56 static const GLenum debug_source_enums[] = {
57 GL_DEBUG_SOURCE_API,
58 GL_DEBUG_SOURCE_WINDOW_SYSTEM,
59 GL_DEBUG_SOURCE_SHADER_COMPILER,
60 GL_DEBUG_SOURCE_THIRD_PARTY,
61 GL_DEBUG_SOURCE_APPLICATION,
62 GL_DEBUG_SOURCE_OTHER,
63 };
64
65 static const GLenum debug_type_enums[] = {
66 GL_DEBUG_TYPE_ERROR,
67 GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
68 GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
69 GL_DEBUG_TYPE_PORTABILITY,
70 GL_DEBUG_TYPE_PERFORMANCE,
71 GL_DEBUG_TYPE_OTHER,
72 GL_DEBUG_TYPE_MARKER,
73 GL_DEBUG_TYPE_PUSH_GROUP,
74 GL_DEBUG_TYPE_POP_GROUP,
75 };
76
77 static const GLenum debug_severity_enums[] = {
78 GL_DEBUG_SEVERITY_LOW,
79 GL_DEBUG_SEVERITY_MEDIUM,
80 GL_DEBUG_SEVERITY_HIGH,
81 GL_DEBUG_SEVERITY_NOTIFICATION,
82 };
83
84 static enum mesa_debug_source
85 gl_enum_to_debug_source(GLenum e)
86 {
87 int i;
88
89 for (i = 0; i < Elements(debug_source_enums); i++) {
90 if (debug_source_enums[i] == e)
91 break;
92 }
93 return i;
94 }
95
96 static enum mesa_debug_type
97 gl_enum_to_debug_type(GLenum e)
98 {
99 int i;
100
101 for (i = 0; i < Elements(debug_type_enums); i++) {
102 if (debug_type_enums[i] == e)
103 break;
104 }
105 return i;
106 }
107
108 static enum mesa_debug_severity
109 gl_enum_to_debug_severity(GLenum e)
110 {
111 int i;
112
113 for (i = 0; i < Elements(debug_severity_enums); i++) {
114 if (debug_severity_enums[i] == e)
115 break;
116 }
117 return i;
118 }
119
120 /**
121 * Handles generating a GL_ARB_debug_output message ID generated by the GL or
122 * GLSL compiler.
123 *
124 * The GL API has this "ID" mechanism, where the intention is to allow a
125 * client to filter in/out messages based on source, type, and ID. Of course,
126 * building a giant enum list of all debug output messages that Mesa might
127 * generate is ridiculous, so instead we have our caller pass us a pointer to
128 * static storage where the ID should get stored. This ID will be shared
129 * across all contexts for that message (which seems like a desirable
130 * property, even if it's not expected by the spec), but note that it won't be
131 * the same between executions if messages aren't generated in the same order.
132 */
133 static void
134 debug_get_id(GLuint *id)
135 {
136 if (!(*id)) {
137 _glthread_LOCK_MUTEX(DynamicIDMutex);
138 if (!(*id))
139 *id = NextDynamicID++;
140 _glthread_UNLOCK_MUTEX(DynamicIDMutex);
141 }
142 }
143
144 /*
145 * We store a bitfield in the hash table, with five possible values total.
146 *
147 * The ENABLED_BIT's purpose is self-explanatory.
148 *
149 * The FOUND_BIT is needed to differentiate the value of DISABLED from
150 * the value returned by HashTableLookup() when it can't find the given key.
151 *
152 * The KNOWN_SEVERITY bit is a bit complicated:
153 *
154 * A client may call Control() with an array of IDs, then call Control()
155 * on all message IDs of a certain severity, then Insert() one of the
156 * previously specified IDs, giving us a known severity level, then call
157 * Control() on all message IDs of a certain severity level again.
158 *
159 * After the first call, those IDs will have a FOUND_BIT, but will not
160 * exist in any severity-specific list, so the second call will not
161 * impact them. This is undesirable but unavoidable given the API:
162 * The only entrypoint that gives a severity for a client-defined ID
163 * is the Insert() call.
164 *
165 * For the sake of Control(), we want to maintain the invariant
166 * that an ID will either appear in none of the three severity lists,
167 * or appear once, to minimize pointless duplication and potential surprises.
168 *
169 * Because Insert() is the only place that will learn an ID's severity,
170 * it should insert an ID into the appropriate list, but only if the ID
171 * doesn't exist in it or any other list yet. Because searching all three
172 * lists at O(n) is needlessly expensive, we store KNOWN_SEVERITY.
173 */
174 enum {
175 FOUND_BIT = 1 << 0,
176 ENABLED_BIT = 1 << 1,
177 KNOWN_SEVERITY = 1 << 2,
178
179 /* HashTable reserves zero as a return value meaning 'not found' */
180 NOT_FOUND = 0,
181 DISABLED = FOUND_BIT,
182 ENABLED = ENABLED_BIT | FOUND_BIT
183 };
184
185 /**
186 * Returns the state of the given message source/type/ID tuple.
187 */
188 static GLboolean
189 should_log(struct gl_context *ctx,
190 enum mesa_debug_source source,
191 enum mesa_debug_type type,
192 GLuint id,
193 enum mesa_debug_severity severity)
194 {
195 GLint gstack = ctx->Debug.GroupStackDepth;
196 struct gl_debug_namespace *nspace =
197 &ctx->Debug.Namespaces[gstack][source][type];
198 uintptr_t state;
199
200 if (!ctx->Debug.DebugOutput)
201 return GL_FALSE;
202
203 /* In addition to not being able to store zero as a value, HashTable also
204 can't use zero as a key. */
205 if (id)
206 state = (uintptr_t)_mesa_HashLookup(nspace->IDs, id);
207 else
208 state = nspace->ZeroID;
209
210 /* Only do this once for each ID. This makes sure the ID exists in,
211 at most, one list, and does not pointlessly appear multiple times. */
212 if (!(state & KNOWN_SEVERITY)) {
213 struct gl_debug_severity *entry;
214
215 if (state == NOT_FOUND) {
216 if (ctx->Debug.Defaults[gstack][severity][source][type])
217 state = ENABLED;
218 else
219 state = DISABLED;
220 }
221
222 entry = malloc(sizeof *entry);
223 if (!entry)
224 goto out;
225
226 state |= KNOWN_SEVERITY;
227
228 if (id)
229 _mesa_HashInsert(nspace->IDs, id, (void*)state);
230 else
231 nspace->ZeroID = state;
232
233 entry->ID = id;
234 insert_at_tail(&nspace->Severity[severity], &entry->link);
235 }
236
237 out:
238 return !!(state & ENABLED_BIT);
239 }
240
241 /**
242 * Sets the state of the given message source/type/ID tuple.
243 */
244 static void
245 set_message_state(struct gl_context *ctx,
246 enum mesa_debug_source source,
247 enum mesa_debug_type type,
248 GLuint id, GLboolean enabled)
249 {
250 GLint gstack = ctx->Debug.GroupStackDepth;
251 struct gl_debug_namespace *nspace =
252 &ctx->Debug.Namespaces[gstack][source][type];
253 uintptr_t state;
254
255 /* In addition to not being able to store zero as a value, HashTable also
256 can't use zero as a key. */
257 if (id)
258 state = (uintptr_t)_mesa_HashLookup(nspace->IDs, id);
259 else
260 state = nspace->ZeroID;
261
262 if (state == NOT_FOUND)
263 state = enabled ? ENABLED : DISABLED;
264 else {
265 if (enabled)
266 state |= ENABLED_BIT;
267 else
268 state &= ~ENABLED_BIT;
269 }
270
271 if (id)
272 _mesa_HashInsert(nspace->IDs, id, (void*)state);
273 else
274 nspace->ZeroID = state;
275 }
276
277 static void
278 store_message_details(struct gl_debug_msg *emptySlot,
279 enum mesa_debug_source source,
280 enum mesa_debug_type type, GLuint id,
281 enum mesa_debug_severity severity, GLint len,
282 const char *buf)
283 {
284 assert(!emptySlot->message && !emptySlot->length);
285
286 emptySlot->message = malloc(len+1);
287 if (emptySlot->message) {
288 (void) strncpy(emptySlot->message, buf, (size_t)len);
289 emptySlot->message[len] = '\0';
290
291 emptySlot->length = len+1;
292 emptySlot->source = source;
293 emptySlot->type = type;
294 emptySlot->id = id;
295 emptySlot->severity = severity;
296 } else {
297 static GLuint oom_msg_id = 0;
298 debug_get_id(&oom_msg_id);
299
300 /* malloc failed! */
301 emptySlot->message = out_of_memory;
302 emptySlot->length = strlen(out_of_memory)+1;
303 emptySlot->source = MESA_DEBUG_SOURCE_OTHER;
304 emptySlot->type = MESA_DEBUG_TYPE_ERROR;
305 emptySlot->id = oom_msg_id;
306 emptySlot->severity = MESA_DEBUG_SEVERITY_HIGH;
307 }
308 }
309
310 /**
311 * Remap any type exclusive to KHR_debug to something suitable
312 * for ARB_debug_output
313 */
314 inline static int
315 remap_type(GLenum type) {
316
317 switch(type) {
318 case GL_DEBUG_TYPE_MARKER:
319 case GL_DEBUG_TYPE_PUSH_GROUP:
320 case GL_DEBUG_TYPE_POP_GROUP:
321 type = GL_DEBUG_TYPE_OTHER;
322 default:
323 ;
324 }
325
326 return type;
327 }
328
329 /**
330 * Remap severity exclusive to KHR_debug to something suitable
331 * for ARB_debug_output
332 */
333 inline static int
334 remap_severity(GLenum severity) {
335
336 if (GL_DEBUG_SEVERITY_NOTIFICATION == severity)
337 severity = GL_DEBUG_SEVERITY_LOW;
338
339 return severity;
340 }
341
342 /**
343 * 'buf' is not necessarily a null-terminated string. When logging, copy
344 * 'len' characters from it, store them in a new, null-terminated string,
345 * and remember the number of bytes used by that string, *including*
346 * the null terminator this time.
347 */
348 static void
349 _mesa_log_msg(struct gl_context *ctx, enum mesa_debug_source source,
350 enum mesa_debug_type type, GLuint id,
351 enum mesa_debug_severity severity, GLint len, const char *buf)
352 {
353 GLint nextEmpty;
354 struct gl_debug_msg *emptySlot;
355
356 assert(len >= 0 && len < MAX_DEBUG_MESSAGE_LENGTH);
357
358 if (!should_log(ctx, source, type, id, severity))
359 return;
360
361 if (ctx->Debug.Callback) {
362 GLenum gl_type = debug_type_enums[type];
363 GLenum gl_severity = debug_severity_enums[severity];
364
365 if (ctx->Debug.ARBCallback) {
366 gl_severity = remap_severity(gl_severity);
367 gl_type = remap_type(gl_type);
368 }
369 ctx->Debug.Callback(debug_source_enums[source],
370 gl_type,
371 id,
372 gl_severity,
373 len, buf, ctx->Debug.CallbackData);
374 return;
375 }
376
377 if (ctx->Debug.NumMessages == MAX_DEBUG_LOGGED_MESSAGES)
378 return;
379
380 nextEmpty = (ctx->Debug.NextMsg + ctx->Debug.NumMessages)
381 % MAX_DEBUG_LOGGED_MESSAGES;
382 emptySlot = &ctx->Debug.Log[nextEmpty];
383
384 store_message_details(emptySlot, source, type, id, severity, len, buf);
385
386 if (ctx->Debug.NumMessages == 0)
387 ctx->Debug.NextMsgLength = ctx->Debug.Log[ctx->Debug.NextMsg].length;
388
389 ctx->Debug.NumMessages++;
390 }
391
392 /**
393 * Pop the oldest debug message out of the log.
394 * Writes the message string, including the null terminator, into 'buf',
395 * using up to 'bufSize' bytes. If 'bufSize' is too small, or
396 * if 'buf' is NULL, nothing is written.
397 *
398 * Returns the number of bytes written on success, or when 'buf' is NULL,
399 * the number that would have been written. A return value of 0
400 * indicates failure.
401 */
402 static GLsizei
403 _mesa_get_msg(struct gl_context *ctx, GLenum *source, GLenum *type,
404 GLuint *id, GLenum *severity, GLsizei bufSize, char *buf,
405 unsigned caller)
406 {
407 struct gl_debug_msg *msg;
408 GLsizei length;
409
410 if (ctx->Debug.NumMessages == 0)
411 return 0;
412
413 msg = &ctx->Debug.Log[ctx->Debug.NextMsg];
414 length = msg->length;
415
416 assert(length > 0 && length == ctx->Debug.NextMsgLength);
417
418 if (bufSize < length && buf != NULL)
419 return 0;
420
421 if (severity) {
422 *severity = debug_severity_enums[msg->severity];
423 if (caller == MESSAGE_LOG_ARB)
424 *severity = remap_severity(*severity);
425 }
426 if (source)
427 *source = debug_source_enums[msg->source];
428 if (type) {
429 *type = debug_type_enums[msg->type];
430 if (caller == MESSAGE_LOG_ARB)
431 *type = remap_type(*type);
432 }
433 if (id)
434 *id = msg->id;
435
436 if (buf) {
437 assert(msg->message[length-1] == '\0');
438 (void) strncpy(buf, msg->message, (size_t)length);
439 }
440
441 if (msg->message != (char*)out_of_memory)
442 free(msg->message);
443 msg->message = NULL;
444 msg->length = 0;
445
446 ctx->Debug.NumMessages--;
447 ctx->Debug.NextMsg++;
448 ctx->Debug.NextMsg %= MAX_DEBUG_LOGGED_MESSAGES;
449 ctx->Debug.NextMsgLength = ctx->Debug.Log[ctx->Debug.NextMsg].length;
450
451 return length;
452 }
453
454 /**
455 * Verify that source, type, and severity are valid enums.
456 * glDebugMessageInsertARB only accepts two values for 'source',
457 * and glDebugMessageControlARB will additionally accept GL_DONT_CARE
458 * in any parameter, so handle those cases specially.
459 *
460 * There is also special cases for handling values available in
461 * GL_KHR_debug that are not avaliable in GL_ARB_debug_output
462 */
463 static GLboolean
464 validate_params(struct gl_context *ctx, unsigned caller,
465 const char *callerstr, GLenum source, GLenum type,
466 GLenum severity)
467 {
468 #define INSERT 1
469 #define CONTROL 2
470 #define INSERT_ARB 3
471 #define CONTROL_ARB 4
472 switch(source) {
473 case GL_DEBUG_SOURCE_APPLICATION_ARB:
474 case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
475 break;
476 case GL_DEBUG_SOURCE_API_ARB:
477 case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
478 case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
479 case GL_DEBUG_SOURCE_OTHER_ARB:
480 if (caller != INSERT || caller == INSERT_ARB)
481 break;
482 case GL_DONT_CARE:
483 if (caller == CONTROL || caller == CONTROL_ARB)
484 break;
485 default:
486 goto error;
487 }
488
489 switch(type) {
490 case GL_DEBUG_TYPE_ERROR_ARB:
491 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
492 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
493 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
494 case GL_DEBUG_TYPE_PORTABILITY_ARB:
495 case GL_DEBUG_TYPE_OTHER_ARB:
496 break;
497 case GL_DEBUG_TYPE_MARKER:
498 /* this value is only valid for GL_KHR_debug functions */
499 if (caller == CONTROL || caller == INSERT)
500 break;
501 case GL_DONT_CARE:
502 if (caller == CONTROL || caller == CONTROL_ARB)
503 break;
504 default:
505 goto error;
506 }
507
508 switch(severity) {
509 case GL_DEBUG_SEVERITY_HIGH_ARB:
510 case GL_DEBUG_SEVERITY_MEDIUM_ARB:
511 case GL_DEBUG_SEVERITY_LOW_ARB:
512 break;
513 case GL_DEBUG_SEVERITY_NOTIFICATION:
514 /* this value is only valid for GL_KHR_debug functions */
515 if (caller == CONTROL || caller == INSERT)
516 break;
517 case GL_DONT_CARE:
518 if (caller == CONTROL || caller == CONTROL_ARB)
519 break;
520 default:
521 goto error;
522 }
523 return GL_TRUE;
524
525 error:
526 {
527 _mesa_error(ctx, GL_INVALID_ENUM, "bad values passed to %s"
528 "(source=0x%x, type=0x%x, severity=0x%x)", callerstr,
529 source, type, severity);
530 }
531 return GL_FALSE;
532 }
533
534 /**
535 * Set the state of all message IDs found in the given intersection of
536 * 'source', 'type', and 'severity'. The _COUNT enum can be used for
537 * GL_DONT_CARE (include all messages in the class).
538 *
539 * This requires both setting the state of all previously seen message
540 * IDs in the hash table, and setting the default state for all
541 * applicable combinations of source/type/severity, so that all the
542 * yet-unknown message IDs that may be used in the future will be
543 * impacted as if they were already known.
544 */
545 static void
546 control_messages(struct gl_context *ctx,
547 enum mesa_debug_source source,
548 enum mesa_debug_type type,
549 enum mesa_debug_severity severity,
550 GLboolean enabled)
551 {
552 int s, t, sev, smax, tmax, sevmax;
553 GLint gstack = ctx->Debug.GroupStackDepth;
554
555 if (source == MESA_DEBUG_SOURCE_COUNT) {
556 source = 0;
557 smax = MESA_DEBUG_SOURCE_COUNT;
558 } else {
559 smax = source+1;
560 }
561
562 if (type == MESA_DEBUG_TYPE_COUNT) {
563 type = 0;
564 tmax = MESA_DEBUG_TYPE_COUNT;
565 } else {
566 tmax = type+1;
567 }
568
569 if (severity == MESA_DEBUG_SEVERITY_COUNT) {
570 severity = 0;
571 sevmax = MESA_DEBUG_SEVERITY_COUNT;
572 } else {
573 sevmax = severity+1;
574 }
575
576 for (sev = severity; sev < sevmax; sev++)
577 for (s = source; s < smax; s++)
578 for (t = type; t < tmax; t++) {
579 struct simple_node *node;
580 struct gl_debug_severity *entry;
581
582 /* change the default for IDs we've never seen before. */
583 ctx->Debug.Defaults[gstack][sev][s][t] = enabled;
584
585 /* Now change the state of IDs we *have* seen... */
586 foreach(node, &ctx->Debug.Namespaces[gstack][s][t].Severity[sev]) {
587 entry = (struct gl_debug_severity *)node;
588 set_message_state(ctx, s, t, entry->ID, enabled);
589 }
590 }
591 }
592
593 /**
594 * Debugging-message namespaces with the source APPLICATION or THIRD_PARTY
595 * require special handling, since the IDs in them are controlled by clients,
596 * not the OpenGL implementation.
597 *
598 * 'count' is the length of the array 'ids'. If 'count' is nonzero, all
599 * the given IDs in the namespace defined by 'esource' and 'etype'
600 * will be affected.
601 *
602 * If 'count' is zero, this sets the state of all IDs that match
603 * the combination of 'esource', 'etype', and 'eseverity'.
604 */
605 static void
606 control_app_messages(struct gl_context *ctx, GLenum esource, GLenum etype,
607 GLenum eseverity, GLsizei count, const GLuint *ids,
608 GLboolean enabled)
609 {
610 GLsizei i;
611 enum mesa_debug_source source = gl_enum_to_debug_source(esource);
612 enum mesa_debug_type type = gl_enum_to_debug_type(etype);
613 enum mesa_debug_severity severity = gl_enum_to_debug_severity(eseverity);
614
615 for (i = 0; i < count; i++)
616 set_message_state(ctx, source, type, ids[i], enabled);
617
618 if (count)
619 return;
620
621 control_messages(ctx, source, type, severity, enabled);
622 }
623
624 /**
625 * This is a generic message control function for use by both
626 * glDebugMessageControlARB and glDebugMessageControl.
627 */
628 static void
629 message_control(GLenum gl_source, GLenum gl_type,
630 GLenum gl_severity,
631 GLsizei count, const GLuint *ids,
632 GLboolean enabled,
633 unsigned caller, const char *callerstr)
634 {
635 GET_CURRENT_CONTEXT(ctx);
636
637 if (count < 0) {
638 _mesa_error(ctx, GL_INVALID_VALUE,
639 "%s(count=%d : count must not be negative)", callerstr,
640 count);
641 return;
642 }
643
644 if (!validate_params(ctx, caller, callerstr, gl_source, gl_type,
645 gl_severity))
646 return; /* GL_INVALID_ENUM */
647
648 if (count && (gl_severity != GL_DONT_CARE || gl_type == GL_DONT_CARE
649 || gl_source == GL_DONT_CARE)) {
650 _mesa_error(ctx, GL_INVALID_OPERATION,
651 "%s(When passing an array of ids, severity must be"
652 " GL_DONT_CARE, and source and type must not be GL_DONT_CARE.",
653 callerstr);
654 return;
655 }
656
657 control_app_messages(ctx, gl_source, gl_type, gl_severity,
658 count, ids, enabled);
659 }
660
661 /**
662 * This is a generic message insert function.
663 * Validation of source, type and severity parameters should be done
664 * before calling this funtion.
665 */
666 static void
667 message_insert(GLenum source, GLenum type, GLuint id,
668 GLenum severity, GLint length, const GLchar* buf,
669 const char *callerstr)
670 {
671 GET_CURRENT_CONTEXT(ctx);
672
673 if (length < 0)
674 length = strlen(buf);
675
676 if (length >= MAX_DEBUG_MESSAGE_LENGTH) {
677 _mesa_error(ctx, GL_INVALID_VALUE,
678 "%s(length=%d, which is not less than "
679 "GL_MAX_DEBUG_MESSAGE_LENGTH=%d)", callerstr, length,
680 MAX_DEBUG_MESSAGE_LENGTH);
681 return;
682 }
683
684 _mesa_log_msg(ctx,
685 gl_enum_to_debug_source(source),
686 gl_enum_to_debug_type(type), id,
687 gl_enum_to_debug_severity(severity), length, buf);
688 }
689
690 /**
691 * This is a generic message insert function for use by both
692 * glGetDebugMessageLogARB and glGetDebugMessageLog.
693 */
694 static GLuint
695 get_message_log(GLuint count, GLsizei logSize, GLenum* sources,
696 GLenum* types, GLenum* ids, GLenum* severities,
697 GLsizei* lengths, GLchar* messageLog,
698 unsigned caller, const char *callerstr)
699 {
700 GET_CURRENT_CONTEXT(ctx);
701 GLuint ret;
702
703 if (!messageLog)
704 logSize = 0;
705
706 if (logSize < 0) {
707 _mesa_error(ctx, GL_INVALID_VALUE,
708 "%s(logSize=%d : logSize must not be negative)", callerstr,
709 logSize);
710 return 0;
711 }
712
713 for (ret = 0; ret < count; ret++) {
714 GLsizei written = _mesa_get_msg(ctx, sources, types, ids, severities,
715 logSize, messageLog, caller);
716 if (!written)
717 break;
718
719 if (messageLog) {
720 messageLog += written;
721 logSize -= written;
722 }
723 if (lengths) {
724 *lengths = written;
725 lengths++;
726 }
727
728 if (severities)
729 severities++;
730 if (sources)
731 sources++;
732 if (types)
733 types++;
734 if (ids)
735 ids++;
736 }
737
738 return ret;
739 }
740
741 static void
742 do_nothing(GLuint key, void *data, void *userData)
743 {
744 }
745
746 static void
747 free_errors_data(struct gl_context *ctx, GLint gstack)
748 {
749 enum mesa_debug_type t;
750 enum mesa_debug_source s;
751 enum mesa_debug_severity sev;
752
753 /* Tear down state for filtering debug messages. */
754 for (s = 0; s < MESA_DEBUG_SOURCE_COUNT; s++)
755 for (t = 0; t < MESA_DEBUG_TYPE_COUNT; t++) {
756 _mesa_HashDeleteAll(ctx->Debug.Namespaces[gstack][s][t].IDs,
757 do_nothing, NULL);
758 _mesa_DeleteHashTable(ctx->Debug.Namespaces[gstack][s][t].IDs);
759 for (sev = 0; sev < MESA_DEBUG_SEVERITY_COUNT; sev++) {
760 struct simple_node *node, *tmp;
761 struct gl_debug_severity *entry;
762
763 foreach_s(node, tmp,
764 &ctx->Debug.Namespaces[gstack][s][t].Severity[sev]) {
765 entry = (struct gl_debug_severity *)node;
766 free(entry);
767 }
768 }
769 }
770 }
771
772 void GLAPIENTRY
773 _mesa_DebugMessageInsert(GLenum source, GLenum type, GLuint id,
774 GLenum severity, GLint length,
775 const GLchar* buf)
776 {
777 const char *callerstr = "glDebugMessageInsert";
778
779 GET_CURRENT_CONTEXT(ctx);
780
781 if (!validate_params(ctx, INSERT, callerstr, source, type, severity))
782 return; /* GL_INVALID_ENUM */
783
784 message_insert(source, type, id, severity, length, buf,
785 callerstr);
786 }
787
788 GLuint GLAPIENTRY
789 _mesa_GetDebugMessageLog(GLuint count, GLsizei logSize, GLenum* sources,
790 GLenum* types, GLenum* ids, GLenum* severities,
791 GLsizei* lengths, GLchar* messageLog)
792 {
793 const char *callerstr = "glGetDebugMessageLog";
794
795 return get_message_log(count, logSize, sources, types, ids, severities,
796 lengths, messageLog, MESSAGE_LOG, callerstr);
797 }
798
799 void GLAPIENTRY
800 _mesa_DebugMessageControl(GLenum source, GLenum type, GLenum severity,
801 GLsizei count, const GLuint *ids,
802 GLboolean enabled)
803 {
804 const char *callerstr = "glDebugMessageControl";
805
806 message_control(source, type, severity, count, ids,
807 enabled, CONTROL, callerstr);
808 }
809
810 void GLAPIENTRY
811 _mesa_DebugMessageCallback(GLDEBUGPROC callback, const void *userParam)
812 {
813 GET_CURRENT_CONTEXT(ctx);
814 ctx->Debug.Callback = callback;
815 ctx->Debug.CallbackData = userParam;
816 ctx->Debug.ARBCallback = GL_FALSE;
817 }
818
819 void GLAPIENTRY
820 _mesa_PushDebugGroup(GLenum source, GLuint id, GLsizei length,
821 const GLchar *message)
822 {
823 const char *callerstr = "glPushDebugGroup";
824 int s, t, sev;
825 GLint prevStackDepth;
826 GLint currStackDepth;
827 struct gl_debug_msg *emptySlot;
828
829 GET_CURRENT_CONTEXT(ctx);
830
831 if (ctx->Debug.GroupStackDepth >= MAX_DEBUG_GROUP_STACK_DEPTH-1) {
832 _mesa_error(ctx, GL_STACK_OVERFLOW, "%s", callerstr);
833 return;
834 }
835
836 switch(source) {
837 case GL_DEBUG_SOURCE_APPLICATION:
838 case GL_DEBUG_SOURCE_THIRD_PARTY:
839 break;
840 default:
841 _mesa_error(ctx, GL_INVALID_ENUM, "bad value passed to %s"
842 "(source=0x%x)", callerstr, source);
843 return;
844 }
845
846 message_insert(source, GL_DEBUG_TYPE_PUSH_GROUP, id,
847 GL_DEBUG_SEVERITY_NOTIFICATION, length,
848 message, callerstr);
849
850 prevStackDepth = ctx->Debug.GroupStackDepth;
851 ctx->Debug.GroupStackDepth++;
852 currStackDepth = ctx->Debug.GroupStackDepth;
853
854 /* pop reuses the message details from push so we store this */
855 if (length < 0)
856 length = strlen(message);
857 emptySlot = &ctx->Debug.DebugGroupMsgs[ctx->Debug.GroupStackDepth];
858 store_message_details(emptySlot, gl_enum_to_debug_source(source),
859 gl_enum_to_debug_type(GL_DEBUG_TYPE_PUSH_GROUP),
860 id,
861 gl_enum_to_debug_severity(GL_DEBUG_SEVERITY_NOTIFICATION),
862 length, message);
863
864 /* inherit the control volume of the debug group previously residing on
865 * the top of the debug group stack
866 */
867 for (s = 0; s < MESA_DEBUG_SOURCE_COUNT; s++)
868 for (t = 0; t < MESA_DEBUG_TYPE_COUNT; t++) {
869 /* copy id settings */
870 ctx->Debug.Namespaces[currStackDepth][s][t].IDs =
871 _mesa_HashClone(ctx->Debug.Namespaces[prevStackDepth][s][t].IDs);
872
873 for (sev = 0; sev < MESA_DEBUG_SEVERITY_COUNT; sev++) {
874 struct gl_debug_severity *entry, *prevEntry;
875 struct simple_node *node;
876
877 /* copy default settings for unknown ids */
878 ctx->Debug.Defaults[currStackDepth][sev][s][t] = ctx->Debug.Defaults[prevStackDepth][sev][s][t];
879
880 /* copy known id severity settings */
881 make_empty_list(&ctx->Debug.Namespaces[currStackDepth][s][t].Severity[sev]);
882 foreach(node, &ctx->Debug.Namespaces[prevStackDepth][s][t].Severity[sev]) {
883 prevEntry = (struct gl_debug_severity *)node;
884 entry = malloc(sizeof *entry);
885 if (!entry)
886 return;
887
888 entry->ID = prevEntry->ID;
889 insert_at_tail(&ctx->Debug.Namespaces[currStackDepth][s][t].Severity[sev], &entry->link);
890 }
891 }
892 }
893 }
894
895 void GLAPIENTRY
896 _mesa_PopDebugGroup()
897 {
898 const char *callerstr = "glPopDebugGroup";
899 struct gl_debug_msg *gdmessage;
900 GLint prevStackDepth;
901
902 GET_CURRENT_CONTEXT(ctx);
903
904 if (ctx->Debug.GroupStackDepth <= 0) {
905 _mesa_error(ctx, GL_STACK_UNDERFLOW, "%s", callerstr);
906 return;
907 }
908
909 prevStackDepth = ctx->Debug.GroupStackDepth;
910 ctx->Debug.GroupStackDepth--;
911
912 gdmessage = &ctx->Debug.DebugGroupMsgs[prevStackDepth];
913 /* using _mesa_log_msg() directly here as verification of parameters
914 * already done in push
915 */
916 _mesa_log_msg(ctx, gdmessage->source,
917 gl_enum_to_debug_type(GL_DEBUG_TYPE_POP_GROUP),
918 gdmessage->id,
919 gl_enum_to_debug_severity(GL_DEBUG_SEVERITY_NOTIFICATION),
920 gdmessage->length, gdmessage->message);
921
922 if (gdmessage->message != (char*)out_of_memory)
923 free(gdmessage->message);
924 gdmessage->message = NULL;
925 gdmessage->length = 0;
926
927 /* free popped debug group data */
928 free_errors_data(ctx, prevStackDepth);
929 }
930
931 void GLAPIENTRY
932 _mesa_DebugMessageInsertARB(GLenum source, GLenum type, GLuint id,
933 GLenum severity, GLint length,
934 const GLcharARB* buf)
935 {
936 const char *callerstr = "glDebugMessageInsertARB";
937
938 GET_CURRENT_CONTEXT(ctx);
939
940 if (!validate_params(ctx, INSERT_ARB, callerstr, source, type, severity))
941 return; /* GL_INVALID_ENUM */
942
943 message_insert(source, type, id, severity, length, buf,
944 callerstr);
945 }
946
947 GLuint GLAPIENTRY
948 _mesa_GetDebugMessageLogARB(GLuint count, GLsizei logSize, GLenum* sources,
949 GLenum* types, GLenum* ids, GLenum* severities,
950 GLsizei* lengths, GLcharARB* messageLog)
951 {
952 const char *callerstr = "glGetDebugMessageLogARB";
953
954 return get_message_log(count, logSize, sources, types, ids, severities,
955 lengths, messageLog, MESSAGE_LOG_ARB, callerstr);
956 }
957
958 void GLAPIENTRY
959 _mesa_DebugMessageControlARB(GLenum gl_source, GLenum gl_type,
960 GLenum gl_severity,
961 GLsizei count, const GLuint *ids,
962 GLboolean enabled)
963 {
964 const char *callerstr = "glDebugMessageControlARB";
965
966 message_control(gl_source, gl_type, gl_severity, count, ids,
967 enabled, CONTROL_ARB, callerstr);
968 }
969
970 void GLAPIENTRY
971 _mesa_DebugMessageCallbackARB(GLDEBUGPROCARB callback, const void *userParam)
972 {
973 GET_CURRENT_CONTEXT(ctx);
974 ctx->Debug.Callback = callback;
975 ctx->Debug.CallbackData = userParam;
976 ctx->Debug.ARBCallback = GL_TRUE;
977 }
978
979 void
980 _mesa_init_errors(struct gl_context *ctx)
981 {
982 int s, t, sev;
983
984 ctx->Debug.Callback = NULL;
985 ctx->Debug.SyncOutput = GL_FALSE;
986 ctx->Debug.Log[0].length = 0;
987 ctx->Debug.NumMessages = 0;
988 ctx->Debug.NextMsg = 0;
989 ctx->Debug.NextMsgLength = 0;
990 ctx->Debug.GroupStackDepth = 0;
991
992 /* Enable all the messages with severity HIGH or MEDIUM by default. */
993 memset(ctx->Debug.Defaults[0][MESA_DEBUG_SEVERITY_HIGH], GL_TRUE,
994 sizeof ctx->Debug.Defaults[0][MESA_DEBUG_SEVERITY_HIGH]);
995 memset(ctx->Debug.Defaults[0][MESA_DEBUG_SEVERITY_MEDIUM], GL_TRUE,
996 sizeof ctx->Debug.Defaults[0][MESA_DEBUG_SEVERITY_MEDIUM]);
997 memset(ctx->Debug.Defaults[0][MESA_DEBUG_SEVERITY_LOW], GL_FALSE,
998 sizeof ctx->Debug.Defaults[0][MESA_DEBUG_SEVERITY_LOW]);
999
1000 /* Initialize state for filtering known debug messages. */
1001 for (s = 0; s < MESA_DEBUG_SOURCE_COUNT; s++)
1002 for (t = 0; t < MESA_DEBUG_TYPE_COUNT; t++) {
1003 ctx->Debug.Namespaces[0][s][t].IDs = _mesa_NewHashTable();
1004 assert(ctx->Debug.Namespaces[0][s][t].IDs);
1005
1006 for (sev = 0; sev < MESA_DEBUG_SEVERITY_COUNT; sev++)
1007 make_empty_list(&ctx->Debug.Namespaces[0][s][t].Severity[sev]);
1008 }
1009 }
1010
1011 /**
1012 * Loop through debug group stack tearing down states for
1013 * filtering debug messages.
1014 */
1015 void
1016 _mesa_free_errors_data(struct gl_context *ctx)
1017 {
1018 GLint i;
1019
1020 for (i = 0; i <= ctx->Debug.GroupStackDepth; i++) {
1021 free_errors_data(ctx, i);
1022 }
1023 }
1024
1025 /**********************************************************************/
1026 /** \name Diagnostics */
1027 /*@{*/
1028
1029 static void
1030 output_if_debug(const char *prefixString, const char *outputString,
1031 GLboolean newline)
1032 {
1033 static int debug = -1;
1034 static FILE *fout = NULL;
1035
1036 /* Init the local 'debug' var once.
1037 * Note: the _mesa_init_debug() function should have been called
1038 * by now so MESA_DEBUG_FLAGS will be initialized.
1039 */
1040 if (debug == -1) {
1041 /* If MESA_LOG_FILE env var is set, log Mesa errors, warnings,
1042 * etc to the named file. Otherwise, output to stderr.
1043 */
1044 const char *logFile = _mesa_getenv("MESA_LOG_FILE");
1045 if (logFile)
1046 fout = fopen(logFile, "w");
1047 if (!fout)
1048 fout = stderr;
1049 #ifdef DEBUG
1050 /* in debug builds, print messages unless MESA_DEBUG="silent" */
1051 if (MESA_DEBUG_FLAGS & DEBUG_SILENT)
1052 debug = 0;
1053 else
1054 debug = 1;
1055 #else
1056 /* in release builds, be silent unless MESA_DEBUG is set */
1057 debug = _mesa_getenv("MESA_DEBUG") != NULL;
1058 #endif
1059 }
1060
1061 /* Now only print the string if we're required to do so. */
1062 if (debug) {
1063 fprintf(fout, "%s: %s", prefixString, outputString);
1064 if (newline)
1065 fprintf(fout, "\n");
1066 fflush(fout);
1067
1068 #if defined(_WIN32) && !defined(_WIN32_WCE)
1069 /* stderr from windows applications without console is not usually
1070 * visible, so communicate with the debugger instead */
1071 {
1072 char buf[4096];
1073 _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
1074 OutputDebugStringA(buf);
1075 }
1076 #endif
1077 }
1078 }
1079
1080 /**
1081 * When a new type of error is recorded, print a message describing
1082 * previous errors which were accumulated.
1083 */
1084 static void
1085 flush_delayed_errors( struct gl_context *ctx )
1086 {
1087 char s[MAX_DEBUG_MESSAGE_LENGTH];
1088
1089 if (ctx->ErrorDebugCount) {
1090 _mesa_snprintf(s, MAX_DEBUG_MESSAGE_LENGTH, "%d similar %s errors",
1091 ctx->ErrorDebugCount,
1092 _mesa_lookup_enum_by_nr(ctx->ErrorValue));
1093
1094 output_if_debug("Mesa", s, GL_TRUE);
1095
1096 ctx->ErrorDebugCount = 0;
1097 }
1098 }
1099
1100
1101 /**
1102 * Report a warning (a recoverable error condition) to stderr if
1103 * either DEBUG is defined or the MESA_DEBUG env var is set.
1104 *
1105 * \param ctx GL context.
1106 * \param fmtString printf()-like format string.
1107 */
1108 void
1109 _mesa_warning( struct gl_context *ctx, const char *fmtString, ... )
1110 {
1111 char str[MAX_DEBUG_MESSAGE_LENGTH];
1112 va_list args;
1113 va_start( args, fmtString );
1114 (void) _mesa_vsnprintf( str, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args );
1115 va_end( args );
1116
1117 if (ctx)
1118 flush_delayed_errors( ctx );
1119
1120 output_if_debug("Mesa warning", str, GL_TRUE);
1121 }
1122
1123
1124 /**
1125 * Report an internal implementation problem.
1126 * Prints the message to stderr via fprintf().
1127 *
1128 * \param ctx GL context.
1129 * \param fmtString problem description string.
1130 */
1131 void
1132 _mesa_problem( const struct gl_context *ctx, const char *fmtString, ... )
1133 {
1134 va_list args;
1135 char str[MAX_DEBUG_MESSAGE_LENGTH];
1136 static int numCalls = 0;
1137
1138 (void) ctx;
1139
1140 if (numCalls < 50) {
1141 numCalls++;
1142
1143 va_start( args, fmtString );
1144 _mesa_vsnprintf( str, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args );
1145 va_end( args );
1146 fprintf(stderr, "Mesa %s implementation error: %s\n",
1147 PACKAGE_VERSION, str);
1148 fprintf(stderr, "Please report at " PACKAGE_BUGREPORT "\n");
1149 }
1150 }
1151
1152 static GLboolean
1153 should_output(struct gl_context *ctx, GLenum error, const char *fmtString)
1154 {
1155 static GLint debug = -1;
1156
1157 /* Check debug environment variable only once:
1158 */
1159 if (debug == -1) {
1160 const char *debugEnv = _mesa_getenv("MESA_DEBUG");
1161
1162 #ifdef DEBUG
1163 if (debugEnv && strstr(debugEnv, "silent"))
1164 debug = GL_FALSE;
1165 else
1166 debug = GL_TRUE;
1167 #else
1168 if (debugEnv)
1169 debug = GL_TRUE;
1170 else
1171 debug = GL_FALSE;
1172 #endif
1173 }
1174
1175 if (debug) {
1176 if (ctx->ErrorValue != error ||
1177 ctx->ErrorDebugFmtString != fmtString) {
1178 flush_delayed_errors( ctx );
1179 ctx->ErrorDebugFmtString = fmtString;
1180 ctx->ErrorDebugCount = 0;
1181 return GL_TRUE;
1182 }
1183 ctx->ErrorDebugCount++;
1184 }
1185 return GL_FALSE;
1186 }
1187
1188 void
1189 _mesa_gl_debug(struct gl_context *ctx,
1190 GLuint *id,
1191 enum mesa_debug_type type,
1192 enum mesa_debug_severity severity,
1193 const char *fmtString, ...)
1194 {
1195 char s[MAX_DEBUG_MESSAGE_LENGTH];
1196 int len;
1197 va_list args;
1198
1199 debug_get_id(id);
1200
1201 va_start(args, fmtString);
1202 len = _mesa_vsnprintf(s, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args);
1203 va_end(args);
1204
1205 _mesa_log_msg(ctx, MESA_DEBUG_SOURCE_API, type,
1206 *id, severity, len, s);
1207 }
1208
1209
1210 /**
1211 * Record an OpenGL state error. These usually occur when the user
1212 * passes invalid parameters to a GL function.
1213 *
1214 * If debugging is enabled (either at compile-time via the DEBUG macro, or
1215 * run-time via the MESA_DEBUG environment variable), report the error with
1216 * _mesa_debug().
1217 *
1218 * \param ctx the GL context.
1219 * \param error the error value.
1220 * \param fmtString printf() style format string, followed by optional args
1221 */
1222 void
1223 _mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... )
1224 {
1225 GLboolean do_output, do_log;
1226 /* Ideally this would be set up by the caller, so that we had proper IDs
1227 * per different message.
1228 */
1229 static GLuint error_msg_id = 0;
1230
1231 debug_get_id(&error_msg_id);
1232
1233 do_output = should_output(ctx, error, fmtString);
1234 do_log = should_log(ctx,
1235 MESA_DEBUG_SOURCE_API,
1236 MESA_DEBUG_TYPE_ERROR,
1237 error_msg_id,
1238 MESA_DEBUG_SEVERITY_HIGH);
1239
1240 if (do_output || do_log) {
1241 char s[MAX_DEBUG_MESSAGE_LENGTH], s2[MAX_DEBUG_MESSAGE_LENGTH];
1242 int len;
1243 va_list args;
1244
1245 va_start(args, fmtString);
1246 len = _mesa_vsnprintf(s, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args);
1247 va_end(args);
1248
1249 if (len >= MAX_DEBUG_MESSAGE_LENGTH) {
1250 /* Too long error message. Whoever calls _mesa_error should use
1251 * shorter strings. */
1252 ASSERT(0);
1253 return;
1254 }
1255
1256 len = _mesa_snprintf(s2, MAX_DEBUG_MESSAGE_LENGTH, "%s in %s",
1257 _mesa_lookup_enum_by_nr(error), s);
1258 if (len >= MAX_DEBUG_MESSAGE_LENGTH) {
1259 /* Same as above. */
1260 ASSERT(0);
1261 return;
1262 }
1263
1264 /* Print the error to stderr if needed. */
1265 if (do_output) {
1266 output_if_debug("Mesa: User error", s2, GL_TRUE);
1267 }
1268
1269 /* Log the error via ARB_debug_output if needed.*/
1270 if (do_log) {
1271 _mesa_log_msg(ctx,
1272 MESA_DEBUG_SOURCE_API,
1273 MESA_DEBUG_TYPE_ERROR,
1274 error_msg_id,
1275 MESA_DEBUG_SEVERITY_HIGH, len, s2);
1276 }
1277 }
1278
1279 /* Set the GL context error state for glGetError. */
1280 _mesa_record_error(ctx, error);
1281 }
1282
1283
1284 /**
1285 * Report debug information. Print error message to stderr via fprintf().
1286 * No-op if DEBUG mode not enabled.
1287 *
1288 * \param ctx GL context.
1289 * \param fmtString printf()-style format string, followed by optional args.
1290 */
1291 void
1292 _mesa_debug( const struct gl_context *ctx, const char *fmtString, ... )
1293 {
1294 #ifdef DEBUG
1295 char s[MAX_DEBUG_MESSAGE_LENGTH];
1296 va_list args;
1297 va_start(args, fmtString);
1298 _mesa_vsnprintf(s, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args);
1299 va_end(args);
1300 output_if_debug("Mesa", s, GL_FALSE);
1301 #endif /* DEBUG */
1302 (void) ctx;
1303 (void) fmtString;
1304 }
1305
1306
1307 /**
1308 * Report debug information from the shader compiler via GL_ARB_debug_output.
1309 *
1310 * \param ctx GL context.
1311 * \param type The namespace to which this message belongs.
1312 * \param id The message ID within the given namespace.
1313 * \param msg The message to output. Need not be null-terminated.
1314 * \param len The length of 'msg'. If negative, 'msg' must be null-terminated.
1315 */
1316 void
1317 _mesa_shader_debug( struct gl_context *ctx, GLenum type, GLuint *id,
1318 const char *msg, int len )
1319 {
1320 enum mesa_debug_source source = MESA_DEBUG_SOURCE_SHADER_COMPILER;
1321 enum mesa_debug_severity severity = MESA_DEBUG_SEVERITY_HIGH;
1322
1323 debug_get_id(id);
1324
1325 if (len < 0)
1326 len = strlen(msg);
1327
1328 /* Truncate the message if necessary. */
1329 if (len >= MAX_DEBUG_MESSAGE_LENGTH)
1330 len = MAX_DEBUG_MESSAGE_LENGTH - 1;
1331
1332 _mesa_log_msg(ctx, source, type, *id, severity, len, msg);
1333 }
1334
1335 /*@}*/