Skip to content

Commit f7facbb

Browse files
[UR][L0] Added safety checks to prevent double urProgramRelease
Users used to be able to call urProgramRelease on the same module, but with these changes, that would no longer be possible. Signed-off-by: Zhang, Winston <[email protected]>
1 parent 6276f1b commit f7facbb

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

unified-runtime/source/adapters/level_zero/program.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,55 @@ ur_result_t urProgramRetain(
565565
ur_result_t urProgramRelease(
566566
/// [in] handle for the Program to release
567567
ur_program_handle_t Program) {
568+
if (!Program)
569+
return UR_RESULT_ERROR_INVALID_NULL_HANDLE;
570+
571+
// Detect double-release by attempting to safely access program members
572+
// and catching any access violations that indicate freed memory
573+
try {
574+
// First, try to access the RefCount to see if it's valid
575+
uint32_t currentRefCount = Program->RefCount.getCount();
576+
577+
if (currentRefCount == 0) {
578+
// This is a double-release - RefCount should never be 0 when
579+
// urProgramRelease is called
580+
return UR_RESULT_ERROR_INVALID_PROGRAM;
581+
}
582+
583+
if (Program->resourcesReleased) {
584+
// Resources already released, this is a double-release attempt
585+
return UR_RESULT_ERROR_INVALID_PROGRAM;
586+
}
587+
588+
if (!Program->Context) {
589+
// Check if the program has a valid context
590+
return UR_RESULT_ERROR_INVALID_PROGRAM;
591+
}
592+
593+
if (!Program->AssociatedDevices.empty()) {
594+
for (const auto &Device : Program->AssociatedDevices) {
595+
if (Device && Device->ZeDevice) {
596+
ze_module_handle_t zeModuleHandle =
597+
Program->getZeModuleHandle(Device->ZeDevice);
598+
599+
// Validate that the retrieved module handle is valid
600+
// A null module handle in certain states could indicate corruption or
601+
// double-release
602+
if (!zeModuleHandle) {
603+
return UR_RESULT_ERROR_INVALID_PROGRAM;
604+
}
605+
}
606+
}
607+
}
608+
609+
} catch (...) {
610+
// If we can't safely access the program members, it's likely
611+
// corrupted/freed This catches the case where urProgramRelease is called on
612+
// the same module twice
613+
return UR_RESULT_ERROR_INVALID_PROGRAM;
614+
}
615+
616+
// Perform the actual release
568617
if (!Program->RefCount.release())
569618
return UR_RESULT_SUCCESS;
570619

0 commit comments

Comments
 (0)