2 * ReactOS W32 Subsystem
3 * Copyright (C) 1998 - 2004 ReactOS Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 * GDIOBJ.C - GDI object manipulation routines
25 #include <ddk/ntddk.h>
33 /* F*(&#$ header mess!!!! */
35 STDCALL
PsGetProcessId(
40 KeRosGetStackFrames ( PULONG Frames
, ULONG FrameCount
);
41 #endif /* __USE_W32API */
46 #define GDI_ENTRY_TO_INDEX(ht, e) \
47 (((ULONG_PTR)(e) - (ULONG_PTR)&((ht)->Entries[0])) / sizeof(GDI_TABLE_ENTRY))
48 #define GDI_HANDLE_GET_ENTRY(HandleTable, h) \
49 (&(HandleTable)->Entries[GDI_HANDLE_GET_INDEX((h))])
51 #define GDIBdyToHdr(body) \
52 ((PGDIOBJHDR)(body) - 1)
53 #define GDIHdrToBdy(hdr) \
54 (PGDIOBJ)((PGDIOBJHDR)(hdr) + 1)
56 /* apparently the first 10 entries are never used in windows as they are empty */
57 #define RESERVE_ENTRIES_COUNT 10
59 typedef struct _GDI_HANDLE_TABLE
61 /* the table must be located at the beginning of this structure so it can be
63 GDI_TABLE_ENTRY Entries
[GDI_HANDLE_COUNT
];
65 PPAGED_LOOKASIDE_LIST LookasideLists
;
67 SLIST_HEADER FreeEntriesHead
;
68 SLIST_ENTRY FreeEntries
[((GDI_HANDLE_COUNT
* sizeof(GDI_TABLE_ENTRY
)) << 3) /
69 (sizeof(SLIST_ENTRY
) << 3)];
70 } GDI_HANDLE_TABLE
, *PGDI_HANDLE_TABLE
;
76 GDICLEANUPPROC CleanupProc
;
77 } GDI_OBJ_INFO
, *PGDI_OBJ_INFO
;
80 * Dummy GDI Cleanup Callback
83 GDI_CleanupDummy(PVOID ObjectBody
)
88 /* Testing shows that regions are the most used GDIObj type,
89 so put that one first for performance */
91 GDI_OBJ_INFO ObjInfo
[] =
93 /* Type */ /* Size */ /* CleanupProc */
94 {GDI_OBJECT_TYPE_REGION
, sizeof(ROSRGNDATA
), RGNDATA_Cleanup
},
95 {GDI_OBJECT_TYPE_BITMAP
, sizeof(BITMAPOBJ
), BITMAP_Cleanup
},
96 {GDI_OBJECT_TYPE_DC
, sizeof(DC
), DC_Cleanup
},
97 {GDI_OBJECT_TYPE_PALETTE
, sizeof(PALGDI
), PALETTE_Cleanup
},
98 {GDI_OBJECT_TYPE_BRUSH
, sizeof(GDIBRUSHOBJ
), BRUSH_Cleanup
},
99 {GDI_OBJECT_TYPE_PEN
, sizeof(GDIBRUSHOBJ
), GDI_CleanupDummy
},
100 {GDI_OBJECT_TYPE_FONT
, sizeof(TEXTOBJ
), GDI_CleanupDummy
},
101 {GDI_OBJECT_TYPE_DCE
, sizeof(DCE
), DCE_Cleanup
},
102 /*{GDI_OBJECT_TYPE_DIRECTDRAW, sizeof(DD_DIRECTDRAW), DD_Cleanup},
103 {GDI_OBJECT_TYPE_DD_SURFACE, sizeof(DD_SURFACE), DDSURF_Cleanup},*/
104 {GDI_OBJECT_TYPE_EXTPEN
, 0, GDI_CleanupDummy
},
105 {GDI_OBJECT_TYPE_METADC
, 0, GDI_CleanupDummy
},
106 {GDI_OBJECT_TYPE_METAFILE
, 0, GDI_CleanupDummy
},
107 {GDI_OBJECT_TYPE_ENHMETAFILE
, 0, GDI_CleanupDummy
},
108 {GDI_OBJECT_TYPE_ENHMETADC
, 0, GDI_CleanupDummy
},
109 {GDI_OBJECT_TYPE_MEMDC
, 0, GDI_CleanupDummy
},
110 {GDI_OBJECT_TYPE_EMF
, 0, GDI_CleanupDummy
}
113 #define OBJTYPE_COUNT (sizeof(ObjInfo) / sizeof(ObjInfo[0]))
115 static PGDI_HANDLE_TABLE HandleTable
= NULL
;
116 static LARGE_INTEGER ShortDelay
;
118 #define DelayExecution() \
119 DPRINT("%s:%i: Delay\n", __FILE__, __LINE__); \
120 KeDelayExecutionThread(KernelMode, FALSE, &ShortDelay)
123 * Allocate GDI object table.
124 * \param Size - number of entries in the object table.
126 static PGDI_HANDLE_TABLE INTERNAL_CALL
127 GDIOBJ_iAllocHandleTable(VOID
)
129 PGDI_HANDLE_TABLE handleTable
;
133 PGDI_TABLE_ENTRY Entry
;
136 htSize
= sizeof(GDI_HANDLE_TABLE
);
138 IntUserCreateSharedSection(SessionSharedSectionPool
,
139 (PVOID
*)&handleTable
,
141 ASSERT( handleTable
);
142 RtlZeroMemory(handleTable
, sizeof(GDI_HANDLE_TABLE
));
145 * initialize the free entry cache
147 InitializeSListHead(&handleTable
->FreeEntriesHead
);
148 Entry
= &HandleTable
->Entries
[RESERVE_ENTRIES_COUNT
];
149 for(i
= GDI_HANDLE_COUNT
- 1; i
>= RESERVE_ENTRIES_COUNT
; i
--)
151 InterlockedPushEntrySList(&handleTable
->FreeEntriesHead
, &handleTable
->FreeEntries
[i
]);
154 handleTable
->LookasideLists
= ExAllocatePoolWithTag(NonPagedPool
,
155 OBJTYPE_COUNT
* sizeof(PAGED_LOOKASIDE_LIST
),
157 if(handleTable
->LookasideLists
== NULL
)
159 InUserDeleteSharedSection(SessionSharedSectionPool
,
164 for(ObjType
= 0; ObjType
< OBJTYPE_COUNT
; ObjType
++)
166 ExInitializePagedLookasideList(handleTable
->LookasideLists
+ ObjType
, NULL
, NULL
, 0,
167 ObjInfo
[ObjType
].Size
+ sizeof(GDIOBJHDR
), TAG_GDIOBJ
, 0);
170 ShortDelay
.QuadPart
= -5000LL; /* FIXME - 0.5 ms? */
175 static inline PPAGED_LOOKASIDE_LIST
176 FindLookasideList(DWORD ObjectType
)
180 for (Index
= 0; Index
< OBJTYPE_COUNT
; Index
++)
182 if (ObjInfo
[Index
].Type
== ObjectType
)
184 return HandleTable
->LookasideLists
+ Index
;
188 DPRINT1("Can't find lookaside list for object type 0x%08x\n", ObjectType
);
194 RunCleanupCallback(PGDIOBJ pObj
, DWORD ObjectType
)
198 for (Index
= 0; Index
< OBJTYPE_COUNT
; Index
++)
200 if (ObjInfo
[Index
].Type
== ObjectType
)
202 return ((GDICLEANUPPROC
)ObjInfo
[Index
].CleanupProc
)(pObj
);
206 DPRINT1("Can't find cleanup callback for object type 0x%08x\n", ObjectType
);
211 GetObjectSize(DWORD ObjectType
)
215 for (Index
= 0; Index
< OBJTYPE_COUNT
; Index
++)
217 if (ObjInfo
[Index
].Type
== ObjectType
)
219 return ObjInfo
[Index
].Size
;
223 DPRINT1("Can't find size for object type 0x%08x\n", ObjectType
);
229 static int leak_reported
= 0;
230 #define GDI_STACK_LEVELS 12
231 static ULONG GDIHandleAllocator
[GDI_HANDLE_COUNT
][GDI_STACK_LEVELS
];
232 struct DbgOpenGDIHandle
238 static struct DbgOpenGDIHandle h
[H
];
240 void IntDumpHandleTable()
242 int i
, n
= 0, j
, k
, J
;
246 DPRINT1("gdi handle abusers already reported!\n");
251 DPRINT1("reporting gdi handle abusers:\n");
253 /* step through GDI handle table and find out who our culprit is... */
254 for ( i
= RESERVE_ENTRIES_COUNT
; i
< GDI_HANDLE_COUNT
; i
++ )
256 for ( j
= 0; j
< n
; j
++ )
260 for ( k
= 0; k
< GDI_STACK_LEVELS
; k
++ )
262 if ( GDIHandleAllocator
[i
][k
]
263 != GDIHandleAllocator
[J
][k
] )
286 /* bubble sort time! weeeeee!! */
287 for ( i
= 0; i
< n
-1; i
++ )
289 if ( h
[i
].count
< h
[i
+1].count
)
291 struct DbgOpenGDIHandle t
;
295 while ( j
> 0 && h
[j
-1].count
< t
.count
)
300 /* print the worst offenders... */
301 DbgPrint ( "Worst GDI Handle leak offenders (out of %i unique locations):\n", n
);
302 for ( i
= 0; i
< n
&& h
[i
].count
> 1; i
++ )
305 DbgPrint ( " %i allocs: ", h
[i
].count
);
306 for ( j
= 0; j
< GDI_STACK_LEVELS
; j
++ )
308 ULONG Addr
= GDIHandleAllocator
[h
[i
].idx
][j
];
309 if ( !KiRosPrintAddress ( (PVOID
)Addr
) )
310 DbgPrint ( "<%X>", Addr
);
314 if ( i
< n
&& h
[i
].count
== 1 )
315 DbgPrint ( "(list terminated - the remaining entries have 1 allocation only)\n" );
317 #endif /* GDI_DEBUG */
320 * Allocate memory for GDI object and return handle to it.
322 * \param ObjectType - type of object \ref GDI object types
324 * \return Handle of the allocated object.
326 * \note Use GDIOBJ_Lock() to obtain pointer to the new object.
327 * \todo return the object pointer and lock it by default.
329 HGDIOBJ INTERNAL_CALL
331 GDIOBJ_AllocObjDbg(const char* file
, int line
, ULONG ObjectType
)
332 #else /* !GDI_DEBUG */
333 GDIOBJ_AllocObj(ULONG ObjectType
)
334 #endif /* GDI_DEBUG */
336 PW32PROCESS W32Process
;
337 PGDIOBJHDR newObject
;
338 PPAGED_LOOKASIDE_LIST LookasideList
;
339 HANDLE CurrentProcessId
, LockedProcessId
;
344 W32Process
= PsGetWin32Process();
345 /* HACK HACK HACK: simplest-possible quota implementation - don't allow a process
346 to take too many GDI objects, itself. */
347 if ( W32Process
&& W32Process
->GDIObjects
>= 0x2710 )
350 ASSERT(ObjectType
!= GDI_OBJECT_TYPE_DONTCARE
);
352 LookasideList
= FindLookasideList(ObjectType
);
353 if(LookasideList
!= NULL
)
355 newObject
= ExAllocateFromPagedLookasideList(LookasideList
);
356 if(newObject
!= NULL
)
358 PSLIST_ENTRY FreeEntry
;
359 PGDI_TABLE_ENTRY Entry
;
363 CurrentProcessId
= PsGetCurrentProcessId();
364 LockedProcessId
= (HANDLE
)((ULONG_PTR
)CurrentProcessId
| 0x1);
366 newObject
->LockingThread
= NULL
;
367 newObject
->Locks
= 0;
370 newObject
->createdfile
= file
;
371 newObject
->createdline
= line
;
372 newObject
->lockfile
= NULL
;
373 newObject
->lockline
= 0;
376 ObjectBody
= GDIHdrToBdy(newObject
);
378 RtlZeroMemory(ObjectBody
, GetObjectSize(ObjectType
));
380 TypeInfo
= (ObjectType
& GDI_HANDLE_TYPE_MASK
) | (ObjectType
>> 16);
382 FreeEntry
= InterlockedPopEntrySList(&HandleTable
->FreeEntriesHead
);
383 if(FreeEntry
!= NULL
)
388 /* calculate the entry from the address of the entry in the free slot array */
389 Index
= ((ULONG_PTR
)FreeEntry
- (ULONG_PTR
)&HandleTable
->FreeEntries
[0]) /
390 sizeof(HandleTable
->FreeEntries
[0]);
391 Entry
= &HandleTable
->Entries
[Index
];
394 PrevProcId
= InterlockedCompareExchangePointer(&Entry
->ProcessId
, LockedProcessId
, 0);
395 if(PrevProcId
== NULL
)
399 ASSERT(Entry
->KernelData
== NULL
);
401 Entry
->KernelData
= ObjectBody
;
403 /* copy the reuse-counter */
404 TypeInfo
|= Entry
->Type
& GDI_HANDLE_REUSE_MASK
;
406 /* we found a free entry, no need to exchange this field atomically
407 since we're holding the lock */
408 Entry
->Type
= TypeInfo
;
410 /* unlock the entry */
411 InterlockedExchangePointer(&Entry
->ProcessId
, CurrentProcessId
);
414 memset ( GDIHandleAllocator
[Index
], 0xcd, GDI_STACK_LEVELS
* sizeof(ULONG
) );
415 KeRosGetStackFrames ( GDIHandleAllocator
[Index
], GDI_STACK_LEVELS
);
416 #endif /* GDI_DEBUG */
418 if(W32Process
!= NULL
)
420 InterlockedIncrement(&W32Process
->GDIObjects
);
422 Handle
= (HGDIOBJ
)((Index
& 0xFFFF) | (TypeInfo
& (GDI_HANDLE_TYPE_MASK
| GDI_HANDLE_REUSE_MASK
)));
424 DPRINT("GDIOBJ_AllocObj: 0x%x ob: 0x%x\n", Handle
, ObjectBody
);
432 DPRINT1("[%d]Waiting on handle in index 0x%x\n", Attempts
, Index
);
435 /* damn, someone is trying to lock the object even though it doesn't
436 eve nexist anymore, wait a little and try again!
437 FIXME - we shouldn't loop forever! Give up after some time! */
444 ExFreeToPagedLookasideList(LookasideList
, newObject
);
445 DPRINT1("Failed to insert gdi object into the handle table, no handles left!\n");
447 IntDumpHandleTable();
448 #endif /* GDI_DEBUG */
452 DPRINT1("Not enough memory to allocate gdi object!\n");
457 DPRINT1("Failed to find lookaside list for object type 0x%x\n", ObjectType
);
463 * Free memory allocated for the GDI object. For each object type this function calls the
464 * appropriate cleanup routine.
466 * \param hObj - handle of the object to be deleted.
468 * \return Returns TRUE if succesful.
469 * \return Returns FALSE if the cleanup routine returned FALSE or the object doesn't belong
470 * to the calling process.
474 GDIOBJ_FreeObjDbg(const char* file
, int line
, HGDIOBJ hObj
, DWORD ObjectType
)
475 #else /* !GDI_DEBUG */
476 GDIOBJ_FreeObj(HGDIOBJ hObj
, DWORD ObjectType
)
477 #endif /* GDI_DEBUG */
479 PGDI_TABLE_ENTRY Entry
;
480 PPAGED_LOOKASIDE_LIST LookasideList
;
481 HANDLE ProcessId
, LockedProcessId
, PrevProcId
;
488 DPRINT("GDIOBJ_FreeObj: hObj: 0x%08x\n", hObj
);
490 if(GDI_HANDLE_IS_STOCKOBJ(hObj
))
492 DPRINT1("GDIOBJ_FreeObj() failed, can't delete stock object handle: 0x%x !!!\n", hObj
);
494 DPRINT1("-> called from %s:%i\n", file
, line
);
499 ProcessId
= PsGetCurrentProcessId();
500 LockedProcessId
= (HANDLE
)((ULONG_PTR
)ProcessId
| 0x1);
502 Silent
= (ObjectType
& GDI_OBJECT_TYPE_SILENT
);
503 ObjectType
&= ~GDI_OBJECT_TYPE_SILENT
;
505 ExpectedType
= ((ObjectType
!= GDI_OBJECT_TYPE_DONTCARE
) ? ObjectType
: 0);
507 Entry
= GDI_HANDLE_GET_ENTRY(HandleTable
, hObj
);
510 /* lock the object, we must not delete global objects, so don't exchange the locking
511 process ID to zero when attempting to lock a global object... */
512 PrevProcId
= InterlockedCompareExchangePointer(&Entry
->ProcessId
, LockedProcessId
, ProcessId
);
513 if(PrevProcId
== ProcessId
)
515 if(Entry
->Type
!= 0 && Entry
->KernelData
!= NULL
&&
516 (ExpectedType
== 0 || ((Entry
->Type
<< 16) == ExpectedType
)))
520 GdiHdr
= GDIBdyToHdr(Entry
->KernelData
);
522 if(GdiHdr
->Locks
== 0)
525 PW32PROCESS W32Process
= PsGetWin32Process();
526 ULONG Type
= Entry
->Type
<< 16;
528 /* Clear the type field so when unlocking the handle it gets finally deleted and increment reuse counter */
529 Entry
->Type
= ((Entry
->Type
>> GDI_HANDLE_REUSECNT_SHIFT
) + 1) << GDI_HANDLE_REUSECNT_SHIFT
;
530 Entry
->KernelData
= NULL
;
532 /* unlock the handle slot */
533 InterlockedExchangePointer(&Entry
->ProcessId
, NULL
);
535 /* push this entry to the free list */
536 InterlockedPushEntrySList(&HandleTable
->FreeEntriesHead
,
537 &HandleTable
->FreeEntries
[GDI_ENTRY_TO_INDEX(HandleTable
, Entry
)]);
539 if(W32Process
!= NULL
)
541 InterlockedDecrement(&W32Process
->GDIObjects
);
544 /* call the cleanup routine. */
545 Ret
= RunCleanupCallback(GDIHdrToBdy(GdiHdr
), Type
);
547 /* Now it's time to free the memory */
548 LookasideList
= FindLookasideList(Type
);
549 if(LookasideList
!= NULL
)
551 ExFreeToPagedLookasideList(LookasideList
, GdiHdr
);
559 * The object is currently locked, so freeing is forbidden!
561 DPRINT1("GdiHdr->Locks: %d\n", GdiHdr
->Locks
);
563 DPRINT1("Locked from: %s:%d\n", GdiHdr
->lockfile
, GdiHdr
->lockline
);
570 if((Entry
->Type
& ~GDI_HANDLE_REUSE_MASK
) != 0)
572 DPRINT1("Attempted to delete object 0x%x, type mismatch (0x%x : 0x%x)\n", hObj
, ObjectType
, ExpectedType
);
576 DPRINT1("Attempted to delete object 0x%x which was already deleted!\n", hObj
);
578 InterlockedExchangePointer(&Entry
->ProcessId
, PrevProcId
);
581 else if(PrevProcId
== LockedProcessId
)
586 DPRINT1("[%d]Waiting on 0x%x\n", Attempts
, hObj
);
589 /* the object is currently locked, wait some time and try again.
590 FIXME - we shouldn't loop forever! Give up after some time! */
599 if(((ULONG_PTR
)PrevProcId
& ~0x1) == 0)
601 DPRINT1("Attempted to free global gdi handle 0x%x, caller needs to get ownership first!!!\n", hObj
);
605 DPRINT1("Attempted to free foreign handle: 0x%x Owner: 0x%x from Caller: 0x%x\n", hObj
, (ULONG_PTR
)PrevProcId
& ~0x1, (ULONG_PTR
)ProcessId
& ~0x1);
608 DPRINT1("-> called from %s:%i\n", file
, line
);
617 * Initialization of the GDI object engine.
620 InitGdiObjectHandleTable (VOID
)
622 DPRINT("InitGdiObjectHandleTable\n");
624 HandleTable
= GDIOBJ_iAllocHandleTable();
625 DPRINT("HandleTable: %x\n", HandleTable
);
630 * \param hObject object handle
631 * \return if the function fails the returned value is FALSE.
634 NtGdiDeleteObject(HGDIOBJ hObject
)
636 DPRINT("NtGdiDeleteObject handle 0x%08x\n", hObject
);
638 return NULL
!= hObject
639 ? GDIOBJ_FreeObj(hObject
, GDI_OBJECT_TYPE_DONTCARE
) : FALSE
;
643 * Internal function. Called when the process is destroyed to free the remaining GDI handles.
644 * \param Process - PID of the process that will be destroyed.
647 GDI_CleanupForProcess (struct _EPROCESS
*Process
)
649 PGDI_TABLE_ENTRY Entry
, End
;
650 PEPROCESS CurrentProcess
;
651 PW32PROCESS W32Process
;
653 ULONG Index
= RESERVE_ENTRIES_COUNT
;
655 DPRINT("Starting CleanupForProcess prochandle %x Pid %d\n", Process
, Process
->UniqueProcessId
);
656 CurrentProcess
= PsGetCurrentProcess();
657 if (CurrentProcess
!= Process
)
659 KeAttachProcess(Process
);
661 W32Process
= (PW32PROCESS
)Process
->Win32Process
;
664 if(W32Process
->GDIObjects
> 0)
666 /* FIXME - Instead of building the handle here and delete it using GDIOBJ_FreeObj
667 we should delete it directly here! */
668 ProcId
= Process
->UniqueProcessId
;
670 End
= &HandleTable
->Entries
[GDI_HANDLE_COUNT
];
671 for(Entry
= &HandleTable
->Entries
[RESERVE_ENTRIES_COUNT
];
675 /* ignore the lock bit */
676 if((HANDLE
)((ULONG_PTR
)Entry
->ProcessId
& ~0x1) == ProcId
&& (Entry
->Type
& ~GDI_HANDLE_REUSE_MASK
) != 0)
678 HGDIOBJ ObjectHandle
;
680 /* Create the object handle for the entry, the upper 16 bit of the
681 Type field includes the type of the object including the stock
682 object flag - but since stock objects don't have a process id we can
683 simply ignore this fact here. */
684 ObjectHandle
= (HGDIOBJ
)(Index
| (Entry
->Type
& 0xFFFF0000));
686 if(GDIOBJ_FreeObj(ObjectHandle
, GDI_OBJECT_TYPE_DONTCARE
) &&
687 W32Process
->GDIObjects
== 0)
689 /* there are no more gdi handles for this process, bail */
696 if (CurrentProcess
!= Process
)
701 DPRINT("Completed cleanup for process %d\n", Process
->UniqueProcessId
);
707 * Return pointer to the object by handle.
709 * \param hObj Object handle
710 * \return Pointer to the object.
712 * \note Process can only get pointer to the objects it created or global objects.
714 * \todo Get rid of the ObjectType parameter!
716 PGDIOBJ INTERNAL_CALL
718 GDIOBJ_LockObjDbg (const char* file
, int line
, HGDIOBJ hObj
, DWORD ObjectType
)
719 #else /* !GDI_DEBUG */
720 GDIOBJ_LockObj (HGDIOBJ hObj
, DWORD ObjectType
)
721 #endif /* GDI_DEBUG */
724 PGDI_TABLE_ENTRY HandleEntry
;
725 HANDLE ProcessId
, HandleProcessId
, LockedProcessId
, PrevProcId
;
726 PGDIOBJ Object
= NULL
;
728 HandleIndex
= GDI_HANDLE_GET_INDEX(hObj
);
730 /* Check that the handle index is valid. */
731 if (HandleIndex
>= GDI_HANDLE_COUNT
)
734 HandleEntry
= &HandleTable
->Entries
[HandleIndex
];
736 ProcessId
= (HANDLE
)((ULONG_PTR
)PsGetCurrentProcessId() & ~1);
737 HandleProcessId
= (HANDLE
)((ULONG_PTR
)HandleEntry
->ProcessId
& ~1);
739 /* Check for invalid owner. */
740 if (ProcessId
!= HandleProcessId
&& HandleProcessId
!= NULL
)
746 * Prevent the thread from being terminated during the locking process.
747 * It would result in undesired effects and inconsistency of the global
751 KeEnterCriticalRegion();
754 * Loop until we either successfully lock the handle entry & object or
755 * fail some of the check.
760 /* Lock the handle table entry. */
761 LockedProcessId
= (HANDLE
)((ULONG_PTR
)HandleProcessId
| 0x1);
762 PrevProcId
= InterlockedCompareExchangePointer(&HandleEntry
->ProcessId
,
766 if (PrevProcId
== HandleProcessId
)
768 LONG HandleType
= HandleEntry
->Type
<< 16;
771 * We're locking an object that belongs to our process or it's a
772 * global object if HandleProcessId is 0 here.
775 /* FIXME: Check the upper 16-bits of handle number! */
776 if (HandleType
!= 0 && HandleEntry
->KernelData
!= NULL
&&
777 (ObjectType
== GDI_OBJECT_TYPE_DONTCARE
||
778 HandleType
== ObjectType
))
780 PGDIOBJHDR GdiHdr
= GDIBdyToHdr(HandleEntry
->KernelData
);
781 PETHREAD Thread
= PsGetCurrentThread();
783 if (GdiHdr
->Locks
== 0)
785 GdiHdr
->LockingThread
= Thread
;
788 GdiHdr
->lockfile
= file
;
789 GdiHdr
->lockline
= line
;
791 Object
= HandleEntry
->KernelData
;
795 InterlockedIncrement(&GdiHdr
->Locks
);
796 if (GdiHdr
->LockingThread
!= Thread
)
798 InterlockedDecrement(&GdiHdr
->Locks
);
800 /* Unlock the handle table entry. */
801 InterlockedExchangePointer(&HandleEntry
->ProcessId
, PrevProcId
);
806 Object
= HandleEntry
->KernelData
;
812 * Debugging code. Report attempts to lock deleted handles and
813 * locking type mismatches.
816 if ((HandleType
& ~GDI_HANDLE_REUSE_MASK
) == 0)
818 DPRINT1("Attempted to lock object 0x%x that is deleted!\n", hObj
);
820 KeRosDumpStackFrames(NULL
, 20);
825 DPRINT1("Attempted to lock object 0x%x, type mismatch (0x%x : 0x%x)\n",
826 hObj
, HandleType
& ~GDI_HANDLE_REUSE_MASK
, ObjectType
& ~GDI_HANDLE_REUSE_MASK
);
828 KeRosDumpStackFrames(NULL
, 20);
832 DPRINT1("-> called from %s:%i\n", file
, line
);
836 /* Unlock the handle table entry. */
837 InterlockedExchangePointer(&HandleEntry
->ProcessId
, PrevProcId
);
844 * The handle is currently locked, wait some time and try again.
852 KeLeaveCriticalRegion();
859 * Return pointer to the object by handle (and allow sharing of the handle
862 * \param hObj Object handle
863 * \return Pointer to the object.
865 * \note Process can only get pointer to the objects it created or global objects.
867 * \todo Get rid of the ObjectType parameter!
869 PGDIOBJ INTERNAL_CALL
871 GDIOBJ_ShareLockObjDbg (const char* file
, int line
, HGDIOBJ hObj
, DWORD ObjectType
)
872 #else /* !GDI_DEBUG */
873 GDIOBJ_ShareLockObj (HGDIOBJ hObj
, DWORD ObjectType
)
874 #endif /* GDI_DEBUG */
877 PGDI_TABLE_ENTRY HandleEntry
;
878 HANDLE ProcessId
, HandleProcessId
, LockedProcessId
, PrevProcId
;
879 PGDIOBJ Object
= NULL
;
881 HandleIndex
= GDI_HANDLE_GET_INDEX(hObj
);
883 /* Check that the handle index is valid. */
884 if (HandleIndex
>= GDI_HANDLE_COUNT
)
887 HandleEntry
= &HandleTable
->Entries
[HandleIndex
];
889 ProcessId
= (HANDLE
)((ULONG_PTR
)PsGetCurrentProcessId() & ~1);
890 HandleProcessId
= (HANDLE
)((ULONG_PTR
)HandleEntry
->ProcessId
& ~1);
892 /* Check for invalid owner. */
893 if (ProcessId
!= HandleProcessId
&& HandleProcessId
!= NULL
)
899 * Prevent the thread from being terminated during the locking process.
900 * It would result in undesired effects and inconsistency of the global
904 KeEnterCriticalRegion();
907 * Loop until we either successfully lock the handle entry & object or
908 * fail some of the check.
913 /* Lock the handle table entry. */
914 LockedProcessId
= (HANDLE
)((ULONG_PTR
)HandleProcessId
| 0x1);
915 PrevProcId
= InterlockedCompareExchangePointer(&HandleEntry
->ProcessId
,
919 if (PrevProcId
== HandleProcessId
)
921 LONG HandleType
= HandleEntry
->Type
<< 16;
924 * We're locking an object that belongs to our process or it's a
925 * global object if HandleProcessId is 0 here.
928 /* FIXME: Check the upper 16-bits of handle number! */
929 if (HandleType
!= 0 && HandleEntry
->KernelData
!= NULL
&&
930 (ObjectType
== GDI_OBJECT_TYPE_DONTCARE
||
931 HandleType
== ObjectType
))
933 PGDIOBJHDR GdiHdr
= GDIBdyToHdr(HandleEntry
->KernelData
);
936 if (InterlockedIncrement(&GdiHdr
->Locks
) == 1)
938 GdiHdr
->lockfile
= file
;
939 GdiHdr
->lockline
= line
;
942 InterlockedIncrement(&GdiHdr
->Locks
);
944 Object
= HandleEntry
->KernelData
;
949 * Debugging code. Report attempts to lock deleted handles and
950 * locking type mismatches.
953 if ((HandleType
& ~GDI_HANDLE_REUSE_MASK
) == 0)
955 DPRINT1("Attempted to lock object 0x%x that is deleted!\n", hObj
);
957 KeRosDumpStackFrames(NULL
, 20);
962 DPRINT1("Attempted to lock object 0x%x, type mismatch (0x%x : 0x%x)\n",
963 hObj
, HandleType
& ~GDI_HANDLE_REUSE_MASK
, ObjectType
& ~GDI_HANDLE_REUSE_MASK
);
965 KeRosDumpStackFrames(NULL
, 20);
969 DPRINT1("-> called from %s:%i\n", file
, line
);
973 /* Unlock the handle table entry. */
974 InterlockedExchangePointer(&HandleEntry
->ProcessId
, PrevProcId
);
981 * The handle is currently locked, wait some time and try again.
989 KeLeaveCriticalRegion();
996 * Release GDI object. Every object locked by GDIOBJ_LockObj() must be unlocked. You should unlock the object
997 * as soon as you don't need to have access to it's data.
999 * \param Object Object pointer (as returned by GDIOBJ_LockObj).
1002 GDIOBJ_UnlockObjByPtr(PGDIOBJ Object
)
1004 PGDIOBJHDR GdiHdr
= GDIBdyToHdr(Object
);
1006 if (InterlockedDecrement(&GdiHdr
->Locks
) == 0)
1008 GdiHdr
->lockfile
= NULL
;
1009 GdiHdr
->lockline
= 0;
1012 InterlockedDecrement(&GdiHdr
->Locks
);
1018 GDIOBJ_OwnedByCurrentProcess(HGDIOBJ ObjectHandle
)
1020 PGDI_TABLE_ENTRY Entry
;
1024 DPRINT("GDIOBJ_OwnedByCurrentProcess: ObjectHandle: 0x%08x\n", ObjectHandle
);
1026 if(!GDI_HANDLE_IS_STOCKOBJ(ObjectHandle
))
1028 ProcessId
= PsGetCurrentProcessId();
1030 Entry
= GDI_HANDLE_GET_ENTRY(HandleTable
, ObjectHandle
);
1031 Ret
= Entry
->KernelData
!= NULL
&&
1032 (Entry
->Type
& ~GDI_HANDLE_REUSE_MASK
) != 0 &&
1033 (HANDLE
)((ULONG_PTR
)Entry
->ProcessId
& ~0x1) == ProcessId
;
1042 GDIOBJ_ConvertToStockObj(HGDIOBJ
*hObj
)
1045 * FIXME !!!!! THIS FUNCTION NEEDS TO BE FIXED - IT IS NOT SAFE WHEN OTHER THREADS
1046 * MIGHT ATTEMPT TO LOCK THE OBJECT DURING THIS CALL!!!
1048 PGDI_TABLE_ENTRY Entry
;
1049 HANDLE ProcessId
, LockedProcessId
, PrevProcId
;
1057 DPRINT("GDIOBJ_ConvertToStockObj: hObj: 0x%08x\n", *hObj
);
1059 Thread
= PsGetCurrentThread();
1061 if(!GDI_HANDLE_IS_STOCKOBJ(*hObj
))
1063 ProcessId
= PsGetCurrentProcessId();
1064 LockedProcessId
= (HANDLE
)((ULONG_PTR
)ProcessId
| 0x1);
1066 Entry
= GDI_HANDLE_GET_ENTRY(HandleTable
, *hObj
);
1069 /* lock the object, we must not convert stock objects, so don't check!!! */
1070 PrevProcId
= InterlockedCompareExchangePointer(&Entry
->ProcessId
, LockedProcessId
, ProcessId
);
1071 if(PrevProcId
== ProcessId
)
1073 LONG NewType
, PrevType
, OldType
;
1075 /* we're locking an object that belongs to our process. First calculate
1076 the new object type including the stock object flag and then try to
1078 NewType
= GDI_HANDLE_GET_TYPE(*hObj
);
1079 NewType
|= NewType
>> 16;
1080 NewType
|= (ULONG_PTR
)(*hObj
) & GDI_HANDLE_REUSE_MASK
;
1082 /* This is the type that the object should have right now, save it */
1084 /* As the object should be a stock object, set it's flag, but only in the upper 16 bits */
1085 NewType
|= GDI_HANDLE_STOCK_MASK
;
1087 /* Try to exchange the type field - but only if the old (previous type) matches! */
1088 PrevType
= InterlockedCompareExchange(&Entry
->Type
, NewType
, OldType
);
1089 if(PrevType
== OldType
&& Entry
->KernelData
!= NULL
)
1091 PETHREAD PrevThread
;
1094 /* We successfully set the stock object flag.
1095 KernelData should never be NULL here!!! */
1096 ASSERT(Entry
->KernelData
);
1098 GdiHdr
= GDIBdyToHdr(Entry
->KernelData
);
1100 PrevThread
= GdiHdr
->LockingThread
;
1101 if(GdiHdr
->Locks
== 0 || PrevThread
== Thread
)
1103 /* dereference the process' object counter */
1104 if(PrevProcId
!= GDI_GLOBAL_PROCESS
)
1106 PEPROCESS OldProcess
;
1107 PW32PROCESS W32Process
;
1111 Status
= PsLookupProcessByProcessId((HANDLE
)((ULONG_PTR
)PrevProcId
& ~0x1), &OldProcess
);
1112 if(NT_SUCCESS(Status
))
1114 W32Process
= (PW32PROCESS
)OldProcess
->Win32Process
;
1115 if(W32Process
!= NULL
)
1117 InterlockedDecrement(&W32Process
->GDIObjects
);
1119 ObDereferenceObject(OldProcess
);
1123 /* remove the process id lock and make it global */
1124 InterlockedExchangePointer(&Entry
->ProcessId
, GDI_GLOBAL_PROCESS
);
1126 *hObj
= (HGDIOBJ
)((ULONG
)(*hObj
) | GDI_HANDLE_STOCK_MASK
);
1128 /* we're done, successfully converted the object */
1136 if(GdiHdr
->lockfile
!= NULL
)
1138 DPRINT1("[%d]Locked %s:%i by 0x%x (we're 0x%x)\n", Attempts
, GdiHdr
->lockfile
, GdiHdr
->lockline
, PrevThread
, Thread
);
1142 /* WTF?! The object is already locked by a different thread!
1143 Release the lock, wait a bit and try again!
1144 FIXME - we should give up after some time unless we want to wait forever! */
1145 InterlockedExchangePointer(&Entry
->ProcessId
, PrevProcId
);
1153 DPRINT1("Attempted to convert object 0x%x that is deleted! Should never get here!!!\n", hObj
);
1156 else if(PrevProcId
== LockedProcessId
)
1161 DPRINT1("[%d]Waiting on 0x%x\n", Attempts
, hObj
);
1164 /* the object is currently locked, wait some time and try again.
1165 FIXME - we shouldn't loop forever! Give up after some time! */
1172 DPRINT1("Attempted to convert invalid handle: 0x%x\n", hObj
);
1180 GDIOBJ_SetOwnership(HGDIOBJ ObjectHandle
, PEPROCESS NewOwner
)
1182 PGDI_TABLE_ENTRY Entry
;
1183 HANDLE ProcessId
, LockedProcessId
, PrevProcId
;
1189 DPRINT("GDIOBJ_SetOwnership: hObj: 0x%x, NewProcess: 0x%x\n", ObjectHandle
, (NewOwner
? PsGetProcessId(NewOwner
) : 0));
1191 Thread
= PsGetCurrentThread();
1193 if(!GDI_HANDLE_IS_STOCKOBJ(ObjectHandle
))
1195 ProcessId
= PsGetCurrentProcessId();
1196 LockedProcessId
= (HANDLE
)((ULONG_PTR
)ProcessId
| 0x1);
1198 Entry
= GDI_HANDLE_GET_ENTRY(HandleTable
, ObjectHandle
);
1201 /* lock the object, we must not convert stock objects, so don't check!!! */
1202 PrevProcId
= InterlockedCompareExchangePointer(&Entry
->ProcessId
, ProcessId
, LockedProcessId
);
1203 if(PrevProcId
== ProcessId
)
1205 PETHREAD PrevThread
;
1207 if((Entry
->Type
& ~GDI_HANDLE_REUSE_MASK
) != 0 && Entry
->KernelData
!= NULL
)
1209 PGDIOBJHDR GdiHdr
= GDIBdyToHdr(Entry
->KernelData
);
1211 PrevThread
= GdiHdr
->LockingThread
;
1212 if(GdiHdr
->Locks
== 0 || PrevThread
== Thread
)
1214 PEPROCESS OldProcess
;
1215 PW32PROCESS W32Process
;
1218 /* dereference the process' object counter */
1220 if((ULONG_PTR
)PrevProcId
& ~0x1)
1222 Status
= PsLookupProcessByProcessId((HANDLE
)((ULONG_PTR
)PrevProcId
& ~0x1), &OldProcess
);
1223 if(NT_SUCCESS(Status
))
1225 W32Process
= (PW32PROCESS
)OldProcess
->Win32Process
;
1226 if(W32Process
!= NULL
)
1228 InterlockedDecrement(&W32Process
->GDIObjects
);
1230 ObDereferenceObject(OldProcess
);
1234 if(NewOwner
!= NULL
)
1236 ProcessId
= PsGetProcessId(NewOwner
);
1238 /* Increase the new process' object counter */
1239 W32Process
= (PW32PROCESS
)NewOwner
->Win32Process
;
1240 if(W32Process
!= NULL
)
1242 InterlockedIncrement(&W32Process
->GDIObjects
);
1248 /* remove the process id lock and change it to the new process id */
1249 InterlockedExchangePointer(&Entry
->ProcessId
, ProcessId
);
1259 if(GdiHdr
->lockfile
!= NULL
)
1261 DPRINT1("[%d]Locked from %s:%i by 0x%x (we're 0x%x)\n", Attempts
, GdiHdr
->lockfile
, GdiHdr
->lockline
, PrevThread
, Thread
);
1265 /* WTF?! The object is already locked by a different thread!
1266 Release the lock, wait a bit and try again! DO reset the pid lock
1267 so we make sure we don't access invalid memory in case the object is
1268 being deleted in the meantime (because we don't have aquired a reference
1270 FIXME - we should give up after some time unless we want to wait forever! */
1271 InterlockedExchangePointer(&Entry
->ProcessId
, PrevProcId
);
1279 DPRINT1("Attempted to change ownership of an object 0x%x currently being destroyed!!!\n", ObjectHandle
);
1282 else if(PrevProcId
== LockedProcessId
)
1287 DPRINT1("[%d]Waiting on 0x%x\n", Attempts
, ObjectHandle
);
1290 /* the object is currently locked, wait some time and try again.
1291 FIXME - we shouldn't loop forever! Give up after some time! */
1296 else if(((ULONG_PTR
)PrevProcId
& ~0x1) == 0)
1298 /* allow changing ownership of global objects */
1300 LockedProcessId
= (HANDLE
)((ULONG_PTR
)ProcessId
| 0x1);
1303 else if((HANDLE
)((ULONG_PTR
)PrevProcId
& ~0x1) != PsGetCurrentProcessId())
1305 DPRINT1("Attempted to change ownership of object 0x%x (pid: 0x%x) from pid 0x%x!!!\n", ObjectHandle
, (ULONG_PTR
)PrevProcId
& ~0x1, PsGetCurrentProcessId());
1309 DPRINT1("Attempted to change owner of invalid handle: 0x%x\n", ObjectHandle
);
1315 GDIOBJ_CopyOwnership(HGDIOBJ CopyFrom
, HGDIOBJ CopyTo
)
1317 PGDI_TABLE_ENTRY FromEntry
;
1319 HANDLE FromProcessId
, FromLockedProcessId
, FromPrevProcId
;
1324 DPRINT("GDIOBJ_CopyOwnership: from: 0x%x, to: 0x%x\n", CopyFrom
, CopyTo
);
1326 Thread
= PsGetCurrentThread();
1328 if(!GDI_HANDLE_IS_STOCKOBJ(CopyFrom
) && !GDI_HANDLE_IS_STOCKOBJ(CopyTo
))
1330 FromEntry
= GDI_HANDLE_GET_ENTRY(HandleTable
, CopyFrom
);
1332 FromProcessId
= (HANDLE
)((ULONG_PTR
)FromEntry
->ProcessId
& ~0x1);
1333 FromLockedProcessId
= (HANDLE
)((ULONG_PTR
)FromProcessId
| 0x1);
1336 /* lock the object, we must not convert stock objects, so don't check!!! */
1337 FromPrevProcId
= InterlockedCompareExchangePointer(&FromEntry
->ProcessId
, FromProcessId
, FromLockedProcessId
);
1338 if(FromPrevProcId
== FromProcessId
)
1340 PETHREAD PrevThread
;
1343 if((FromEntry
->Type
& ~GDI_HANDLE_REUSE_MASK
) != 0 && FromEntry
->KernelData
!= NULL
)
1345 GdiHdr
= GDIBdyToHdr(FromEntry
->KernelData
);
1347 /* save the pointer to the calling thread so we know it was this thread
1348 that locked the object */
1349 PrevThread
= GdiHdr
->LockingThread
;
1350 if(GdiHdr
->Locks
== 0 || PrevThread
== Thread
)
1352 /* now let's change the ownership of the target object */
1354 if(((ULONG_PTR
)FromPrevProcId
& ~0x1) != 0)
1356 PEPROCESS ProcessTo
;
1358 if(NT_SUCCESS(PsLookupProcessByProcessId((HANDLE
)((ULONG_PTR
)FromPrevProcId
& ~0x1), &ProcessTo
)))
1360 GDIOBJ_SetOwnership(CopyTo
, ProcessTo
);
1361 ObDereferenceObject(ProcessTo
);
1366 /* mark the object as global */
1367 GDIOBJ_SetOwnership(CopyTo
, NULL
);
1370 InterlockedExchangePointer(&FromEntry
->ProcessId
, FromPrevProcId
);
1377 if(GdiHdr
->lockfile
!= NULL
)
1379 DPRINT1("[%d]Locked from %s:%i by 0x%x (we're 0x%x)\n", Attempts
, GdiHdr
->lockfile
, GdiHdr
->lockline
, PrevThread
, Thread
);
1383 /* WTF?! The object is already locked by a different thread!
1384 Release the lock, wait a bit and try again! DO reset the pid lock
1385 so we make sure we don't access invalid memory in case the object is
1386 being deleted in the meantime (because we don't have aquired a reference
1388 FIXME - we should give up after some time unless we want to wait forever! */
1389 InterlockedExchangePointer(&FromEntry
->ProcessId
, FromPrevProcId
);
1392 goto LockHandleFrom
;
1397 DPRINT1("Attempted to copy ownership from an object 0x%x currently being destroyed!!!\n", CopyFrom
);
1400 else if(FromPrevProcId
== FromLockedProcessId
)
1405 DPRINT1("[%d]Waiting on 0x%x\n", Attempts
, CopyFrom
);
1408 /* the object is currently locked, wait some time and try again.
1409 FIXME - we shouldn't loop forever! Give up after some time! */
1412 goto LockHandleFrom
;
1414 else if((HANDLE
)((ULONG_PTR
)FromPrevProcId
& ~0x1) != PsGetCurrentProcessId())
1416 /* FIXME - should we really allow copying ownership from objects that we don't even own? */
1417 DPRINT1("WARNING! Changing copying ownership of object 0x%x (pid: 0x%x) to pid 0x%x!!!\n", CopyFrom
, (ULONG_PTR
)FromPrevProcId
& ~0x1, PsGetCurrentProcessId());
1418 FromProcessId
= (HANDLE
)((ULONG_PTR
)FromPrevProcId
& ~0x1);
1419 FromLockedProcessId
= (HANDLE
)((ULONG_PTR
)FromProcessId
| 0x1);
1420 goto LockHandleFrom
;
1424 DPRINT1("Attempted to copy ownership from invalid handle: 0x%x\n", CopyFrom
);
1430 GDI_MapHandleTable(PEPROCESS Process
)
1432 ULONG TableSize
= sizeof(HandleTable
->Entries
);
1433 PVOID MappedGdiTable
= NULL
; /* FIXME - try preferred GDI_HANDLE_TABLE_BASE_ADDRESS? */
1434 NTSTATUS Status
= IntUserMapSharedSection(SessionSharedSectionPool
,
1441 if(NT_SUCCESS(Status
))
1443 return MappedGdiTable
;