mesa: Replace open-coded _mesa_lookup_enum_by_nr().
[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 * Version: 7.1
9 *
10 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
11 *
12 * Permission is hereby granted, free of charge, to any person obtaining a
13 * copy of this software and associated documentation files (the "Software"),
14 * to deal in the Software without restriction, including without limitation
15 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
16 * and/or sell copies of the Software, and to permit persons to whom the
17 * Software is furnished to do so, subject to the following conditions:
18 *
19 * The above copyright notice and this permission notice shall be included
20 * in all copies or substantial portions of the Software.
21 *
22 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
26 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
27 * CONNECTION WITH THE SOFTWARE OR THE USE OR 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
40
41
42 struct gl_client_severity
43 {
44 struct simple_node link;
45 GLuint ID;
46 };
47
48 static char out_of_memory[] = "Debugging error: out of memory";
49
50 #define enum_is(e, kind1, kind2) \
51 ((e) == GL_DEBUG_##kind1##_##kind2##_ARB || (e) == GL_DONT_CARE)
52 #define severity_is(sev, kind) enum_is(sev, SEVERITY, kind)
53 #define source_is(s, kind) enum_is(s, SOURCE, kind)
54 #define type_is(t, kind) enum_is(t, TYPE, kind)
55
56 /* Prevent define collision on Windows */
57 #undef ERROR
58
59 enum {
60 SOURCE_APPLICATION,
61 SOURCE_THIRD_PARTY,
62
63 SOURCE_COUNT,
64 SOURCE_ANY = -1
65 };
66
67 enum {
68 TYPE_ERROR,
69 TYPE_DEPRECATED,
70 TYPE_UNDEFINED,
71 TYPE_PORTABILITY,
72 TYPE_PERFORMANCE,
73 TYPE_OTHER,
74
75 TYPE_COUNT,
76 TYPE_ANY = -1
77 };
78
79 enum {
80 SEVERITY_LOW,
81 SEVERITY_MEDIUM,
82 SEVERITY_HIGH,
83
84 SEVERITY_COUNT,
85 SEVERITY_ANY = -1
86 };
87
88 static int
89 enum_to_index(GLenum e)
90 {
91 switch (e) {
92 case GL_DEBUG_SOURCE_APPLICATION_ARB:
93 return (int)SOURCE_APPLICATION;
94 case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
95 return (int)SOURCE_THIRD_PARTY;
96
97 case GL_DEBUG_TYPE_ERROR_ARB:
98 return (int)TYPE_ERROR;
99 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
100 return (int)TYPE_DEPRECATED;
101 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
102 return (int)TYPE_UNDEFINED;
103 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
104 return (int)TYPE_PERFORMANCE;
105 case GL_DEBUG_TYPE_PORTABILITY_ARB:
106 return (int)TYPE_PORTABILITY;
107 case GL_DEBUG_TYPE_OTHER_ARB:
108 return (int)TYPE_OTHER;
109
110 case GL_DEBUG_SEVERITY_LOW_ARB:
111 return (int)SEVERITY_LOW;
112 case GL_DEBUG_SEVERITY_MEDIUM_ARB:
113 return (int)SEVERITY_MEDIUM;
114 case GL_DEBUG_SEVERITY_HIGH_ARB:
115 return (int)SEVERITY_HIGH;
116
117 case GL_DONT_CARE:
118 return (int)TYPE_ANY;
119
120 default:
121 assert(0 && "unreachable");
122 return -2;
123 };
124 }
125
126
127 /*
128 * We store a bitfield in the hash table, with five possible values total.
129 *
130 * The ENABLED_BIT's purpose is self-explanatory.
131 *
132 * The FOUND_BIT is needed to differentiate the value of DISABLED from
133 * the value returned by HashTableLookup() when it can't find the given key.
134 *
135 * The KNOWN_SEVERITY bit is a bit complicated:
136 *
137 * A client may call Control() with an array of IDs, then call Control()
138 * on all message IDs of a certain severity, then Insert() one of the
139 * previously specified IDs, giving us a known severity level, then call
140 * Control() on all message IDs of a certain severity level again.
141 *
142 * After the first call, those IDs will have a FOUND_BIT, but will not
143 * exist in any severity-specific list, so the second call will not
144 * impact them. This is undesirable but unavoidable given the API:
145 * The only entrypoint that gives a severity for a client-defined ID
146 * is the Insert() call.
147 *
148 * For the sake of Control(), we want to maintain the invariant
149 * that an ID will either appear in none of the three severity lists,
150 * or appear once, to minimize pointless duplication and potential surprises.
151 *
152 * Because Insert() is the only place that will learn an ID's severity,
153 * it should insert an ID into the appropriate list, but only if the ID
154 * doesn't exist in it or any other list yet. Because searching all three
155 * lists at O(n) is needlessly expensive, we store KNOWN_SEVERITY.
156 */
157 enum {
158 FOUND_BIT = 1 << 0,
159 ENABLED_BIT = 1 << 1,
160 KNOWN_SEVERITY = 1 << 2,
161
162 /* HashTable reserves zero as a return value meaning 'not found' */
163 NOT_FOUND = 0,
164 DISABLED = FOUND_BIT,
165 ENABLED = ENABLED_BIT | FOUND_BIT
166 };
167
168 /**
169 * Returns the state of the given message ID in a client-controlled
170 * namespace.
171 * 'source', 'type', and 'severity' are array indices like TYPE_ERROR,
172 * not GL enums.
173 */
174 static GLboolean
175 get_message_state(struct gl_context *ctx, int source, int type,
176 GLuint id, int severity)
177 {
178 struct gl_client_namespace *nspace =
179 &ctx->Debug.ClientIDs.Namespaces[source][type];
180 uintptr_t state;
181
182 /* In addition to not being able to store zero as a value, HashTable also
183 can't use zero as a key. */
184 if (id)
185 state = (uintptr_t)_mesa_HashLookup(nspace->IDs, id);
186 else
187 state = nspace->ZeroID;
188
189 /* Only do this once for each ID. This makes sure the ID exists in,
190 at most, one list, and does not pointlessly appear multiple times. */
191 if (!(state & KNOWN_SEVERITY)) {
192 struct gl_client_severity *entry;
193
194 if (state == NOT_FOUND) {
195 if (ctx->Debug.ClientIDs.Defaults[severity][source][type])
196 state = ENABLED;
197 else
198 state = DISABLED;
199 }
200
201 entry = malloc(sizeof *entry);
202 if (!entry)
203 goto out;
204
205 state |= KNOWN_SEVERITY;
206
207 if (id)
208 _mesa_HashInsert(nspace->IDs, id, (void*)state);
209 else
210 nspace->ZeroID = state;
211
212 entry->ID = id;
213 insert_at_tail(&nspace->Severity[severity], &entry->link);
214 }
215
216 out:
217 return !!(state & ENABLED_BIT);
218 }
219
220 /**
221 * Sets the state of the given message ID in a client-controlled
222 * namespace.
223 * 'source' and 'type' are array indices like TYPE_ERROR, not GL enums.
224 */
225 static void
226 set_message_state(struct gl_context *ctx, int source, int type,
227 GLuint id, GLboolean enabled)
228 {
229 struct gl_client_namespace *nspace =
230 &ctx->Debug.ClientIDs.Namespaces[source][type];
231 uintptr_t state;
232
233 /* In addition to not being able to store zero as a value, HashTable also
234 can't use zero as a key. */
235 if (id)
236 state = (uintptr_t)_mesa_HashLookup(nspace->IDs, id);
237 else
238 state = nspace->ZeroID;
239
240 if (state == NOT_FOUND)
241 state = enabled ? ENABLED : DISABLED;
242 else {
243 if (enabled)
244 state |= ENABLED_BIT;
245 else
246 state &= ~ENABLED_BIT;
247 }
248
249 if (id)
250 _mesa_HashInsert(nspace->IDs, id, (void*)state);
251 else
252 nspace->ZeroID = state;
253 }
254
255 /**
256 * Whether a debugging message should be logged or not.
257 * For implementation-controlled namespaces, we keep an array
258 * of booleans per namespace, per context, recording whether
259 * each individual message is enabled or not. The message ID
260 * is an index into the namespace's array.
261 */
262 static GLboolean
263 should_log(struct gl_context *ctx, GLenum source, GLenum type,
264 GLuint id, GLenum severity)
265 {
266 if (source == GL_DEBUG_SOURCE_APPLICATION_ARB ||
267 source == GL_DEBUG_SOURCE_THIRD_PARTY_ARB) {
268 int s, t, sev;
269 s = enum_to_index(source);
270 t = enum_to_index(type);
271 sev = enum_to_index(severity);
272
273 return get_message_state(ctx, s, t, sev, id);
274 }
275
276 if (type_is(type, ERROR)) {
277 if (source_is(source, API))
278 return ctx->Debug.ApiErrors[id];
279 if (source_is(source, WINDOW_SYSTEM))
280 return ctx->Debug.WinsysErrors[id];
281 if (source_is(source, SHADER_COMPILER))
282 return ctx->Debug.ShaderErrors[id];
283 if (source_is(source, OTHER))
284 return ctx->Debug.OtherErrors[id];
285 }
286
287 return (severity != GL_DEBUG_SEVERITY_LOW_ARB);
288 }
289
290 /**
291 * 'buf' is not necessarily a null-terminated string. When logging, copy
292 * 'len' characters from it, store them in a new, null-terminated string,
293 * and remember the number of bytes used by that string, *including*
294 * the null terminator this time.
295 */
296 static void
297 _mesa_log_msg(struct gl_context *ctx, GLenum source, GLenum type,
298 GLuint id, GLenum severity, GLint len, const char *buf)
299 {
300 GLint nextEmpty;
301 struct gl_debug_msg *emptySlot;
302
303 assert(len >= 0 && len < MAX_DEBUG_MESSAGE_LENGTH);
304
305 if (!should_log(ctx, source, type, id, severity))
306 return;
307
308 if (ctx->Debug.Callback) {
309 ctx->Debug.Callback(source, type, id, severity,
310 len, buf, ctx->Debug.CallbackData);
311 return;
312 }
313
314 if (ctx->Debug.NumMessages == MAX_DEBUG_LOGGED_MESSAGES)
315 return;
316
317 nextEmpty = (ctx->Debug.NextMsg + ctx->Debug.NumMessages)
318 % MAX_DEBUG_LOGGED_MESSAGES;
319 emptySlot = &ctx->Debug.Log[nextEmpty];
320
321 assert(!emptySlot->message && !emptySlot->length);
322
323 emptySlot->message = malloc(len+1);
324 if (emptySlot->message) {
325 (void) strncpy(emptySlot->message, buf, (size_t)len);
326 emptySlot->message[len] = '\0';
327
328 emptySlot->length = len+1;
329 emptySlot->source = source;
330 emptySlot->type = type;
331 emptySlot->id = id;
332 emptySlot->severity = severity;
333 } else {
334 /* malloc failed! */
335 emptySlot->message = out_of_memory;
336 emptySlot->length = strlen(out_of_memory)+1;
337 emptySlot->source = GL_DEBUG_SOURCE_OTHER_ARB;
338 emptySlot->type = GL_DEBUG_TYPE_ERROR_ARB;
339 emptySlot->id = OTHER_ERROR_OUT_OF_MEMORY;
340 emptySlot->severity = GL_DEBUG_SEVERITY_HIGH_ARB;
341 }
342
343 if (ctx->Debug.NumMessages == 0)
344 ctx->Debug.NextMsgLength = ctx->Debug.Log[ctx->Debug.NextMsg].length;
345
346 ctx->Debug.NumMessages++;
347 }
348
349 /**
350 * Pop the oldest debug message out of the log.
351 * Writes the message string, including the null terminator, into 'buf',
352 * using up to 'bufSize' bytes. If 'bufSize' is too small, or
353 * if 'buf' is NULL, nothing is written.
354 *
355 * Returns the number of bytes written on success, or when 'buf' is NULL,
356 * the number that would have been written. A return value of 0
357 * indicates failure.
358 */
359 static GLsizei
360 _mesa_get_msg(struct gl_context *ctx, GLenum *source, GLenum *type,
361 GLuint *id, GLenum *severity, GLsizei bufSize, char *buf)
362 {
363 struct gl_debug_msg *msg;
364 GLsizei length;
365
366 if (ctx->Debug.NumMessages == 0)
367 return 0;
368
369 msg = &ctx->Debug.Log[ctx->Debug.NextMsg];
370 length = msg->length;
371
372 assert(length > 0 && length == ctx->Debug.NextMsgLength);
373
374 if (bufSize < length && buf != NULL)
375 return 0;
376
377 if (severity)
378 *severity = msg->severity;
379 if (source)
380 *source = msg->source;
381 if (type)
382 *type = msg->type;
383 if (id)
384 *id = msg->id;
385
386 if (buf) {
387 assert(msg->message[length-1] == '\0');
388 (void) strncpy(buf, msg->message, (size_t)length);
389 }
390
391 if (msg->message != (char*)out_of_memory)
392 free(msg->message);
393 msg->message = NULL;
394 msg->length = 0;
395
396 ctx->Debug.NumMessages--;
397 ctx->Debug.NextMsg++;
398 ctx->Debug.NextMsg %= MAX_DEBUG_LOGGED_MESSAGES;
399 ctx->Debug.NextMsgLength = ctx->Debug.Log[ctx->Debug.NextMsg].length;
400
401 return length;
402 }
403
404 /**
405 * Verify that source, type, and severity are valid enums.
406 * glDebugMessageInsertARB only accepts two values for 'source',
407 * and glDebugMessageControlARB will additionally accept GL_DONT_CARE
408 * in any parameter, so handle those cases specially.
409 */
410 static GLboolean
411 validate_params(struct gl_context *ctx, unsigned caller,
412 GLenum source, GLenum type, GLenum severity)
413 {
414 #define INSERT 1
415 #define CONTROL 2
416 switch(source) {
417 case GL_DEBUG_SOURCE_APPLICATION_ARB:
418 case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
419 break;
420 case GL_DEBUG_SOURCE_API_ARB:
421 case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
422 case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
423 case GL_DEBUG_SOURCE_OTHER_ARB:
424 if (caller != INSERT)
425 break;
426 case GL_DONT_CARE:
427 if (caller == CONTROL)
428 break;
429 default:
430 goto error;
431 }
432
433 switch(type) {
434 case GL_DEBUG_TYPE_ERROR_ARB:
435 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
436 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
437 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
438 case GL_DEBUG_TYPE_PORTABILITY_ARB:
439 case GL_DEBUG_TYPE_OTHER_ARB:
440 break;
441 case GL_DONT_CARE:
442 if (caller == CONTROL)
443 break;
444 default:
445 goto error;
446 }
447
448 switch(severity) {
449 case GL_DEBUG_SEVERITY_HIGH_ARB:
450 case GL_DEBUG_SEVERITY_MEDIUM_ARB:
451 case GL_DEBUG_SEVERITY_LOW_ARB:
452 break;
453 case GL_DONT_CARE:
454 if (caller == CONTROL)
455 break;
456 default:
457 goto error;
458 }
459 return GL_TRUE;
460
461 error:
462 {
463 const char *callerstr;
464 if (caller == INSERT)
465 callerstr = "glDebugMessageInsertARB";
466 else if (caller == CONTROL)
467 callerstr = "glDebugMessageControlARB";
468 else
469 return GL_FALSE;
470
471 _mesa_error( ctx, GL_INVALID_ENUM, "bad values passed to %s"
472 "(source=0x%x, type=0x%x, severity=0x%x)", callerstr,
473 source, type, severity);
474 }
475 return GL_FALSE;
476 }
477
478 void GLAPIENTRY
479 _mesa_DebugMessageInsertARB(GLenum source, GLenum type, GLuint id,
480 GLenum severity, GLint length,
481 const GLcharARB* buf)
482 {
483 GET_CURRENT_CONTEXT(ctx);
484
485 if (!validate_params(ctx, INSERT, source, type, severity))
486 return; /* GL_INVALID_ENUM */
487
488 if (length < 0)
489 length = strlen(buf);
490
491 if (length >= MAX_DEBUG_MESSAGE_LENGTH) {
492 _mesa_error(ctx, GL_INVALID_VALUE, "glDebugMessageInsertARB"
493 "(length=%d, which is not less than "
494 "GL_MAX_DEBUG_MESSAGE_LENGTH_ARB=%d)", length,
495 MAX_DEBUG_MESSAGE_LENGTH);
496 return;
497 }
498
499 _mesa_log_msg(ctx, source, type, id, severity, length, buf);
500 }
501
502 GLuint GLAPIENTRY
503 _mesa_GetDebugMessageLogARB(GLuint count, GLsizei logSize, GLenum* sources,
504 GLenum* types, GLenum* ids, GLenum* severities,
505 GLsizei* lengths, GLcharARB* messageLog)
506 {
507 GET_CURRENT_CONTEXT(ctx);
508 GLuint ret;
509
510 if (!messageLog)
511 logSize = 0;
512
513 if (logSize < 0) {
514 _mesa_error(ctx, GL_INVALID_VALUE, "glGetDebugMessageLogARB"
515 "(logSize=%d : logSize must not be negative)", logSize);
516 return 0;
517 }
518
519 for (ret = 0; ret < count; ret++) {
520 GLsizei written = _mesa_get_msg(ctx, sources, types, ids, severities,
521 logSize, messageLog);
522 if (!written)
523 break;
524
525 if (messageLog) {
526 messageLog += written;
527 logSize -= written;
528 }
529 if (lengths) {
530 *lengths = written;
531 lengths++;
532 }
533
534 if (severities)
535 severities++;
536 if (sources)
537 sources++;
538 if (types)
539 types++;
540 if (ids)
541 ids++;
542 }
543
544 return ret;
545 }
546
547 /**
548 * 'array' is an array representing a particular debugging-message namespace.
549 * I.e., the set of all API errors, or the set of all Shader Compiler errors.
550 * 'size' is the size of 'array'. 'count' is the size of 'ids', an array
551 * of indices into 'array'. All the elements of 'array' at the indices
552 * listed in 'ids' will be overwritten with the value of 'enabled'.
553 *
554 * If 'count' is zero, all elements in 'array' are overwritten with the
555 * value of 'enabled'.
556 */
557 static void
558 control_messages(GLboolean *array, GLuint size,
559 GLsizei count, const GLuint *ids, GLboolean enabled)
560 {
561 GLsizei i;
562
563 if (!count) {
564 GLuint id;
565 for (id = 0; id < size; id++) {
566 array[id] = enabled;
567 }
568 return;
569 }
570
571 for (i = 0; i < count; i++) {
572 if (ids[i] >= size) {
573 /* XXX: The spec doesn't say what to do with a non-existent ID. */
574 continue;
575 }
576 array[ids[i]] = enabled;
577 }
578 }
579
580 /**
581 * Set the state of all message IDs found in the given intersection
582 * of 'source', 'type', and 'severity'. Note that all three of these
583 * parameters are array indices, not the corresponding GL enums.
584 *
585 * This requires both setting the state of all previously seen message
586 * IDs in the hash table, and setting the default state for all
587 * applicable combinations of source/type/severity, so that all the
588 * yet-unknown message IDs that may be used in the future will be
589 * impacted as if they were already known.
590 */
591 static void
592 control_app_messages_by_group(struct gl_context *ctx, int source, int type,
593 int severity, GLboolean enabled)
594 {
595 struct gl_client_debug *ClientIDs = &ctx->Debug.ClientIDs;
596 int s, t, sev, smax, tmax, sevmax;
597
598 if (source == SOURCE_ANY) {
599 source = 0;
600 smax = SOURCE_COUNT;
601 } else {
602 smax = source+1;
603 }
604
605 if (type == TYPE_ANY) {
606 type = 0;
607 tmax = TYPE_COUNT;
608 } else {
609 tmax = type+1;
610 }
611
612 if (severity == SEVERITY_ANY) {
613 severity = 0;
614 sevmax = SEVERITY_COUNT;
615 } else {
616 sevmax = severity+1;
617 }
618
619 for (sev = severity; sev < sevmax; sev++)
620 for (s = source; s < smax; s++)
621 for (t = type; t < tmax; t++) {
622 struct simple_node *node;
623 struct gl_client_severity *entry;
624
625 /* change the default for IDs we've never seen before. */
626 ClientIDs->Defaults[sev][s][t] = enabled;
627
628 /* Now change the state of IDs we *have* seen... */
629 foreach(node, &ClientIDs->Namespaces[s][t].Severity[sev]) {
630 entry = (struct gl_client_severity *)node;
631 set_message_state(ctx, s, t, entry->ID, enabled);
632 }
633 }
634 }
635
636 /**
637 * Debugging-message namespaces with the source APPLICATION or THIRD_PARTY
638 * require special handling, since the IDs in them are controlled by clients,
639 * not the OpenGL implementation.
640 *
641 * 'count' is the length of the array 'ids'. If 'count' is nonzero, all
642 * the given IDs in the namespace defined by 'esource' and 'etype'
643 * will be affected.
644 *
645 * If 'count' is zero, this sets the state of all IDs that match
646 * the combination of 'esource', 'etype', and 'eseverity'.
647 */
648 static void
649 control_app_messages(struct gl_context *ctx, GLenum esource, GLenum etype,
650 GLenum eseverity, GLsizei count, const GLuint *ids,
651 GLboolean enabled)
652 {
653 int source, type, severity;
654 GLsizei i;
655
656 source = enum_to_index(esource);
657 type = enum_to_index(etype);
658 severity = enum_to_index(eseverity);
659
660 if (count)
661 assert(severity == SEVERITY_ANY && type != TYPE_ANY
662 && source != SOURCE_ANY);
663
664 for (i = 0; i < count; i++)
665 set_message_state(ctx, source, type, ids[i], enabled);
666
667 if (count)
668 return;
669
670 control_app_messages_by_group(ctx, source, type, severity, enabled);
671 }
672
673 void GLAPIENTRY
674 _mesa_DebugMessageControlARB(GLenum source, GLenum type, GLenum severity,
675 GLsizei count, const GLuint *ids,
676 GLboolean enabled)
677 {
678 GET_CURRENT_CONTEXT(ctx);
679
680 if (count < 0) {
681 _mesa_error(ctx, GL_INVALID_VALUE, "glDebugMessageControlARB"
682 "(count=%d : count must not be negative)", count);
683 return;
684 }
685
686 if (!validate_params(ctx, CONTROL, source, type, severity))
687 return; /* GL_INVALID_ENUM */
688
689 if (count && (severity != GL_DONT_CARE || type == GL_DONT_CARE
690 || source == GL_DONT_CARE)) {
691 _mesa_error(ctx, GL_INVALID_OPERATION, "glDebugMessageControlARB"
692 "(When passing an array of ids, severity must be"
693 " GL_DONT_CARE, and source and type must not be GL_DONT_CARE.");
694 return;
695 }
696
697 if (source_is(source, APPLICATION) || source_is(source, THIRD_PARTY))
698 control_app_messages(ctx, source, type, severity, count, ids, enabled);
699
700 if (severity_is(severity, HIGH)) {
701 if (type_is(type, ERROR)) {
702 if (source_is(source, API))
703 control_messages(ctx->Debug.ApiErrors, API_ERROR_COUNT,
704 count, ids, enabled);
705 if (source_is(source, WINDOW_SYSTEM))
706 control_messages(ctx->Debug.WinsysErrors, WINSYS_ERROR_COUNT,
707 count, ids, enabled);
708 if (source_is(source, SHADER_COMPILER))
709 control_messages(ctx->Debug.ShaderErrors, SHADER_ERROR_COUNT,
710 count, ids, enabled);
711 if (source_is(source, OTHER))
712 control_messages(ctx->Debug.OtherErrors, OTHER_ERROR_COUNT,
713 count, ids, enabled);
714 }
715 }
716 }
717
718 void GLAPIENTRY
719 _mesa_DebugMessageCallbackARB(GLDEBUGPROCARB callback, const GLvoid *userParam)
720 {
721 GET_CURRENT_CONTEXT(ctx);
722 ctx->Debug.Callback = callback;
723 ctx->Debug.CallbackData = (void *) userParam;
724 }
725
726 void
727 _mesa_init_errors(struct gl_context *ctx)
728 {
729 int s, t, sev;
730 struct gl_client_debug *ClientIDs = &ctx->Debug.ClientIDs;
731
732 ctx->Debug.Callback = NULL;
733 ctx->Debug.SyncOutput = GL_FALSE;
734 ctx->Debug.Log[0].length = 0;
735 ctx->Debug.NumMessages = 0;
736 ctx->Debug.NextMsg = 0;
737 ctx->Debug.NextMsgLength = 0;
738
739 /* Enable all the messages with severity HIGH or MEDIUM by default. */
740 memset(ctx->Debug.ApiErrors, GL_TRUE, sizeof ctx->Debug.ApiErrors);
741 memset(ctx->Debug.WinsysErrors, GL_TRUE, sizeof ctx->Debug.WinsysErrors);
742 memset(ctx->Debug.ShaderErrors, GL_TRUE, sizeof ctx->Debug.ShaderErrors);
743 memset(ctx->Debug.OtherErrors, GL_TRUE, sizeof ctx->Debug.OtherErrors);
744 memset(ClientIDs->Defaults[SEVERITY_HIGH], GL_TRUE,
745 sizeof ClientIDs->Defaults[SEVERITY_HIGH]);
746 memset(ClientIDs->Defaults[SEVERITY_MEDIUM], GL_TRUE,
747 sizeof ClientIDs->Defaults[SEVERITY_MEDIUM]);
748 memset(ClientIDs->Defaults[SEVERITY_LOW], GL_FALSE,
749 sizeof ClientIDs->Defaults[SEVERITY_LOW]);
750
751 /* Initialize state for filtering client-provided debug messages. */
752 for (s = 0; s < SOURCE_COUNT; s++)
753 for (t = 0; t < TYPE_COUNT; t++) {
754 ClientIDs->Namespaces[s][t].IDs = _mesa_NewHashTable();
755 assert(ClientIDs->Namespaces[s][t].IDs);
756
757 for (sev = 0; sev < SEVERITY_COUNT; sev++)
758 make_empty_list(&ClientIDs->Namespaces[s][t].Severity[sev]);
759 }
760 }
761
762 void
763 _mesa_free_errors_data(struct gl_context *ctx)
764 {
765 int s, t, sev;
766 struct gl_client_debug *ClientIDs = &ctx->Debug.ClientIDs;
767
768 /* Tear down state for filtering client-provided debug messages. */
769 for (s = 0; s < SOURCE_COUNT; s++)
770 for (t = 0; t < TYPE_COUNT; t++) {
771 _mesa_DeleteHashTable(ClientIDs->Namespaces[s][t].IDs);
772 for (sev = 0; sev < SEVERITY_COUNT; sev++) {
773 struct simple_node *node, *tmp;
774 struct gl_client_severity *entry;
775
776 foreach_s(node, tmp, &ClientIDs->Namespaces[s][t].Severity[sev]) {
777 entry = (struct gl_client_severity *)node;
778 free(entry);
779 }
780 }
781 }
782 }
783
784 /**********************************************************************/
785 /** \name Diagnostics */
786 /*@{*/
787
788 static void
789 output_if_debug(const char *prefixString, const char *outputString,
790 GLboolean newline)
791 {
792 static int debug = -1;
793 static FILE *fout = NULL;
794
795 /* Init the local 'debug' var once.
796 * Note: the _mesa_init_debug() function should have been called
797 * by now so MESA_DEBUG_FLAGS will be initialized.
798 */
799 if (debug == -1) {
800 /* If MESA_LOG_FILE env var is set, log Mesa errors, warnings,
801 * etc to the named file. Otherwise, output to stderr.
802 */
803 const char *logFile = _mesa_getenv("MESA_LOG_FILE");
804 if (logFile)
805 fout = fopen(logFile, "w");
806 if (!fout)
807 fout = stderr;
808 #ifdef DEBUG
809 /* in debug builds, print messages unless MESA_DEBUG="silent" */
810 if (MESA_DEBUG_FLAGS & DEBUG_SILENT)
811 debug = 0;
812 else
813 debug = 1;
814 #else
815 /* in release builds, be silent unless MESA_DEBUG is set */
816 debug = _mesa_getenv("MESA_DEBUG") != NULL;
817 #endif
818 }
819
820 /* Now only print the string if we're required to do so. */
821 if (debug) {
822 fprintf(fout, "%s: %s", prefixString, outputString);
823 if (newline)
824 fprintf(fout, "\n");
825 fflush(fout);
826
827 #if defined(_WIN32) && !defined(_WIN32_WCE)
828 /* stderr from windows applications without console is not usually
829 * visible, so communicate with the debugger instead */
830 {
831 char buf[4096];
832 _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
833 OutputDebugStringA(buf);
834 }
835 #endif
836 }
837 }
838
839 /**
840 * When a new type of error is recorded, print a message describing
841 * previous errors which were accumulated.
842 */
843 static void
844 flush_delayed_errors( struct gl_context *ctx )
845 {
846 char s[MAX_DEBUG_MESSAGE_LENGTH];
847
848 if (ctx->ErrorDebugCount) {
849 _mesa_snprintf(s, MAX_DEBUG_MESSAGE_LENGTH, "%d similar %s errors",
850 ctx->ErrorDebugCount,
851 _mesa_lookup_enum_by_nr(ctx->ErrorValue));
852
853 output_if_debug("Mesa", s, GL_TRUE);
854
855 ctx->ErrorDebugCount = 0;
856 }
857 }
858
859
860 /**
861 * Report a warning (a recoverable error condition) to stderr if
862 * either DEBUG is defined or the MESA_DEBUG env var is set.
863 *
864 * \param ctx GL context.
865 * \param fmtString printf()-like format string.
866 */
867 void
868 _mesa_warning( struct gl_context *ctx, const char *fmtString, ... )
869 {
870 char str[MAX_DEBUG_MESSAGE_LENGTH];
871 va_list args;
872 va_start( args, fmtString );
873 (void) _mesa_vsnprintf( str, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args );
874 va_end( args );
875
876 if (ctx)
877 flush_delayed_errors( ctx );
878
879 output_if_debug("Mesa warning", str, GL_TRUE);
880 }
881
882
883 /**
884 * Report an internal implementation problem.
885 * Prints the message to stderr via fprintf().
886 *
887 * \param ctx GL context.
888 * \param fmtString problem description string.
889 */
890 void
891 _mesa_problem( const struct gl_context *ctx, const char *fmtString, ... )
892 {
893 va_list args;
894 char str[MAX_DEBUG_MESSAGE_LENGTH];
895 static int numCalls = 0;
896
897 (void) ctx;
898
899 if (numCalls < 50) {
900 numCalls++;
901
902 va_start( args, fmtString );
903 _mesa_vsnprintf( str, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args );
904 va_end( args );
905 fprintf(stderr, "Mesa %s implementation error: %s\n",
906 MESA_VERSION_STRING, str);
907 fprintf(stderr, "Please report at bugs.freedesktop.org\n");
908 }
909 }
910
911 static GLboolean
912 should_output(struct gl_context *ctx, GLenum error, const char *fmtString)
913 {
914 static GLint debug = -1;
915
916 /* Check debug environment variable only once:
917 */
918 if (debug == -1) {
919 const char *debugEnv = _mesa_getenv("MESA_DEBUG");
920
921 #ifdef DEBUG
922 if (debugEnv && strstr(debugEnv, "silent"))
923 debug = GL_FALSE;
924 else
925 debug = GL_TRUE;
926 #else
927 if (debugEnv)
928 debug = GL_TRUE;
929 else
930 debug = GL_FALSE;
931 #endif
932 }
933
934 if (debug) {
935 if (ctx->ErrorValue != error ||
936 ctx->ErrorDebugFmtString != fmtString) {
937 flush_delayed_errors( ctx );
938 ctx->ErrorDebugFmtString = fmtString;
939 ctx->ErrorDebugCount = 0;
940 return GL_TRUE;
941 }
942 ctx->ErrorDebugCount++;
943 }
944 return GL_FALSE;
945 }
946
947
948 /**
949 * Record an OpenGL state error. These usually occur when the user
950 * passes invalid parameters to a GL function.
951 *
952 * If debugging is enabled (either at compile-time via the DEBUG macro, or
953 * run-time via the MESA_DEBUG environment variable), report the error with
954 * _mesa_debug().
955 *
956 * \param ctx the GL context.
957 * \param error the error value.
958 * \param fmtString printf() style format string, followed by optional args
959 */
960 void
961 _mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... )
962 {
963 GLboolean do_output, do_log;
964
965 do_output = should_output(ctx, error, fmtString);
966 do_log = should_log(ctx, GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_ERROR_ARB,
967 API_ERROR_UNKNOWN, GL_DEBUG_SEVERITY_HIGH_ARB);
968
969 if (do_output || do_log) {
970 char s[MAX_DEBUG_MESSAGE_LENGTH], s2[MAX_DEBUG_MESSAGE_LENGTH];
971 int len;
972 va_list args;
973
974 va_start(args, fmtString);
975 len = _mesa_vsnprintf(s, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args);
976 va_end(args);
977
978 if (len >= MAX_DEBUG_MESSAGE_LENGTH) {
979 /* Too long error message. Whoever calls _mesa_error should use
980 * shorter strings. */
981 ASSERT(0);
982 return;
983 }
984
985 len = _mesa_snprintf(s2, MAX_DEBUG_MESSAGE_LENGTH, "%s in %s",
986 _mesa_lookup_enum_by_nr(error), s);
987 if (len >= MAX_DEBUG_MESSAGE_LENGTH) {
988 /* Same as above. */
989 ASSERT(0);
990 return;
991 }
992
993 /* Print the error to stderr if needed. */
994 if (do_output) {
995 output_if_debug("Mesa: User error", s2, GL_TRUE);
996 }
997
998 /* Log the error via ARB_debug_output if needed.*/
999 if (do_log) {
1000 _mesa_log_msg(ctx, GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_ERROR_ARB,
1001 API_ERROR_UNKNOWN, GL_DEBUG_SEVERITY_HIGH_ARB, len, s2);
1002 }
1003 }
1004
1005 /* Set the GL context error state for glGetError. */
1006 _mesa_record_error(ctx, error);
1007 }
1008
1009
1010 /**
1011 * Report debug information. Print error message to stderr via fprintf().
1012 * No-op if DEBUG mode not enabled.
1013 *
1014 * \param ctx GL context.
1015 * \param fmtString printf()-style format string, followed by optional args.
1016 */
1017 void
1018 _mesa_debug( const struct gl_context *ctx, const char *fmtString, ... )
1019 {
1020 #ifdef DEBUG
1021 char s[MAX_DEBUG_MESSAGE_LENGTH];
1022 va_list args;
1023 va_start(args, fmtString);
1024 _mesa_vsnprintf(s, MAX_DEBUG_MESSAGE_LENGTH, fmtString, args);
1025 va_end(args);
1026 output_if_debug("Mesa", s, GL_FALSE);
1027 #endif /* DEBUG */
1028 (void) ctx;
1029 (void) fmtString;
1030 }
1031
1032
1033 /**
1034 * Report debug information from the shader compiler via GL_ARB_debug_output.
1035 *
1036 * \param ctx GL context.
1037 * \param type The namespace to which this message belongs.
1038 * \param id The message ID within the given namespace.
1039 * \param msg The message to output. Need not be null-terminated.
1040 * \param len The length of 'msg'. If negative, 'msg' must be null-terminated.
1041 */
1042 void
1043 _mesa_shader_debug( struct gl_context *ctx, GLenum type, GLuint id,
1044 const char *msg, int len )
1045 {
1046 GLenum source = GL_DEBUG_SOURCE_SHADER_COMPILER_ARB,
1047 severity;
1048
1049 switch (type) {
1050 case GL_DEBUG_TYPE_ERROR_ARB:
1051 assert(id < SHADER_ERROR_COUNT);
1052 severity = GL_DEBUG_SEVERITY_HIGH_ARB;
1053 break;
1054 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1055 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1056 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1057 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1058 case GL_DEBUG_TYPE_OTHER_ARB:
1059 assert(0 && "other categories not implemented yet");
1060 default:
1061 _mesa_problem(ctx, "bad enum in _mesa_shader_debug()");
1062 return;
1063 }
1064
1065 if (len < 0)
1066 len = strlen(msg);
1067
1068 /* Truncate the message if necessary. */
1069 if (len >= MAX_DEBUG_MESSAGE_LENGTH)
1070 len = MAX_DEBUG_MESSAGE_LENGTH - 1;
1071
1072 _mesa_log_msg(ctx, source, type, id, severity, len, msg);
1073 }
1074
1075 /*@}*/