]> granicus.if.org Git - imagemagick/blob - MagickCore/nt-base.c
cleanup identical conditions (#1339)
[imagemagick] / MagickCore / nt-base.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                                 N   N  TTTTT                                %
7 %                                 NN  N    T                                  %
8 %                                 N N N    T                                  %
9 %                                 N  NN    T                                  %
10 %                                 N   N    T                                  %
11 %                                                                             %
12 %                                                                             %
13 %                   Windows NT Utility Methods for MagickCore                 %
14 %                                                                             %
15 %                               Software Design                               %
16 %                                    Cristy                                   %
17 %                                December 1996                                %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    https://imagemagick.org/script/license.php                               %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 /*
39   Include declarations.
40 */
41 #include "MagickCore/studio.h"
42 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
43 #include "MagickCore/client.h"
44 #include "MagickCore/exception-private.h"
45 #include "MagickCore/locale_.h"
46 #include "MagickCore/log.h"
47 #include "MagickCore/magick.h"
48 #include "MagickCore/memory_.h"
49 #include "MagickCore/memory-private.h"
50 #include "MagickCore/nt-base.h"
51 #include "MagickCore/nt-base-private.h"
52 #include "MagickCore/resource_.h"
53 #include "MagickCore/resource-private.h"
54 #include "MagickCore/timer.h"
55 #include "MagickCore/string_.h"
56 #include "MagickCore/string-private.h"
57 #include "MagickCore/utility.h"
58 #include "MagickCore/utility-private.h"
59 #include "MagickCore/version.h"
60 #if defined(MAGICKCORE_LTDL_DELEGATE)
61 #  include "ltdl.h"
62 #endif
63 #if defined(MAGICKCORE_CIPHER_SUPPORT)
64 #include <ntsecapi.h>
65 #include <wincrypt.h>
66 #endif
67 \f
68 /*
69   Define declarations.
70 */
71 #if !defined(MAP_FAILED)
72 #define MAP_FAILED      ((void *)(LONG_PTR)-1)
73 #endif
74
75 /*
76   Typdef declarations.
77 */
78
79 /*
80   We need to make sure only one instance is created for each process and that
81   is why we wrap the new/delete instance methods.
82
83   From: http://www.ghostscript.com/doc/current/API.htm
84   "The Win32 DLL gsdll32.dll can be used by multiple programs simultaneously,
85    but only once within each process"
86 */
87 typedef struct _NTGhostInfo
88 {
89   void
90     (MagickDLLCall *delete_instance)(gs_main_instance *);
91
92   int
93     (MagickDLLCall *new_instance)(gs_main_instance **,void *);
94
95   MagickBooleanType
96     has_instance;
97 } NTGhostInfo;
98 \f
99 /*
100   Static declarations.
101 */
102 #if !defined(MAGICKCORE_LTDL_DELEGATE)
103 static char
104   *lt_slsearchpath = (char *) NULL;
105 #endif
106
107 static NTGhostInfo
108   nt_ghost_info;
109
110 static GhostInfo
111   ghost_info;
112
113 static void
114   *ghost_handle = (void *) NULL;
115
116 static SemaphoreInfo
117   *ghost_semaphore = (SemaphoreInfo *) NULL,
118   *winsock_semaphore = (SemaphoreInfo *) NULL;
119
120 static WSADATA
121   *wsaData = (WSADATA*) NULL;
122 \f
123 struct
124 {
125   const HKEY
126     hkey;
127
128   const char
129     *name;
130 }
131 const registry_roots[2] =
132 {
133   { HKEY_CURRENT_USER,  "HKEY_CURRENT_USER"  },
134   { HKEY_LOCAL_MACHINE, "HKEY_LOCAL_MACHINE" }
135 };
136
137 /*
138   External declarations.
139 */
140 #if !defined(MAGICKCORE_WINDOWS_SUPPORT)
141 extern "C" BOOL WINAPI
142   DllMain(HINSTANCE handle,DWORD reason,LPVOID lpvReserved);
143 #endif
144
145 static void MagickDLLCall NTGhostscriptDeleteInstance(
146   gs_main_instance *instance)
147 {
148   LockSemaphoreInfo(ghost_semaphore);
149   nt_ghost_info.delete_instance(instance);
150   nt_ghost_info.has_instance=MagickFalse;
151   UnlockSemaphoreInfo(ghost_semaphore);
152 }
153
154 static int MagickDLLCall NTGhostscriptNewInstance(gs_main_instance **pinstance,
155   void *caller_handle)
156 {
157   int
158     status;
159
160   LockSemaphoreInfo(ghost_semaphore);
161   status=-1;
162   if (nt_ghost_info.has_instance == MagickFalse)
163     {
164       status=nt_ghost_info.new_instance(pinstance,caller_handle);
165       if (status >= 0)
166         nt_ghost_info.has_instance=MagickTrue;
167     }
168   UnlockSemaphoreInfo(ghost_semaphore);
169   return(status);
170 }
171
172 static inline char *create_utf8_string(const wchar_t *wideChar)
173 {
174   char
175     *utf8;
176
177   int
178     count;
179
180   count=WideCharToMultiByte(CP_UTF8,0,wideChar,-1,NULL,0,NULL,NULL);
181   if (count < 0)
182     return((char *) NULL);
183   utf8=(char *) AcquireQuantumMemory(count+1,sizeof(*utf8));
184   if (utf8 == (char *) NULL)
185     return((char *) NULL);
186   count=WideCharToMultiByte(CP_UTF8,0,wideChar,-1,utf8,count,NULL,NULL);
187   if (count == 0)
188     {
189       utf8=DestroyString(utf8);
190       return((char *) NULL);
191     }
192   utf8[count]=0;
193   return(utf8);
194 }
195 \f
196 /*
197 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
198 %                                                                             %
199 %                                                                             %
200 %                                                                             %
201 %   D l l M a i n                                                             %
202 %                                                                             %
203 %                                                                             %
204 %                                                                             %
205 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
206 %
207 %  DllMain() is an entry point to the DLL which is called when processes and
208 %  threads are initialized and terminated, or upon calls to the Windows
209 %  LoadLibrary and FreeLibrary functions.
210 %
211 %  The function returns TRUE of it succeeds, or FALSE if initialization fails.
212 %
213 %  The format of the DllMain method is:
214 %
215 %    BOOL WINAPI DllMain(HINSTANCE handle,DWORD reason,LPVOID lpvReserved)
216 %
217 %  A description of each parameter follows:
218 %
219 %    o handle: handle to the DLL module
220 %
221 %    o reason: reason for calling function:
222 %
223 %      DLL_PROCESS_ATTACH - DLL is being loaded into virtual address
224 %                           space of current process.
225 %      DLL_THREAD_ATTACH - Indicates that the current process is
226 %                          creating a new thread.  Called under the
227 %                          context of the new thread.
228 %      DLL_THREAD_DETACH - Indicates that the thread is exiting.
229 %                          Called under the context of the exiting
230 %                          thread.
231 %      DLL_PROCESS_DETACH - Indicates that the DLL is being unloaded
232 %                           from the virtual address space of the
233 %                           current process.
234 %
235 %    o lpvReserved: Used for passing additional info during DLL_PROCESS_ATTACH
236 %                   and DLL_PROCESS_DETACH.
237 %
238 */
239 #if defined(_DLL) && defined(ProvideDllMain)
240 BOOL WINAPI DllMain(HINSTANCE handle,DWORD reason,LPVOID lpvReserved)
241 {
242   switch (reason)
243   {
244     case DLL_PROCESS_ATTACH:
245     {
246       char
247         *module_path;
248
249       ssize_t
250         count;
251
252       wchar_t
253         *wide_path;
254
255       MagickCoreGenesis((const char *) NULL,MagickFalse);
256       wide_path=(wchar_t *) AcquireQuantumMemory(MagickPathExtent,
257         sizeof(*wide_path));
258       if (wide_path == (wchar_t *) NULL)
259         return(FALSE);
260       count=(ssize_t) GetModuleFileNameW(handle,wide_path,MagickPathExtent);
261       if (count != 0)
262         {
263           char
264             *path;
265
266           module_path=create_utf8_string(wide_path);
267           for ( ; count > 0; count--)
268             if (module_path[count] == '\\')
269               {
270                 module_path[count+1]='\0';
271                 break;
272               }
273           path=(char *) AcquireQuantumMemory(16UL*MagickPathExtent,sizeof(*path));
274           if (path == (char *) NULL)
275             {
276               module_path=DestroyString(module_path);
277               wide_path=(wchar_t *) RelinquishMagickMemory(wide_path);
278               return(FALSE);
279             }
280           count=(ssize_t) GetEnvironmentVariable("PATH",path,16*MagickPathExtent);
281           if ((count != 0) && (strstr(path,module_path) == (char *) NULL))
282             {
283               if ((strlen(module_path)+count+1) < (16*MagickPathExtent-1))
284                 {
285                   char
286                     *variable;
287
288                   variable=(char *) AcquireQuantumMemory(16UL*MagickPathExtent,
289                     sizeof(*variable));
290                   if (variable == (char *) NULL)
291                     {
292                       path=DestroyString(path);
293                       module_path=DestroyString(module_path);
294                       wide_path=(wchar_t *) RelinquishMagickMemory(wide_path);
295                       return(FALSE);
296                     }
297                   (void) FormatLocaleString(variable,16*MagickPathExtent,
298                     "%s;%s",module_path,path);
299                   SetEnvironmentVariable("PATH",variable);
300                   variable=DestroyString(variable);
301                 }
302             }
303           path=DestroyString(path);
304           module_path=DestroyString(module_path);
305         }
306       wide_path=(wchar_t *) RelinquishMagickMemory(wide_path);
307       break;
308     }
309     case DLL_PROCESS_DETACH:
310     {
311       MagickCoreTerminus();
312       break;
313     }
314     default:
315       break;
316   }
317   return(TRUE);
318 }
319 #endif
320 \f
321 /*
322 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
323 %                                                                             %
324 %                                                                             %
325 %                                                                             %
326 %   E x i t                                                                   %
327 %                                                                             %
328 %                                                                             %
329 %                                                                             %
330 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
331 %
332 %  Exit() calls TerminateProcess for Win95.
333 %
334 %  The format of the exit method is:
335 %
336 %      int Exit(int status)
337 %
338 %  A description of each parameter follows:
339 %
340 %    o status: an integer value representing the status of the terminating
341 %      process.
342 %
343 */
344 MagickPrivate int Exit(int status)
345 {
346   if (IsWindows95())
347     {
348       TerminateProcess(GetCurrentProcess(),(unsigned int) status);
349       return(0);
350     }
351   exit(status);
352 }
353 \f
354 #if !defined(__MINGW32__)
355 /*
356 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
357 %                                                                             %
358 %                                                                             %
359 %                                                                             %
360 %   g e t t i m e o f d a y                                                   %
361 %                                                                             %
362 %                                                                             %
363 %                                                                             %
364 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
365 %
366 %  The gettimeofday() method get the time of day.
367 %
368 %  The format of the gettimeofday method is:
369 %
370 %      int gettimeofday(struct timeval *time_value,struct timezone *time_zone)
371 %
372 %  A description of each parameter follows:
373 %
374 %    o time_value: the time value.
375 %
376 %    o time_zone: the time zone.
377 %
378 */
379 MagickPrivate int gettimeofday (struct timeval *time_value,
380   struct timezone *time_zone)
381 {
382 #define EpochFiletime  MagickLLConstant(116444736000000000)
383
384   static int
385     is_tz_set;
386
387   if (time_value != (struct timeval *) NULL)
388     {
389       FILETIME
390         file_time;
391
392       __int64
393         time;
394
395       LARGE_INTEGER
396         date_time;
397
398       GetSystemTimeAsFileTime(&file_time);
399       date_time.LowPart=file_time.dwLowDateTime;
400       date_time.HighPart=file_time.dwHighDateTime;
401       time=date_time.QuadPart;
402       time-=EpochFiletime;
403       time/=10;
404       time_value->tv_sec=(ssize_t) (time / 1000000);
405       time_value->tv_usec=(ssize_t) (time % 1000000);
406     }
407   if (time_zone != (struct timezone *) NULL)
408     {
409       if (is_tz_set == 0)
410         {
411           _tzset();
412           is_tz_set++;
413         }
414       time_zone->tz_minuteswest=_timezone/60;
415       time_zone->tz_dsttime=_daylight;
416     }
417   return(0);
418 }
419 #endif
420 \f
421 /*
422 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
423 %                                                                             %
424 %                                                                             %
425 %                                                                             %
426 %   I s W i n d o w s 9 5                                                     %
427 %                                                                             %
428 %                                                                             %
429 %                                                                             %
430 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
431 %
432 %  IsWindows95() returns true if the system is Windows 95.
433 %
434 %  The format of the IsWindows95 method is:
435 %
436 %      int IsWindows95()
437 %
438 */
439 MagickPrivate int IsWindows95()
440 {
441   OSVERSIONINFO
442     version_info;
443
444   version_info.dwOSVersionInfoSize=sizeof(version_info);
445   if (GetVersionEx(&version_info) &&
446       (version_info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS))
447     return(1);
448   return(0);
449 }
450 \f
451 /*
452 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
453 %                                                                             %
454 %                                                                             %
455 %                                                                             %
456 %   N T A r g v T o U T F 8                                                   %
457 %                                                                             %
458 %                                                                             %
459 %                                                                             %
460 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
461 %
462 %  NTArgvToUTF8() converts the wide command line arguments to UTF-8 to ensure
463 %  compatibility with Linux.
464 %
465 %  The format of the NTArgvToUTF8 method is:
466 %
467 %      char **NTArgvToUTF8(const int argc,wchar_t **argv)
468 %
469 %  A description of each parameter follows:
470 %
471 %    o argc: the number of command line arguments.
472 %
473 %    o argv:  the  wide-character command line arguments.
474 %
475 */
476 MagickPrivate char **NTArgvToUTF8(const int argc,wchar_t **argv)
477 {
478   char
479     **utf8;
480
481   ssize_t
482     i;
483
484   utf8=(char **) AcquireQuantumMemory(argc,sizeof(*utf8));
485   if (utf8 == (char **) NULL)
486     ThrowFatalException(ResourceLimitFatalError,"UnableToConvertStringToARGV");
487   for (i=0; i < (ssize_t) argc; i++)
488   {
489     utf8[i]=create_utf8_string(argv[i]);
490     if (utf8[i] == (char *) NULL)
491       {
492         for (i--; i >= 0; i--)
493           utf8[i]=DestroyString(utf8[i]);
494         ThrowFatalException(ResourceLimitFatalError,
495           "UnableToConvertStringToARGV");
496       }
497   }
498   return(utf8);
499 }
500 \f
501 /*
502 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
503 %                                                                             %
504 %                                                                             %
505 %                                                                             %
506 %   N T C l o s e D i r e c t o r y                                           %
507 %                                                                             %
508 %                                                                             %
509 %                                                                             %
510 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
511 %
512 %  NTCloseDirectory() closes the named directory stream and frees the DIR
513 %  structure.
514 %
515 %  The format of the NTCloseDirectory method is:
516 %
517 %      int NTCloseDirectory(DIR *entry)
518 %
519 %  A description of each parameter follows:
520 %
521 %    o entry: Specifies a pointer to a DIR structure.
522 %
523 */
524 MagickPrivate int NTCloseDirectory(DIR *entry)
525 {
526   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
527   assert(entry != (DIR *) NULL);
528   FindClose(entry->hSearch);
529   entry=(DIR *) RelinquishMagickMemory(entry);
530   return(0);
531 }
532 /*
533 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
534 %                                                                             %
535 %                                                                             %
536 %                                                                             %
537 %   N T C l o s e L i b r a r y                                               %
538 %                                                                             %
539 %                                                                             %
540 %                                                                             %
541 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
542 %
543 %  NTCloseLibrary() unloads the module associated with the passed handle.
544 %
545 %  The format of the NTCloseLibrary method is:
546 %
547 %      void NTCloseLibrary(void *handle)
548 %
549 %  A description of each parameter follows:
550 %
551 %    o handle: Specifies a handle to a previously loaded dynamic module.
552 %
553 */
554 MagickPrivate int NTCloseLibrary(void *handle)
555 {
556   if (IsWindows95())
557     return(FreeLibrary((HINSTANCE) handle));
558   return(!(FreeLibrary((HINSTANCE) handle)));
559 }
560 \f
561 /*
562 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
563 %                                                                             %
564 %                                                                             %
565 %                                                                             %
566 %   N T C o n t r o l H a n d l e r                                           %
567 %                                                                             %
568 %                                                                             %
569 %                                                                             %
570 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
571 %
572 %  NTControlHandler() registers a control handler that is activated when, for
573 %  example, a ctrl-c is received.
574 %
575 %  The format of the NTControlHandler method is:
576 %
577 %      int NTControlHandler(void)
578 %
579 */
580
581 static BOOL ControlHandler(DWORD type)
582 {
583   (void) type;
584   AsynchronousResourceComponentTerminus();
585   return(FALSE);
586 }
587
588 MagickPrivate int NTControlHandler(void)
589 {
590   return(SetConsoleCtrlHandler((PHANDLER_ROUTINE) ControlHandler,TRUE));
591 }
592 \f
593 /*
594 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
595 %                                                                             %
596 %                                                                             %
597 %                                                                             %
598 %   N T E l a p s e d T i m e                                                 %
599 %                                                                             %
600 %                                                                             %
601 %                                                                             %
602 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
603 %
604 %  NTElapsedTime() returns the elapsed time (in seconds) since the last call to
605 %  StartTimer().
606 %
607 %  The format of the ElapsedTime method is:
608 %
609 %      double NTElapsedTime(void)
610 %
611 */
612 MagickPrivate double NTElapsedTime(void)
613 {
614   union
615   {
616     FILETIME
617       filetime;
618
619     __int64
620       filetime64;
621   } elapsed_time;
622
623   SYSTEMTIME
624     system_time;
625
626   GetSystemTime(&system_time);
627   SystemTimeToFileTime(&system_time,&elapsed_time.filetime);
628   return((double) 1.0e-7*elapsed_time.filetime64);
629 }
630
631 /*
632 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
633 %                                                                             %
634 %                                                                             %
635 %                                                                             %
636 %   N T E r f                                                                 %
637 %                                                                             %
638 %                                                                             %
639 %                                                                             %
640 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
641 %
642 %  NTErf() computes the error function of x.
643 %
644 %  The format of the NTErf method is:
645 %
646 %      double NTCloseDirectory(DIR *entry)
647 %
648 %  A description of each parameter follows:
649 %
650 %    o x: Specifies a pointer to a DIR structure.
651 %
652 */
653 MagickPrivate double NTErf(double x)
654 {
655   double
656     a1,
657     a2,
658     a3,
659     a4,
660     a5,
661     p,
662     t,
663     y;
664
665   int
666     sign;
667
668   a1=0.254829592;
669   a2=-0.284496736;
670   a3=1.421413741;
671   a4=-1.453152027;
672   a5=1.061405429;
673   p=0.3275911;
674   sign=1;
675   if (x < 0)
676     sign=-1;
677   x=abs(x);
678   t=1.0/(1.0+p*x);
679   y=1.0-(((((a5*t+a4)*t)+a3)*t+a2)*t+a1)*t*exp(-x*x);
680   return(sign*y);
681 }
682 \f
683 \f
684 /*
685 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
686 %                                                                             %
687 %                                                                             %
688 %                                                                             %
689 +   N T E r r o r H a n d l e r                                               %
690 %                                                                             %
691 %                                                                             %
692 %                                                                             %
693 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
694 %
695 %  NTErrorHandler() displays an error reason and then terminates the program.
696 %
697 %  The format of the NTErrorHandler method is:
698 %
699 %      void NTErrorHandler(const ExceptionType severity,const char *reason,
700 %        const char *description)
701 %
702 %  A description of each parameter follows:
703 %
704 %    o severity: Specifies the numeric error category.
705 %
706 %    o reason: Specifies the reason to display before terminating the
707 %      program.
708 %
709 %    o description: Specifies any description to the reason.
710 %
711 */
712 MagickPrivate void NTErrorHandler(const ExceptionType severity,
713   const char *reason,const char *description)
714 {
715   char
716     buffer[3*MagickPathExtent],
717     *message;
718
719   (void) severity;
720   if (reason == (char *) NULL)
721     {
722       MagickCoreTerminus();
723       exit(0);
724     }
725   message=GetExceptionMessage(errno);
726   if ((description != (char *) NULL) && errno)
727     (void) FormatLocaleString(buffer,MagickPathExtent,"%s: %s (%s) [%s].\n",
728       GetClientName(),reason,description,message);
729   else
730     if (description != (char *) NULL)
731       (void) FormatLocaleString(buffer,MagickPathExtent,"%s: %s (%s).\n",
732         GetClientName(),reason,description);
733     else
734       if (errno != 0)
735         (void) FormatLocaleString(buffer,MagickPathExtent,"%s: %s [%s].\n",
736           GetClientName(),reason,message);
737       else
738         (void) FormatLocaleString(buffer,MagickPathExtent,"%s: %s.\n",
739           GetClientName(),reason);
740   message=DestroyString(message);
741   (void) MessageBox(NULL,buffer,"ImageMagick Exception",MB_OK | MB_TASKMODAL |
742     MB_SETFOREGROUND | MB_ICONEXCLAMATION);
743   MagickCoreTerminus();
744   exit(0);
745 }
746 \f
747 /*
748 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
749 %                                                                             %
750 %                                                                             %
751 %                                                                             %
752 %   N T E x i t L i b r a r y                                                 %
753 %                                                                             %
754 %                                                                             %
755 %                                                                             %
756 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
757 %
758 %  NTExitLibrary() exits the dynamic module loading subsystem.
759 %
760 %  The format of the NTExitLibrary method is:
761 %
762 %      int NTExitLibrary(void)
763 %
764 */
765 MagickPrivate int NTExitLibrary(void)
766 {
767   return(0);
768 }
769 \f
770 /*
771 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
772 %                                                                             %
773 %                                                                             %
774 %                                                                             %
775 %   N T G a t h e r R a n d o m D a t a                                       %
776 %                                                                             %
777 %                                                                             %
778 %                                                                             %
779 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
780 %
781 %  NTGatherRandomData() gathers random data and returns it.
782 %
783 %  The format of the GatherRandomData method is:
784 %
785 %      MagickBooleanType NTGatherRandomData(const size_t length,
786 %        unsigned char *random)
787 %
788 %  A description of each parameter follows:
789 %
790 %    length: the length of random data buffer
791 %
792 %    random: the random data is returned here.
793 %
794 */
795 MagickPrivate MagickBooleanType NTGatherRandomData(const size_t length,
796   unsigned char *random)
797 {
798 #if defined(MAGICKCORE_CIPHER_SUPPORT) && defined(_MSC_VER) && (_MSC_VER > 1200)
799   HCRYPTPROV
800     handle;
801
802   int
803     status;
804
805   handle=(HCRYPTPROV) NULL;
806   status=CryptAcquireContext(&handle,NULL,MS_DEF_PROV,PROV_RSA_FULL,
807     (CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET));
808   if (status == 0)
809     status=CryptAcquireContext(&handle,NULL,MS_DEF_PROV,PROV_RSA_FULL,
810       (CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET | CRYPT_NEWKEYSET));
811   if (status == 0)
812     return(MagickFalse);
813   status=CryptGenRandom(handle,(DWORD) length,random);
814   if (status == 0)
815     {
816       status=CryptReleaseContext(handle,0);
817       return(MagickFalse);
818     }
819   status=CryptReleaseContext(handle,0);
820   if (status == 0)
821     return(MagickFalse);
822 #else
823   (void) random;
824   (void) length;
825 #endif
826   return(MagickTrue);
827 }
828 \f
829 /*
830 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
831 %                                                                             %
832 %                                                                             %
833 %                                                                             %
834 %   N T G e t E x e c u t i o n P a t h                                       %
835 %                                                                             %
836 %                                                                             %
837 %                                                                             %
838 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
839 %
840 %  NTGetExecutionPath() returns the execution path of a program.
841 %
842 %  The format of the GetExecutionPath method is:
843 %
844 %      MagickBooleanType NTGetExecutionPath(char *path,const size_t extent)
845 %
846 %  A description of each parameter follows:
847 %
848 %    o path: the pathname of the executable that started the process.
849 %
850 %    o extent: the maximum extent of the path.
851 %
852 */
853 MagickPrivate MagickBooleanType NTGetExecutionPath(char *path,
854   const size_t extent)
855 {
856   wchar_t
857     wide_path[MagickPathExtent];
858
859   (void) GetModuleFileNameW((HMODULE) NULL,wide_path,(DWORD) extent);
860   (void) WideCharToMultiByte(CP_UTF8,0,wide_path,-1,path,(int) extent,NULL,
861     NULL);
862   return(MagickTrue);
863 }
864 \f
865 /*
866 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
867 %                                                                             %
868 %                                                                             %
869 %                                                                             %
870 %   N T G e t L a s t E r r o r                                               %
871 %                                                                             %
872 %                                                                             %
873 %                                                                             %
874 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
875 %
876 %  NTGetLastError() returns the last error that occurred.
877 %
878 %  The format of the NTGetLastError method is:
879 %
880 %      char *NTGetLastError(void)
881 %
882 */
883 char *NTGetLastError(void)
884 {
885   char
886     *reason;
887
888   int
889     status;
890
891   LPVOID
892     buffer;
893
894   status=FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
895     FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),
896     MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR) &buffer,0,NULL);
897   if (!status)
898     reason=AcquireString("An unknown error occurred");
899   else
900     {
901       reason=AcquireString((const char *) buffer);
902       LocalFree(buffer);
903     }
904   return(reason);
905 }
906 \f
907 /*
908 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
909 %                                                                             %
910 %                                                                             %
911 %                                                                             %
912 %   N T G e t L i b r a r y E r r o r                                         %
913 %                                                                             %
914 %                                                                             %
915 %                                                                             %
916 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
917 %
918 %  Lt_dlerror() returns a pointer to a string describing the last error
919 %  associated with a lt_dl method.  Note that this function is not thread
920 %  safe so it should only be used under the protection of a lock.
921 %
922 %  The format of the NTGetLibraryError method is:
923 %
924 %      const char *NTGetLibraryError(void)
925 %
926 */
927 MagickPrivate const char *NTGetLibraryError(void)
928 {
929   static char
930     last_error[MagickPathExtent];
931
932   char
933     *error;
934
935   *last_error='\0';
936   error=NTGetLastError();
937   if (error)
938     (void) CopyMagickString(last_error,error,MagickPathExtent);
939   error=DestroyString(error);
940   return(last_error);
941 }
942 \f
943 /*
944 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
945 %                                                                             %
946 %                                                                             %
947 %                                                                             %
948 %   N T G e t L i b r a r y S y m b o l                                       %
949 %                                                                             %
950 %                                                                             %
951 %                                                                             %
952 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
953 %
954 %  NTGetLibrarySymbol() retrieve the procedure address of the method
955 %  specified by the passed character string.
956 %
957 %  The format of the NTGetLibrarySymbol method is:
958 %
959 %      void *NTGetLibrarySymbol(void *handle,const char *name)
960 %
961 %  A description of each parameter follows:
962 %
963 %    o handle: Specifies a handle to the previously loaded dynamic module.
964 %
965 %    o name: Specifies the procedure entry point to be returned.
966 %
967 */
968 void *NTGetLibrarySymbol(void *handle,const char *name)
969 {
970   LPFNDLLFUNC1
971     lpfnDllFunc1;
972
973   lpfnDllFunc1=(LPFNDLLFUNC1) GetProcAddress((HINSTANCE) handle,name);
974   if (!lpfnDllFunc1)
975     return((void *) NULL);
976   return((void *) lpfnDllFunc1);
977 }
978 \f
979 /*
980 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
981 %                                                                             %
982 %                                                                             %
983 %                                                                             %
984 %   N T G e t M o d u l e P a t h                                             %
985 %                                                                             %
986 %                                                                             %
987 %                                                                             %
988 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
989 %
990 %  NTGetModulePath() returns the path of the specified module.
991 %
992 %  The format of the GetModulePath method is:
993 %
994 %      MagickBooleanType NTGetModulePath(const char *module,char *path)
995 %
996 %  A description of each parameter follows:
997 %
998 %    modith: the module name.
999 %
1000 %    path: the module path is returned here.
1001 %
1002 */
1003 MagickPrivate MagickBooleanType NTGetModulePath(const char *module,char *path)
1004 {
1005   char
1006     module_path[MagickPathExtent];
1007
1008   HMODULE
1009     handle;
1010
1011   ssize_t
1012     length;
1013
1014   *path='\0';
1015   handle=GetModuleHandle(module);
1016   if (handle == (HMODULE) NULL)
1017     return(MagickFalse);
1018   length=GetModuleFileName(handle,module_path,MagickPathExtent);
1019   if (length != 0)
1020     GetPathComponent(module_path,HeadPath,path);
1021   return(MagickTrue);
1022 }
1023 \f
1024 /*
1025 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1026 %                                                                             %
1027 %                                                                             %
1028 %                                                                             %
1029 +    N T G e t P a g e S i z e                                                %
1030 %                                                                             %
1031 %                                                                             %
1032 %                                                                             %
1033 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1034 %
1035 %  NTGetPageSize() returns the memory page size under Windows.
1036 %
1037 %  The format of the NTPageSize
1038 %
1039 %      NTPageSize()
1040 %
1041 */
1042 MagickPrivate ssize_t NTGetPageSize(void)
1043 {
1044   SYSTEM_INFO
1045     system_info;
1046
1047    GetSystemInfo(&system_info);
1048    return((ssize_t) system_info.dwPageSize);
1049 }
1050 \f
1051 /*
1052 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1053 %                                                                             %
1054 %                                                                             %
1055 %                                                                             %
1056 %   N T G h o s t s c r i p t D L L                                           %
1057 %                                                                             %
1058 %                                                                             %
1059 %                                                                             %
1060 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1061 %
1062 %  NTGhostscriptDLL() returns the path to the most recent Ghostscript version
1063 %  DLL.  The method returns TRUE on success otherwise FALSE.
1064 %
1065 %  The format of the NTGhostscriptDLL method is:
1066 %
1067 %      int NTGhostscriptDLL(char *path,int length)
1068 %
1069 %  A description of each parameter follows:
1070 %
1071 %    o path: return the Ghostscript DLL path here.
1072 %
1073 %    o length: the buffer length.
1074 %
1075 */
1076
1077 static int NTGetRegistryValue(HKEY root,const char *key,DWORD flags,
1078   const char *name,char *value,int *length)
1079 {
1080   BYTE
1081     byte,
1082     *p;
1083
1084   DWORD
1085     extent,
1086     type;
1087
1088   HKEY
1089     hkey;
1090
1091   LONG
1092     status;
1093
1094   /*
1095     Get a registry value: key = root\\key, named value = name.
1096   */
1097   if (RegOpenKeyExA(root,key,0,KEY_READ | flags,&hkey) != ERROR_SUCCESS)
1098     return(1);  /* no match */
1099   p=(BYTE *) value;
1100   type=REG_SZ;
1101   extent=(*length);
1102   if (p == (BYTE *) NULL)
1103     p=(&byte);  /* ERROR_MORE_DATA only if value is NULL */
1104   status=RegQueryValueExA(hkey,(char *) name,0,&type,p,&extent);
1105   RegCloseKey(hkey);
1106   if (status == ERROR_SUCCESS)
1107     {
1108       *length=extent;
1109       return(0);  /* return the match */
1110     }
1111   if (status == ERROR_MORE_DATA)
1112     {
1113       *length=extent;
1114       return(-1);  /* buffer not large enough */
1115     }
1116   return(1);  /* not found */
1117 }
1118
1119 static int NTLocateGhostscript(DWORD flags,int *root_index,
1120   const char **product_family,int *major_version,int *minor_version)
1121 {
1122   int
1123     i;
1124
1125   MagickBooleanType
1126     status;
1127
1128   static const char
1129     *products[4] =
1130     {
1131       "GPL Ghostscript",
1132       "GNU Ghostscript",
1133       "AFPL Ghostscript",
1134       "Aladdin Ghostscript"
1135     };
1136
1137   /*
1138     Find the most recent version of Ghostscript.
1139   */
1140   status=MagickFalse;
1141   *root_index=0;
1142   *product_family=NULL;
1143   *major_version=5;
1144   *minor_version=49; /* min version of Ghostscript is 5.50 */
1145   for (i=0; i < (ssize_t) (sizeof(products)/sizeof(products[0])); i++)
1146   {
1147     char
1148       key[MagickPathExtent];
1149
1150     HKEY
1151       hkey;
1152
1153     int
1154       j;
1155
1156     REGSAM
1157       mode;
1158
1159     (void) FormatLocaleString(key,MagickPathExtent,"SOFTWARE\\%s",products[i]);
1160     for (j=0; j < (ssize_t) (sizeof(registry_roots)/sizeof(registry_roots[0]));
1161          j++)
1162     {
1163       mode=KEY_READ | flags;
1164       if (RegOpenKeyExA(registry_roots[j].hkey,key,0,mode,&hkey) ==
1165             ERROR_SUCCESS)
1166         {
1167           DWORD
1168             extent;
1169
1170           int
1171             k;
1172
1173           /*
1174             Now enumerate the keys.
1175           */
1176           extent=sizeof(key)/sizeof(char);
1177           for (k=0; RegEnumKeyA(hkey,k,key,extent) == ERROR_SUCCESS; k++)
1178           {
1179             int
1180               major,
1181               minor;
1182
1183             major=0;
1184             minor=0;
1185             if (sscanf(key,"%d.%d",&major,&minor) != 2)
1186               continue;
1187             if ((major > *major_version) || ((major == *major_version) &&
1188                 (minor > *minor_version)))
1189               {
1190                 *root_index=j;
1191                 *product_family=products[i];
1192                 *major_version=major;
1193                 *minor_version=minor;
1194                 status=MagickTrue;
1195               }
1196          }
1197          (void) RegCloseKey(hkey);
1198        }
1199     }
1200   }
1201   if (status == MagickFalse)
1202     {
1203       *major_version=0;
1204       *minor_version=0;
1205     }
1206   (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),"Ghostscript (%s) "
1207     "version %d.%02d",*product_family,*major_version,*minor_version);
1208   return(status);
1209 }
1210
1211 static int NTGhostscriptGetString(const char *name,BOOL *is_64_bit,
1212   char *value,const size_t length)
1213 {
1214   char
1215     buffer[MagickPathExtent],
1216     *directory;
1217
1218   int
1219     extent;
1220
1221   static const char
1222     *product_family=(const char *) NULL;
1223
1224   static BOOL
1225     is_64_bit_version=FALSE;
1226
1227   static int
1228     flags=0,
1229     major_version=0,
1230     minor_version=0,
1231     root_index=0;
1232
1233   /*
1234     Get a string from the installed Ghostscript.
1235   */
1236   *value='\0';
1237   directory=(char *) NULL;
1238   if (LocaleCompare(name,"GS_DLL") == 0)
1239     {
1240       directory=GetEnvironmentValue("MAGICK_GHOSTSCRIPT_PATH");
1241       if (directory != (char *) NULL)
1242         {
1243           (void) FormatLocaleString(buffer,MagickPathExtent,"%s%sgsdll32.dll",
1244             directory,DirectorySeparator);
1245           if (IsPathAccessible(buffer) != MagickFalse)
1246             {
1247               directory=DestroyString(directory);
1248               (void) CopyMagickString(value,buffer,length);
1249               if (is_64_bit != NULL)
1250                 *is_64_bit=FALSE;
1251               return(TRUE);
1252             }
1253           (void) FormatLocaleString(buffer,MagickPathExtent,"%s%sgsdll64.dll",
1254             directory,DirectorySeparator);
1255           if (IsPathAccessible(buffer) != MagickFalse)
1256             {
1257               directory=DestroyString(directory);
1258               (void) CopyMagickString(value,buffer,length);
1259               if (is_64_bit != NULL)
1260                 *is_64_bit=TRUE;
1261               return(TRUE);
1262             }
1263           return(FALSE);
1264         }
1265     }
1266   if (product_family == NULL)
1267     {
1268       flags=0;
1269 #if defined(KEY_WOW64_32KEY)
1270 #if defined(_WIN64)
1271       flags=KEY_WOW64_64KEY;
1272 #else
1273       flags=KEY_WOW64_32KEY;
1274 #endif
1275       (void) NTLocateGhostscript(flags,&root_index,&product_family,
1276         &major_version,&minor_version);
1277       if (product_family == NULL)
1278 #if defined(_WIN64)
1279         flags=KEY_WOW64_32KEY;
1280       else
1281         is_64_bit_version=TRUE;
1282 #else
1283         flags=KEY_WOW64_64KEY;
1284 #endif
1285 #endif
1286     }
1287   if (product_family == NULL)
1288     {
1289       (void) NTLocateGhostscript(flags,&root_index,&product_family,
1290       &major_version,&minor_version);
1291 #if !defined(_WIN64)
1292       is_64_bit_version=TRUE;
1293 #endif
1294     }
1295   if (product_family == NULL)
1296     return(FALSE);
1297   if (is_64_bit != NULL)
1298     *is_64_bit=is_64_bit_version;
1299   (void) FormatLocaleString(buffer,MagickPathExtent,"SOFTWARE\\%s\\%d.%02d",
1300     product_family,major_version,minor_version);
1301   extent=(int) length;
1302   if (NTGetRegistryValue(registry_roots[root_index].hkey,buffer,flags,name,
1303     value,&extent) == 0)
1304     {
1305       (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
1306         "registry: \"%s\\%s\\%s\"=\"%s\"",registry_roots[root_index].name,
1307         buffer,name,value);
1308       return(TRUE);
1309     }
1310   return(FALSE);
1311 }
1312
1313 MagickPrivate int NTGhostscriptDLL(char *path,int length)
1314 {
1315   static char
1316     dll[MagickPathExtent] = { "" };
1317
1318   static BOOL
1319     is_64_bit_version;
1320
1321   *path='\0';
1322   if ((*dll == '\0') &&
1323       (NTGhostscriptGetString("GS_DLL",&is_64_bit_version,dll,sizeof(dll)) == FALSE))
1324     return(FALSE);
1325
1326 #if defined(_WIN64)
1327   if (!is_64_bit_version)
1328     return(FALSE);
1329 #else
1330   if (is_64_bit_version)
1331     return(FALSE);
1332 #endif
1333   (void) CopyMagickString(path,dll,length);
1334   return(TRUE);
1335 }
1336 \f
1337 /*
1338 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1339 %                                                                             %
1340 %                                                                             %
1341 %                                                                             %
1342 %   N T G h o s t s c r i p t D L L V e c t o r s                             %
1343 %                                                                             %
1344 %                                                                             %
1345 %                                                                             %
1346 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1347 %
1348 %  NTGhostscriptDLLVectors() returns a GhostInfo structure that includes
1349 %  function vectors to invoke Ghostscript DLL functions. A null pointer is
1350 %  returned if there is an error when loading the DLL or retrieving the
1351 %  function vectors.
1352 %
1353 %  The format of the NTGhostscriptDLLVectors method is:
1354 %
1355 %      const GhostInfo *NTGhostscriptDLLVectors(void)
1356 %
1357 */
1358 MagickPrivate const GhostInfo *NTGhostscriptDLLVectors(void)
1359 {
1360   if (NTGhostscriptLoadDLL() == FALSE)
1361     return((GhostInfo *) NULL);
1362   return(&ghost_info);
1363 }
1364 \f
1365 /*
1366 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1367 %                                                                             %
1368 %                                                                             %
1369 %                                                                             %
1370 %   N T G h o s t s c r i p t E X E                                           %
1371 %                                                                             %
1372 %                                                                             %
1373 %                                                                             %
1374 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1375 %
1376 %  NTGhostscriptEXE() obtains the path to the latest Ghostscript executable.
1377 %  The method returns FALSE if a full path value is not obtained and returns
1378 %  a default path of gswin32c.exe.
1379 %
1380 %  The format of the NTGhostscriptEXE method is:
1381 %
1382 %      int NTGhostscriptEXE(char *path,int length)
1383 %
1384 %  A description of each parameter follows:
1385 %
1386 %    o path: return the Ghostscript executable path here.
1387 %
1388 %    o length: length of buffer.
1389 %
1390 */
1391 MagickPrivate int NTGhostscriptEXE(char *path,int length)
1392 {
1393   register char
1394     *p;
1395
1396   static char
1397     program[MagickPathExtent] = { "" };
1398
1399   static BOOL
1400     is_64_bit_version = FALSE;
1401
1402   (void) CopyMagickString(path,"gswin32c.exe",length);
1403   if (*program == '\0')
1404     {
1405       if (ghost_semaphore == (SemaphoreInfo *) NULL)
1406         ActivateSemaphoreInfo(&ghost_semaphore);
1407       LockSemaphoreInfo(ghost_semaphore);
1408       if (NTGhostscriptGetString("GS_DLL",&is_64_bit_version,program,
1409           sizeof(program)) == FALSE)
1410         {
1411           UnlockSemaphoreInfo(ghost_semaphore);
1412           return(FALSE);
1413         }
1414       p=strrchr(program,'\\');
1415       if (p != (char *) NULL)
1416         {
1417           p++;
1418           *p='\0';
1419           (void) ConcatenateMagickString(program,is_64_bit_version ?
1420             "gswin64c.exe" : "gswin32c.exe",sizeof(program));
1421         }
1422       UnlockSemaphoreInfo(ghost_semaphore);
1423     }
1424   (void) CopyMagickString(path,program,length);
1425   return(TRUE);
1426 }
1427 \f
1428 /*
1429 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1430 %                                                                             %
1431 %                                                                             %
1432 %                                                                             %
1433 %   N T G h o s t s c r i p t F o n t s                                       %
1434 %                                                                             %
1435 %                                                                             %
1436 %                                                                             %
1437 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1438 %
1439 %  NTGhostscriptFonts() obtains the path to the Ghostscript fonts.  The method
1440 %  returns FALSE if it cannot determine the font path.
1441 %
1442 %  The format of the NTGhostscriptFonts method is:
1443 %
1444 %      int NTGhostscriptFonts(char *path, int length)
1445 %
1446 %  A description of each parameter follows:
1447 %
1448 %    o path: return the font path here.
1449 %
1450 %    o length: length of the path buffer.
1451 %
1452 */
1453 MagickPrivate int NTGhostscriptFonts(char *path,int length)
1454 {
1455   char
1456     buffer[MagickPathExtent],
1457     *directory,
1458     filename[MagickPathExtent];
1459
1460   register char
1461     *p,
1462     *q;
1463
1464   *path='\0';
1465   directory=GetEnvironmentValue("MAGICK_GHOSTSCRIPT_FONT_PATH");
1466   if (directory != (char *) NULL)
1467     {
1468       (void) CopyMagickString(buffer,directory,MagickPathExtent);
1469       directory=DestroyString(directory);
1470     }
1471   else
1472     {
1473       if (NTGhostscriptGetString("GS_LIB",NULL,buffer,MagickPathExtent) == FALSE)
1474         return(FALSE);
1475     }
1476   for (p=buffer-1; p != (char *) NULL; p=strchr(p+1,DirectoryListSeparator))
1477   {
1478     (void) CopyMagickString(path,p+1,length+1);
1479     q=strchr(path,DirectoryListSeparator);
1480     if (q != (char *) NULL)
1481       *q='\0';
1482     (void) FormatLocaleString(filename,MagickPathExtent,"%s%sfonts.dir",path,
1483       DirectorySeparator);
1484     if (IsPathAccessible(filename) != MagickFalse)
1485       return(TRUE);
1486   }
1487   *path='\0';
1488   return(FALSE);
1489 }
1490 \f
1491 /*
1492 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1493 %                                                                             %
1494 %                                                                             %
1495 %                                                                             %
1496 %   N T G h o s t s c r i p t L o a d D L L                                   %
1497 %                                                                             %
1498 %                                                                             %
1499 %                                                                             %
1500 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1501 %
1502 %  NTGhostscriptLoadDLL() attempts to load the Ghostscript DLL and returns
1503 %  TRUE if it succeeds.
1504 %
1505 %  The format of the NTGhostscriptLoadDLL method is:
1506 %
1507 %      int NTGhostscriptLoadDLL(void)
1508 %
1509 */
1510 static inline int NTGhostscriptHasValidHandle()
1511 {
1512   if ((nt_ghost_info.delete_instance == NULL) || (ghost_info.exit == NULL) ||
1513       (ghost_info.init_with_args == NULL) ||
1514       (nt_ghost_info.new_instance == NULL) ||
1515       (ghost_info.run_string == NULL) || (ghost_info.set_stdio == NULL) ||
1516       (ghost_info.revision == NULL))
1517     {
1518       return(FALSE);
1519     }
1520   return(TRUE);
1521 }
1522
1523 MagickPrivate int NTGhostscriptLoadDLL(void)
1524 {
1525   char
1526     path[MagickPathExtent];
1527
1528   if (ghost_semaphore == (SemaphoreInfo *) NULL)
1529     ActivateSemaphoreInfo(&ghost_semaphore);
1530   LockSemaphoreInfo(ghost_semaphore);
1531   if (ghost_handle != (void *) NULL)
1532     {
1533       UnlockSemaphoreInfo(ghost_semaphore);
1534       return(NTGhostscriptHasValidHandle());
1535     }
1536   if (NTGhostscriptDLL(path,sizeof(path)) == FALSE)
1537     {
1538       UnlockSemaphoreInfo(ghost_semaphore);
1539       return(FALSE);
1540     }
1541   ghost_handle=lt_dlopen(path);
1542   if (ghost_handle == (void *) NULL)
1543     {
1544       UnlockSemaphoreInfo(ghost_semaphore);
1545       return(FALSE);
1546     }
1547   (void) memset((void *) &nt_ghost_info,0,sizeof(NTGhostInfo));
1548   nt_ghost_info.delete_instance=(void (MagickDLLCall *)(gs_main_instance *)) (
1549     lt_dlsym(ghost_handle,"gsapi_delete_instance"));
1550   nt_ghost_info.new_instance=(int (MagickDLLCall *)(gs_main_instance **,
1551     void *)) (lt_dlsym(ghost_handle,"gsapi_new_instance"));
1552   nt_ghost_info.has_instance=MagickFalse;
1553   (void) memset((void *) &ghost_info,0,sizeof(GhostInfo));
1554   ghost_info.delete_instance=NTGhostscriptDeleteInstance;
1555   ghost_info.exit=(int (MagickDLLCall *)(gs_main_instance*))
1556     lt_dlsym(ghost_handle,"gsapi_exit");
1557   ghost_info.init_with_args=(int (MagickDLLCall *)(gs_main_instance *,int,
1558     char **)) (lt_dlsym(ghost_handle,"gsapi_init_with_args"));
1559   ghost_info.new_instance=NTGhostscriptNewInstance;
1560   ghost_info.run_string=(int (MagickDLLCall *)(gs_main_instance *,const char *,
1561     int,int *)) (lt_dlsym(ghost_handle,"gsapi_run_string"));
1562   ghost_info.set_stdio=(int (MagickDLLCall *)(gs_main_instance *,int(
1563     MagickDLLCall *)(void *,char *,int),int(MagickDLLCall *)(void *,
1564     const char *,int),int(MagickDLLCall *)(void *,const char *,int)))
1565     (lt_dlsym(ghost_handle,"gsapi_set_stdio"));
1566   ghost_info.revision=(int (MagickDLLCall *)(gsapi_revision_t *,int)) (
1567     lt_dlsym(ghost_handle,"gsapi_revision"));
1568   UnlockSemaphoreInfo(ghost_semaphore);
1569   return(NTGhostscriptHasValidHandle());
1570 }
1571 \f
1572 /*
1573 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1574 %                                                                             %
1575 %                                                                             %
1576 %                                                                             %
1577 %   N T G h o s t s c r i p t U n L o a d D L L                               %
1578 %                                                                             %
1579 %                                                                             %
1580 %                                                                             %
1581 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1582 %
1583 %  NTGhostscriptUnLoadDLL() unloads the Ghostscript DLL and returns TRUE if
1584 %  it succeeds.
1585 %
1586 %  The format of the NTGhostscriptUnLoadDLL method is:
1587 %
1588 %      int NTGhostscriptUnLoadDLL(void)
1589 %
1590 */
1591 MagickPrivate void NTGhostscriptUnLoadDLL(void)
1592 {
1593   if (ghost_semaphore == (SemaphoreInfo *) NULL)
1594     ActivateSemaphoreInfo(&ghost_semaphore);
1595   LockSemaphoreInfo(ghost_semaphore);
1596   if (ghost_handle != (void *) NULL)
1597     {
1598       (void) lt_dlclose(ghost_handle);
1599       ghost_handle=(void *) NULL;
1600       (void) memset((void *) &ghost_info,0,sizeof(GhostInfo));
1601     }
1602   UnlockSemaphoreInfo(ghost_semaphore);
1603   RelinquishSemaphoreInfo(&ghost_semaphore);
1604 }
1605 \f
1606 /*
1607 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1608 %                                                                             %
1609 %                                                                             %
1610 %                                                                             %
1611 %   N T I n i t i a l i z e L i b r a r y                                     %
1612 %                                                                             %
1613 %                                                                             %
1614 %                                                                             %
1615 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1616 %
1617 %  NTInitializeLibrary() initializes the dynamic module loading subsystem.
1618 %
1619 %  The format of the NTInitializeLibrary method is:
1620 %
1621 %      int NTInitializeLibrary(void)
1622 %
1623 */
1624 MagickPrivate int NTInitializeLibrary(void)
1625 {
1626   return(0);
1627 }
1628 \f
1629 /*
1630 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1631 %                                                                             %
1632 %                                                                             %
1633 %                                                                             %
1634 %   N T I n i t i a l i z e W i n s o c k                                     %
1635 %                                                                             %
1636 %                                                                             %
1637 %                                                                             %
1638 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1639 %
1640 %  NTInitializeWinsock() initializes Winsock.
1641 %
1642 %  The format of the NTInitializeWinsock method is:
1643 %
1644 %      void NTInitializeWinsock(void)
1645 %
1646 */
1647 MagickPrivate void NTInitializeWinsock(MagickBooleanType use_lock)
1648 {
1649   if (use_lock)
1650     {
1651       if (winsock_semaphore == (SemaphoreInfo *) NULL)
1652         ActivateSemaphoreInfo(&winsock_semaphore);
1653       LockSemaphoreInfo(winsock_semaphore);
1654     }
1655   if (wsaData == (WSADATA *) NULL)
1656     {
1657       wsaData=(WSADATA *) AcquireMagickMemory(sizeof(WSADATA));
1658       if (WSAStartup(MAKEWORD(2,2),wsaData) != 0)
1659         ThrowFatalException(CacheFatalError,"WSAStartup failed");
1660     }
1661   if (use_lock)
1662     UnlockSemaphoreInfo(winsock_semaphore);
1663 }
1664 \f
1665 /*
1666 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1667 %                                                                             %
1668 %                                                                             %
1669 %                                                                             %
1670 +  N T M a p M e m o r y                                                      %
1671 %                                                                             %
1672 %                                                                             %
1673 %                                                                             %
1674 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1675 %
1676 %  Mmap() emulates the Unix method of the same name.
1677 %
1678 %  The format of the NTMapMemory method is:
1679 %
1680 %    MagickPrivate void *NTMapMemory(char *address,size_t length,int protection,
1681 %      int access,int file,MagickOffsetType offset)
1682 %
1683 */
1684 MagickPrivate void *NTMapMemory(char *address,size_t length,int protection,
1685   int flags,int file,MagickOffsetType offset)
1686 {
1687   DWORD
1688     access_mode,
1689     high_length,
1690     high_offset,
1691     low_length,
1692     low_offset,
1693     protection_mode;
1694
1695   HANDLE
1696     file_handle,
1697     map_handle;
1698
1699   void
1700     *map;
1701
1702   (void) address;
1703   access_mode=0;
1704   file_handle=INVALID_HANDLE_VALUE;
1705   low_length=(DWORD) (length & 0xFFFFFFFFUL);
1706   high_length=(DWORD) ((((MagickOffsetType) length) >> 32) & 0xFFFFFFFFUL);
1707   map_handle=INVALID_HANDLE_VALUE;
1708   map=(void *) NULL;
1709   low_offset=(DWORD) (offset & 0xFFFFFFFFUL);
1710   high_offset=(DWORD) ((offset >> 32) & 0xFFFFFFFFUL);
1711   protection_mode=0;
1712   if (protection & PROT_WRITE)
1713     {
1714       access_mode=FILE_MAP_WRITE;
1715       if (!(flags & MAP_PRIVATE))
1716         protection_mode=PAGE_READWRITE;
1717       else
1718         {
1719           access_mode=FILE_MAP_COPY;
1720           protection_mode=PAGE_WRITECOPY;
1721         }
1722     }
1723   else
1724     if (protection & PROT_READ)
1725       {
1726         access_mode=FILE_MAP_READ;
1727         protection_mode=PAGE_READONLY;
1728       }
1729   if ((file == -1) && (flags & MAP_ANONYMOUS))
1730     file_handle=INVALID_HANDLE_VALUE;
1731   else
1732     file_handle=(HANDLE) _get_osfhandle(file);
1733   map_handle=CreateFileMapping(file_handle,0,protection_mode,high_length,
1734     low_length,0);
1735   if (map_handle)
1736     {
1737       map=(void *) MapViewOfFile(map_handle,access_mode,high_offset,low_offset,
1738         length);
1739       CloseHandle(map_handle);
1740     }
1741   if (map == (void *) NULL)
1742     return((void *) ((char *) MAP_FAILED));
1743   return((void *) ((char *) map));
1744 }
1745 \f
1746 /*
1747 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1748 %                                                                             %
1749 %                                                                             %
1750 %                                                                             %
1751 %   N T O p e n D i r e c t o r y                                             %
1752 %                                                                             %
1753 %                                                                             %
1754 %                                                                             %
1755 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1756 %
1757 %  NTOpenDirectory() opens the directory named by filename and associates a
1758 %  directory stream with it.
1759 %
1760 %  The format of the NTOpenDirectory method is:
1761 %
1762 %      DIR *NTOpenDirectory(const char *path)
1763 %
1764 %  A description of each parameter follows:
1765 %
1766 %    o entry: Specifies a pointer to a DIR structure.
1767 %
1768 */
1769 MagickPrivate DIR *NTOpenDirectory(const char *path)
1770 {
1771   DIR
1772     *entry;
1773
1774   size_t
1775     length;
1776
1777   wchar_t
1778     file_specification[MagickPathExtent];
1779
1780   assert(path != (const char *) NULL);
1781   length=MultiByteToWideChar(CP_UTF8,0,path,-1,file_specification,
1782     MagickPathExtent);
1783   if (length == 0)
1784     return((DIR *) NULL);
1785   if (wcsncat(file_specification,(const wchar_t*) DirectorySeparator,
1786         MagickPathExtent-wcslen(file_specification)-1) == (wchar_t*) NULL)
1787     return((DIR *) NULL);
1788   entry=(DIR *) AcquireCriticalMemory(sizeof(DIR));
1789   entry->firsttime=TRUE;
1790   entry->hSearch=FindFirstFileW(file_specification,&entry->Win32FindData);
1791   if (entry->hSearch == INVALID_HANDLE_VALUE)
1792     {
1793       if(wcsncat(file_specification,L"*.*",
1794         MagickPathExtent-wcslen(file_specification)-1) == (wchar_t*) NULL)
1795         {
1796           entry=(DIR *) RelinquishMagickMemory(entry);
1797           return((DIR *) NULL);
1798         }
1799       entry->hSearch=FindFirstFileW(file_specification,&entry->Win32FindData);
1800       if (entry->hSearch == INVALID_HANDLE_VALUE)
1801         {
1802           entry=(DIR *) RelinquishMagickMemory(entry);
1803           return((DIR *) NULL);
1804         }
1805     }
1806   return(entry);
1807 }
1808 \f
1809 /*
1810 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1811 %                                                                             %
1812 %                                                                             %
1813 %                                                                             %
1814 %   N T O p e n L i b r a r y                                                 %
1815 %                                                                             %
1816 %                                                                             %
1817 %                                                                             %
1818 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1819 %
1820 %  NTOpenLibrary() loads a dynamic module into memory and returns a handle that
1821 %  can be used to access the various procedures in the module.
1822 %
1823 %  The format of the NTOpenLibrary method is:
1824 %
1825 %      void *NTOpenLibrary(const char *filename)
1826 %
1827 %  A description of each parameter follows:
1828 %
1829 %    o path: Specifies a pointer to string representing dynamic module that
1830 %      is to be loaded.
1831 %
1832 */
1833
1834 static inline const char *GetSearchPath(void)
1835 {
1836 #if defined(MAGICKCORE_LTDL_DELEGATE)
1837   return(lt_dlgetsearchpath());
1838 #else
1839   return(lt_slsearchpath);
1840 #endif
1841 }
1842
1843 static UINT ChangeErrorMode(void)
1844 {
1845   typedef UINT
1846     (CALLBACK *GETERRORMODE)(void);
1847
1848   GETERRORMODE
1849     getErrorMode;
1850
1851   HMODULE
1852     handle;
1853
1854   UINT
1855     mode;
1856
1857   mode=SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX;
1858
1859   handle=GetModuleHandle("kernel32.dll");
1860   if (handle == (HMODULE) NULL)
1861     return SetErrorMode(mode);
1862
1863   getErrorMode=(GETERRORMODE) NTGetLibrarySymbol(handle,"GetErrorMode");
1864   if (getErrorMode != (GETERRORMODE) NULL)
1865     mode=getErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX;
1866
1867   return SetErrorMode(mode);
1868 }
1869
1870 static inline void *NTLoadLibrary(const char *filename)
1871 {
1872   int
1873     length;
1874
1875   wchar_t
1876     path[MagickPathExtent];
1877
1878   length=MultiByteToWideChar(CP_UTF8,0,filename,-1,path,MagickPathExtent);
1879   if (length == 0)
1880     return((void *) NULL);
1881   return (void *) LoadLibraryExW(path,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
1882 }
1883
1884 MagickPrivate void *NTOpenLibrary(const char *filename)
1885 {
1886   char
1887     path[MagickPathExtent];
1888
1889   register const char
1890     *p,
1891     *q;
1892
1893   UINT
1894     mode;
1895
1896   void
1897     *handle;
1898
1899   mode=ChangeErrorMode();
1900   handle=NTLoadLibrary(filename);
1901   if (handle == (void *) NULL)
1902     {
1903       p=GetSearchPath();
1904       while (p != (const char*) NULL)
1905       {
1906         q=strchr(p,DirectoryListSeparator);
1907         if (q != (const char*) NULL)
1908           (void) CopyMagickString(path,p,q-p+1);
1909         else
1910           (void) CopyMagickString(path,p,MagickPathExtent);
1911         (void) ConcatenateMagickString(path,DirectorySeparator,MagickPathExtent);
1912         (void) ConcatenateMagickString(path,filename,MagickPathExtent);
1913         handle=NTLoadLibrary(path);
1914         if (handle != (void *) NULL || q == (const char*) NULL)
1915           break;
1916         p=q+1;
1917       }
1918     }
1919   SetErrorMode(mode);
1920   return(handle);
1921 }
1922 \f
1923 /*
1924 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1925 %                                                                             %
1926 %                                                                             %
1927 %                                                                             %
1928 %    N T R e a d D i r e c t o r y                                            %
1929 %                                                                             %
1930 %                                                                             %
1931 %                                                                             %
1932 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1933 %
1934 %  NTReadDirectory() returns a pointer to a structure representing the
1935 %  directory entry at the current position in the directory stream to which
1936 %  entry refers.
1937 %
1938 %  The format of the NTReadDirectory
1939 %
1940 %      NTReadDirectory(entry)
1941 %
1942 %  A description of each parameter follows:
1943 %
1944 %    o entry: Specifies a pointer to a DIR structure.
1945 %
1946 */
1947 MagickPrivate struct dirent *NTReadDirectory(DIR *entry)
1948 {
1949   int
1950     status;
1951
1952   size_t
1953     length;
1954
1955   if (entry == (DIR *) NULL)
1956     return((struct dirent *) NULL);
1957   if (!entry->firsttime)
1958     {
1959       status=FindNextFileW(entry->hSearch,&entry->Win32FindData);
1960       if (status == 0)
1961         return((struct dirent *) NULL);
1962     }
1963   length=WideCharToMultiByte(CP_UTF8,0,entry->Win32FindData.cFileName,-1,
1964     entry->file_info.d_name,sizeof(entry->file_info.d_name),NULL,NULL);
1965   if (length == 0)
1966     return((struct dirent *) NULL);
1967   entry->firsttime=FALSE;
1968   entry->file_info.d_namlen=(int) strlen(entry->file_info.d_name);
1969   return(&entry->file_info);
1970 }
1971 \f
1972 /*
1973 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1974 %                                                                             %
1975 %                                                                             %
1976 %                                                                             %
1977 %   N T R e g i s t r y K e y L o o k u p                                     %
1978 %                                                                             %
1979 %                                                                             %
1980 %                                                                             %
1981 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1982 %
1983 %  NTRegistryKeyLookup() returns ImageMagick installation path settings
1984 %  stored in the Windows Registry.  Path settings are specific to the
1985 %  installed ImageMagick version so that multiple Image Magick installations
1986 %  may coexist.
1987 %
1988 %  Values are stored in the registry under a base path path similar to
1989 %  "HKEY_LOCAL_MACHINE/SOFTWARE\ImageMagick\6.7.4\Q:16" or
1990 %  "HKEY_CURRENT_USER/SOFTWARE\ImageMagick\6.7.4\Q:16". The provided subkey
1991 %  is appended to this base path to form the full key.
1992 %
1993 %  The format of the NTRegistryKeyLookup method is:
1994 %
1995 %      unsigned char *NTRegistryKeyLookup(const char *subkey)
1996 %
1997 %  A description of each parameter follows:
1998 %
1999 %    o subkey: Specifies a string that identifies the registry object.
2000 %      Currently supported sub-keys include: "BinPath", "ConfigurePath",
2001 %      "LibPath", "CoderModulesPath", "FilterModulesPath", "SharePath".
2002 %
2003 */
2004 MagickPrivate unsigned char *NTRegistryKeyLookup(const char *subkey)
2005 {
2006   char
2007     package_key[MagickPathExtent];
2008
2009   DWORD
2010     size,
2011     type;
2012
2013   HKEY
2014     registry_key;
2015
2016   LONG
2017     status;
2018
2019   unsigned char
2020     *value;
2021
2022   /*
2023     Look-up base key.
2024   */
2025   (void) FormatLocaleString(package_key,MagickPathExtent,
2026     "SOFTWARE\\%s\\%s\\Q:%d",MagickPackageName,MagickLibVersionText,
2027     MAGICKCORE_QUANTUM_DEPTH);
2028   (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),"%s",package_key);
2029   registry_key=(HKEY) INVALID_HANDLE_VALUE;
2030   status=RegOpenKeyExA(HKEY_LOCAL_MACHINE,package_key,0,KEY_READ,&registry_key);
2031   if (status != ERROR_SUCCESS)
2032     status=RegOpenKeyExA(HKEY_CURRENT_USER,package_key,0,KEY_READ,
2033       &registry_key);
2034   if (status != ERROR_SUCCESS)
2035     return((unsigned char *) NULL);
2036   /*
2037     Look-up sub key.
2038   */
2039   size=32;
2040   value=(unsigned char *) AcquireQuantumMemory(size,sizeof(*value));
2041   if (value == (unsigned char *) NULL)
2042     {
2043       RegCloseKey(registry_key);
2044       return((unsigned char *) NULL);
2045     }
2046   (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),"%s",subkey);
2047   status=RegQueryValueExA(registry_key,subkey,0,&type,value,&size);
2048   if ((status == ERROR_MORE_DATA) && (type == REG_SZ))
2049     {
2050       value=(unsigned char *) ResizeQuantumMemory(value,size,sizeof(*value));
2051       if (value == (BYTE *) NULL)
2052         {
2053           RegCloseKey(registry_key);
2054           return((unsigned char *) NULL);
2055         }
2056       status=RegQueryValueExA(registry_key,subkey,0,&type,value,&size);
2057     }
2058   RegCloseKey(registry_key);
2059   if ((type != REG_SZ) || (status != ERROR_SUCCESS))
2060     value=(unsigned char *) RelinquishMagickMemory(value);
2061   return((unsigned char *) value);
2062 }
2063 \f
2064 /*
2065 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2066 %                                                                             %
2067 %                                                                             %
2068 %                                                                             %
2069 %   N T R e p o r t E v e n t                                                 %
2070 %                                                                             %
2071 %                                                                             %
2072 %                                                                             %
2073 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2074 %
2075 %  NTReportEvent() reports an event.
2076 %
2077 %  The format of the NTReportEvent method is:
2078 %
2079 %      MagickBooleanType NTReportEvent(const char *event,
2080 %        const MagickBooleanType error)
2081 %
2082 %  A description of each parameter follows:
2083 %
2084 %    o event: the event.
2085 %
2086 %    o error: MagickTrue the event is an error.
2087 %
2088 */
2089 MagickPrivate MagickBooleanType NTReportEvent(const char *event,
2090   const MagickBooleanType error)
2091 {
2092   const char
2093     *events[1];
2094
2095   HANDLE
2096     handle;
2097
2098   WORD
2099     type;
2100
2101   handle=RegisterEventSource(NULL,MAGICKCORE_PACKAGE_NAME);
2102   if (handle == NULL)
2103     return(MagickFalse);
2104   events[0]=event;
2105   type=error ? EVENTLOG_ERROR_TYPE : EVENTLOG_WARNING_TYPE;
2106   ReportEvent(handle,type,0,0,NULL,1,0,events,NULL);
2107   DeregisterEventSource(handle);
2108   return(MagickTrue);
2109 }
2110 \f
2111 /*
2112 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2113 %                                                                             %
2114 %                                                                             %
2115 %                                                                             %
2116 %   N T R e s o u r c e T o B l o b                                           %
2117 %                                                                             %
2118 %                                                                             %
2119 %                                                                             %
2120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2121 %
2122 %  NTResourceToBlob() returns a blob containing the contents of the resource
2123 %  in the current executable specified by the id parameter. This currently
2124 %  used to retrieve MGK files tha have been embedded into the various command
2125 %  line utilities.
2126 %
2127 %  The format of the NTResourceToBlob method is:
2128 %
2129 %      unsigned char *NTResourceToBlob(const char *id)
2130 %
2131 %  A description of each parameter follows:
2132 %
2133 %    o id: Specifies a string that identifies the resource.
2134 %
2135 */
2136 MagickPrivate unsigned char *NTResourceToBlob(const char *id)
2137 {
2138
2139 #ifndef MAGICKCORE_LIBRARY_NAME
2140   char
2141     path[MagickPathExtent];
2142 #endif
2143
2144   DWORD
2145     length;
2146
2147   HGLOBAL
2148     global;
2149
2150   HMODULE
2151     handle;
2152
2153   HRSRC
2154     resource;
2155
2156   unsigned char
2157     *blob,
2158     *value;
2159
2160   assert(id != (const char *) NULL);
2161   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",id);
2162 #ifdef MAGICKCORE_LIBRARY_NAME
2163   handle=GetModuleHandle(MAGICKCORE_LIBRARY_NAME);
2164 #else
2165   (void) FormatLocaleString(path,MagickPathExtent,"%s%s%s",GetClientPath(),
2166     DirectorySeparator,GetClientName());
2167   if (IsPathAccessible(path) != MagickFalse)
2168     handle=GetModuleHandle(path);
2169   else
2170     handle=GetModuleHandle(0);
2171 #endif
2172   if (!handle)
2173     return((unsigned char *) NULL);
2174   resource=FindResource(handle,id,"IMAGEMAGICK");
2175   if (!resource)
2176     return((unsigned char *) NULL);
2177   global=LoadResource(handle,resource);
2178   if (!global)
2179     return((unsigned char *) NULL);
2180   length=SizeofResource(handle,resource);
2181   value=(unsigned char *) LockResource(global);
2182   if (!value)
2183     {
2184       FreeResource(global);
2185       return((unsigned char *) NULL);
2186     }
2187   blob=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent,
2188     sizeof(*blob));
2189   if (blob != (unsigned char *) NULL)
2190     {
2191       (void) memcpy(blob,value,length);
2192       blob[length]='\0';
2193     }
2194   UnlockResource(global);
2195   FreeResource(global);
2196   return(blob);
2197 }
2198 \f
2199 /*
2200 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2201 %                                                                             %
2202 %                                                                             %
2203 %                                                                             %
2204 %   N T S e e k D i r e c t o r y                                             %
2205 %                                                                             %
2206 %                                                                             %
2207 %                                                                             %
2208 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2209 %
2210 %  NTSeekDirectory() sets the position of the next NTReadDirectory() operation
2211 %  on the directory stream.
2212 %
2213 %  The format of the NTSeekDirectory method is:
2214 %
2215 %      void NTSeekDirectory(DIR *entry,ssize_t position)
2216 %
2217 %  A description of each parameter follows:
2218 %
2219 %    o entry: Specifies a pointer to a DIR structure.
2220 %
2221 %    o position: specifies the position associated with the directory
2222 %      stream.
2223 %
2224 */
2225 MagickPrivate void NTSeekDirectory(DIR *entry,ssize_t position)
2226 {
2227   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2228   assert(entry != (DIR *) NULL);
2229   (void) entry;
2230   (void) position;
2231 }
2232 \f
2233 /*
2234 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2235 %                                                                             %
2236 %                                                                             %
2237 %                                                                             %
2238 %   N T S e t S e a r c h P a t h                                             %
2239 %                                                                             %
2240 %                                                                             %
2241 %                                                                             %
2242 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2243 %
2244 %  NTSetSearchPath() sets the current locations that the subsystem should
2245 %  look at to find dynamically loadable modules.
2246 %
2247 %  The format of the NTSetSearchPath method is:
2248 %
2249 %      int NTSetSearchPath(const char *path)
2250 %
2251 %  A description of each parameter follows:
2252 %
2253 %    o path: Specifies a pointer to string representing the search path
2254 %      for DLL's that can be dynamically loaded.
2255 %
2256 */
2257 MagickPrivate int NTSetSearchPath(const char *path)
2258 {
2259 #if defined(MAGICKCORE_LTDL_DELEGATE)
2260   lt_dlsetsearchpath(path);
2261 #else
2262   if (lt_slsearchpath != (char *) NULL)
2263     lt_slsearchpath=DestroyString(lt_slsearchpath);
2264   if (path != (char *) NULL)
2265     lt_slsearchpath=AcquireString(path);
2266 #endif
2267   return(0);
2268 }
2269 \f
2270 /*
2271 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2272 %                                                                             %
2273 %                                                                             %
2274 %                                                                             %
2275 +  N T S y n c M e m o r y                                                    %
2276 %                                                                             %
2277 %                                                                             %
2278 %                                                                             %
2279 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2280 %
2281 %  NTSyncMemory() emulates the Unix method of the same name.
2282 %
2283 %  The format of the NTSyncMemory method is:
2284 %
2285 %      int NTSyncMemory(void *address,size_t length,int flags)
2286 %
2287 %  A description of each parameter follows:
2288 %
2289 %    o address: the address of the binary large object.
2290 %
2291 %    o length: the length of the binary large object.
2292 %
2293 %    o flags: Option flags (ignored for Windows).
2294 %
2295 */
2296 MagickPrivate int NTSyncMemory(void *address,size_t length,int flags)
2297 {
2298   (void) flags;
2299   if (FlushViewOfFile(address,length) == MagickFalse)
2300     return(-1);
2301   return(0);
2302 }
2303 \f
2304 /*
2305 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2306 %                                                                             %
2307 %                                                                             %
2308 %                                                                             %
2309 %   N T S y s t e m C o m m a n d                                             %
2310 %                                                                             %
2311 %                                                                             %
2312 %                                                                             %
2313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2314 %
2315 %  NTSystemCommand() executes the specified command and waits until it
2316 %  terminates.  The returned value is the exit status of the command.
2317 %
2318 %  The format of the NTSystemCommand method is:
2319 %
2320 %      int NTSystemCommand(MagickFalse,const char *command)
2321 %
2322 %  A description of each parameter follows:
2323 %
2324 %    o command: This string is the command to execute.
2325 %
2326 %    o output: an optional buffer to store the output from stderr/stdout.
2327 %
2328 */
2329 MagickPrivate int NTSystemCommand(const char *command,char *output)
2330 {
2331 #define CleanupOutputHandles \
2332   if (read_output != (HANDLE) NULL) \
2333     { \
2334        CloseHandle(read_output); \
2335        read_output=(HANDLE) NULL; \
2336        CloseHandle(write_output); \
2337        write_output=(HANDLE) NULL; \
2338     }
2339
2340 #define CopyLastError \
2341   if (output != (char *) NULL) \
2342     { \
2343       error=NTGetLastError(); \
2344       if (error != (char *) NULL) \
2345         { \
2346           CopyMagickString(output,error,MagickPathExtent); \
2347           error=DestroyString(error); \
2348         } \
2349     }
2350
2351   char
2352     *error,
2353     local_command[MagickPathExtent];
2354
2355   DWORD
2356     bytes_read,
2357     child_status,
2358     size;
2359
2360   int
2361     status;
2362
2363   MagickBooleanType
2364     asynchronous;
2365
2366   HANDLE
2367     read_output,
2368     write_output;
2369
2370   PROCESS_INFORMATION
2371     process_info;
2372
2373   SECURITY_ATTRIBUTES
2374     sa;
2375
2376   STARTUPINFO
2377     startup_info;
2378
2379   if (command == (char *) NULL)
2380     return(-1);
2381   read_output=(HANDLE) NULL;
2382   write_output=(HANDLE) NULL;
2383   GetStartupInfo(&startup_info);
2384   startup_info.dwFlags=STARTF_USESHOWWINDOW;
2385   startup_info.wShowWindow=SW_SHOWMINNOACTIVE;
2386   (void) CopyMagickString(local_command,command,MagickPathExtent);
2387   asynchronous=command[strlen(command)-1] == '&' ? MagickTrue : MagickFalse;
2388   if (asynchronous != MagickFalse)
2389     {
2390       local_command[strlen(command)-1]='\0';
2391       startup_info.wShowWindow=SW_SHOWDEFAULT;
2392     }
2393   else
2394     {
2395       if (command[strlen(command)-1] == '|')
2396         local_command[strlen(command)-1]='\0';
2397       else
2398         startup_info.wShowWindow=SW_HIDE;
2399       read_output=(HANDLE) NULL;
2400       if (output != (char *) NULL)
2401         {
2402           sa.nLength=sizeof(SECURITY_ATTRIBUTES);
2403           sa.bInheritHandle=TRUE;
2404           sa.lpSecurityDescriptor=NULL;
2405           if (CreatePipe(&read_output,&write_output,NULL,0))
2406             {
2407               if (SetHandleInformation(write_output,HANDLE_FLAG_INHERIT,
2408                   HANDLE_FLAG_INHERIT))
2409                 {
2410                   startup_info.dwFlags|=STARTF_USESTDHANDLES;
2411                   startup_info.hStdOutput=write_output;
2412                   startup_info.hStdError=write_output;
2413                 }
2414               else
2415                 CleanupOutputHandles;
2416             }
2417           else
2418             read_output=(HANDLE) NULL;
2419         }
2420     }
2421   status=CreateProcess((LPCTSTR) NULL,local_command,(LPSECURITY_ATTRIBUTES)
2422     NULL,(LPSECURITY_ATTRIBUTES) NULL,(BOOL) TRUE,(DWORD)
2423     NORMAL_PRIORITY_CLASS,(LPVOID) NULL,(LPCSTR) NULL,&startup_info,
2424     &process_info);
2425   if (status == 0)
2426     {
2427       CopyLastError;
2428       CleanupOutputHandles;
2429       return(-1);
2430     }
2431   if (asynchronous != MagickFalse)
2432     return(status == 0);
2433   status=WaitForSingleObject(process_info.hProcess,INFINITE);
2434   if (status != WAIT_OBJECT_0)
2435     {
2436       CopyLastError;
2437       CleanupOutputHandles;
2438       return(status);
2439     }
2440   status=GetExitCodeProcess(process_info.hProcess,&child_status);
2441   if (status == 0)
2442     {
2443       CopyLastError;
2444       CleanupOutputHandles;
2445       return(-1);
2446     }
2447   CloseHandle(process_info.hProcess);
2448   CloseHandle(process_info.hThread);
2449   if (read_output != (HANDLE) NULL)
2450     if (PeekNamedPipe(read_output,(LPVOID) NULL,0,(LPDWORD) NULL,&size,
2451           (LPDWORD) NULL))
2452       if ((size > 0) && (ReadFile(read_output,output,MagickPathExtent-1,
2453           &bytes_read,NULL))) 
2454         output[bytes_read]='\0';
2455   CleanupOutputHandles;
2456   return((int) child_status);
2457 }
2458 \f
2459 /*
2460 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2461 %                                                                             %
2462 %                                                                             %
2463 %                                                                             %
2464 %   N T S y s t e m C o n i f i g u r a t i o n                               %
2465 %                                                                             %
2466 %                                                                             %
2467 %                                                                             %
2468 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2469 %
2470 %  NTSystemConfiguration() provides a way for the application to determine
2471 %  values for system limits or options at runtime.
2472 %
2473 %  The format of the exit method is:
2474 %
2475 %      ssize_t NTSystemConfiguration(int name)
2476 %
2477 %  A description of each parameter follows:
2478 %
2479 %    o name: _SC_PAGE_SIZE or _SC_PHYS_PAGES.
2480 %
2481 */
2482 MagickPrivate ssize_t NTSystemConfiguration(int name)
2483 {
2484   switch (name)
2485   {
2486     case _SC_PAGESIZE:
2487     {
2488       SYSTEM_INFO
2489         system_info;
2490
2491       GetSystemInfo(&system_info);
2492       return(system_info.dwPageSize);
2493     }
2494     case _SC_PHYS_PAGES:
2495     {
2496       HMODULE
2497         handle;
2498
2499       LPFNDLLFUNC2
2500         module;
2501
2502       NTMEMORYSTATUSEX
2503         status;
2504
2505       SYSTEM_INFO
2506         system_info;
2507
2508       handle=GetModuleHandle("kernel32.dll");
2509       if (handle == (HMODULE) NULL)
2510         return(0L);
2511       GetSystemInfo(&system_info);
2512       module=(LPFNDLLFUNC2) NTGetLibrarySymbol(handle,"GlobalMemoryStatusEx");
2513       if (module == (LPFNDLLFUNC2) NULL)
2514         {
2515           MEMORYSTATUS
2516             global_status;
2517
2518           GlobalMemoryStatus(&global_status);
2519           return((ssize_t) global_status.dwTotalPhys/system_info.dwPageSize/4);
2520         }
2521       status.dwLength=sizeof(status);
2522       if (module(&status) == 0)
2523         return(0L);
2524       return((ssize_t) status.ullTotalPhys/system_info.dwPageSize/4);
2525     }
2526     case _SC_OPEN_MAX:
2527       return(2048);
2528     default:
2529       break;
2530   }
2531   return(-1);
2532 }
2533 \f
2534 /*
2535 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2536 %                                                                             %
2537 %                                                                             %
2538 %                                                                             %
2539 %   N T T e l l D i r e c t o r y                                             %
2540 %                                                                             %
2541 %                                                                             %
2542 %                                                                             %
2543 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2544 %
2545 %  NTTellDirectory() returns the current location associated with the named
2546 %  directory stream.
2547 %
2548 %  The format of the NTTellDirectory method is:
2549 %
2550 %      ssize_t NTTellDirectory(DIR *entry)
2551 %
2552 %  A description of each parameter follows:
2553 %
2554 %    o entry: Specifies a pointer to a DIR structure.
2555 %
2556 */
2557 MagickPrivate ssize_t NTTellDirectory(DIR *entry)
2558 {
2559   assert(entry != (DIR *) NULL);
2560   return(0);
2561 }
2562 \f
2563 /*
2564 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2565 %                                                                             %
2566 %                                                                             %
2567 %                                                                             %
2568 %   N T T r u n c a t e F i l e                                               %
2569 %                                                                             %
2570 %                                                                             %
2571 %                                                                             %
2572 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2573 %
2574 %  NTTruncateFile() truncates a file to a specified length.
2575 %
2576 %  The format of the NTTruncateFile method is:
2577 %
2578 %      int NTTruncateFile(int file,off_t length)
2579 %
2580 %  A description of each parameter follows:
2581 %
2582 %    o file: the file.
2583 %
2584 %    o length: the file length.
2585 %
2586 */
2587 MagickPrivate int NTTruncateFile(int file,off_t length)
2588 {
2589   DWORD
2590     file_pointer;
2591
2592   HANDLE
2593     file_handle;
2594
2595   long
2596     high,
2597     low;
2598
2599   file_handle=(HANDLE) _get_osfhandle(file);
2600   if (file_handle == INVALID_HANDLE_VALUE)
2601     return(-1);
2602   low=(long) (length & 0xffffffffUL);
2603   high=(long) ((((MagickOffsetType) length) >> 32) & 0xffffffffUL);
2604   file_pointer=SetFilePointer(file_handle,low,&high,FILE_BEGIN);
2605   if ((file_pointer == 0xFFFFFFFF) && (GetLastError() != NO_ERROR))
2606     return(-1);
2607   if (SetEndOfFile(file_handle) == 0)
2608     return(-1);
2609   return(0);
2610 }
2611 \f
2612 /*
2613 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2614 %                                                                             %
2615 %                                                                             %
2616 %                                                                             %
2617 +  N T U n m a p M e m o r y                                                  %
2618 %                                                                             %
2619 %                                                                             %
2620 %                                                                             %
2621 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2622 %
2623 %  NTUnmapMemory() emulates the Unix munmap method.
2624 %
2625 %  The format of the NTUnmapMemory method is:
2626 %
2627 %      int NTUnmapMemory(void *map,size_t length)
2628 %
2629 %  A description of each parameter follows:
2630 %
2631 %    o map: the address of the binary large object.
2632 %
2633 %    o length: the length of the binary large object.
2634 %
2635 */
2636 MagickPrivate int NTUnmapMemory(void *map,size_t length)
2637 {
2638   (void) length;
2639   if (UnmapViewOfFile(map) == 0)
2640     return(-1);
2641   return(0);
2642 }
2643 \f
2644 /*
2645 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2646 %                                                                             %
2647 %                                                                             %
2648 %                                                                             %
2649 %   N T U s e r T i m e                                                       %
2650 %                                                                             %
2651 %                                                                             %
2652 %                                                                             %
2653 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2654 %
2655 %  NTUserTime() returns the total time the process has been scheduled (e.g.
2656 %  seconds) since the last call to StartTimer().
2657 %
2658 %  The format of the UserTime method is:
2659 %
2660 %      double NTUserTime(void)
2661 %
2662 */
2663 MagickPrivate double NTUserTime(void)
2664 {
2665   DWORD
2666     status;
2667
2668   FILETIME
2669     create_time,
2670     exit_time;
2671
2672   OSVERSIONINFO
2673     OsVersionInfo;
2674
2675   union
2676   {
2677     FILETIME
2678       filetime;
2679
2680     __int64
2681       filetime64;
2682   } kernel_time;
2683
2684   union
2685   {
2686     FILETIME
2687       filetime;
2688
2689     __int64
2690       filetime64;
2691   } user_time;
2692
2693   OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
2694   GetVersionEx(&OsVersionInfo);
2695   if (OsVersionInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
2696     return(NTElapsedTime());
2697   status=GetProcessTimes(GetCurrentProcess(),&create_time,&exit_time,
2698     &kernel_time.filetime,&user_time.filetime);
2699   if (status != TRUE)
2700     return(0.0);
2701   return((double) 1.0e-7*(kernel_time.filetime64+user_time.filetime64));
2702 }
2703 \f
2704 /*
2705 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2706 %                                                                             %
2707 %                                                                             %
2708 %                                                                             %
2709 %   N T W a r n i n g H a n d l e r                                           %
2710 %                                                                             %
2711 %                                                                             %
2712 %                                                                             %
2713 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2714 %
2715 %  NTWarningHandler() displays a warning reason.
2716 %
2717 %  The format of the NTWarningHandler method is:
2718 %
2719 %      void NTWarningHandler(const ExceptionType severity,const char *reason,
2720 %        const char *description)
2721 %
2722 %  A description of each parameter follows:
2723 %
2724 %    o severity: Specifies the numeric warning category.
2725 %
2726 %    o reason: Specifies the reason to display before terminating the
2727 %      program.
2728 %
2729 %    o description: Specifies any description to the reason.
2730 %
2731 */
2732 MagickPrivate void NTWarningHandler(const ExceptionType severity,
2733   const char *reason,const char *description)
2734 {
2735   char
2736     buffer[2*MagickPathExtent];
2737
2738   (void) severity;
2739   if (reason == (char *) NULL)
2740     return;
2741   if (description == (char *) NULL)
2742     (void) FormatLocaleString(buffer,MagickPathExtent,"%s: %s.\n",GetClientName(),
2743       reason);
2744   else
2745     (void) FormatLocaleString(buffer,MagickPathExtent,"%s: %s (%s).\n",
2746       GetClientName(),reason,description);
2747   (void) MessageBox(NULL,buffer,"ImageMagick Warning",MB_OK | MB_TASKMODAL |
2748     MB_SETFOREGROUND | MB_ICONINFORMATION);
2749 }
2750 \f
2751 /*
2752 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2753 %                                                                             %
2754 %                                                                             %
2755 %                                                                             %
2756 %   N T W i n d o w s G e n e s i s                                           %
2757 %                                                                             %
2758 %                                                                             %
2759 %                                                                             %
2760 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2761 %
2762 %  NTWindowsGenesis() initializes the MagickCore Windows environment.
2763 %
2764 %  The format of the NTWindowsGenesis method is:
2765 %
2766 %      void NTWindowsGenesis(void)
2767 %
2768 */
2769
2770 static LONG WINAPI NTUncaughtException(EXCEPTION_POINTERS *info)
2771 {
2772   magick_unreferenced(info);
2773   AsynchronousResourceComponentTerminus();
2774   return(EXCEPTION_CONTINUE_SEARCH);
2775 }
2776
2777 MagickPrivate void NTWindowsGenesis(void)
2778 {
2779   char
2780     *mode;
2781
2782   SetUnhandledExceptionFilter(NTUncaughtException);
2783   mode=GetEnvironmentValue("MAGICK_ERRORMODE");
2784   if (mode != (char *) NULL)
2785     {
2786       (void) SetErrorMode(StringToInteger(mode));
2787       mode=DestroyString(mode);
2788     }
2789 #if defined(_DEBUG) && !defined(__BORLANDC__) && !defined(__MINGW32__)
2790   if (IsEventLogging() != MagickFalse)
2791     {
2792       int
2793         debug;
2794
2795       debug=_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
2796       debug|=_CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_DELAY_FREE_MEM_DF |
2797         _CRTDBG_LEAK_CHECK_DF;
2798       (void) _CrtSetDbgFlag(debug);
2799       _ASSERTE(_CrtCheckMemory());
2800     }
2801 #endif
2802 #if defined(MAGICKCORE_INSTALLED_SUPPORT)
2803   {
2804     unsigned char
2805       *path;
2806
2807     path=NTRegistryKeyLookup("LibPath");
2808     if (path != (unsigned char *) NULL)
2809       {
2810         size_t
2811           length;
2812
2813         wchar_t
2814           lib_path[MagickPathExtent];
2815
2816         length=MultiByteToWideChar(CP_UTF8,0,(char *) path,-1,lib_path,
2817           MagickPathExtent);
2818         if (length != 0)
2819           SetDllDirectoryW(lib_path);
2820         path=(unsigned char *) RelinquishMagickMemory(path);
2821       }
2822   }
2823 #endif
2824 }
2825 \f
2826 /*
2827 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2828 %                                                                             %
2829 %                                                                             %
2830 %                                                                             %
2831 %   N T W i n d o w s T e r m i n u s                                         %
2832 %                                                                             %
2833 %                                                                             %
2834 %                                                                             %
2835 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2836 %
2837 %  NTWindowsTerminus() terminates the MagickCore Windows environment.
2838 %
2839 %  The format of the NTWindowsTerminus method is:
2840 %
2841 %      void NTWindowsTerminus(void)
2842 %
2843 */
2844 MagickPrivate void NTWindowsTerminus(void)
2845 {
2846   NTGhostscriptUnLoadDLL();
2847   if (winsock_semaphore == (SemaphoreInfo *) NULL)
2848     ActivateSemaphoreInfo(&winsock_semaphore);
2849   LockSemaphoreInfo(winsock_semaphore);
2850   if (wsaData != (WSADATA *) NULL)
2851     {
2852       WSACleanup();
2853       wsaData=(WSADATA *) RelinquishMagickMemory((void *) wsaData);
2854     }
2855   UnlockSemaphoreInfo(winsock_semaphore);
2856   RelinquishSemaphoreInfo(&winsock_semaphore);
2857 }
2858 #endif