setupapi: Always initialize output parameter to avoid crash in buggy applications.
[wine] / dlls / quartz / systemclock.c
1 /*
2  * Implementation of IReferenceClock
3  *
4  * Copyright 2004 Raphael Junqueira
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "quartz_private.h"
22
23 #include "wine/debug.h"
24 #include "wine/unicode.h"
25 #include <assert.h>
26
27 WINE_DEFAULT_DEBUG_CHANNEL(quartz);
28
29 typedef struct SystemClockAdviseEntry SystemClockAdviseEntry;
30 struct SystemClockAdviseEntry {
31   SystemClockAdviseEntry* next;
32   SystemClockAdviseEntry* prev;
33
34   HANDLE           hEvent;
35   REFERENCE_TIME   rtBaseTime;
36   REFERENCE_TIME   rtIntervalTime;
37 };
38
39 typedef struct SystemClockImpl {
40   IReferenceClock IReferenceClock_iface;
41   LONG ref;
42
43   /** IReferenceClock */
44   HANDLE         adviseThread;
45   DWORD          adviseThreadId;
46   BOOL           adviseThreadActive;
47   REFERENCE_TIME lastRefTime;
48   DWORD          lastTimeTickCount;
49   CRITICAL_SECTION safe;
50
51   SystemClockAdviseEntry* pSingleShotAdvise;
52   SystemClockAdviseEntry* pPeriodicAdvise;
53 } SystemClockImpl;
54
55 static inline SystemClockImpl *impl_from_IReferenceClock(IReferenceClock *iface)
56 {
57     return CONTAINING_RECORD(iface, SystemClockImpl, IReferenceClock_iface);
58 }
59
60
61 static void QUARTZ_RemoveAviseEntryFromQueue(SystemClockImpl* This, SystemClockAdviseEntry* pEntry) {
62   if (pEntry->prev) pEntry->prev->next = pEntry->next;
63   if (pEntry->next) pEntry->next->prev = pEntry->prev;
64   if (This->pSingleShotAdvise == pEntry) This->pSingleShotAdvise = pEntry->next;
65   if (This->pPeriodicAdvise == pEntry)    This->pPeriodicAdvise = pEntry->next;
66 }
67
68 static void QUARTZ_InsertAviseEntryFromQueue(SystemClockImpl* This, SystemClockAdviseEntry* pEntry, SystemClockAdviseEntry** pQueue) {
69   SystemClockAdviseEntry* prev_it = NULL;
70   SystemClockAdviseEntry* it = NULL;
71   REFERENCE_TIME bornTime =  pEntry->rtBaseTime + pEntry->rtIntervalTime;
72
73   for (it = *pQueue; NULL != it && (it->rtBaseTime + it->rtIntervalTime) < bornTime; it = it->next) {
74     prev_it = it;
75   }
76   if (NULL == prev_it) {
77     pEntry->prev = NULL;
78     if (NULL != (*pQueue)) pEntry->next = (*pQueue)->next;
79     /*assert( NULL == pEntry->next->prev );*/
80     if (NULL != pEntry->next) pEntry->next->prev = pEntry;
81     (*pQueue) = pEntry;
82   } else {
83     pEntry->prev = prev_it;
84     pEntry->next = prev_it->next;
85     prev_it->next = pEntry;
86     if (NULL != pEntry->next) pEntry->next->prev = pEntry;
87   }
88 }
89
90 #define MAX_REFTIME            (REFERENCE_TIME)(0x7FFFFFFFFFFFFFFF)
91 #define ADVISE_EXIT            (WM_APP + 0)
92 #define ADVISE_REMOVE          (WM_APP + 2)
93 #define ADVISE_ADD_SINGLESHOT  (WM_APP + 4)
94 #define ADVISE_ADD_PERIODIC    (WM_APP + 8)
95
96 static DWORD WINAPI SystemClockAdviseThread(LPVOID lpParam) {
97   SystemClockImpl* This = lpParam;
98   DWORD timeOut = INFINITE;
99   DWORD tmpTimeOut;
100   MSG msg;
101   HRESULT hr;
102   REFERENCE_TIME curTime;
103   SystemClockAdviseEntry* it = NULL;
104
105   TRACE("(%p): Main Loop\n", This);
106
107   while (TRUE) {
108     if (timeOut > 0) MsgWaitForMultipleObjects(0, NULL, FALSE, timeOut, QS_POSTMESSAGE|QS_SENDMESSAGE|QS_TIMER);
109     
110     EnterCriticalSection(&This->safe);
111     /*timeOut = IReferenceClock_OnTimerUpdated(This); */
112     hr = IReferenceClock_GetTime(&This->IReferenceClock_iface, &curTime);
113     if (FAILED(hr)) {
114       timeOut = INFINITE;
115       goto outrefresh;
116     }
117
118     /** First SingleShots Advice: sorted list */
119     for (it = This->pSingleShotAdvise; NULL != it && (it->rtBaseTime + it->rtIntervalTime) <= curTime; it = it->next) {
120       /** send event ... */
121       SetEvent(it->hEvent);
122       /** ... and Release it */
123       QUARTZ_RemoveAviseEntryFromQueue(This, it);
124       CoTaskMemFree(it);
125     }
126     if (NULL != it) timeOut = (DWORD) ((it->rtBaseTime + it->rtIntervalTime) - curTime) / (REFERENCE_TIME)10000;
127
128     /** Now Periodics Advice: semi sorted list (sort cannot be used) */
129     for (it = This->pPeriodicAdvise; NULL != it; it = it->next) {
130       if (it->rtBaseTime <= curTime) {
131         DWORD nPeriods = (DWORD) ((curTime - it->rtBaseTime) / it->rtIntervalTime);
132         /** Release the semaphore ... */
133         ReleaseSemaphore(it->hEvent, nPeriods, NULL);
134         /** ... and refresh time */
135         it->rtBaseTime += nPeriods * it->rtIntervalTime;
136         /*assert( it->rtBaseTime + it->rtIntervalTime < curTime );*/
137       }
138       tmpTimeOut = (DWORD) ((it->rtBaseTime + it->rtIntervalTime) - curTime) / (REFERENCE_TIME)10000;
139       if (timeOut > tmpTimeOut) timeOut = tmpTimeOut; 
140     }
141
142 outrefresh:
143     LeaveCriticalSection(&This->safe);
144     
145     while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
146       /** if hwnd we suppose that is a windows event ... */
147       if  (NULL != msg.hwnd) {
148         TranslateMessage(&msg);
149         DispatchMessageW(&msg);
150       } else {
151         switch (msg.message) {      
152         case WM_QUIT:
153         case ADVISE_EXIT:
154           goto outofthread;
155         case ADVISE_ADD_SINGLESHOT:
156         case ADVISE_ADD_PERIODIC:
157           /** set timeout to 0 to do a rescan now */
158           timeOut = 0;
159           break;
160         case ADVISE_REMOVE:
161           /** hmmmm what we can do here ... */
162           timeOut = INFINITE;
163           break;
164         default:
165           ERR("Unhandled message %u. Critical Path\n", msg.message);
166           break;
167         }
168       }
169     }
170   }
171
172 outofthread:
173   TRACE("(%p): Exiting\n", This);
174   return 0;
175 }
176 /*static DWORD WINAPI SystemClockAdviseThread(LPVOID lpParam) { */
177
178 static BOOL SystemClockPostMessageToAdviseThread(SystemClockImpl* This, UINT iMsg) {
179   if (FALSE == This->adviseThreadActive) {
180     BOOL res;
181     This->adviseThread = CreateThread(NULL, 0, SystemClockAdviseThread, This, 0, &This->adviseThreadId);
182     if (NULL == This->adviseThread) return FALSE;
183     SetThreadPriority(This->adviseThread, THREAD_PRIORITY_TIME_CRITICAL);
184     This->adviseThreadActive = TRUE;
185     while(1) {
186       res = PostThreadMessageW(This->adviseThreadId, iMsg, 0, 0);
187       /* Let the thread creates its message queue (with MsgWaitForMultipleObjects call) by yielding and retrying */
188       if (!res && (GetLastError() == ERROR_INVALID_THREAD_ID))
189         Sleep(0);
190       else
191         break;
192     }
193     return res;
194   }
195   return PostThreadMessageW(This->adviseThreadId, iMsg, 0, 0);
196 }
197
198 static ULONG WINAPI SystemClockImpl_AddRef(IReferenceClock* iface) {
199   SystemClockImpl *This = impl_from_IReferenceClock(iface);
200   ULONG ref = InterlockedIncrement(&This->ref);
201
202   TRACE("(%p): AddRef from %d\n", This, ref - 1);
203
204   return ref;
205 }
206
207 static HRESULT WINAPI SystemClockImpl_QueryInterface(IReferenceClock* iface, REFIID riid, void** ppobj) {
208   SystemClockImpl *This = impl_from_IReferenceClock(iface);
209   TRACE("(%p, %s,%p)\n", This, debugstr_guid(riid), ppobj);
210   
211   if (IsEqualIID (riid, &IID_IUnknown) || 
212       IsEqualIID (riid, &IID_IReferenceClock)) {
213     SystemClockImpl_AddRef(iface);
214     *ppobj = This;
215     return S_OK;
216   }
217   
218   *ppobj = NULL;
219   WARN("(%p, %s,%p): not found\n", This, debugstr_guid(riid), ppobj);
220   return E_NOINTERFACE;
221 }
222
223 static ULONG WINAPI SystemClockImpl_Release(IReferenceClock* iface) {
224   SystemClockImpl *This = impl_from_IReferenceClock(iface);
225   ULONG ref = InterlockedDecrement(&This->ref);
226   TRACE("(%p): ReleaseRef to %d\n", This, ref);
227   if (ref == 0) {
228     if (SystemClockPostMessageToAdviseThread(This, ADVISE_EXIT)) {
229       WaitForSingleObject(This->adviseThread, INFINITE);
230       CloseHandle(This->adviseThread);
231     }
232     This->safe.DebugInfo->Spare[0] = 0;
233     DeleteCriticalSection(&This->safe);
234     CoTaskMemFree(This);
235   }
236   return ref;
237 }
238
239 static HRESULT WINAPI SystemClockImpl_GetTime(IReferenceClock* iface, REFERENCE_TIME* pTime) {
240   SystemClockImpl *This = impl_from_IReferenceClock(iface);
241   DWORD curTimeTickCount;
242   HRESULT hr = S_OK;
243
244   TRACE("(%p, %p)\n", This, pTime);
245
246   if (NULL == pTime) {
247     return E_POINTER;
248   }
249
250   curTimeTickCount = GetTickCount();
251
252   EnterCriticalSection(&This->safe);
253   if (This->lastTimeTickCount == curTimeTickCount) hr = S_FALSE;
254   This->lastRefTime += (REFERENCE_TIME) (DWORD) (curTimeTickCount - This->lastTimeTickCount) * (REFERENCE_TIME) 10000;
255   This->lastTimeTickCount = curTimeTickCount;
256   *pTime = This->lastRefTime;
257   LeaveCriticalSection(&This->safe);
258   return hr;
259 }
260
261 static HRESULT WINAPI SystemClockImpl_AdviseTime(IReferenceClock* iface, REFERENCE_TIME rtBaseTime, REFERENCE_TIME rtStreamTime, HEVENT hEvent, DWORD_PTR* pdwAdviseCookie) {
262   SystemClockImpl *This = impl_from_IReferenceClock(iface);
263   SystemClockAdviseEntry* pEntry = NULL;
264
265   TRACE("(%p, 0x%s, 0x%s, %ld, %p)\n", This, wine_dbgstr_longlong(rtBaseTime),
266       wine_dbgstr_longlong(rtStreamTime), hEvent, pdwAdviseCookie);
267
268   if (!hEvent) {
269     return E_INVALIDARG;
270   }
271   if (0 >= rtBaseTime + rtStreamTime) {
272     return E_INVALIDARG;
273   }
274   if (NULL == pdwAdviseCookie) {
275     return E_POINTER;
276   }
277   pEntry = CoTaskMemAlloc(sizeof(SystemClockAdviseEntry));
278   if (NULL == pEntry) {
279     return E_OUTOFMEMORY;
280   }
281   ZeroMemory(pEntry, sizeof(SystemClockAdviseEntry));
282
283   pEntry->hEvent = (HANDLE) hEvent;
284   pEntry->rtBaseTime = rtBaseTime + rtStreamTime;
285   pEntry->rtIntervalTime = 0;
286
287   EnterCriticalSection(&This->safe);
288   QUARTZ_InsertAviseEntryFromQueue(This, pEntry, &This->pSingleShotAdvise);
289   LeaveCriticalSection(&This->safe);
290
291   SystemClockPostMessageToAdviseThread(This, ADVISE_ADD_SINGLESHOT);
292
293   *pdwAdviseCookie = (DWORD_PTR) (pEntry);
294   return S_OK;
295 }
296
297 static HRESULT WINAPI SystemClockImpl_AdvisePeriodic(IReferenceClock* iface, REFERENCE_TIME rtStartTime, REFERENCE_TIME rtPeriodTime, HSEMAPHORE hSemaphore, DWORD_PTR* pdwAdviseCookie) {
298   SystemClockImpl *This = impl_from_IReferenceClock(iface);
299   SystemClockAdviseEntry* pEntry = NULL;
300
301   TRACE("(%p, 0x%s, 0x%s, %ld, %p)\n", This, wine_dbgstr_longlong(rtStartTime),
302       wine_dbgstr_longlong(rtPeriodTime), hSemaphore, pdwAdviseCookie);
303
304   if (!hSemaphore) {
305     return E_INVALIDARG;
306   }
307   if (0 >= rtStartTime || 0 >= rtPeriodTime) {
308     return E_INVALIDARG;
309   }
310   if (NULL == pdwAdviseCookie) {
311     return E_POINTER;
312   }
313   pEntry = CoTaskMemAlloc(sizeof(SystemClockAdviseEntry));
314   if (NULL == pEntry) {
315     return E_OUTOFMEMORY;
316   }
317   ZeroMemory(pEntry, sizeof(SystemClockAdviseEntry));
318
319   pEntry->hEvent = (HANDLE) hSemaphore;
320   pEntry->rtBaseTime = rtStartTime;
321   pEntry->rtIntervalTime = rtPeriodTime;
322
323   EnterCriticalSection(&This->safe);
324   QUARTZ_InsertAviseEntryFromQueue(This, pEntry, &This->pPeriodicAdvise);
325   LeaveCriticalSection(&This->safe);
326
327   SystemClockPostMessageToAdviseThread(This, ADVISE_ADD_PERIODIC);
328
329   *pdwAdviseCookie = (DWORD_PTR) (pEntry);
330   return S_OK;
331 }
332
333 static HRESULT WINAPI SystemClockImpl_Unadvise(IReferenceClock* iface, DWORD_PTR dwAdviseCookie) {
334   SystemClockImpl *This = impl_from_IReferenceClock(iface);
335   SystemClockAdviseEntry* pEntry = NULL;
336   SystemClockAdviseEntry* it = NULL;
337   HRESULT ret = S_OK;
338   TRACE("(%p, %lu)\n", This, dwAdviseCookie);
339
340   pEntry = (SystemClockAdviseEntry*) dwAdviseCookie;
341
342   EnterCriticalSection(&This->safe);
343   for (it = This->pPeriodicAdvise; NULL != it && it != pEntry; it = it->next) ;
344   if (it != pEntry) {
345     for (it = This->pSingleShotAdvise; NULL != it && it != pEntry; it = it->next) ;
346     if (it != pEntry) {
347       ret = S_FALSE;
348       goto out;
349     }
350   }
351
352   QUARTZ_RemoveAviseEntryFromQueue(This, pEntry);
353   CoTaskMemFree(pEntry);
354
355   SystemClockPostMessageToAdviseThread(This, ADVISE_REMOVE);
356
357 out:
358   LeaveCriticalSection(&This->safe);
359   return ret;
360 }
361
362 static const IReferenceClockVtbl SystemClock_Vtbl = 
363 {
364     SystemClockImpl_QueryInterface,
365     SystemClockImpl_AddRef,
366     SystemClockImpl_Release,
367     SystemClockImpl_GetTime,
368     SystemClockImpl_AdviseTime,
369     SystemClockImpl_AdvisePeriodic,
370     SystemClockImpl_Unadvise
371 };
372
373 HRESULT QUARTZ_CreateSystemClock(IUnknown * pUnkOuter, LPVOID * ppv) {
374   SystemClockImpl* obj = NULL;
375   
376   TRACE("(%p,%p)\n", ppv, pUnkOuter);
377   
378   obj = CoTaskMemAlloc(sizeof(SystemClockImpl));
379   if (NULL == obj)      {
380     *ppv = NULL;
381     return E_OUTOFMEMORY;
382   }
383   ZeroMemory(obj, sizeof(SystemClockImpl));
384
385   obj->IReferenceClock_iface.lpVtbl = &SystemClock_Vtbl;
386   obj->ref = 0;  /* will be inited by QueryInterface */
387
388   obj->lastTimeTickCount = GetTickCount();
389   InitializeCriticalSection(&obj->safe);
390   obj->safe.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": SystemClockImpl.safe");
391
392   return SystemClockImpl_QueryInterface(&obj->IReferenceClock_iface, &IID_IReferenceClock, ppv);
393 }