File: valddi.cpp.mako

package info (click to toggle)
level-zero 1.28.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,308 kB
  • sloc: cpp: 149,246; ansic: 16,655; python: 12,807; makefile: 5
file content (426 lines) | stat: -rw-r--r-- 17,274 bytes parent folder | download
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
<%!
import re
from templates import helper as th
%><%
    n=namespace
    N=n.upper()

    x=tags['$x']
    X=x.upper()
%>/*
 * ***THIS FILE IS GENERATED. ***
 * See valddi.cpp.mako for modifications
 *
 * Copyright (C) 2019-2026 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 * @file ${name}
 *
 */
#include "${x}_validation_layer.h"
#include <sstream>

// Define a macro for marking potentially unused functions
#if defined(_MSC_VER)
    // MSVC doesn't support __attribute__((unused)), just omit the marking
    #define VALIDATION_MAYBE_UNUSED
#elif defined(__GNUC__) || defined(__clang__)
    // GCC and Clang support __attribute__((unused))
    #define VALIDATION_MAYBE_UNUSED __attribute__((unused))
#else
    #define VALIDATION_MAYBE_UNUSED
#endif

namespace validation_layer
{
%if n == 'ze':
    // Forward declaration for Intel experimental extension
    // This is needed because zeDriverGetExtensionFunctionAddress needs to reference zexCounterBasedEventCreate2
    __zedlllocal ze_result_t ZE_APICALL zexCounterBasedEventCreate2(
        ze_context_handle_t hContext,
        ze_device_handle_t hDevice,
        const void *desc,
        ze_event_handle_t *phEvent
    );

%endif
    // Generate specific logAndPropagateResult functions for each API function
    %for obj in th.extract_objs(specs, r"function"):
    <%
    func_name = th.make_func_name(n, tags, obj)
    param_lines = [line for line in th.make_param_lines(n, tags, obj, format=['name','delim'])]
    param_names = [line for line in th.make_param_lines(n, tags, obj, format=['name'])]
    is_void_params = len(param_lines) == 0
    %>\
    %if 'condition' in obj:
#if ${th.subt(n, tags, obj['condition'])}
    %endif
    VALIDATION_MAYBE_UNUSED static ze_result_t logAndPropagateResult_${func_name}(
        ze_result_t result\
%if not is_void_params:
,
        %for line in th.make_param_lines(n, tags, obj):
        ${line}
        %endfor
%endif
) {
        // Only log success results if verbose logging is enabled
        if (result == ${X}_RESULT_SUCCESS && !context.verboseLogging) {
            return result;
        }
        std::string status = (result == ${X}_RESULT_SUCCESS) ? "SUCCESS" : "ERROR";
        %if is_void_params:
        context.logger->log_trace(status + " (" + loader::to_string(result) + ") in ${func_name}()");
        %else:
        std::ostringstream oss;
        oss << status << " (" << loader::to_string(result) << ") in ${func_name}(";
        <%
        params_list = obj.get('params', [])
        %>
        %for i, param_name in enumerate([p for p in th.make_param_lines(n, tags, obj, format=['name'])]):
        <%
        # Get parameter metadata
        param_obj = params_list[i] if i < len(params_list) else None
        param_type = param_obj.get('type', '') if param_obj else ''
        param_desc = param_obj.get('desc', '') if param_obj else ''
        is_output_param = '[out]' in param_desc
        is_pointer = '*' in param_type and param_type.strip().endswith('*')
        %>
        %if i > 0:
        oss << ", ";
        %endif
        oss << "${param_name}=";
        %if is_output_param and is_pointer:
        // Dereference output parameter if not null and result is success
        if (result == ${X}_RESULT_SUCCESS && ${param_name} != nullptr) {
            oss << loader::to_string(*${param_name});
        } else {
            oss << loader::to_string(${param_name});
        }
        %else:
        oss << loader::to_string(${param_name});
        %endif
        %endfor
        oss << ")";
        context.logger->log_trace(oss.str());
        %endif
        return result;
    }
    %if 'condition' in obj:
#endif // ${th.subt(n, tags, obj['condition'])}
    %endif
    %endfor
\
%if n == 'ze':
    // Special function for zexCounterBasedEventCreate2
    VALIDATION_MAYBE_UNUSED static ze_result_t logAndPropagateResult_zexCounterBasedEventCreate2(
        ze_result_t result,
        ze_context_handle_t hContext,
        ze_device_handle_t hDevice,
        const void* desc,
        ze_event_handle_t* phEvent
    ) {
        // Only log success results if verbose logging is enabled
        if (result == ${X}_RESULT_SUCCESS && !context.verboseLogging) {
            return result;
        }
        std::string status = (result == ${X}_RESULT_SUCCESS) ? "SUCCESS" : "ERROR";
        std::ostringstream oss;
        oss << status << " (" << loader::to_string(result) << ") in zexCounterBasedEventCreate2("
            << "hContext=" << static_cast<const void*>(hContext) << ", "
            << "hDevice=" << static_cast<const void*>(hDevice) << ", "
            << "desc=" << desc << ", "
            << "phEvent=";
        // Dereference output parameter if not null and result is success
        if (result == ${X}_RESULT_SUCCESS && phEvent != nullptr) {
            oss << loader::to_string(*phEvent);
        } else {
            oss << static_cast<const void*>(phEvent);
        }
        oss << ")";
        context.logger->log_trace(oss.str());
        return result;
    }
%endif

    %for obj in th.extract_objs(specs, r"function"):
    <%
    ret_type = obj['return_type']
    failure_return = None
    if ret_type != 'ze_result_t':
        failure_return = th.get_first_failure_return(obj)
    param_lines = [line for line in th.make_param_lines(n, tags, obj, format=['name','delim'])]
    is_void_params = len(param_lines) == 0
    %>///////////////////////////////////////////////////////////////////////////////
    /// @brief Intercept function for ${th.make_func_name(n, tags, obj)}
    %if 'condition' in obj:
    #if ${th.subt(n, tags, obj['condition'])}
    %endif
    __${x}dlllocal ${ret_type} ${X}_APICALL
    ${th.make_func_name(n, tags, obj)}(
        %for line in th.make_param_lines(n, tags, obj):
        ${line}
        %endfor
        )
    {
        context.logger->log_trace("${th.make_func_name(n, tags, obj)}(${", ".join(th.make_param_lines(n, tags, obj, format=["name", "local"]))})");

        auto ${th.make_pfn_name(n, tags, obj)} = context.${n}DdiTable.${th.get_table_name(n, tags, obj)}.${th.make_pfn_name(n, tags, obj)};

        if( nullptr == ${th.make_pfn_name(n, tags, obj)} )
        %if ret_type == "ze_result_t":
            return logAndPropagateResult_${th.make_func_name(n, tags, obj)}(${X}_RESULT_ERROR_UNSUPPORTED_FEATURE${', ' if not is_void_params else ''}${', '.join(th.make_param_lines(n, tags, obj, format=["name"]))});
        %else:
            return ${failure_return};
        %endif

        auto numValHandlers = context.validationHandlers.size();
        for (size_t i = 0; i < numValHandlers; i++) {
            auto result = context.validationHandlers[i]->${n}Validation->${th.make_func_name(n, tags, obj)}Prologue( \
% for line in param_lines:
${line} \
%endfor
);
            if(result!=${X}_RESULT_SUCCESS) \
%if ret_type == "ze_result_t":
return logAndPropagateResult_${th.make_func_name(n, tags, obj)}(result${', ' if not is_void_params else ''}${', '.join(th.make_param_lines(n, tags, obj, format=["name"]))});
%else:
return ${failure_return};
%endif
        }


        if( context.enableThreadingValidation ){ 
            //Unimplemented
        }

        <% 
        func_name = th.make_func_name(n, tags, obj)
        generate_post_call = re.match(r"\w+Create\w*$|\w+Get$|\w+Get\w*Exp$|\w+GetIpcHandle$|\w+GetSubDevices$", func_name)
        %>
        if(context.enableHandleLifetime ){
            auto result = context.handleLifetime->${n}HandleLifetime.${th.make_func_name(n, tags, obj)}Prologue( \
% for line in param_lines:
${line} \
%endfor
);
            if(result!=${X}_RESULT_SUCCESS) \
%if ret_type == "ze_result_t":
return logAndPropagateResult_${th.make_func_name(n, tags, obj)}(result${', ' if not is_void_params else ''}${', '.join(th.make_param_lines(n, tags, obj, format=["name"]))});
%else:
return ${failure_return};
%endif
        }

        auto driver_result = ${th.make_pfn_name(n, tags, obj)}( ${", ".join(th.make_param_lines(n, tags, obj, format=["name"]))} );
%if 'ppFunctionAddress' in [p.get('name', '') for p in obj.get('params', [])] and n == 'ze':

        // For Intel experimental extensions, we need to return our validation layer function
        // instead of the raw driver function so that validation/leak tracking works
        if (driver_result == ZE_RESULT_SUCCESS && ppFunctionAddress && name) {
            if (strcmp(name, "zexCounterBasedEventCreate2") == 0) {
                // Return our validation layer intercept function instead of the raw driver function
                *ppFunctionAddress = (void*)zexCounterBasedEventCreate2;
            }
        }
%endif

        for (size_t i = 0; i < numValHandlers; i++) {
            auto result = context.validationHandlers[i]->${n}Validation->${th.make_func_name(n, tags, obj)}Epilogue( \
%if not is_void_params:
% for line in param_lines:
${line} \
%endfor
,driver_result);
%else:
driver_result );
%endif
            if(result!=${X}_RESULT_SUCCESS) \
%if ret_type == "ze_result_t":
return logAndPropagateResult_${th.make_func_name(n, tags, obj)}(result${', ' if not is_void_params else ''}${', '.join(th.make_param_lines(n, tags, obj, format=["name"]))});
%else:
return ${failure_return};
%endif
        }

        %if generate_post_call:

        if( driver_result == ${X}_RESULT_SUCCESS && context.enableHandleLifetime ){
            ## Add 'Created' handles/objects to dependent maps
            <% lines = th.make_param_lines(n, tags, obj, format=['name','delim'])
            %>
            %for i, item in enumerate(th.get_loader_epilogue(n, tags, obj, meta)):
            %if 'range' in item:
            for (size_t i = ${item['range'][0]}; ( nullptr != ${item['name']}) && (i < ${item['range'][1]}); ++i){
                if (${item['name']}[i]){
                    context.handleLifetime->addHandle( ${item['name']}[i] );
                    %if th.type_traits.is_handle(item['type']):
                    context.handleLifetime->addDependent( ${lines[0]} ${item['name']}[i] );
                    %endif
                }
            }
            %else:
            if (${item['name']}){
                %if re.match(r"\w+Immediate$", func_name):
                context.handleLifetime->addHandle( *${item['name']} , false);
                %else:
                context.handleLifetime->addHandle( *${item['name']} );
                %if th.type_traits.is_handle(item['type']):
                context.handleLifetime->addDependent( ${lines[0]} *${item['name']} );
                %endif

                %endif
            }
            %endif
            %endfor
        }
        %endif
        %if ret_type == "ze_result_t":
        return logAndPropagateResult_${th.make_func_name(n, tags, obj)}(driver_result${', ' if not is_void_params else ''}${', '.join(th.make_param_lines(n, tags, obj, format=["name"]))});
        %else:
        return driver_result;
        %endif
    }
    %if 'condition' in obj:
    #endif // ${th.subt(n, tags, obj['condition'])}
    %endif

    %endfor
%if n == 'ze':
    ///////////////////////////////////////////////////////////////////////////////
    /// @brief Intercept function for zexCounterBasedEventCreate2
    __zedlllocal ze_result_t ZE_APICALL zexCounterBasedEventCreate2(
        ze_context_handle_t hContext,                   ///< [in] handle of the context object
        ze_device_handle_t hDevice,                     ///< [in] handle of the device
        const void* desc,                               ///< [in] pointer to counter-based event descriptor
        ze_event_handle_t* phEvent                      ///< [out] pointer to handle of event object created
        )
    {
        context.logger->log_trace("zexCounterBasedEventCreate2(hContext, hDevice, desc, phEvent)");

        // Note: This is an experimental function that may not have a DDI table entry.
        // For now, we'll return unsupported feature as this function should be
        // accessed through zeDriverGetExtensionFunctionAddress mechanism, but we
        // still want to track it in the validation layers for leak checking purposes.

        auto numValHandlers = context.validationHandlers.size();
        for (size_t i = 0; i < numValHandlers; i++) {
            auto result = context.validationHandlers[i]->zeValidation->zexCounterBasedEventCreate2Prologue( hContext, hDevice, desc, phEvent );
            if(result!=ZE_RESULT_SUCCESS) return logAndPropagateResult_zexCounterBasedEventCreate2(result, hContext, hDevice, desc, phEvent);
        }

        if(context.enableThreadingValidation){
            //Unimplemented
        }

        if(context.enableHandleLifetime){
            auto result = context.handleLifetime->zeHandleLifetime.zexCounterBasedEventCreate2Prologue( hContext, hDevice, desc, phEvent );
            if(result!=ZE_RESULT_SUCCESS) return logAndPropagateResult_zexCounterBasedEventCreate2(result, hContext, hDevice, desc, phEvent);
        }

        // This is an experimental function that must be accessed through the extension mechanism
        // We need to get the function pointer through zeDriverGetExtensionFunctionAddress
        ze_result_t driver_result = ZE_RESULT_ERROR_UNSUPPORTED_FEATURE;

        // Get the real Intel experimental function through the extension mechanism
        auto pfnGetExtensionFunctionAddress = context.zeDdiTable.Driver.pfnGetExtensionFunctionAddress;

        if (pfnGetExtensionFunctionAddress) {
            // Get the driver handle - use the first available driver
            ze_driver_handle_t hDriver = nullptr;

            if (context.zeDdiTable.Driver.pfnGet) {
                uint32_t driverCount = 1;
                ze_driver_handle_t drivers[1] = {nullptr};
                auto result = context.zeDdiTable.Driver.pfnGet(&driverCount, drivers);
                if (result == ZE_RESULT_SUCCESS && driverCount > 0) {
                    hDriver = drivers[0];
                }
            }

            if (hDriver) {
                // Get the real Intel experimental function
                typedef ze_result_t (*zexCounterBasedEventCreate2_t)(ze_context_handle_t, ze_device_handle_t, const void*, ze_event_handle_t*);
                zexCounterBasedEventCreate2_t pfnRealFunction = nullptr;

                auto ext_result = pfnGetExtensionFunctionAddress(hDriver, "zexCounterBasedEventCreate2", (void**)&pfnRealFunction);

                if (ext_result == ZE_RESULT_SUCCESS && pfnRealFunction) {
                    // Call the real Intel experimental function
                    driver_result = pfnRealFunction(hContext, hDevice, desc, phEvent);
                } else {
                    // Extension not available in this driver
                    driver_result = ZE_RESULT_ERROR_UNSUPPORTED_FEATURE;
                }
            }
        }

        for (size_t i = 0; i < numValHandlers; i++) {
            auto result = context.validationHandlers[i]->zeValidation->zexCounterBasedEventCreate2Epilogue( hContext, hDevice, desc, phEvent, driver_result);
            if(result!=ZE_RESULT_SUCCESS) return logAndPropagateResult_zexCounterBasedEventCreate2(result, hContext, hDevice, desc, phEvent);
        }

        if(driver_result == ZE_RESULT_SUCCESS && context.enableHandleLifetime){
            if (phEvent){
                context.handleLifetime->addHandle( *phEvent );
                // Note: counter-based events may not have a traditional event pool dependency
            }
        }
        return logAndPropagateResult_zexCounterBasedEventCreate2(driver_result, hContext, hDevice, desc, phEvent);
    }
%endif
} // namespace validation_layer

#if defined(__cplusplus)
extern "C" {
#endif

%for tbl in th.get_pfntables(specs, meta, n, tags):
///////////////////////////////////////////////////////////////////////////////
/// @brief Exported function for filling application's ${tbl['name']} table
///        with current process' addresses
///
/// @returns
///     - ::${X}_RESULT_SUCCESS
///     - ::${X}_RESULT_ERROR_INVALID_NULL_POINTER
///     - ::${X}_RESULT_ERROR_UNSUPPORTED_VERSION
${X}_DLLEXPORT ${x}_result_t ${X}_APICALL
${tbl['export']['name']}(
    %for line in th.make_param_lines(n, tags, tbl['export']):
    ${line}
    %endfor
    )
{
    auto& dditable = validation_layer::context.${n}DdiTable.${tbl['name']};

    if( nullptr == pDdiTable )
        return ${X}_RESULT_ERROR_INVALID_NULL_POINTER;

    if (validation_layer::context.version < version)
        return ${X}_RESULT_ERROR_UNSUPPORTED_VERSION;

    ${x}_result_t result = ${X}_RESULT_SUCCESS;

    %for obj in tbl['functions']:
    if (version >= ${th.get_version(obj)}) {
    %if 'condition' in obj:
#if ${th.subt(n, tags, obj['condition'])}
    %endif
        dditable.${th.append_ws(th.make_pfn_name(n, tags, obj), 43)} = pDdiTable->${th.make_pfn_name(n, tags, obj)};
        pDdiTable->${th.append_ws(th.make_pfn_name(n, tags, obj), 41)} = validation_layer::${th.make_func_name(n, tags, obj)};
    %if 'condition' in obj:
#else
        dditable.${th.append_ws(th.make_pfn_name(n, tags, obj), 43)} = nullptr;
        pDdiTable->${th.append_ws(th.make_pfn_name(n, tags, obj), 41)} = nullptr;
#endif
    %endif
    }
    %endfor
    return result;
}

%endfor
#if defined(__cplusplus)
};
#endif