winmm: Rearrange device mapping when a new default device is chosen.
[wine] / dlls / pdh / pdh_main.c
1 /*
2  * Performance Data Helper (pdh.dll)
3  *
4  * Copyright 2007 Andrey Turkin
5  * Copyright 2007 Hans Leidekker
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include <stdarg.h>
23 #include <math.h>
24
25 #define NONAMELESSUNION
26 #define NONAMELESSSTRUCT
27 #include "windef.h"
28 #include "winbase.h"
29
30 #include "pdh.h"
31 #include "pdhmsg.h"
32 #include "winperf.h"
33
34 #include "wine/debug.h"
35 #include "wine/list.h"
36 #include "wine/unicode.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(pdh);
39
40 static CRITICAL_SECTION pdh_handle_cs;
41 static CRITICAL_SECTION_DEBUG pdh_handle_cs_debug =
42 {
43     0, 0, &pdh_handle_cs,
44     { &pdh_handle_cs_debug.ProcessLocksList,
45       &pdh_handle_cs_debug.ProcessLocksList },
46       0, 0, { (DWORD_PTR)(__FILE__ ": pdh_handle_cs") }
47 };
48 static CRITICAL_SECTION pdh_handle_cs = { &pdh_handle_cs_debug, -1, 0, 0, 0, 0 };
49
50 static inline void *heap_alloc( SIZE_T size )
51 {
52     return HeapAlloc( GetProcessHeap(), 0, size );
53 }
54
55 static inline void *heap_alloc_zero( SIZE_T size )
56 {
57     return HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size );
58 }
59
60 static inline void heap_free( LPVOID mem )
61 {
62     HeapFree( GetProcessHeap(), 0, mem );
63 }
64
65 static inline WCHAR *pdh_strdup( const WCHAR *src )
66 {
67     WCHAR *dst;
68
69     if (!src) return NULL;
70     if ((dst = heap_alloc( (strlenW( src ) + 1) * sizeof(WCHAR) ))) strcpyW( dst, src );
71     return dst;
72 }
73
74 static inline WCHAR *pdh_strdup_aw( const char *src )
75 {
76     int len;
77     WCHAR *dst;
78
79     if (!src) return NULL;
80     len = MultiByteToWideChar( CP_ACP, 0, src, -1, NULL, 0 );
81     if ((dst = heap_alloc( len * sizeof(WCHAR) ))) MultiByteToWideChar( CP_ACP, 0, src, -1, dst, len );
82     return dst;
83 }
84
85 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
86 {
87     TRACE("(0x%p, %d, %p)\n",hinstDLL,fdwReason,lpvReserved);
88     switch (fdwReason)
89     {
90     case DLL_WINE_PREATTACH:
91         return FALSE;    /* prefer native version */
92     case DLL_PROCESS_ATTACH:
93         DisableThreadLibraryCalls(hinstDLL);
94         break;
95     case DLL_PROCESS_DETACH:
96         DeleteCriticalSection(&pdh_handle_cs);
97         break;
98     }
99
100     return TRUE;
101 }
102
103 union value
104 {
105     LONG     longvalue;
106     double   doublevalue;
107     LONGLONG largevalue;
108 };
109
110 struct counter
111 {
112     DWORD           magic;                          /* signature */
113     struct list     entry;                          /* list entry */
114     WCHAR          *path;                           /* identifier */
115     DWORD           type;                           /* counter type */
116     DWORD           status;                         /* update status */
117     LONG            scale;                          /* scale factor */
118     LONG            defaultscale;                   /* default scale factor */
119     DWORD_PTR       user;                           /* user data */
120     DWORD_PTR       queryuser;                      /* query user data */
121     LONGLONG        base;                           /* samples per second */
122     FILETIME        stamp;                          /* time stamp */
123     void (CALLBACK *collect)( struct counter * );   /* collect callback */
124     union value     one;                            /* first value */
125     union value     two;                            /* second value */
126 };
127
128 #define PDH_MAGIC_COUNTER   0x50444831 /* 'PDH1' */
129
130 static struct counter *create_counter( void )
131 {
132     struct counter *counter;
133
134     if ((counter = heap_alloc_zero( sizeof(struct counter) )))
135     {
136         counter->magic = PDH_MAGIC_COUNTER;
137         return counter;
138     }
139     return NULL;
140 }
141
142 static void destroy_counter( struct counter *counter )
143 {
144     counter->magic = 0;
145     heap_free( counter->path );
146     heap_free( counter );
147 }
148
149 #define PDH_MAGIC_QUERY     0x50444830 /* 'PDH0' */
150
151 struct query
152 {
153     DWORD       magic;      /* signature */
154     DWORD_PTR   user;       /* user data */
155     HANDLE      thread;     /* collect thread */
156     DWORD       interval;   /* collect interval */
157     HANDLE      wait;       /* wait event */
158     HANDLE      stop;       /* stop event */
159     struct list counters;   /* counter list */
160 };
161
162 static struct query *create_query( void )
163 {
164     struct query *query;
165
166     if ((query = heap_alloc_zero( sizeof(struct query) )))
167     {
168         query->magic = PDH_MAGIC_QUERY;
169         list_init( &query->counters );
170         return query;
171     }
172     return NULL;
173 }
174
175 static void destroy_query( struct query *query )
176 {
177     query->magic = 0;
178     heap_free( query );
179 }
180
181 struct source
182 {
183     DWORD           index;                          /* name index */
184     const WCHAR    *path;                           /* identifier */
185     void (CALLBACK *collect)( struct counter * );   /* collect callback */
186     DWORD           type;                           /* counter type */
187     LONG            scale;                          /* default scale factor */
188     LONGLONG        base;                           /* samples per second */
189 };
190
191 static const WCHAR path_processor_time[] =
192     {'\\','P','r','o','c','e','s','s','o','r','(','_','T','o','t','a','l',')',
193      '\\','%',' ','P','r','o','c','e','s','s','o','r',' ','T','i','m','e',0};
194 static const WCHAR path_uptime[] =
195     {'\\','S','y','s','t','e','m', '\\', 'S','y','s','t','e','m',' ','U','p',' ','T','i','m','e',0};
196
197 static void CALLBACK collect_processor_time( struct counter *counter )
198 {
199     counter->two.largevalue = 500000; /* FIXME */
200     counter->status = PDH_CSTATUS_VALID_DATA;
201 }
202
203 static void CALLBACK collect_uptime( struct counter *counter )
204 {
205     counter->two.largevalue = GetTickCount64();
206     counter->status = PDH_CSTATUS_VALID_DATA;
207 }
208
209 #define TYPE_PROCESSOR_TIME \
210     (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_DELTA_COUNTER | \
211      PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT)
212
213 #define TYPE_UPTIME \
214     (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_ELAPSED | PERF_OBJECT_TIMER | PERF_DISPLAY_SECONDS)
215
216 /* counter source registry */
217 static const struct source counter_sources[] =
218 {
219     { 6,    path_processor_time,    collect_processor_time,     TYPE_PROCESSOR_TIME,    -5,     10000000 },
220     { 674,  path_uptime,            collect_uptime,             TYPE_UPTIME,            -3,     1000 }
221 };
222
223 static BOOL is_local_machine( const WCHAR *name, DWORD len )
224 {
225     WCHAR buf[MAX_COMPUTERNAME_LENGTH + 1];
226     DWORD buflen = sizeof(buf) / sizeof(buf[0]);
227
228     if (!GetComputerNameW( buf, &buflen )) return FALSE;
229     return len == buflen && !memicmpW( name, buf, buflen );
230 }
231
232 static BOOL pdh_match_path( LPCWSTR fullpath, LPCWSTR path )
233 {
234     const WCHAR *p;
235
236     if (path[0] == '\\' && path[1] == '\\' && (p = strchrW( path + 2, '\\' )) &&
237         is_local_machine( path + 2, p - path - 2 ))
238     {
239         path += p - path;
240     }
241     if (strchrW( path, '\\' )) p = fullpath;
242     else p = strrchrW( fullpath, '\\' ) + 1;
243     return !strcmpW( p, path );
244 }
245
246 /***********************************************************************
247  *              PdhAddCounterA   (PDH.@)
248  */
249 PDH_STATUS WINAPI PdhAddCounterA( PDH_HQUERY query, LPCSTR path,
250                                   DWORD_PTR userdata, PDH_HCOUNTER *counter )
251 {
252     PDH_STATUS ret;
253     WCHAR *pathW;
254
255     TRACE("%p %s %lx %p\n", query, debugstr_a(path), userdata, counter);
256
257     if (!path) return PDH_INVALID_ARGUMENT;
258
259     if (!(pathW = pdh_strdup_aw( path )))
260         return PDH_MEMORY_ALLOCATION_FAILURE;
261
262     ret = PdhAddCounterW( query, pathW, userdata, counter );
263
264     heap_free( pathW );
265     return ret;
266 }
267
268 /***********************************************************************
269  *              PdhAddCounterW   (PDH.@)
270  */
271 PDH_STATUS WINAPI PdhAddCounterW( PDH_HQUERY hquery, LPCWSTR path,
272                                   DWORD_PTR userdata, PDH_HCOUNTER *hcounter )
273 {
274     struct query *query = hquery;
275     struct counter *counter;
276     unsigned int i;
277
278     TRACE("%p %s %lx %p\n", hquery, debugstr_w(path), userdata, hcounter);
279
280     if (!path  || !hcounter) return PDH_INVALID_ARGUMENT;
281
282     EnterCriticalSection( &pdh_handle_cs );
283     if (!query || query->magic != PDH_MAGIC_QUERY)
284     {
285         LeaveCriticalSection( &pdh_handle_cs );
286         return PDH_INVALID_HANDLE;
287     }
288
289     *hcounter = NULL;
290     for (i = 0; i < sizeof(counter_sources) / sizeof(counter_sources[0]); i++)
291     {
292         if (pdh_match_path( counter_sources[i].path, path ))
293         {
294             if ((counter = create_counter()))
295             {
296                 counter->path         = pdh_strdup( counter_sources[i].path );
297                 counter->collect      = counter_sources[i].collect;
298                 counter->type         = counter_sources[i].type;
299                 counter->defaultscale = counter_sources[i].scale;
300                 counter->base         = counter_sources[i].base;
301                 counter->queryuser    = query->user;
302                 counter->user         = userdata;
303
304                 list_add_tail( &query->counters, &counter->entry );
305                 *hcounter = counter;
306
307                 LeaveCriticalSection( &pdh_handle_cs );
308                 return ERROR_SUCCESS;
309             }
310             LeaveCriticalSection( &pdh_handle_cs );
311             return PDH_MEMORY_ALLOCATION_FAILURE;
312         }
313     }
314     LeaveCriticalSection( &pdh_handle_cs );
315     return PDH_CSTATUS_NO_COUNTER;
316 }
317
318 /***********************************************************************
319  *              PdhAddEnglishCounterA   (PDH.@)
320  */
321 PDH_STATUS WINAPI PdhAddEnglishCounterA( PDH_HQUERY query, LPCSTR path,
322                                          DWORD_PTR userdata, PDH_HCOUNTER *counter )
323 {
324     TRACE("%p %s %lx %p\n", query, debugstr_a(path), userdata, counter);
325
326     if (!query) return PDH_INVALID_ARGUMENT;
327     return PdhAddCounterA( query, path, userdata, counter );
328 }
329
330 /***********************************************************************
331  *              PdhAddEnglishCounterW   (PDH.@)
332  */
333 PDH_STATUS WINAPI PdhAddEnglishCounterW( PDH_HQUERY query, LPCWSTR path,
334                                          DWORD_PTR userdata, PDH_HCOUNTER *counter )
335 {
336     TRACE("%p %s %lx %p\n", query, debugstr_w(path), userdata, counter);
337
338     if (!query) return PDH_INVALID_ARGUMENT;
339     return PdhAddCounterW( query, path, userdata, counter );
340 }
341
342 /* caller must hold counter lock */
343 static PDH_STATUS format_value( struct counter *counter, DWORD format, union value *raw1,
344                                 union value *raw2, PDH_FMT_COUNTERVALUE *value )
345 {
346     LONG factor;
347
348     factor = counter->scale ? counter->scale : counter->defaultscale;
349     if (format & PDH_FMT_LONG)
350     {
351         if (format & PDH_FMT_1000) value->u.longValue = raw2->longvalue * 1000;
352         else value->u.longValue = raw2->longvalue * pow( 10, factor );
353     }
354     else if (format & PDH_FMT_LARGE)
355     {
356         if (format & PDH_FMT_1000) value->u.largeValue = raw2->largevalue * 1000;
357         else value->u.largeValue = raw2->largevalue * pow( 10, factor );
358     }
359     else if (format & PDH_FMT_DOUBLE)
360     {
361         if (format & PDH_FMT_1000) value->u.doubleValue = raw2->doublevalue * 1000;
362         else value->u.doubleValue = raw2->doublevalue * pow( 10, factor );
363     }
364     else
365     {
366         WARN("unknown format %x\n", format);
367         return PDH_INVALID_ARGUMENT;
368     }
369     return ERROR_SUCCESS;
370 }
371
372 /***********************************************************************
373  *              PdhCalculateCounterFromRawValue   (PDH.@)
374  */
375 PDH_STATUS WINAPI PdhCalculateCounterFromRawValue( PDH_HCOUNTER handle, DWORD format,
376                                                    PPDH_RAW_COUNTER raw1, PPDH_RAW_COUNTER raw2,
377                                                    PPDH_FMT_COUNTERVALUE value )
378 {
379     PDH_STATUS ret;
380     struct counter *counter = handle;
381
382     TRACE("%p 0x%08x %p %p %p\n", handle, format, raw1, raw2, value);
383
384     if (!value) return PDH_INVALID_ARGUMENT;
385
386     EnterCriticalSection( &pdh_handle_cs );
387     if (!counter || counter->magic != PDH_MAGIC_COUNTER)
388     {
389         LeaveCriticalSection( &pdh_handle_cs );
390         return PDH_INVALID_HANDLE;
391     }
392
393     ret = format_value( counter, format, (union value *)&raw1->SecondValue,
394                                          (union value *)&raw2->SecondValue, value );
395
396     LeaveCriticalSection( &pdh_handle_cs );
397     return ret;
398 }
399
400
401 /***********************************************************************
402  *              PdhCloseQuery   (PDH.@)
403  */
404 PDH_STATUS WINAPI PdhCloseQuery( PDH_HQUERY handle )
405 {
406     struct query *query = handle;
407     struct list *item, *next;
408
409     TRACE("%p\n", handle);
410
411     EnterCriticalSection( &pdh_handle_cs );
412     if (!query || query->magic != PDH_MAGIC_QUERY)
413     {
414         LeaveCriticalSection( &pdh_handle_cs );
415         return PDH_INVALID_HANDLE;
416     }
417
418     if (query->thread)
419     {
420         HANDLE thread = query->thread;
421         SetEvent( query->stop );
422         LeaveCriticalSection( &pdh_handle_cs );
423
424         WaitForSingleObject( thread, INFINITE );
425
426         EnterCriticalSection( &pdh_handle_cs );
427         if (query->magic != PDH_MAGIC_QUERY)
428         {
429             LeaveCriticalSection( &pdh_handle_cs );
430             return ERROR_SUCCESS;
431         }
432         CloseHandle( query->stop );
433         CloseHandle( query->thread );
434         query->thread = NULL;
435     }
436
437     LIST_FOR_EACH_SAFE( item, next, &query->counters )
438     {
439         struct counter *counter = LIST_ENTRY( item, struct counter, entry );
440
441         list_remove( &counter->entry );
442         destroy_counter( counter );
443     }
444
445     destroy_query( query );
446
447     LeaveCriticalSection( &pdh_handle_cs );
448     return ERROR_SUCCESS;
449 }
450
451 /* caller must hold query lock */
452 static void collect_query_data( struct query *query )
453 {
454     struct list *item;
455
456     LIST_FOR_EACH( item, &query->counters )
457     {
458         SYSTEMTIME time;
459         struct counter *counter = LIST_ENTRY( item, struct counter, entry );
460
461         counter->collect( counter );
462
463         GetLocalTime( &time );
464         SystemTimeToFileTime( &time, &counter->stamp );
465     }
466 }
467
468 /***********************************************************************
469  *              PdhCollectQueryData   (PDH.@)
470  */
471 PDH_STATUS WINAPI PdhCollectQueryData( PDH_HQUERY handle )
472 {
473     struct query *query = handle;
474
475     TRACE("%p\n", handle);
476
477     EnterCriticalSection( &pdh_handle_cs );
478     if (!query || query->magic != PDH_MAGIC_QUERY)
479     {
480         LeaveCriticalSection( &pdh_handle_cs );
481         return PDH_INVALID_HANDLE;
482     }
483
484     if (list_empty( &query->counters ))
485     {
486         LeaveCriticalSection( &pdh_handle_cs );
487         return PDH_NO_DATA;
488     }
489
490     collect_query_data( query );
491
492     LeaveCriticalSection( &pdh_handle_cs );
493     return ERROR_SUCCESS;
494 }
495
496 static DWORD CALLBACK collect_query_thread( void *arg )
497 {
498     struct query *query = arg;
499     DWORD interval = query->interval;
500     HANDLE stop = query->stop;
501
502     for (;;)
503     {
504         if (WaitForSingleObject( stop, interval ) != WAIT_TIMEOUT) ExitThread( 0 );
505
506         EnterCriticalSection( &pdh_handle_cs );
507         if (query->magic != PDH_MAGIC_QUERY)
508         {
509             LeaveCriticalSection( &pdh_handle_cs );
510             ExitThread( PDH_INVALID_HANDLE );
511         }
512
513         collect_query_data( query );
514
515         if (!SetEvent( query->wait ))
516         {
517             LeaveCriticalSection( &pdh_handle_cs );
518             ExitThread( 0 );
519         }
520         LeaveCriticalSection( &pdh_handle_cs );
521     }
522 }
523
524 /***********************************************************************
525  *              PdhCollectQueryDataEx   (PDH.@)
526  */
527 PDH_STATUS WINAPI PdhCollectQueryDataEx( PDH_HQUERY handle, DWORD interval, HANDLE event )
528 {
529     PDH_STATUS ret;
530     struct query *query = handle;
531
532     TRACE("%p %d %p\n", handle, interval, event);
533
534     EnterCriticalSection( &pdh_handle_cs );
535     if (!query || query->magic != PDH_MAGIC_QUERY)
536     {
537         LeaveCriticalSection( &pdh_handle_cs );
538         return PDH_INVALID_HANDLE;
539     }
540     if (list_empty( &query->counters ))
541     {
542         LeaveCriticalSection( &pdh_handle_cs );
543         return PDH_NO_DATA;
544     }
545     if (query->thread)
546     {
547         HANDLE thread = query->thread;
548         SetEvent( query->stop );
549         LeaveCriticalSection( &pdh_handle_cs );
550
551         WaitForSingleObject( thread, INFINITE );
552
553         EnterCriticalSection( &pdh_handle_cs );
554         if (query->magic != PDH_MAGIC_QUERY)
555         {
556             LeaveCriticalSection( &pdh_handle_cs );
557             return PDH_INVALID_HANDLE;
558         }
559         CloseHandle( query->thread );
560         query->thread = NULL;
561     }
562     else if (!(query->stop = CreateEventW( NULL, FALSE, FALSE, NULL )))
563     {
564         ret = GetLastError();
565         LeaveCriticalSection( &pdh_handle_cs );
566         return ret;
567     }
568     query->wait = event;
569     query->interval = interval * 1000;
570     if (!(query->thread = CreateThread( NULL, 0, collect_query_thread, query, 0, NULL )))
571     {
572         ret = GetLastError();
573         CloseHandle( query->stop );
574
575         LeaveCriticalSection( &pdh_handle_cs );
576         return ret;
577     }
578
579     LeaveCriticalSection( &pdh_handle_cs );
580     return ERROR_SUCCESS;
581 }
582
583 /***********************************************************************
584  *              PdhCollectQueryDataWithTime   (PDH.@)
585  */
586 PDH_STATUS WINAPI PdhCollectQueryDataWithTime( PDH_HQUERY handle, LONGLONG *timestamp )
587 {
588     struct query *query = handle;
589     struct counter *counter;
590     struct list *item;
591
592     TRACE("%p %p\n", handle, timestamp);
593
594     if (!timestamp) return PDH_INVALID_ARGUMENT;
595
596     EnterCriticalSection( &pdh_handle_cs );
597     if (!query || query->magic != PDH_MAGIC_QUERY)
598     {
599         LeaveCriticalSection( &pdh_handle_cs );
600         return PDH_INVALID_HANDLE;
601     }
602     if (list_empty( &query->counters ))
603     {
604         LeaveCriticalSection( &pdh_handle_cs );
605         return PDH_NO_DATA;
606     }
607
608     collect_query_data( query );
609
610     item = list_head( &query->counters );
611     counter = LIST_ENTRY( item, struct counter, entry );
612
613     *timestamp = ((LONGLONG)counter->stamp.dwHighDateTime << 32) | counter->stamp.dwLowDateTime;
614
615     LeaveCriticalSection( &pdh_handle_cs );
616     return ERROR_SUCCESS;
617 }
618
619 /***********************************************************************
620  *              PdhExpandWildCardPathA   (PDH.@)
621  */
622 PDH_STATUS WINAPI PdhExpandWildCardPathA( LPCSTR szDataSource, LPCSTR szWildCardPath, LPSTR mszExpandedPathList, LPDWORD pcchPathListLength, DWORD dwFlags )
623 {
624     FIXME("%s, %s, %p, %p, 0x%x: stub\n", debugstr_a(szDataSource), debugstr_a(szWildCardPath), mszExpandedPathList, pcchPathListLength, dwFlags);
625     return PDH_NOT_IMPLEMENTED;
626 }
627
628 /***********************************************************************
629  *              PdhExpandWildCardPathW   (PDH.@)
630  */
631 PDH_STATUS WINAPI PdhExpandWildCardPathW( LPCWSTR szDataSource, LPCWSTR szWildCardPath, LPWSTR mszExpandedPathList, LPDWORD pcchPathListLength, DWORD dwFlags )
632 {
633     FIXME("%s, %s, %p, %p, 0x%x: stub\n", debugstr_w(szDataSource), debugstr_w(szWildCardPath), mszExpandedPathList, pcchPathListLength, dwFlags);
634     return PDH_NOT_IMPLEMENTED;
635 }
636
637 /***********************************************************************
638  *              PdhGetCounterInfoA   (PDH.@)
639  */
640 PDH_STATUS WINAPI PdhGetCounterInfoA( PDH_HCOUNTER handle, BOOLEAN text, LPDWORD size, PPDH_COUNTER_INFO_A info )
641 {
642     struct counter *counter = handle;
643
644     TRACE("%p %d %p %p\n", handle, text, size, info);
645
646     EnterCriticalSection( &pdh_handle_cs );
647     if (!counter || counter->magic != PDH_MAGIC_COUNTER)
648     {
649         LeaveCriticalSection( &pdh_handle_cs );
650         return PDH_INVALID_HANDLE;
651     }
652     if (!size)
653     {
654         LeaveCriticalSection( &pdh_handle_cs );
655         return PDH_INVALID_ARGUMENT;
656     }
657     if (*size < sizeof(PDH_COUNTER_INFO_A))
658     {
659         *size = sizeof(PDH_COUNTER_INFO_A);
660         LeaveCriticalSection( &pdh_handle_cs );
661         return PDH_MORE_DATA;
662     }
663
664     memset( info, 0, sizeof(PDH_COUNTER_INFO_A) );
665
666     info->dwType          = counter->type;
667     info->CStatus         = counter->status;
668     info->lScale          = counter->scale;
669     info->lDefaultScale   = counter->defaultscale;
670     info->dwUserData      = counter->user;
671     info->dwQueryUserData = counter->queryuser;
672
673     *size = sizeof(PDH_COUNTER_INFO_A);
674
675     LeaveCriticalSection( &pdh_handle_cs );
676     return ERROR_SUCCESS;
677 }
678
679 /***********************************************************************
680  *              PdhGetCounterInfoW   (PDH.@)
681  */
682 PDH_STATUS WINAPI PdhGetCounterInfoW( PDH_HCOUNTER handle, BOOLEAN text, LPDWORD size, PPDH_COUNTER_INFO_W info )
683 {
684     struct counter *counter = handle;
685
686     TRACE("%p %d %p %p\n", handle, text, size, info);
687
688     EnterCriticalSection( &pdh_handle_cs );
689     if (!counter || counter->magic != PDH_MAGIC_COUNTER)
690     {
691         LeaveCriticalSection( &pdh_handle_cs );
692         return PDH_INVALID_HANDLE;
693     }
694     if (!size)
695     {
696         LeaveCriticalSection( &pdh_handle_cs );
697         return PDH_INVALID_ARGUMENT;
698     }
699     if (*size < sizeof(PDH_COUNTER_INFO_W))
700     {
701         *size = sizeof(PDH_COUNTER_INFO_W);
702         LeaveCriticalSection( &pdh_handle_cs );
703         return PDH_MORE_DATA;
704     }
705
706     memset( info, 0, sizeof(PDH_COUNTER_INFO_W) );
707
708     info->dwType          = counter->type;
709     info->CStatus         = counter->status;
710     info->lScale          = counter->scale;
711     info->lDefaultScale   = counter->defaultscale;
712     info->dwUserData      = counter->user;
713     info->dwQueryUserData = counter->queryuser;
714
715     *size = sizeof(PDH_COUNTER_INFO_W);
716
717     LeaveCriticalSection( &pdh_handle_cs );
718     return ERROR_SUCCESS;
719 }
720
721 /***********************************************************************
722  *              PdhGetCounterTimeBase   (PDH.@)
723  */
724 PDH_STATUS WINAPI PdhGetCounterTimeBase( PDH_HCOUNTER handle, LONGLONG *base )
725 {
726     struct counter *counter = handle;
727
728     TRACE("%p %p\n", handle, base);
729
730     if (!base) return PDH_INVALID_ARGUMENT;
731
732     EnterCriticalSection( &pdh_handle_cs );
733     if (!counter || counter->magic != PDH_MAGIC_COUNTER)
734     {
735         LeaveCriticalSection( &pdh_handle_cs );
736         return PDH_INVALID_HANDLE;
737     }
738
739     *base = counter->base;
740
741     LeaveCriticalSection( &pdh_handle_cs );
742     return ERROR_SUCCESS;
743 }
744
745 /***********************************************************************
746  *              PdhGetDllVersion   (PDH.@)
747  */
748 PDH_STATUS WINAPI PdhGetDllVersion( LPDWORD version )
749 {
750     if (!version)
751         return PDH_INVALID_ARGUMENT;
752
753     *version = PDH_VERSION;
754
755     return ERROR_SUCCESS;
756 }
757
758 /***********************************************************************
759  *              PdhGetFormattedCounterValue   (PDH.@)
760  */
761 PDH_STATUS WINAPI PdhGetFormattedCounterValue( PDH_HCOUNTER handle, DWORD format,
762                                                LPDWORD type, PPDH_FMT_COUNTERVALUE value )
763 {
764     PDH_STATUS ret;
765     struct counter *counter = handle;
766
767     TRACE("%p %x %p %p\n", handle, format, type, value);
768
769     if (!value) return PDH_INVALID_ARGUMENT;
770
771     EnterCriticalSection( &pdh_handle_cs );
772     if (!counter || counter->magic != PDH_MAGIC_COUNTER)
773     {
774         LeaveCriticalSection( &pdh_handle_cs );
775         return PDH_INVALID_HANDLE;
776     }
777     if (counter->status)
778     {
779         LeaveCriticalSection( &pdh_handle_cs );
780         return PDH_INVALID_DATA;
781     }
782     if (!(ret = format_value( counter, format, &counter->one, &counter->two, value )))
783     {
784         value->CStatus = ERROR_SUCCESS;
785         if (type) *type = counter->type;
786     }
787
788     LeaveCriticalSection( &pdh_handle_cs );
789     return ret;
790 }
791
792 /***********************************************************************
793  *              PdhGetRawCounterValue   (PDH.@)
794  */
795 PDH_STATUS WINAPI PdhGetRawCounterValue( PDH_HCOUNTER handle, LPDWORD type,
796                                          PPDH_RAW_COUNTER value )
797 {
798     struct counter *counter = handle;
799
800     TRACE("%p %p %p\n", handle, type, value);
801
802     if (!value) return PDH_INVALID_ARGUMENT;
803
804     EnterCriticalSection( &pdh_handle_cs );
805     if (!counter || counter->magic != PDH_MAGIC_COUNTER)
806     {
807         LeaveCriticalSection( &pdh_handle_cs );
808         return PDH_INVALID_HANDLE;
809     }
810
811     value->CStatus                  = counter->status;
812     value->TimeStamp.dwLowDateTime  = counter->stamp.dwLowDateTime;
813     value->TimeStamp.dwHighDateTime = counter->stamp.dwHighDateTime;
814     value->FirstValue               = counter->one.largevalue;
815     value->SecondValue              = counter->two.largevalue;
816     value->MultiCount               = 1; /* FIXME */
817
818     if (type) *type = counter->type;
819
820     LeaveCriticalSection( &pdh_handle_cs );
821     return ERROR_SUCCESS;
822 }
823
824 /***********************************************************************
825  *              PdhLookupPerfIndexByNameA   (PDH.@)
826  */
827 PDH_STATUS WINAPI PdhLookupPerfIndexByNameA( LPCSTR machine, LPCSTR name, LPDWORD index )
828 {
829     PDH_STATUS ret;
830     WCHAR *machineW = NULL;
831     WCHAR *nameW;
832
833     TRACE("%s %s %p\n", debugstr_a(machine), debugstr_a(name), index);
834
835     if (!name) return PDH_INVALID_ARGUMENT;
836
837     if (machine && !(machineW = pdh_strdup_aw( machine ))) return PDH_MEMORY_ALLOCATION_FAILURE;
838
839     if (!(nameW = pdh_strdup_aw( name )))
840         return PDH_MEMORY_ALLOCATION_FAILURE;
841
842     ret = PdhLookupPerfIndexByNameW( machineW, nameW, index );
843
844     heap_free( nameW );
845     heap_free( machineW );
846     return ret;
847 }
848
849 /***********************************************************************
850  *              PdhLookupPerfIndexByNameW   (PDH.@)
851  */
852 PDH_STATUS WINAPI PdhLookupPerfIndexByNameW( LPCWSTR machine, LPCWSTR name, LPDWORD index )
853 {
854     unsigned int i;
855
856     TRACE("%s %s %p\n", debugstr_w(machine), debugstr_w(name), index);
857
858     if (!name || !index) return PDH_INVALID_ARGUMENT;
859
860     if (machine)
861     {
862         FIXME("remote machine not supported\n");
863         return PDH_CSTATUS_NO_MACHINE;
864     }
865     for (i = 0; i < sizeof(counter_sources) / sizeof(counter_sources[0]); i++)
866     {
867         if (pdh_match_path( counter_sources[i].path, name ))
868         {
869             *index = counter_sources[i].index;
870             return ERROR_SUCCESS;
871         }
872     }
873     return PDH_STRING_NOT_FOUND;
874 }
875
876 /***********************************************************************
877  *              PdhLookupPerfNameByIndexA   (PDH.@)
878  */
879 PDH_STATUS WINAPI PdhLookupPerfNameByIndexA( LPCSTR machine, DWORD index, LPSTR buffer, LPDWORD size )
880 {
881     PDH_STATUS ret;
882     WCHAR *machineW = NULL;
883     WCHAR bufferW[PDH_MAX_COUNTER_NAME];
884     DWORD sizeW = sizeof(bufferW) / sizeof(WCHAR);
885
886     TRACE("%s %d %p %p\n", debugstr_a(machine), index, buffer, size);
887
888     if (!buffer || !size) return PDH_INVALID_ARGUMENT;
889
890     if (machine && !(machineW = pdh_strdup_aw( machine ))) return PDH_MEMORY_ALLOCATION_FAILURE;
891
892     if (!(ret = PdhLookupPerfNameByIndexW( machineW, index, bufferW, &sizeW )))
893     {
894         int required = WideCharToMultiByte( CP_ACP, 0, bufferW, -1, NULL, 0, NULL, NULL );
895
896         if (size && *size < required) ret = PDH_MORE_DATA;
897         else WideCharToMultiByte( CP_ACP, 0, bufferW, -1, buffer, required, NULL, NULL );
898         if (size) *size = required;
899     }
900     heap_free( machineW );
901     return ret;
902 }
903
904 /***********************************************************************
905  *              PdhLookupPerfNameByIndexW   (PDH.@)
906  */
907 PDH_STATUS WINAPI PdhLookupPerfNameByIndexW( LPCWSTR machine, DWORD index, LPWSTR buffer, LPDWORD size )
908 {
909     PDH_STATUS ret;
910     unsigned int i;
911
912     TRACE("%s %d %p %p\n", debugstr_w(machine), index, buffer, size);
913
914     if (machine)
915     {
916         FIXME("remote machine not supported\n");
917         return PDH_CSTATUS_NO_MACHINE;
918     }
919
920     if (!buffer || !size) return PDH_INVALID_ARGUMENT;
921     if (!index) return ERROR_SUCCESS;
922
923     for (i = 0; i < sizeof(counter_sources) / sizeof(counter_sources[0]); i++)
924     {
925         if (counter_sources[i].index == index)
926         {
927             WCHAR *p = strrchrW( counter_sources[i].path, '\\' ) + 1;
928             unsigned int required = strlenW( p ) + 1;
929
930             if (*size < required) ret = PDH_MORE_DATA;
931             else
932             {
933                 strcpyW( buffer, p );
934                 ret = ERROR_SUCCESS;
935             }
936             *size = required;
937             return ret;
938         }
939     }
940     return PDH_INVALID_ARGUMENT;
941 }
942
943 /***********************************************************************
944  *              PdhOpenQueryA   (PDH.@)
945  */
946 PDH_STATUS WINAPI PdhOpenQueryA( LPCSTR source, DWORD_PTR userdata, PDH_HQUERY *query )
947 {
948     PDH_STATUS ret;
949     WCHAR *sourceW = NULL;
950
951     TRACE("%s %lx %p\n", debugstr_a(source), userdata, query);
952
953     if (source && !(sourceW = pdh_strdup_aw( source ))) return PDH_MEMORY_ALLOCATION_FAILURE;
954
955     ret = PdhOpenQueryW( sourceW, userdata, query );
956     heap_free( sourceW );
957
958     return ret;
959 }
960
961 /***********************************************************************
962  *              PdhOpenQueryW   (PDH.@)
963  */
964 PDH_STATUS WINAPI PdhOpenQueryW( LPCWSTR source, DWORD_PTR userdata, PDH_HQUERY *handle )
965 {
966     struct query *query;
967
968     TRACE("%s %lx %p\n", debugstr_w(source), userdata, handle);
969
970     if (!handle) return PDH_INVALID_ARGUMENT;
971
972     if (source)
973     {
974         FIXME("log file data source not supported\n");
975         return PDH_INVALID_ARGUMENT;
976     }
977     if ((query = create_query()))
978     {
979         query->user = userdata;
980         *handle = query;
981
982         return ERROR_SUCCESS;
983     }
984     return PDH_MEMORY_ALLOCATION_FAILURE;
985 }
986
987 /***********************************************************************
988  *              PdhRemoveCounter   (PDH.@)
989  */
990 PDH_STATUS WINAPI PdhRemoveCounter( PDH_HCOUNTER handle )
991 {
992     struct counter *counter = handle;
993
994     TRACE("%p\n", handle);
995
996     EnterCriticalSection( &pdh_handle_cs );
997     if (!counter || counter->magic != PDH_MAGIC_COUNTER)
998     {
999         LeaveCriticalSection( &pdh_handle_cs );
1000         return PDH_INVALID_HANDLE;
1001     }
1002
1003     list_remove( &counter->entry );
1004     destroy_counter( counter );
1005
1006     LeaveCriticalSection( &pdh_handle_cs );
1007     return ERROR_SUCCESS;
1008 }
1009
1010 /***********************************************************************
1011  *              PdhSetCounterScaleFactor   (PDH.@)
1012  */
1013 PDH_STATUS WINAPI PdhSetCounterScaleFactor( PDH_HCOUNTER handle, LONG factor )
1014 {
1015     struct counter *counter = handle;
1016
1017     TRACE("%p\n", handle);
1018
1019     EnterCriticalSection( &pdh_handle_cs );
1020     if (!counter || counter->magic != PDH_MAGIC_COUNTER)
1021     {
1022         LeaveCriticalSection( &pdh_handle_cs );
1023         return PDH_INVALID_HANDLE;
1024     }
1025     if (factor < PDH_MIN_SCALE || factor > PDH_MAX_SCALE)
1026     {
1027         LeaveCriticalSection( &pdh_handle_cs );
1028         return PDH_INVALID_ARGUMENT;
1029     }
1030
1031     counter->scale = factor;
1032
1033     LeaveCriticalSection( &pdh_handle_cs );
1034     return ERROR_SUCCESS;
1035 }
1036
1037 /***********************************************************************
1038  *              PdhValidatePathA   (PDH.@)
1039  */
1040 PDH_STATUS WINAPI PdhValidatePathA( LPCSTR path )
1041 {
1042     PDH_STATUS ret;
1043     WCHAR *pathW;
1044
1045     TRACE("%s\n", debugstr_a(path));
1046
1047     if (!path) return PDH_INVALID_ARGUMENT;
1048     if (!(pathW = pdh_strdup_aw( path ))) return PDH_MEMORY_ALLOCATION_FAILURE;
1049
1050     ret = PdhValidatePathW( pathW );
1051
1052     heap_free( pathW );
1053     return ret;
1054 }
1055
1056 static PDH_STATUS validate_path( LPCWSTR path )
1057 {
1058     if (!path || !*path) return PDH_INVALID_ARGUMENT;
1059     if (*path++ != '\\' || !strchrW( path, '\\' )) return PDH_CSTATUS_BAD_COUNTERNAME;
1060     return ERROR_SUCCESS;
1061  }
1062
1063 /***********************************************************************
1064  *              PdhValidatePathW   (PDH.@)
1065  */
1066 PDH_STATUS WINAPI PdhValidatePathW( LPCWSTR path )
1067 {
1068     PDH_STATUS ret;
1069     unsigned int i;
1070
1071     TRACE("%s\n", debugstr_w(path));
1072
1073     if ((ret = validate_path( path ))) return ret;
1074
1075     for (i = 0; i < sizeof(counter_sources) / sizeof(counter_sources[0]); i++)
1076         if (pdh_match_path( counter_sources[i].path, path )) return ERROR_SUCCESS;
1077
1078     return PDH_CSTATUS_NO_COUNTER;
1079 }
1080
1081 /***********************************************************************
1082  *              PdhValidatePathExA   (PDH.@)
1083  */
1084 PDH_STATUS WINAPI PdhValidatePathExA( PDH_HLOG source, LPCSTR path )
1085 {
1086     TRACE("%p %s\n", source, debugstr_a(path));
1087
1088     if (source)
1089     {
1090         FIXME("log file data source not supported\n");
1091         return ERROR_SUCCESS;
1092     }
1093     return PdhValidatePathA( path );
1094 }
1095
1096 /***********************************************************************
1097  *              PdhValidatePathExW   (PDH.@)
1098  */
1099 PDH_STATUS WINAPI PdhValidatePathExW( PDH_HLOG source, LPCWSTR path )
1100 {
1101     TRACE("%p %s\n", source, debugstr_w(path));
1102
1103     if (source)
1104     {
1105         FIXME("log file data source not supported\n");
1106         return ERROR_SUCCESS;
1107     }
1108     return PdhValidatePathW( path );
1109 }
1110
1111 /***********************************************************************
1112  *              PdhMakeCounterPathA   (PDH.@)
1113  */
1114 PDH_STATUS WINAPI PdhMakeCounterPathA( PDH_COUNTER_PATH_ELEMENTS_A *e, LPSTR buffer,
1115                                        LPDWORD buflen, DWORD flags )
1116 {
1117     PDH_STATUS ret = PDH_MEMORY_ALLOCATION_FAILURE;
1118     PDH_COUNTER_PATH_ELEMENTS_W eW;
1119     WCHAR *bufferW;
1120     DWORD buflenW;
1121
1122     TRACE("%p %p %p 0x%08x\n", e, buffer, buflen, flags);
1123
1124     if (!e || !buflen) return PDH_INVALID_ARGUMENT;
1125
1126     memset( &eW, 0, sizeof(eW) );
1127     if (e->szMachineName    && !(eW.szMachineName    = pdh_strdup_aw( e->szMachineName ))) goto done;
1128     if (e->szObjectName     && !(eW.szObjectName     = pdh_strdup_aw( e->szObjectName ))) goto done;
1129     if (e->szInstanceName   && !(eW.szInstanceName   = pdh_strdup_aw( e->szInstanceName ))) goto done;
1130     if (e->szParentInstance && !(eW.szParentInstance = pdh_strdup_aw( e->szParentInstance ))) goto done;
1131     if (e->szCounterName    && !(eW.szCounterName    = pdh_strdup_aw( e->szCounterName ))) goto done;
1132     eW.dwInstanceIndex = e->dwInstanceIndex;
1133
1134     buflenW = 0;
1135     ret = PdhMakeCounterPathW( &eW, NULL, &buflenW, flags );
1136     if (ret == PDH_MORE_DATA)
1137     {
1138         if ((bufferW = heap_alloc( buflenW * sizeof(WCHAR) )))
1139         {
1140             if (!(ret = PdhMakeCounterPathW( &eW, bufferW, &buflenW, flags )))
1141             {
1142                 int len = WideCharToMultiByte(CP_ACP, 0, bufferW, -1, NULL, 0, NULL, NULL);
1143                 if (*buflen >= len) WideCharToMultiByte(CP_ACP, 0, bufferW, -1, buffer, *buflen, NULL, NULL);
1144                 else ret = PDH_MORE_DATA;
1145                 *buflen = len;
1146             }
1147             heap_free( bufferW );
1148         }
1149         else
1150             ret = PDH_MEMORY_ALLOCATION_FAILURE;
1151     }
1152
1153 done:
1154     heap_free( eW.szMachineName );
1155     heap_free( eW.szObjectName );
1156     heap_free( eW.szInstanceName );
1157     heap_free( eW.szParentInstance );
1158     heap_free( eW.szCounterName );
1159     return ret;
1160 }
1161
1162 /***********************************************************************
1163  *              PdhMakeCounterPathW   (PDH.@)
1164  */
1165 PDH_STATUS WINAPI PdhMakeCounterPathW( PDH_COUNTER_PATH_ELEMENTS_W *e, LPWSTR buffer,
1166                                        LPDWORD buflen, DWORD flags )
1167 {
1168     static const WCHAR bslash[] = {'\\',0};
1169     static const WCHAR fslash[] = {'/',0};
1170     static const WCHAR lparen[] = {'(',0};
1171     static const WCHAR rparen[] = {')',0};
1172     static const WCHAR fmt[]    = {'#','%','u',0};
1173
1174     WCHAR path[PDH_MAX_COUNTER_NAME], instance[12];
1175     PDH_STATUS ret = ERROR_SUCCESS;
1176     DWORD len;
1177
1178     TRACE("%p %p %p 0x%08x\n", e, buffer, buflen, flags);
1179
1180     if (flags) FIXME("unimplemented flags 0x%08x\n", flags);
1181
1182     if (!e || !e->szCounterName || !e->szObjectName || !buflen)
1183         return PDH_INVALID_ARGUMENT;
1184
1185     path[0] = 0;
1186     if (e->szMachineName)
1187     {
1188         strcatW(path, bslash);
1189         strcatW(path, bslash);
1190         strcatW(path, e->szMachineName);
1191     }
1192     strcatW(path, bslash);
1193     strcatW(path, e->szObjectName);
1194     if (e->szInstanceName)
1195     {
1196         strcatW(path, lparen);
1197         if (e->szParentInstance)
1198         {
1199             strcatW(path, e->szParentInstance);
1200             strcatW(path, fslash);
1201         }
1202         strcatW(path, e->szInstanceName);
1203         sprintfW(instance, fmt, e->dwInstanceIndex);
1204         strcatW(path, instance);
1205         strcatW(path, rparen);
1206     }
1207     strcatW(path, bslash);
1208     strcatW(path, e->szCounterName);
1209
1210     len = strlenW(path) + 1;
1211     if (*buflen >= len) strcpyW(buffer, path);
1212     else ret = PDH_MORE_DATA;
1213     *buflen = len;
1214     return ret;
1215 }
1216
1217 /***********************************************************************
1218  *              PdhEnumObjectItemsA   (PDH.@)
1219  */
1220 PDH_STATUS WINAPI PdhEnumObjectItemsA(LPCSTR szDataSource, LPCSTR szMachineName, LPCSTR szObjectName,
1221                                       LPSTR mszCounterList, LPDWORD pcchCounterListLength, LPSTR mszInstanceList,
1222                                       LPDWORD pcchInstanceListLength, DWORD dwDetailLevel, DWORD dwFlags)
1223 {
1224     FIXME("%s, %s, %s, %p, %p, %p, %p, %d, 0x%x: stub\n", debugstr_a(szDataSource), debugstr_a(szMachineName),
1225          debugstr_a(szObjectName), mszCounterList, pcchCounterListLength, mszInstanceList,
1226          pcchInstanceListLength, dwDetailLevel, dwFlags);
1227
1228     return PDH_NOT_IMPLEMENTED;
1229 }
1230
1231 /***********************************************************************
1232  *              PdhEnumObjectItemsW   (PDH.@)
1233  */
1234 PDH_STATUS WINAPI PdhEnumObjectItemsW(LPCWSTR szDataSource, LPCWSTR szMachineName, LPCWSTR szObjectName,
1235                                       LPWSTR mszCounterList, LPDWORD pcchCounterListLength, LPWSTR mszInstanceList,
1236                                       LPDWORD pcchInstanceListLength, DWORD dwDetailLevel, DWORD dwFlags)
1237 {
1238     FIXME("%s, %s, %s, %p, %p, %p, %p, %d, 0x%x: stub\n", debugstr_w(szDataSource), debugstr_w(szMachineName),
1239          debugstr_w(szObjectName), mszCounterList, pcchCounterListLength, mszInstanceList,
1240          pcchInstanceListLength, dwDetailLevel, dwFlags);
1241
1242     return PDH_NOT_IMPLEMENTED;
1243 }
1244
1245 /***********************************************************************
1246  *              PdhSetDefaultRealTimeDataSource   (PDH.@)
1247  */
1248 PDH_STATUS WINAPI PdhSetDefaultRealTimeDataSource( DWORD source )
1249 {
1250     FIXME("%u\n", source);
1251     return ERROR_SUCCESS;
1252 }