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