File: AssertTracer.cpp

package info (click to toggle)
intel-gmmlib 22.7.2%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 5,444 kB
  • sloc: cpp: 59,645; ansic: 11,358; makefile: 6
file content (365 lines) | stat: -rw-r--r-- 13,048 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*==============================================================================
Copyright(c) 2017 Intel Corporation

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files(the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
============================================================================*/
/*

File Name:  AssertTracer.cpp

Abstract:
    These functions enables reporting asserts to system log in the debug
    driver build.

Notes:

\*****************************************************************************/

#if defined( _WIN32 ) && (defined( _DEBUG ) || defined( _RELEASE_INTERNAL ))
#include "AssertTracer.h"
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

// Windows.h defines MemoryFence as _mm_mfence, but this conflicts with llvm::sys::MemoryFence
#undef MemoryFence
#include <stdio.h>
#include <stdlib.h>

#if defined( __GMM_KMD__ ) || defined( STATIC_DRIVER_MODEL )
#include"BufferedDbg.h"
#include "igdKrnlEtwMacros.h"
#endif //__GMM_KMD__ || STATIC_DRIVER_MODEL

#if _DEBUG
/*****************************************************************************\

Function:
    ReportAsserts

Description:
    Sends message to the system log.

Input:
    const char *expr -
        The expression passed to function.
    const char *file -
        The name of the file that is the origin of the expression.
    const char *func -
        The function from which call to this function was made.
    const unsigned long line -
        The line number from file, which caused this function call.
    const char *msg -
        Message passed to the system log.
Output:
    void - None.

\*****************************************************************************/
void __stdcall ReportAssert(
    const char              *expr,
    const char              *file,
    const char              *func,
    const unsigned long      line,
    const char              *msg )
{
#if !defined( __GMM_KMD__ ) && !defined( STATIC_DRIVER_MODEL )//We are in UMD, use the UMD implementation

#if 0

    HANDLE hEventLog = RegisterEventSourceA( NULL, "GFX Driver AssertTracer" );
    char *wideMessage;
    if ( hEventLog != NULL )
    {
        // Calculate length with hard coded max unsigned long length plus some safe space.
        size_t length = strlen( expr ) + strlen( file ) + strlen( func ) + strlen( msg ) + 15;

        // Checks against maximum string size for ReportEvent lpStrings parameter.
        // Cuts string to the limit size.
        uint32_t maxSizeReached = 0;
        if ( length > 31839 )
        {
            length = 31839;
            maxSizeReached = 1;
        }

        wideMessage = ( char * ) malloc( sizeof( char ) * length );
        if( wideMessage != NULL )
        {
            // snprintf spec: "The resulting character string will be terminated with a null character"
            _snprintf_s( wideMessage, length, length / sizeof( char ), "%s:%lu\n%s\n%s\n%s", file, line, expr, func, msg);

            ReportEventA( hEventLog, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, ( LPCSTR* ) &wideMessage, NULL );
            free( wideMessage );
        }

        DeregisterEventSource( hEventLog );
    }

#endif //!define( WINDOWS_MOBILE )

    // Windows Mobile has no implementation. Reference the parameters to remove the unreference param warnings.
    (void)expr;
    (void)file;
    (void)func;
    (void)line;
    (void)msg;

#else //We are in KMD, use the KMD implementation
    BufDbgPrint("ASSERT_TRACE: %s::%s:%i : %s : %s\n", file, func, line, expr, msg);
#endif //!defined( __GMM_KMD__ ) && !defined( STATIC_DRIVER_MODEL )
}
#endif

/*****************************************************************************\

Function:
    ReportAssertsETW

Description:
    Sends message to the system log.

Input:
    const unsigned long ComponentMask
        Contains the component id for which raised assert (KMD, MINIPORT..)
    const char *expr -
        The expression passed to function.
    const char *file -
        The name of the file that is the origin of the expression.
    const char *func -
        The function from which call to this function was made.
    const unsigned long line -
        The line number from file, which caused this function call.
    const char *msg -
        Message passed to the system log.
Output:
    void - None.

\*****************************************************************************/

void __stdcall ReportAssertETW( const unsigned short     compId,
                                const unsigned long      compMsk,
                                const char              *expr,
                                const char              *file,
                                const char              *func,
                                const unsigned long     line,
                                const char              *msg)
{
#if !defined( __GMM_KMD__ ) && !defined( STATIC_DRIVER_MODEL ) //We are in UMD, use the UMD implementation
    // TODO: Add UMD code for ETW here.
    // Reference the parameters to remove the unreference param warnings.
    (void)compId;
    (void)compMsk;
    (void)expr;
    (void)file;
    (void)func;
    (void)line;
    (void)msg;
#else //We are in KMD, use the KMD implementation
    // Log event if ETW session is active
    if (g_ulHDGraphics_SessionActive)
    {
        EtwAssertPrint(compId, compMsk, expr, file, func, line, msg);
    }
#endif
}

#elif defined( __linux__ ) && defined( _RELEASE_INTERNAL ) && !defined( __ANDROID__ )
#include <algorithm>
#include <syslog.h>
#include <execinfo.h>
#include <string>
#include <cxxabi.h>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <fstream>
#define CALL_STACK_REPORT_SIZE 50  // maximal limit of call stack to be reported in case of assertion
#define MAX_FUNCTION_NAME_LENGTH 100 // no worries it can be extended (relocated by driver if needed)
#define MAX_SYSLOG_ENTRY_LENGTH 1000 // Syslog protocol recommends minimum entry length 1KB (ubuntu rsyslog message limit is about 2K)
void LogAssertion( const char *function_name, const char *file_name, unsigned int line_number, const char *expr )
{
    std::string  stack;
    std::string  part1;
    std::string  part2;
    std::size_t  pos;
    void         *buffer[CALL_STACK_REPORT_SIZE];
    char         *function_name_buffer = NULL;
    int          nframes;        // numer of frames to be returned
    char         **strings;
    int          i;
    int          status;
    size_t       length;
    const size_t stringLength = 4096;
    std::string  oclAppCmdLine;

    nframes = backtrace( buffer, CALL_STACK_REPORT_SIZE );

    strings = backtrace_symbols( buffer, nframes );
    if( strings == NULL )
    {
        perror( "Getting backtrace symbols error:" );
        nframes = 0;
    }
    else
    {
        // Get Commandline of process (in that case OCL app)
        // from process info itself eg. /proc/self/cmdline

        oclAppCmdLine.reserve( stringLength );
        std::ifstream fileCmdline( "/proc/self/cmdline", std::ifstream::binary );
        if( fileCmdline.is_open() )
        {
            oclAppCmdLine = std::string( std::istreambuf_iterator< char >( fileCmdline ), std::istreambuf_iterator< char >() );
            if( oclAppCmdLine.size() > 0 )
            {
                // Trim last \0 character
                oclAppCmdLine.resize( oclAppCmdLine.size() - 1 );
                // Format of /proc/self/cmdline is that args are separated with '\0'
                // so for nicer printing we replace zeros with spaces (without terminating 0)
                std::replace( oclAppCmdLine.begin(), oclAppCmdLine.end(), '\0', ' ' );
            }
            else
            {
                fprintf( stderr, "Getting Commandline of OCL app error: Error reading /proc/self/cmdline\n" );
            }
        }
        else
        {
            fprintf( stderr, "Getting Commandline of OCL app error:" );
        }
    }

    // allocation by malloc is suggessted by documentation as abi function may do some relocation
    function_name_buffer = ( char * )malloc( MAX_FUNCTION_NAME_LENGTH );
    if( function_name_buffer == NULL )
    {
        // Not enough memory to get small allocation then do not print stack
        nframes = 0;
    }
    else
    {
        length = MAX_FUNCTION_NAME_LENGTH;
        memset( function_name_buffer, 0, length );
    }

    for( i = 0; i < nframes; ++i )
    {
        // Generate signature of given stack frame eg. #0 #1 etc...
        std::stringstream framePromptBuilder;
        framePromptBuilder << "#" << i << " ";
        const std::string &framePrompt = framePromptBuilder.str();
        // demangle name eg. split stack frame into two pieces
        part1 = strings[i];
        pos   = part1.find( "(" );
        if( pos != std::string::npos )
        {
            // For final level instead of binary print whole commandline
            // if were able to get one
            if( ( i == nframes - 1 ) && ( !oclAppCmdLine.empty() ) )
            {
                //..call stack's part1 contains "(" so we add it here manualy
                stack.append( ( oclAppCmdLine.insert( 0, "COMMANDLINE(" ) ).c_str() );
            }
            else
            {
                // part1 contains everything before section to be demangled
                part1 = part1.substr( 0, pos + 1 );
                stack.append(framePrompt);
                stack.append( part1 );
            }
            // part2 contains string to be demangled
            part2 = strings[i];
            part2 = part2.substr( pos + 1 );
            pos   = part2.find( "+" );
            // Final level may not have any function (static functions are not exposed)
            if( pos != std::string::npos )
            {
                part2                = part2.substr( 0, pos );
                function_name_buffer = abi::__cxa_demangle( part2.c_str(), function_name_buffer, &length, &status );
                // in case of error during demangling attach mangled name
                if( status != 0 )
                {
                    stack.append( part2 );
                }
                else
                {
                    stack.append( function_name_buffer );
                }
                stack.append( "())" );
                free( function_name_buffer );
                function_name_buffer = NULL;

            }
            else
            {
                // if there was no function then attach ")"
                stack.append( ")" );
            }
        }
        else
        {
            if( ( i == nframes - 1 ) && ( !oclAppCmdLine.empty() ) )
            {
                stack.append( ( oclAppCmdLine.insert( 0, "COMMANDLINE(" ) ).c_str() );
                stack.append( ")" );
            }
            else
            {
                stack.append(framePrompt);
                stack.append( strings[i] );
            }
        }
        stack.append( " " );
    }
    //Compose full message..
    std::string fullMsg = "File: ";
    std::string syslogEntry;
    fullMsg += file_name;
    fullMsg += " line: ";
    std::stringstream lineStr;
    lineStr << line_number;
    fullMsg += lineStr.str();
    fullMsg += " function: ";
    fullMsg += function_name;
    fullMsg += " expr: ";
    fullMsg += expr;
    fullMsg += " ";
    fullMsg += stack.c_str();

    // split it into chunks we can send
    openlog( "OpenCL", LOG_PID, LOG_USER );
    pos = 0;
    int numberOfChunks = ( fullMsg.length() / MAX_SYSLOG_ENTRY_LENGTH ) + 1;
    while( pos < fullMsg.length() )
    {
        syslogEntry = fullMsg.substr( pos, MAX_SYSLOG_ENTRY_LENGTH );
        // Add chunk ID / part number and send to syslog
        syslog( LOG_MAKEPRI( LOG_USER,
                             LOG_ERR ), "[%zd/%d]%s", ( pos / MAX_SYSLOG_ENTRY_LENGTH + 1 ), numberOfChunks,
                syslogEntry.c_str() );
        pos += MAX_SYSLOG_ENTRY_LENGTH;
    }
    closelog();

    // backtrace_symbols allocates memory in a malloc like way sop it should be freed
    free( strings );
    strings = NULL;
}
#endif //defined( _WIN32 ) && defined( _DEBUG )