Debug Output

From OpenGL Wiki
Jump to navigation Jump to search
Debug Output
Core in version 4.6
Core since version 4.3
Core ARB extension KHR_debug
ARB extension ARB_debug_output
Vendor extension AMD_debug_output

Debug Output is an OpenGL feature that makes debugging and optimizing OpenGL applications easier.

Briefly, this feature provides a method for the driver to provide textual message information back to the application. It also provides a mechanism for an application to insert its own debugging messages into the stream and to annotate GL objects with human-readable names.

The KHR_debug extension defines the core feature. Previous extensions defined similar features, but reduced functionality relative to the full core feature. This page only describes the KHR/core functionality.

Message Events[edit]

The heart of debug output is a message event. Message events are generated when certain "interesting events" occur within the OpenGL implementation. These message events are provided to the application via a callback function.

Here are some events that a typical OpenGL driver might notify the application of via a message event:

  • A GL error has occurred (possibly including extended information about why that error occurred).
  • Your app is using a slow path in the GL driver.
  • Based on your app's GL usage, the GL driver has a performance tip to offer for improving your app's performance.
  • An important state change has occurred with the GL driver that you might want to know about.
  • The application has inserted its own debugging message into the message stream.

Note that catching GL errors with this method is much easier than by using glGetError() error checking, as there is no need to sprinkle glGetError() calls throughout the code. Even better, on some GL drivers, when a GL error occurs the message callback function is invoked on the same thread and within the very same call stack as the GL call that triggered the GL error (or performance warning).

Enabling Debug Output[edit]

Unless debug output is enabled, no messages will be generated, retrieved, or logged. It is enabled by using glEnable with the GL_DEBUG_OUTPUT enumerator.

In Debug Contexts, debug output starts enabled. In non-debug contexts, the OpenGL implementation may not generate messages even if debug output is enabled.

Message Components[edit]

Messages can come from a variety of sources, but they each contain the following data:

  • The source that produced the message, by GLenum.
  • The type of message, by GLenum.
  • The message severity (how important it is), by GLenum.
  • An ID, as a GLuint.
  • A null-terminated string describing the message.

Implementations may create messages at their discretion. In debug contexts, the implementation is required to generate messages for OpenGL Errors and GLSL compilation/linking failures. Beyond these, whether additional warnings and so forth are generated is a matter of the implementation's discretion and quality.

If the context isn't a debug context, then the implementation is free to provide fewer messages than debug contexts, or none at all. It may even swallow up user-generated messages. So messages are only guaranteed when using a debug context.

Message Sources
Source enum Generated by
GL_DEBUG_SOURCE_API Calls to the OpenGL API
GL_DEBUG_SOURCE_WINDOW_SYSTEM Calls to a window-system API
GL_DEBUG_SOURCE_SHADER_COMPILER A compiler for a shading language
GL_DEBUG_SOURCE_THIRD_PARTY An application associated with OpenGL
GL_DEBUG_SOURCE_APPLICATION Generated by the user of this application
GL_DEBUG_SOURCE_OTHER Some source that isn't one of these
Message Types
Type enum Meaning
GL_DEBUG_TYPE_ERROR An error, typically from the API
GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR Some behavior marked deprecated has been used
GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR Something has invoked undefined behavior
GL_DEBUG_TYPE_PORTABILITY Some functionality the user relies upon is not portable
GL_DEBUG_TYPE_PERFORMANCE Code has triggered possible performance issues
GL_DEBUG_TYPE_MARKER Command stream annotation
GL_DEBUG_TYPE_PUSH_GROUP Group pushing
GL_DEBUG_TYPE_POP_GROUP Group popping
GL_DEBUG_TYPE_OTHER Some type that isn't one of these
Message Severity
Severity enum Meaning
GL_DEBUG_SEVERITY_HIGH All OpenGL Errors, shader compilation/linking errors, or highly-dangerous undefined behavior
GL_DEBUG_SEVERITY_MEDIUM Major performance warnings, shader compilation/linking warnings, or the use of deprecated functionality
GL_DEBUG_SEVERITY_LOW Redundant state change performance warning, or unimportant undefined behavior
GL_DEBUG_SEVERITY_NOTIFICATION Anything that isn't an error or performance issue.

User messages[edit]

While most debug output messages are generated by the OpenGL implementation, it is possible to generate messages from outside of the implementation. These messages are generated by the following command:

glDebugMessageInsert(GLenum source​, GLenum type​, GLuint id​, GLenum severity​, GLsizei length​, const char *message​)

The source​ represents who is sending the message. However, in order to be able to differentiate between user-created messages and implementation-generated ones, the source​ must be either GL_DEBUG_SOURCE_APPLICATION or GL_DEBUG_SOURCE_THIRD_PARTY. These sources will never be used for implementation-generated messages. The GL_DEBUG_SOURCE_APPLICATION represents a message generated by the application, while GL_DEBUG_SOURCE_THIRD_PARTY generally represents some code that is interposing itself between the implementation and the application.

The type​ can be any of the message types listed above, and the severity​ can be any of those severities. The id​ is purely for the benefit of the user and may be any unsigned 32-bit integer value. The message​ and length​ represent the text string to be stored. length​ may be negative, which means that message​ must be NULL-terminated. The length of the message (either null-terminated or length-specified) must be less than GL_MAX_DEBUG_MESSAGE_LENGTH.

Getting messages[edit]

Messages, once generated, can either be stored in a log or passed directly to the application via a callback function. If a callback is registered, then the messages are not stored in a log.

Messages can be routed to a callback via this function:

void glDebugMessageCallback(DEBUGPROC callback​, void* userParam​);

The type of callback​ is a function of the form:

typedef void APIENTRY funcname(GLenum source​, GLenum type​, GLuint id​,
   GLenum severity​, GLsizei length​, const GLchar* message​, const void* userParam​);

source​, type​, and severity​ are the message's source, type, and severity enumerators. id​ is the message's identifier integer. length​ is the length of the message​ string, excluding the null-terminator.

The userParam​ that is registered with glDebugMessageCallback will be passed to the given callback function with each message. This is useful for storing arbitrary data (like a C++ object) along with the function pointer.

The callback can be called synchronously or asynchronously. This is controlled by the glEnable flag GL_DEBUG_OUTPUT_SYNCHRONOUS. If this flag is enabled, then OpenGL guarantees that your callback will be called:

  • In the same thread as the context.
  • In the scope of the OpenGL function call that fired the message.

If the flag is disabled, then none of these are guaranteed. So if you want asynchronous debug output (for performance reasons), you must take into account the following possibilities:

  • The thread the callback is called on is not the context's thread. Indeed, an OpenGL context may not even be current in the callback's thread, which means that you cannot call any OpenGL function without ensuring the status of the thread's current context.
  • Even if you make the OpenGL context current in the callback's thread, you still cannot call OpenGL functions.
  • You also cannot call windowing system functions that may affect OpenGL operations (`SwapBuffers` and the like).
  • Multiple instances of the same callback function may be called at the same time, obviously from different threads.
  • Messages may be issued out of the order of their occurrence.

Logging[edit]

If no callback is registered, then messages are stored in a log. This log has a fixed, implementation defined length of GL_MAX_DEBUG_LOGGED_MESSAGES message entries. If the log is full and more messages are generated, then the new messages will be discarded.

Warning: GL_MAX_DEBUG_LOGGED_MESSAGES is allowed to be as few as one, so it would be unwise to rely on logging without at least verifying that the message log is of reasonable length. So it's more reliable to build your own log.

Each context maintains its own message log queue for commands executed in that context. Logging follows the same synchronization rules as for the callback. So if you need immediate results in the log, or if the order of messages needs to be guaranteed, you must use synchronous behavior.

Messages from the context's log can be fetched with this function:

GLuint glGetDebugMessageLog(GLuint count​, GLsizei bufSize​,

   GLenum *sources​, GLenum *types​, GLuint *ids​, GLenum *severities​,
GLsizei *lengths​, GLchar *messageLog​);

count​ is the number of messages that you want to try to fetch. The return value is the number of messages actually fetched. Any messages successfully fetched will be removed from the message log.

sources​, types​, ids​, severities​, lengths​ are arrays that must be at least count​ in size. For each successfully extracted message, an entry in these arrays will be filled in with the appropriate message data. The lengths​ are the lengths of the string for that index's corresponding messages.

The behavior of the character data is more difficult to deal with. messageLog​ is a single array of characters, of at least bufSize​ in size. The function will copy into this string the message strings for each message extracted, separated by null characters (and terminated by one). However, if it is unable to copy a string due to lack of space remaining in bufSize​, then this message, and all subsequent messages, will remain in the log.

Therefore, if you do not provide enough space in messageLog​, you cannot get any messages from the log. You can query the length of the string in the first message of the log with GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH. This includes the null-terminator, so you can use that directly to get at least the first message. If you want to be able to query any number of messages, you can use the implementation-defined GL_MAX_DEBUG_MESSAGE_LENGTH value, which is the maximum length (including null-terminator) of message strings.

Here is an example of code that can get the first N messages:

V · E

This example code shows how to get the first X messages from the debug output log.

void GetFirstNMessages(GLuint numMsgs)
{
	GLint maxMsgLen = 0;
	glGetIntegerv(GL_MAX_DEBUG_MESSAGE_LENGTH, &maxMsgLen);

	std::vector<GLchar> msgData(numMsgs * maxMsgLen);
	std::vector<GLenum> sources(numMsgs);
	std::vector<GLenum> types(numMsgs);
	std::vector<GLenum> severities(numMsgs);
	std::vector<GLuint> ids(numMsgs);
	std::vector<GLsizei> lengths(numMsgs);

	GLuint numFound = glGetDebugMessageLog(numMsgs, msgs.size(), &sources[0], &types[0], &ids[0], &severities[0], &lengths[0], &msgData[0]);

	sources.resize(numFound);
	types.resize(numFound);
	severities.resize(numFound);
	ids.resize(numFound);
	lengths.resize(numFound);

	std::vector<std::string> messages;
	messages.reserve(numFound);

	std::vector<GLchar>::iterator currPos = msgData.begin();
	for(size_t msg = 0; msg < lengths.size(); ++msg)
	{
		messages.push_back(std::string(currPos, currPos + lengths[msg] - 1));
		currPos = currPos + lengths[msg];
	}
}


Message filtering[edit]

Implementations can emit a lot of messages. As such, it is often useful to be able to filter out certain messages. This can be done using this function:

void glDebugMessageControl(GLenum source​, GLenum type​, GLenum severity​, GLsizei count​, const GLuint *ids​, GLboolean enabled​);

This function has two modes of use: It can be used to filter out a combination of source​/type​/severity​, or it can be used to filter out a specific set of messages using their ids​.

To use it in the first mode, set source​/type​/severity​ to the combination whose filtering options are to be modified. GL_DONT_CARE can be used as any of the three arguments as a wildcard. Depending on whether enabled​ is GL_TRUE or GL_FALSE, the messages matching the filter will be emitted or ignored (respectively.) If the function is being used for this purpose, then count​ should be zero (and ids​ will thus be ignored).

To use it in the second mode (where specific message IDs are blocked), source​ and type​ may not be set to GL_DONT_CARE, but severity​ must be GL_DONT_CARE. The specific IDs to be affected are to be passed in ids​, which should point to an array of at least count​ ID numbers. Since messages are uniquely identified by their source​, type​, and id​, this mode of use affects only the specific set of messages specified.

Scoping messages[edit]

It often requires multiple OpenGL commands in order to achieve a certain desired effect. Therefore, it is frequently useful to designate that a sequence of commands pertains to some particular activity. This would cause any messages generated by those commands to be annotated with that user-defined activity.

OpenGL provides a relatively simple scoping mechanism to define such activity. It is basically a customized mechanism for user-specified messages, except that it is tied into a stack that ensures that, for every opening message, there is a corresponding closing one. The user-provided string will be augmented with information about starting/ending a group. Also, the severity of the message will always be GL_DEBUG_SEVERITY_NOTIFICATION.

The one piece of functionality that a debug group provides beyond this is message filtering. The filtering function operates on the current group, and child groups inherit the parent group's filter state.

The scoping functions are:

void glPushDebugGroup(GLenum source​, GLuint id​, GLsizei length​, const char * message​);

void glPopDebugGroup(void);

The source​, as for any user-defined message, must be GL_DEBUG_SOURCE_APPLICATION or GL_DEBUG_SOURCE_THIRD_PARTY. The id​ can be any user-defined number. The length​ is the length of the message​ string. The actual text of the message generated by the push command will be based on message​, but the system may augment it with other information (like "Pushed Group:" or something).

The pop command emits a message as well. However, it emits a message that has the same source and id as the corresponding pushed command, and its message string will likewise be based on message​, likely augmented with other text (like "Popped Group:").

There is a maximum depth for the stack of groups, defined by GL_MAX_DEBUG_GROUP_STACK_DEPTH, which must be at least 64.

Object names[edit]

V · E

OpenGL Objects, as well as the non-standard objects like Program Objects and Sync Objects, are very useful. However, their names are non-intuitive; they are just numbers (or pointers in the case of sync objects). Furthermore, those numbers are defined by the system, rather than by the user. This makes debugging with objects difficult.

However, OpenGL has a mechanism to associate an arbitrary string name with any object. This also permits system-generated messages to be able to talk about an object by its string name. The functions to set the name for an object are:

void glObjectLabel(GLenum identifier​, GLuint name​, GLsizei length​, const char * label​);

void glObjectPtrLabel(void * ptr​, GLsizei length​, const char * label​);

The first function is used to set all objects that use GLuints for their object types. This means all OpenGL Objects, as well as all Shader/Program Object types. The second function sets the name for Sync Objects.

Identifier Object Type
GL_BUFFER Buffer Object
GL_SHADER Shader object
GL_PROGRAM Program Object
GL_VERTEX_ARRAY Vertex Array Object
GL_QUERY Query Object
GL_PROGRAM_PIPELINE Program Pipeline Object
GL_TRANSFORM_FEEDBACK Transform Feedback Object
GL_SAMPLER Sampler Object
GL_TEXTURE Texture Object
GL_RENDERBUFFER Renderbuffer Object
GL_FRAMEBUFFER Framebuffer Object

For GLuint-based objects, the object name alone is not enough to identify the object, since two objects of different object types may have the same GLuint name. Therefore, the type is specified by the identifier​ parameter, which must be one of the enumerators on the left.

The length​ specifies the length of the string label​, which must be less than GL_MAX_LABEL_LENGTH (which will be no less than 256).

The name of an object may be used by debug output messages that reference this object. This is not a requirement, but it can be useful for debugging purposes.


To retrieve the name of an object, you use these functions:

void glGetObjectLabel(GLenum identifier​, GLuint name​, GLsizei bufSize​, GLsizei * length​, char * label​);

void glGetObjectPtrLabel(void * ptr​, GLsizei bufSize​, GLsizei * length​, char * label​);

The bufSize​ is the total number of bytes in label​; the function will not copy more than this many bytes (including a null-terminator) into label​. If length​ is not NULL, then the function will store the number of characters written into the buffer (including the NULL pointer). If label​ is NULL, then the total length of the string will be copied into length​. If both are NULL, an error results.

Examples[edit]

V · E

A simple example showing how to utilize debug message callbacks (e.g. for detecting OpenGL errors):

void GLAPIENTRY
MessageCallback( GLenum source,
                 GLenum type,
                 GLuint id,
                 GLenum severity,
                 GLsizei length,
                 const GLchar* message,
                 const void* userParam )
{
  fprintf( stderr, "GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n",
           ( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ),
            type, severity, message );
}

// During init, enable debug output
glEnable              ( GL_DEBUG_OUTPUT );
glDebugMessageCallback( MessageCallback, 0 );