OSDN Git Service

Replace valid memory checks with new myfault class "exception handling", almost
[pf3gnuchains/pf3gnuchains4x.git] / winsup / cygwin / fhandler_proc.cc
1 /* fhandler_proc.cc: fhandler for /proc virtual filesystem
2
3    Copyright 2002, 2003, 2004, 2005 Red Hat, Inc.
4
5 This file is part of Cygwin.
6
7 This software is a copyrighted work licensed under the terms of the
8 Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
9 details. */
10
11 #define _WIN32_WINNT 0x0501
12
13 #include "winsup.h"
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <sys/cygwin.h>
17 #include <ntdef.h>
18 #include "cygerrno.h"
19 #include "security.h"
20 #include "path.h"
21 #include "fhandler.h"
22 #include "pinfo.h"
23 #include "dtable.h"
24 #include "cygheap.h"
25 #include <assert.h>
26 #include <sys/utsname.h>
27 #include <sys/param.h>
28 #include "ntdll.h"
29 #include <winioctl.h>
30 #include "cpuid.h"
31
32 #define _COMPILING_NEWLIB
33 #include <dirent.h>
34
35 /* offsets in proc_listing */
36 static const int PROC_LOADAVG  = 2;     // /proc/loadavg
37 static const int PROC_MEMINFO  = 3;     // /proc/meminfo
38 static const int PROC_REGISTRY = 4;     // /proc/registry
39 static const int PROC_STAT     = 5;     // /proc/stat
40 static const int PROC_VERSION  = 6;     // /proc/version
41 static const int PROC_UPTIME   = 7;     // /proc/uptime
42 static const int PROC_CPUINFO  = 8;     // /proc/cpuinfo
43 static const int PROC_PARTITIONS = 9;   // /proc/partitions
44 static const int PROC_SELF     = 10;    // /proc/self
45
46 /* names of objects in /proc */
47 static const char *proc_listing[] = {
48   ".",
49   "..",
50   "loadavg",
51   "meminfo",
52   "registry",
53   "stat",
54   "version",
55   "uptime",
56   "cpuinfo",
57   "partitions",
58   "self",
59   NULL
60 };
61
62 static const int PROC_LINK_COUNT = (sizeof (proc_listing) / sizeof (const char *)) - 1;
63
64 /* FH_PROC in the table below means the file/directory is handles by
65  * fhandler_proc.
66  */
67 static const DWORD proc_fhandlers[PROC_LINK_COUNT] = {
68   FH_PROC,
69   FH_PROC,
70   FH_PROC,
71   FH_PROC,
72   FH_REGISTRY,
73   FH_PROC,
74   FH_PROC,
75   FH_PROC,
76   FH_PROC,
77   FH_PROC,
78   FH_PROC,
79 };
80
81 /* name of the /proc filesystem */
82 const char proc[] = "/proc";
83 const int proc_len = sizeof (proc) - 1;
84
85 static _off64_t format_proc_meminfo (char *destbuf, size_t maxsize);
86 static _off64_t format_proc_stat (char *destbuf, size_t maxsize);
87 static _off64_t format_proc_uptime (char *destbuf, size_t maxsize);
88 static _off64_t format_proc_cpuinfo (char *destbuf, size_t maxsize);
89 static _off64_t format_proc_partitions (char *destbuf, size_t maxsize);
90
91 /* Auxillary function that returns the fhandler associated with the given path
92    this is where it would be nice to have pattern matching in C - polymorphism
93    just doesn't cut it. */
94 DWORD
95 fhandler_proc::get_proc_fhandler (const char *path)
96 {
97   debug_printf ("get_proc_fhandler(%s)", path);
98   path += proc_len;
99   /* Since this method is called from path_conv::check we can't rely on
100      it being normalised and therefore the path may have runs of slashes
101      in it.  */
102   while (isdirsep (*path))
103     path++;
104
105   /* Check if this is the root of the virtual filesystem (i.e. /proc).  */
106   if (*path == 0)
107     return FH_PROC;
108
109   for (int i = 0; proc_listing[i]; i++)
110     {
111       if (path_prefix_p (proc_listing[i], path, strlen (proc_listing[i])))
112         return proc_fhandlers[i];
113     }
114
115   if (pinfo (atoi (path)))
116     return FH_PROCESS;
117
118   bool has_subdir = false;
119   while (*path)
120     if (isdirsep (*path++))
121       {
122         has_subdir = true;
123         break;
124       }
125
126   if (has_subdir)
127     /* The user is trying to access a non-existent subdirectory of /proc. */
128     return FH_BAD;
129   else
130     /* Return FH_PROC so that we can return EROFS if the user is trying to create
131        a file. */
132     return FH_PROC;
133 }
134
135 /* Returns 0 if path doesn't exist, >0 if path is a directory,
136    -1 if path is a file, -2 if it's a symlink.  */
137 int
138 fhandler_proc::exists ()
139 {
140   const char *path = get_name ();
141   debug_printf ("exists (%s)", path);
142   path += proc_len;
143   if (*path == 0)
144     return 2;
145   for (int i = 0; proc_listing[i]; i++)
146     if (pathmatch (path + 1, proc_listing[i]))
147       {
148         fileid = i;
149         return (proc_fhandlers[i] == FH_PROC) ? (i == PROC_SELF ? -2 : -1) : 1;
150       }
151   return 0;
152 }
153
154 fhandler_proc::fhandler_proc ():
155   fhandler_virtual ()
156 {
157 }
158
159 int
160 fhandler_proc::fstat (struct __stat64 *buf)
161 {
162   const char *path = get_name ();
163   debug_printf ("fstat (%s)", path);
164
165   path += proc_len;
166   (void) fhandler_base::fstat (buf);
167
168   buf->st_mode &= ~_IFMT & NO_W;
169
170   if (!*path)
171     {
172       buf->st_nlink = PROC_LINK_COUNT;
173       buf->st_mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
174       return 0;
175     }
176   else
177     {
178       path++;
179       for (int i = 0; proc_listing[i]; i++)
180         if (pathmatch (path, proc_listing[i]))
181           {
182             if (proc_fhandlers[i] != FH_PROC)
183               buf->st_mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
184             else if (i == PROC_SELF)
185               buf->st_mode = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO;
186             else
187               {
188                 buf->st_mode &= NO_X;
189                 buf->st_mode |= S_IFREG;
190               }
191             return 0;
192           }
193     }
194   set_errno (ENOENT);
195   return -1;
196 }
197
198 struct dirent *
199 fhandler_proc::readdir (DIR * dir)
200 {
201   if (dir->__d_position >= PROC_LINK_COUNT)
202     {
203       winpids pids ((DWORD) 0);
204       int found = 0;
205       for (unsigned i = 0; i < pids.npids; i++)
206         if (found++ == dir->__d_position - PROC_LINK_COUNT)
207           {
208             __small_sprintf (dir->__d_dirent->d_name, "%d", pids[i]->pid);
209             dir->__d_position++;
210             return dir->__d_dirent;
211           }
212       return NULL;
213     }
214
215   strcpy (dir->__d_dirent->d_name, proc_listing[dir->__d_position++]);
216   syscall_printf ("%p = readdir (%p) (%s)", &dir->__d_dirent, dir,
217                   dir->__d_dirent->d_name);
218   return dir->__d_dirent;
219 }
220
221 int
222 fhandler_proc::open (int flags, mode_t mode)
223 {
224   int proc_file_no = -1;
225
226   int res = fhandler_virtual::open (flags, mode);
227   if (!res)
228     goto out;
229
230   nohandle (true);
231
232   const char *path;
233
234   path = get_name () + proc_len;
235
236   if (!*path)
237     {
238       if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
239         {
240           set_errno (EEXIST);
241           res = 0;
242           goto out;
243         }
244       else if (flags & O_WRONLY)
245         {
246           set_errno (EISDIR);
247           res = 0;
248           goto out;
249         }
250       else
251         {
252           flags |= O_DIROPEN;
253           goto success;
254         }
255     }
256
257   proc_file_no = -1;
258   for (int i = 0; proc_listing[i]; i++)
259     if (path_prefix_p (proc_listing[i], path + 1, strlen (proc_listing[i])))
260       {
261         proc_file_no = i;
262         if (proc_fhandlers[i] != FH_PROC)
263           {
264             if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
265               {
266                 set_errno (EEXIST);
267                 res = 0;
268                 goto out;
269               }
270             else if (flags & O_WRONLY)
271               {
272                 set_errno (EISDIR);
273                 res = 0;
274                 goto out;
275               }
276             else
277               {
278                 flags |= O_DIROPEN;
279                 goto success;
280               }
281           }
282       }
283
284   if (proc_file_no == -1)
285     {
286       if (flags & O_CREAT)
287         {
288           set_errno (EROFS);
289           res = 0;
290           goto out;
291         }
292       else
293         {
294           set_errno (ENOENT);
295           res = 0;
296           goto out;
297         }
298     }
299   if (flags & O_WRONLY)
300     {
301       set_errno (EROFS);
302       res = 0;
303       goto out;
304     }
305
306   fileid = proc_file_no;
307   if (!fill_filebuf ())
308     {
309       res = 0;
310       goto out;
311         }
312
313   if (flags & O_APPEND)
314     position = filesize;
315   else
316     position = 0;
317
318 success:
319   res = 1;
320   set_flags ((flags & ~O_TEXT) | O_BINARY);
321   set_open_status ();
322 out:
323   syscall_printf ("%d = fhandler_proc::open (%p, %d)", res, flags, mode);
324   return res;
325 }
326
327 bool
328 fhandler_proc::fill_filebuf ()
329 {
330   switch (fileid)
331     {
332     case PROC_VERSION:
333       {
334         if (!filebuf)
335           {
336             struct utsname uts_name;
337             uname (&uts_name);
338                 bufalloc = strlen (uts_name.sysname) + 1 + strlen (uts_name.release) +
339                           1 + strlen (uts_name.version) + 2;
340             filebuf = (char *) realloc (filebuf, bufalloc);
341                 filesize = __small_sprintf (filebuf, "%s %s %s\n", uts_name.sysname,
342                              uts_name.release, uts_name.version);
343           }
344         break;
345       }
346     case PROC_UPTIME:
347       {
348         filebuf = (char *) realloc (filebuf, bufalloc = 80);
349         filesize = format_proc_uptime (filebuf, bufalloc);
350         break;
351       }
352     case PROC_STAT:
353       {
354         filebuf = (char *) realloc (filebuf, bufalloc = 16384);
355         filesize = format_proc_stat (filebuf, bufalloc);
356         break;
357       }
358     case PROC_LOADAVG:
359       {
360         /*
361          * not really supported - Windows doesn't keep track of these values
362          * Windows 95/98/me does have the KERNEL/CPUUsage performance counter
363          * which is similar.
364          */
365         filebuf = (char *) realloc (filebuf, bufalloc = 16);
366         filesize = __small_sprintf (filebuf, "%u.%02u %u.%02u %u.%02u\n",
367                                     0, 0, 0, 0, 0, 0);
368         break;
369       }
370     case PROC_MEMINFO:
371       {
372         filebuf = (char *) realloc (filebuf, bufalloc = 2048);
373         filesize = format_proc_meminfo (filebuf, bufalloc);
374         break;
375       }
376     case PROC_CPUINFO:
377       {
378         filebuf = (char *) realloc (filebuf, bufalloc = 16384);
379         filesize = format_proc_cpuinfo (filebuf, bufalloc);
380         break;
381       }
382     case PROC_PARTITIONS:
383       {
384         filebuf = (char *) realloc (filebuf, bufalloc = 4096);
385         filesize = format_proc_partitions (filebuf, bufalloc);
386         break;
387       }
388     case PROC_SELF:
389       {
390         filebuf = (char *) realloc (filebuf, bufalloc = 32);
391         filesize = __small_sprintf (filebuf, "%d", getpid ());
392       }
393     }
394     return true;
395 }
396
397 static _off64_t
398 format_proc_meminfo (char *destbuf, size_t maxsize)
399 {
400   unsigned long mem_total = 0UL, mem_free = 0UL, swap_total = 0UL,
401                 swap_free = 0UL;
402   MEMORYSTATUS memory_status;
403   GlobalMemoryStatus (&memory_status);
404   mem_total = memory_status.dwTotalPhys;
405   mem_free = memory_status.dwAvailPhys;
406   PSYSTEM_PAGEFILE_INFORMATION spi = NULL;
407   ULONG size = 512;
408   NTSTATUS ret = STATUS_SUCCESS;
409   spi = (PSYSTEM_PAGEFILE_INFORMATION) malloc (size);
410   if (spi)
411     {
412       ret = NtQuerySystemInformation (SystemPagefileInformation, (PVOID) spi,
413                                       size, &size);
414       if (ret == STATUS_INFO_LENGTH_MISMATCH)
415         {
416           free (spi);
417           spi = (PSYSTEM_PAGEFILE_INFORMATION) malloc (size);
418           if (spi)
419             ret = NtQuerySystemInformation (SystemPagefileInformation,
420                                             (PVOID) spi, size, &size);
421         }
422     }
423   if (!spi || ret || (!ret && GetLastError () == ERROR_PROC_NOT_FOUND))
424     {
425       swap_total = memory_status.dwTotalPageFile - mem_total;
426       swap_free = memory_status.dwAvailPageFile - mem_total;
427     }
428   else
429     {
430       PSYSTEM_PAGEFILE_INFORMATION spp = spi;
431       do
432         {
433           swap_total += spp->CurrentSize * getpagesize ();
434           swap_free += (spp->CurrentSize - spp->TotalUsed) * getpagesize ();
435         }
436       while (spp->NextEntryOffset
437              && (spp = (PSYSTEM_PAGEFILE_INFORMATION)
438                            ((char *) spp + spp->NextEntryOffset)));
439     }
440   if (spi)
441     free (spi);
442   return __small_sprintf (destbuf, "         total:      used:      free:\n"
443                                    "Mem:  %10lu %10lu %10lu\n"
444                                    "Swap: %10lu %10lu %10lu\n"
445                                    "MemTotal:     %10lu kB\n"
446                                    "MemFree:      %10lu kB\n"
447                                    "MemShared:             0 kB\n"
448                                    "HighTotal:             0 kB\n"
449                                    "HighFree:              0 kB\n"
450                                    "LowTotal:     %10lu kB\n"
451                                    "LowFree:      %10lu kB\n"
452                                    "SwapTotal:    %10lu kB\n"
453                                    "SwapFree:     %10lu kB\n",
454                                    mem_total, mem_total - mem_free, mem_free,
455                                    swap_total, swap_total - swap_free, swap_free,
456                                    mem_total >> 10, mem_free >> 10,
457                                    mem_total >> 10, mem_free >> 10,
458                                    swap_total >> 10, swap_free >> 10);
459 }
460
461 static _off64_t
462 format_proc_uptime (char *destbuf, size_t maxsize)
463 {
464   unsigned long long uptime = 0ULL, idle_time = 0ULL;
465   SYSTEM_PROCESSOR_TIMES spt;
466
467   if (!GetSystemTimes ((FILETIME *) &spt.IdleTime, (FILETIME *) &spt.KernelTime,
468                        (FILETIME *) &spt.UserTime)
469       && GetLastError () == ERROR_PROC_NOT_FOUND)
470     {
471       NTSTATUS ret = NtQuerySystemInformation (SystemProcessorTimes, (PVOID) &spt,
472                                                sizeof spt, NULL);
473       if (!ret && GetLastError () == ERROR_PROC_NOT_FOUND)
474         {
475           uptime = GetTickCount () / 10;
476           goto out;
477         }
478       else if (ret != STATUS_SUCCESS)
479         {
480           __seterrno_from_nt_status (ret);
481           debug_printf("NtQuerySystemInformation: ret %d, Dos(ret) %E", ret);
482           return 0;
483         }
484     }
485   idle_time = spt.IdleTime.QuadPart / 100000ULL;
486   uptime = (spt.KernelTime.QuadPart +
487             spt.UserTime.QuadPart) / 100000ULL;
488 out:
489
490   return __small_sprintf (destbuf, "%U.%02u %U.%02u\n",
491                           uptime / 100, long (uptime % 100),
492                           idle_time / 100, long (idle_time % 100));
493 }
494
495 static _off64_t
496 format_proc_stat (char *destbuf, size_t maxsize)
497 {
498   unsigned long pages_in = 0UL, pages_out = 0UL, interrupt_count = 0UL,
499                 context_switches = 0UL, swap_in = 0UL, swap_out = 0UL;
500   time_t boot_time = 0;
501
502   char *eobuf = destbuf;
503   if (!wincap.is_winnt ())
504     eobuf += __small_sprintf (destbuf, "cpu %U %U %U %U\n", 0ULL, 0ULL, 0ULL, 0ULL);
505   else
506     {
507       NTSTATUS ret;
508       SYSTEM_PERFORMANCE_INFORMATION spi;
509       SYSTEM_TIME_OF_DAY_INFORMATION stodi;
510
511       SYSTEM_BASIC_INFORMATION sbi;
512       if ((ret = NtQuerySystemInformation (SystemBasicInformation,
513                                            (PVOID) &sbi, sizeof sbi, NULL))
514           != STATUS_SUCCESS)
515         {
516           __seterrno_from_nt_status (ret);
517           debug_printf ("NtQuerySystemInformation: ret %d, Dos(ret) %E", ret);
518           sbi.NumberProcessors = 1;
519         }
520
521       SYSTEM_PROCESSOR_TIMES spt[sbi.NumberProcessors];
522       ret = NtQuerySystemInformation (SystemProcessorTimes, (PVOID) spt,
523                                       sizeof spt[0] * sbi.NumberProcessors, NULL);
524       interrupt_count = 0;
525       if (ret == STATUS_SUCCESS)
526         {
527           unsigned long long user_time = 0ULL, kernel_time = 0ULL, idle_time = 0ULL;
528           for (int i = 0; i < sbi.NumberProcessors; i++)
529             {
530               kernel_time += (spt[i].KernelTime.QuadPart - spt[i].IdleTime.QuadPart) * HZ / 10000000ULL;
531               user_time += spt[i].UserTime.QuadPart * HZ / 10000000ULL;
532               idle_time += spt[i].IdleTime.QuadPart * HZ / 10000000ULL;
533             }
534
535           eobuf += __small_sprintf (eobuf, "cpu %U %U %U %U\n",
536                                     user_time, 0ULL, kernel_time, idle_time);
537           user_time = 0ULL, kernel_time = 0ULL, idle_time = 0ULL;
538           for (int i = 0; i < sbi.NumberProcessors; i++)
539             {
540               interrupt_count += spt[i].InterruptCount;
541               kernel_time = (spt[i].KernelTime.QuadPart - spt[i].IdleTime.QuadPart) * HZ / 10000000ULL;
542               user_time = spt[i].UserTime.QuadPart * HZ / 10000000ULL;
543               idle_time = spt[i].IdleTime.QuadPart * HZ / 10000000ULL;
544               eobuf += __small_sprintf (eobuf, "cpu%d %U %U %U %U\n", i,
545                                         user_time, 0ULL, kernel_time, idle_time);
546             }
547
548           ret = NtQuerySystemInformation (SystemPerformanceInformation,
549                                           (PVOID) &spi, sizeof spi, NULL);
550         }
551       if (ret == STATUS_SUCCESS)
552         ret = NtQuerySystemInformation (SystemTimeOfDayInformation,
553                                         (PVOID) &stodi,
554                                         sizeof stodi, NULL);
555       if (ret != STATUS_SUCCESS)
556         {
557           __seterrno_from_nt_status (ret);
558           debug_printf("NtQuerySystemInformation: ret %d, Dos(ret) %E", ret);
559           return 0;
560         }
561       pages_in = spi.PagesRead;
562       pages_out = spi.PagefilePagesWritten + spi.MappedFilePagesWritten;
563       /*
564        * Note: there is no distinction made in this structure between pages
565        * read from the page file and pages read from mapped files, but there
566        * is such a distinction made when it comes to writing. Goodness knows
567        * why. The value of swap_in, then, will obviously be wrong but its our
568        * best guess.
569        */
570       swap_in = spi.PagesRead;
571       swap_out = spi.PagefilePagesWritten;
572       context_switches = spi.ContextSwitches;
573       boot_time = to_time_t ((FILETIME *) &stodi.BootTime.QuadPart);
574     }
575   /*
576    * else
577    *   {
578    * There are only two relevant performance counters on Windows 95/98/me,
579    * VMM/cPageIns and VMM/cPageOuts. The extra effort needed to read these
580    * counters is by no means worth it.
581    *   }
582    */
583   eobuf += __small_sprintf (eobuf, "page %u %u\n"
584                                    "swap %u %u\n"
585                                    "intr %u\n"
586                                    "ctxt %u\n"
587                                    "btime %u\n",
588                                    pages_in, pages_out,
589                                    swap_in, swap_out,
590                                    interrupt_count,
591                                    context_switches,
592                                    boot_time);
593   return eobuf - destbuf;
594 }
595
596 #define read_value(x,y) \
597       do {\
598         dwCount = BUFSIZE; \
599         if ((dwError = RegQueryValueEx (hKey, x, NULL, &dwType, (BYTE *) szBuffer, &dwCount)), \
600             (dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA)) \
601           { \
602             __seterrno_from_win_error (dwError); \
603             debug_printf ("RegQueryValueEx failed retcode %d", dwError); \
604             return 0; \
605           } \
606         if (dwType != y) \
607           { \
608             debug_printf ("Value %s had an unexpected type (expected %d, found %d)", y, dwType); \
609             return 0; \
610           }\
611       } while (0)
612
613 #define print(x) \
614         do { \
615           strcpy (bufptr, x), \
616           bufptr += sizeof (x) - 1; \
617         } while (0)
618
619 static _off64_t
620 format_proc_cpuinfo (char *destbuf, size_t maxsize)
621 {
622   SYSTEM_INFO siSystemInfo;
623   HKEY hKey;
624   DWORD dwError, dwCount, dwType;
625   DWORD dwOldThreadAffinityMask;
626   int cpu_number;
627   const int BUFSIZE = 256;
628   CHAR szBuffer[BUFSIZE];
629   char *bufptr = destbuf;
630
631   GetSystemInfo (&siSystemInfo);
632
633   for (cpu_number = 0;;cpu_number++)
634     {
635       __small_sprintf (szBuffer, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d", cpu_number);
636
637       if ((dwError = RegOpenKeyEx (HKEY_LOCAL_MACHINE, szBuffer, 0, KEY_QUERY_VALUE, &hKey)) != ERROR_SUCCESS)
638         {
639           if (dwError == ERROR_FILE_NOT_FOUND)
640             break;
641           __seterrno_from_win_error (dwError);
642           debug_printf ("RegOpenKeyEx failed retcode %d", dwError);
643           return 0;
644         }
645
646       dwOldThreadAffinityMask = SetThreadAffinityMask (GetCurrentThread (), 1 << cpu_number);
647       if (dwOldThreadAffinityMask == 0)
648         debug_printf ("SetThreadAffinityMask failed %E");
649       // I'm not sure whether the thread changes processor immediately
650       // and I'm not sure whether this function will cause the thread to be rescheduled
651       low_priority_sleep (0);
652
653       bool has_cpuid = false;
654
655       if (!can_set_flag (0x00040000))
656         debug_printf ("386 processor - no cpuid");
657       else
658         {
659           debug_printf ("486 processor");
660           if (can_set_flag (0x00200000))
661             {
662               debug_printf ("processor supports CPUID instruction");
663               has_cpuid = true;
664             }
665           else
666             debug_printf ("processor does not support CPUID instruction");
667         }
668
669
670       if (!has_cpuid)
671         {
672           bufptr += __small_sprintf (bufptr, "processor       : %d\n", cpu_number);
673           read_value ("VendorIdentifier", REG_SZ);
674           bufptr += __small_sprintf (bufptr, "vendor_id       : %s\n", szBuffer);
675           read_value ("Identifier", REG_SZ);
676           bufptr += __small_sprintf (bufptr, "identifier      : %s\n", szBuffer);
677           if (wincap.is_winnt ())
678             {
679               read_value ("~Mhz", REG_DWORD);
680               bufptr += __small_sprintf (bufptr, "cpu MHz         : %u\n", *(DWORD *) szBuffer);
681
682               print ("flags           :");
683               if (IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE))
684                 print (" 3dnow");
685               if (IsProcessorFeaturePresent (PF_COMPARE_EXCHANGE_DOUBLE))
686                 print (" cx8");
687               if (!IsProcessorFeaturePresent (PF_FLOATING_POINT_EMULATED))
688                 print (" fpu");
689               if (IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE))
690                 print (" mmx");
691               if (IsProcessorFeaturePresent (PF_PAE_ENABLED))
692                 print (" pae");
693               if (IsProcessorFeaturePresent (PF_RDTSC_INSTRUCTION_AVAILABLE))
694                 print (" tsc");
695               if (IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE))
696                 print (" sse");
697               if (IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE))
698                 print (" sse2");
699             }
700         }
701       else
702         {
703           bufptr += __small_sprintf (bufptr, "processor       : %d\n", cpu_number);
704           unsigned maxf, vendor_id[4], unused;
705           cpuid (&maxf, &vendor_id[0], &vendor_id[2], &vendor_id[1], 0);
706           maxf &= 0xffff;
707           vendor_id[3] = 0;
708
709           // vendor identification
710           bool is_amd = false, is_intel = false;
711           if (!strcmp ((char*)vendor_id, "AuthenticAMD"))
712             is_amd = true;
713           else if (!strcmp ((char*)vendor_id, "GenuineIntel"))
714             is_intel = true;
715
716           bufptr += __small_sprintf (bufptr, "vendor_id       : %s\n", (char *)vendor_id);
717           unsigned cpu_mhz  = 0;
718           if (wincap.is_winnt ())
719             {
720               read_value ("~Mhz", REG_DWORD);
721               cpu_mhz = *(DWORD *)szBuffer;
722             }
723           if (maxf >= 1)
724             {
725               unsigned features2, features1, extra_info, cpuid_sig;
726               cpuid (&cpuid_sig, &extra_info, &features2, &features1, 1);
727               /* unsigned extended_family = (cpuid_sig & 0x0ff00000) >> 20,
728                           extended_model  = (cpuid_sig & 0x000f0000) >> 16; */
729               unsigned type             = (cpuid_sig & 0x00003000) >> 12,
730                        family           = (cpuid_sig & 0x00000f00) >> 8,
731                        model            = (cpuid_sig & 0x000000f0) >> 4,
732                        stepping         = cpuid_sig & 0x0000000f;
733               unsigned brand_id         = extra_info & 0x0000000f,
734                        cpu_count        = (extra_info & 0x00ff0000) >> 16,
735                        apic_id          = (extra_info & 0xff000000) >> 24;
736               const char *type_str;
737               switch (type)
738                 {
739                 case 0:
740                   type_str = "primary processor";
741                   break;
742                 case 1:
743                   type_str = "overdrive processor";
744                   break;
745                 case 2:
746                   type_str = "secondary processor";
747                   break;
748                 case 3:
749                 default:
750                   type_str = "reserved";
751                   break;
752                 }
753               unsigned maxe = 0;
754               cpuid (&maxe, &unused, &unused, &unused, 0x80000000);
755               if (maxe >= 0x80000004)
756                 {
757                   unsigned *model_name = (unsigned *) szBuffer;
758                   cpuid (&model_name[0], &model_name[1], &model_name[2], &model_name[3], 0x80000002);
759                   cpuid (&model_name[4], &model_name[5], &model_name[6], &model_name[7], 0x80000003);
760                   cpuid (&model_name[8], &model_name[9], &model_name[10], &model_name[11], 0x80000004);
761                   model_name[12] = 0;
762                 }
763               else
764                 {
765                   // could implement a lookup table here if someone needs it
766                   strcpy (szBuffer, "unknown");
767                 }
768               if (wincap.is_winnt ())
769                 {
770                   bufptr += __small_sprintf (bufptr, "type            : %s\n"
771                                                      "cpu family      : %d\n"
772                                                      "model           : %d\n"
773                                                      "model name      : %s\n"
774                                                      "stepping        : %d\n"
775                                                      "brand id        : %d\n"
776                                                      "cpu count       : %d\n"
777                                                      "apic id         : %d\n"
778                                                      "cpu MHz         : %d\n"
779                                                      "fpu             : %s\n",
780                                              type_str,
781                                              family,
782                                              model,
783                                              szBuffer,
784                                              stepping,
785                                              brand_id,
786                                              cpu_count,
787                                              apic_id,
788                                              cpu_mhz,
789                                              (features1 & (1 << 0)) ? "yes" : "no");
790                 }
791               else
792                 {
793                   bufptr += __small_sprintf (bufptr, "type            : %s\n"
794                                                      "cpu family      : %d\n"
795                                                      "model           : %d\n"
796                                                      "model name      : %s\n"
797                                                      "stepping        : %d\n"
798                                                      "brand id        : %d\n"
799                                                      "cpu count       : %d\n"
800                                                      "apic id         : %d\n"
801                                                      "fpu             : %s\n",
802                                              type_str,
803                                              family,
804                                              model,
805                                              szBuffer,
806                                              stepping,
807                                              brand_id,
808                                              cpu_count,
809                                              apic_id,
810                                              (features1 & (1 << 0)) ? "yes" : "no");
811                 }
812               print ("flags           :");
813               if (features1 & (1 << 0))
814                 print (" fpu");
815               if (features1 & (1 << 1))
816                 print (" vme");
817               if (features1 & (1 << 2))
818                 print (" de");
819               if (features1 & (1 << 3))
820                 print (" pse");
821               if (features1 & (1 << 4))
822                 print (" tsc");
823               if (features1 & (1 << 5))
824                 print (" msr");
825               if (features1 & (1 << 6))
826                 print (" pae");
827               if (features1 & (1 << 7))
828                 print (" mce");
829               if (features1 & (1 << 8))
830                 print (" cx8");
831               if (features1 & (1 << 9))
832                 print (" apic");
833               if (features1 & (1 << 11))
834                 print (" sep");
835               if (features1 & (1 << 12))
836                 print (" mtrr");
837               if (features1 & (1 << 13))
838                 print (" pge");
839               if (features1 & (1 << 14))
840                 print (" mca");
841               if (features1 & (1 << 15))
842                 print (" cmov");
843               if (features1 & (1 << 16))
844                 print (" pat");
845               if (features1 & (1 << 17))
846                 print (" pse36");
847               if (features1 & (1 << 18))
848                 print (" psn");
849               if (features1 & (1 << 19))
850                 print (" clfl");
851               if (is_intel && features1 & (1 << 21))
852                 print (" dtes");
853               if (is_intel && features1 & (1 << 22))
854                 print (" acpi");
855               if (features1 & (1 << 23))
856                 print (" mmx");
857               if (features1 & (1 << 24))
858                 print (" fxsr");
859               if (features1 & (1 << 25))
860                 print (" sse");
861               if (is_intel)
862                 {
863                   if (features1 & (1 << 26))
864                     print (" sse2");
865                   if (features1 & (1 << 27))
866                     print (" ss");
867                   if (features1 & (1 << 28))
868                     print (" htt");
869                   if (features1 & (1 << 29))
870                     print (" tmi");
871                   if (features1 & (1 << 30))
872                     print (" ia-64");
873                   if (features1 & (1 << 31))
874                     print (" pbe");
875
876                   if (features2 & (1 << 0))
877                     print (" pni");
878                   if (features2 & (1 << 3))
879                     print (" monitor");
880                   if (features2 & (1 << 4))
881                     print (" ds_cpl");
882                   if (features2 & (1 << 7))
883                     print (" tm2");
884                   if (features2 & (1 << 8))
885                     print (" est");
886                  if (features2 & (1 << 10))
887                     print (" cid");
888                 }
889
890               if (is_amd && maxe >= 0x80000001)
891                 {
892                   // uses AMD extended calls to check
893                   // for 3dnow and 3dnow extended support
894                   // (source: AMD Athlon Processor Recognition Application Note)
895
896                   if (maxe >= 0x80000001)  // has basic capabilities
897                     {
898                       cpuid (&unused, &unused, &unused, &features2, 0x80000001);
899
900                       if (features2 & (1 << 11))
901                         print (" syscall");
902                       if (features2 & (1 << 19))
903                         print (" mp");
904                       if (features2 & (1 << 22))
905                         print (" mmxext");
906                       if (features2 & (1 << 29))
907                         print (" lm");
908                       if (features2 & (1 << 30)) // 31th bit is on
909                         print (" 3dnowext");
910                       if (features2 & (1 << 31)) // 32th bit (highest) is on
911                         print (" 3dnow");
912                     }
913                 }
914             }
915           else if (wincap.is_winnt ())
916             {
917               bufptr += __small_sprintf (bufptr, "cpu MHz         : %d\n"
918                                                  "fpu             : %s\n",
919                                                  cpu_mhz,
920                                                  IsProcessorFeaturePresent (PF_FLOATING_POINT_EMULATED) ? "no" : "yes");
921             }
922         }
923       if (dwOldThreadAffinityMask != 0)
924         SetThreadAffinityMask (GetCurrentThread (), dwOldThreadAffinityMask);
925
926       RegCloseKey (hKey);
927       bufptr += __small_sprintf (bufptr, "\n");
928   }
929
930   return bufptr - destbuf;
931 }
932
933 #undef read_value
934
935 static _off64_t
936 format_proc_partitions (char *destbuf, size_t maxsize)
937 {
938   char *bufptr = destbuf;
939   print ("major minor  #blocks  name\n\n");
940
941   if (wincap.is_winnt ())
942     {
943       for (int drive_number=0;;drive_number++)
944         {
945           CHAR szDriveName[CYG_MAX_PATH];
946           __small_sprintf (szDriveName, "\\\\.\\PHYSICALDRIVE%d", drive_number);
947           HANDLE hDevice;
948           hDevice = CreateFile (szDriveName,
949                                 GENERIC_READ,
950                                 FILE_SHARE_READ | FILE_SHARE_WRITE,
951                                 NULL,
952                                 OPEN_EXISTING,
953                                 0,
954                                 NULL);
955           if (hDevice == INVALID_HANDLE_VALUE)
956             {
957               if (GetLastError () == ERROR_PATH_NOT_FOUND)
958                   break;
959               __seterrno ();
960               debug_printf ("CreateFile %d %E", GetLastError ());
961               break;
962             }
963           else
964             {
965               DWORD dwBytesReturned, dwRetCode;
966               DISK_GEOMETRY dg;
967               dwRetCode = DeviceIoControl (hDevice,
968                                            IOCTL_DISK_GET_DRIVE_GEOMETRY,
969                                            NULL,
970                                            0,
971                                            &dg,
972                                            sizeof (dg),
973                                            &dwBytesReturned,
974                                            NULL);
975               if (!dwRetCode)
976                 debug_printf ("DeviceIoControl %E");
977               else
978                 {
979                   device dev;
980                   dev.parsedisk (drive_number, 0);
981                   bufptr += __small_sprintf (bufptr, "%5d %5d %9U %s\n",
982                                              dev.major,
983                                              dev.minor,
984                                              (long long)((dg.Cylinders.QuadPart * dg.TracksPerCylinder *
985                                               dg.SectorsPerTrack * dg.BytesPerSector) >> 10),
986                                              dev.name + 5);
987                 }
988               size_t buf_size = 8192;
989               DWORD rc;
990               while (1)
991                 {
992                   char buf[buf_size];
993                   memset (buf, 0, buf_size);
994                   rc = DeviceIoControl (hDevice, IOCTL_DISK_GET_DRIVE_LAYOUT,
995                                         NULL, 0, (DRIVE_LAYOUT_INFORMATION *) buf,
996                                         buf_size, &dwBytesReturned, NULL);
997                   if (rc)
998                     /* fall through */;
999                   else if (GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1000                     {
1001                       buf_size *= 2;
1002                       continue;
1003                     }
1004                   else
1005                     {
1006                       debug_printf ("DeviceIoControl %E");
1007                       break;
1008                     }
1009                   DRIVE_LAYOUT_INFORMATION *dli = (DRIVE_LAYOUT_INFORMATION *) buf;
1010                   for (unsigned partition = 0; partition < dli->PartitionCount; partition++)
1011                     {
1012                       if (!dli->PartitionEntry[partition].PartitionLength.QuadPart
1013                           || !dli->PartitionEntry[partition].RecognizedPartition)
1014                         continue;
1015                       device dev;
1016                       dev.parsedisk (drive_number, dli->PartitionEntry[partition].PartitionNumber);
1017                       bufptr += __small_sprintf (bufptr, "%5d %5d %9U %s\n",
1018                                                  dev.major, dev.minor,
1019                                                  (long long)(dli->PartitionEntry[partition].PartitionLength.QuadPart >> 10),
1020                                                  dev.name + 5);
1021                     }
1022                   break;
1023                 }
1024               CloseHandle (hDevice);
1025             }
1026         }
1027     }
1028   else
1029     {
1030       // not worth the effort
1031       // you need a 16 bit thunk DLL to access the partition table on Win9x
1032       // and then you have to decode it yourself
1033     }
1034   return bufptr - destbuf;
1035 }
1036
1037 #undef print