]> granicus.if.org Git - imagemagick/blob - magick/utility.c
(no commit message)
[imagemagick] / magick / utility.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %             U   U  TTTTT  IIIII  L      IIIII  TTTTT  Y   Y                 %
7 %             U   U    T      I    L        I      T     Y Y                  %
8 %             U   U    T      I    L        I      T      Y                   %
9 %             U   U    T      I    L        I      T      Y                   %
10 %              UUU     T    IIIII  LLLLL  IIIII    T      Y                   %
11 %                                                                             %
12 %                                                                             %
13 %                       MagickCore Utility Methods                            %
14 %                                                                             %
15 %                             Software Design                                 %
16 %                               John Cristy                                   %
17 %                              January 1993                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2010 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 %    http://www.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 \f
39 /*
40   Include declarations.
41 */
42 #include "magick/studio.h"
43 #include "magick/property.h"
44 #include "magick/blob.h"
45 #include "magick/color.h"
46 #include "magick/exception.h"
47 #include "magick/exception-private.h"
48 #include "magick/geometry.h"
49 #include "magick/list.h"
50 #include "magick/log.h"
51 #include "magick/memory_.h"
52 #include "magick/option.h"
53 #include "magick/policy.h"
54 #include "magick/resource_.h"
55 #include "magick/semaphore.h"
56 #include "magick/signature-private.h"
57 #include "magick/statistic.h"
58 #include "magick/string_.h"
59 #include "magick/token.h"
60 #include "magick/utility.h"
61 #if defined(MAGICKCORE_HAVE_PROCESS_H)
62 #include <process.h>
63 #endif
64 #if defined(MAGICKCORE_HAVE_MACH_O_DYLD_H)
65 #include <mach-o/dyld.h>
66 #endif
67 \f
68 /*
69   Static declarations.
70 */
71 static const char
72   Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
73 \f
74 /*
75   Forward declaration.
76 */
77 static int
78   IsPathDirectory(const char *);
79 \f
80 /*
81 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
82 %                                                                             %
83 %                                                                             %
84 %                                                                             %
85 %   A c q u i r e U n i q u e F i l e n a m e                                 %
86 %                                                                             %
87 %                                                                             %
88 %                                                                             %
89 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
90 %
91 %  AcquireUniqueFilename() replaces the contents of path by a unique path name.
92 %
93 %  The format of the AcquireUniqueFilename method is:
94 %
95 %      MagickBooleanType AcquireUniqueFilename(char *path)
96 %
97 %  A description of each parameter follows.
98 %
99 %   o  path:  Specifies a pointer to an array of characters.  The unique path
100 %      name is returned in this array.
101 %
102 */
103 MagickExport MagickBooleanType AcquireUniqueFilename(char *path)
104 {
105   int
106     file;
107
108   file=AcquireUniqueFileResource(path);
109   if (file == -1)
110     return(MagickFalse);
111   file=close(file)-1;
112   return(MagickTrue);
113 }
114 \f
115 /*
116 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
117 %                                                                             %
118 %                                                                             %
119 %                                                                             %
120 %   A c q u i r e U n i q u e S ym b o l i c L i n k                          %
121 %                                                                             %
122 %                                                                             %
123 %                                                                             %
124 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
125 %
126 %  AcquireUniqueSymbolicLink() creates a unique symbolic link to the specified
127 %  source path and returns MagickTrue on success otherwise MagickFalse.  If the
128 %  symlink() method fails or is not available, a unique file name is generated
129 %  and the source file copied to it.  When you are finished with the file, use
130 %  RelinquishUniqueFilename() to destroy it.
131 %
132 %  The format of the AcquireUniqueSymbolicLink method is:
133 %
134 %      MagickBooleanType AcquireUniqueSymbolicLink(const char *source,
135 %        char destination)
136 %
137 %  A description of each parameter follows.
138 %
139 %   o  source:  the source path.
140 %
141 %   o  destination:  the destination path.
142 %
143 */
144
145 static inline size_t MagickMin(const size_t x,const size_t y)
146 {
147   if (x < y)
148     return(x);
149   return(y);
150 }
151
152 MagickExport MagickBooleanType AcquireUniqueSymbolicLink(const char *source,
153   char *destination)
154 {
155   int
156     destination_file,
157     source_file;
158
159   size_t
160     length,
161     quantum;
162
163   ssize_t
164     count;
165
166   struct stat
167     attributes;
168
169   unsigned char
170     *buffer;
171
172   assert(source != (const char *) NULL);
173   assert(destination != (char *) NULL);
174 #if defined(MAGICKCORE_HAVE_SYMLINK)
175   (void) AcquireUniqueFilename(destination);
176   (void) RelinquishUniqueFileResource(destination);
177   if (*source == *DirectorySeparator)
178     {
179       if (symlink(source,destination) == 0)
180         return(MagickTrue);
181     }
182   else
183     {
184       char
185         path[MaxTextExtent];
186
187       *path='\0';
188       if (getcwd(path,MaxTextExtent) == (char *) NULL)
189         return(MagickFalse);
190       (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);
191       (void) ConcatenateMagickString(path,source,MaxTextExtent);
192       if (symlink(path,destination) == 0)
193         return(MagickTrue);
194     }
195 #endif
196   destination_file=AcquireUniqueFileResource(destination);
197   if (destination_file == -1)
198     return(MagickFalse);
199   source_file=open(source,O_RDONLY | O_BINARY);
200   if (source_file == -1)
201     {
202       (void) close(destination_file);
203       (void) RelinquishUniqueFileResource(destination);
204       return(MagickFalse);
205     }
206   quantum=(size_t) MagickMaxBufferExtent;
207   if ((fstat(source_file,&attributes) == 0) && (attributes.st_size != 0))
208     quantum=MagickMin((size_t) attributes.st_size,MagickMaxBufferExtent);
209   buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer));
210   if (buffer == (unsigned char *) NULL)
211     {
212       (void) close(source_file);
213       (void) close(destination_file);
214       (void) RelinquishUniqueFileResource(destination);
215       return(MagickFalse);
216     }
217   for (length=0; ; )
218   {
219     count=(ssize_t) read(source_file,buffer,quantum);
220     if (count <= 0)
221       break;
222     length=(size_t) count;
223     count=(ssize_t) write(destination_file,buffer,length);
224     if ((size_t) count != length)
225       {
226         (void) close(destination_file);
227         (void) close(source_file);
228         buffer=(unsigned char *) RelinquishMagickMemory(buffer);
229         (void) RelinquishUniqueFileResource(destination);
230         return(MagickFalse);
231       }
232   }
233   (void) close(destination_file);
234   (void) close(source_file);
235   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
236   return(MagickTrue);
237 }
238 \f
239 /*
240 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
241 %                                                                             %
242 %                                                                             %
243 %                                                                             %
244 %  A p p e n d I m a g e F o r m a t                                          %
245 %                                                                             %
246 %                                                                             %
247 %                                                                             %
248 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
249 %
250 %  AppendImageFormat() appends the image format type to the filename.  If an
251 %  extension to the file already exists, it is first removed.
252 %
253 %  The format of the AppendImageFormat method is:
254 %
255 %      void AppendImageFormat(const char *format,char *filename)
256 %
257 %  A description of each parameter follows.
258 %
259 %   o  format:  Specifies a pointer to an array of characters.  This the
260 %      format of the image.
261 %
262 %   o  filename:  Specifies a pointer to an array of characters.  The unique
263 %      file name is returned in this array.
264 %
265 */
266 MagickExport void AppendImageFormat(const char *format,char *filename)
267 {
268   char
269     root[MaxTextExtent];
270
271   assert(format != (char *) NULL);
272   assert(filename != (char *) NULL);
273   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename);
274   if ((*format == '\0') || (*filename == '\0'))
275     return;
276   if (LocaleCompare(filename,"-") == 0)
277     {
278       char
279         message[MaxTextExtent];
280
281       (void) FormatMagickString(message,MaxTextExtent,"%s:%s",format,filename);
282       (void) CopyMagickString(filename,message,MaxTextExtent);
283       return;
284     }
285   GetPathComponent(filename,RootPath,root);
286   (void) FormatMagickString(filename,MaxTextExtent,"%s.%s",root,format);
287 }
288 \f
289 /*
290 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
291 %                                                                             %
292 %                                                                             %
293 %                                                                             %
294 %   B a s e 6 4 D e c o d e                                                   %
295 %                                                                             %
296 %                                                                             %
297 %                                                                             %
298 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
299 %
300 %  Base64Decode() decodes Base64-encoded text and returns its binary
301 %  equivalent.  NULL is returned if the text is not valid Base64 data, or a
302 %  memory allocation failure occurs.
303 %
304 %  The format of the Base64Decode method is:
305 %
306 %      unsigned char *Base64Decode(const char *source,length_t *length)
307 %
308 %  A description of each parameter follows:
309 %
310 %    o source:  A pointer to a Base64-encoded string.
311 %
312 %    o length: the number of bytes decoded.
313 %
314 */
315 MagickExport unsigned char *Base64Decode(const char *source,size_t *length)
316 {
317   int
318     state;
319
320   register const char
321     *p,
322     *q;
323
324   register size_t
325     i;
326
327   unsigned char
328     *decode;
329
330   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
331   assert(source != (char *) NULL);
332   assert(length != (size_t *) NULL);
333   *length=0;
334   decode=(unsigned char *) AcquireQuantumMemory(strlen(source)/4+4,
335     3*sizeof(*decode));
336   if (decode == (unsigned char *) NULL)
337     return((unsigned char *) NULL);
338   i=0;
339   state=0;
340   for (p=source; *p != '\0'; p++)
341   {
342     if (isspace((int) ((unsigned char) *p)) != 0)
343       continue;
344     if (*p == '=')
345       break;
346     q=strchr(Base64,*p);
347     if (q == (char *) NULL)
348       {
349         decode=(unsigned char *) RelinquishMagickMemory(decode);
350         return((unsigned char *) NULL);  /* non-Base64 character */
351       }
352     switch (state)
353     {
354       case 0:
355       {
356         decode[i]=(q-Base64) << 2;
357         state++;
358         break;
359       }
360       case 1:
361       {
362         decode[i++]|=(q-Base64) >> 4;
363         decode[i]=((q-Base64) & 0x0f) << 4;
364         state++;
365         break;
366       }
367       case 2:
368       {
369         decode[i++]|=(q-Base64) >> 2;
370         decode[i]=((q-Base64) & 0x03) << 6;
371         state++;
372         break;
373       }
374       case 3:
375       {
376         decode[i++]|=(q-Base64);
377         state=0;
378         break;
379       }
380     }
381   }
382   /*
383     Verify Base-64 string has proper terminal characters.
384   */
385   if (*p != '=')
386     {
387       if (state != 0)
388         {
389           decode=(unsigned char *) RelinquishMagickMemory(decode);
390           return((unsigned char *) NULL);
391         }
392     }
393   else
394     {
395       p++;
396       switch (state)
397       {
398         case 0:
399         case 1:
400         {
401           /*
402             Unrecognized '=' character.
403           */
404           decode=(unsigned char *) RelinquishMagickMemory(decode);
405           return((unsigned char *) NULL);
406         }
407         case 2:
408         {
409           for ( ; *p != '\0'; p++)
410             if (isspace((int) ((unsigned char) *p)) == 0)
411               break;
412           if (*p != '=')
413             {
414               decode=(unsigned char *) RelinquishMagickMemory(decode);
415               return((unsigned char *) NULL);
416             }
417           p++;
418         }
419         case 3:
420         {
421           for ( ; *p != '\0'; p++)
422             if (isspace((int) ((unsigned char) *p)) == 0)
423               {
424                 decode=(unsigned char *) RelinquishMagickMemory(decode);
425                 return((unsigned char *) NULL);
426               }
427           if ((int) decode[i] != 0)
428             {
429               decode=(unsigned char *) RelinquishMagickMemory(decode);
430               return((unsigned char *) NULL);
431             }
432         }
433       }
434     }
435   *length=i;
436   return(decode);
437 }
438 \f
439 /*
440 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
441 %                                                                             %
442 %                                                                             %
443 %                                                                             %
444 %   B a s e 6 4 E n c o d e                                                   %
445 %                                                                             %
446 %                                                                             %
447 %                                                                             %
448 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
449 %
450 %  Base64Encode() encodes arbitrary binary data to Base64 encoded format as
451 %  described by the "Base64 Content-Transfer-Encoding" section of RFC 2045 and
452 %  returns the result as a null-terminated ASCII string.  NULL is returned if
453 %  a memory allocation failure occurs.
454 %
455 %  The format of the Base64Encode method is:
456 %
457 %      char *Base64Encode(const unsigned char *blob,const size_t blob_length,
458 %        size_t *encode_length)
459 %
460 %  A description of each parameter follows:
461 %
462 %    o blob:  A pointer to binary data to encode.
463 %
464 %    o blob_length: the number of bytes to encode.
465 %
466 %    o encode_length:  The number of bytes encoded.
467 %
468 */
469 MagickExport char *Base64Encode(const unsigned char *blob,
470   const size_t blob_length,size_t *encode_length)
471 {
472   char
473     *encode;
474
475   register const unsigned char
476     *p;
477
478   register size_t
479     i;
480
481   size_t
482     remainder;
483
484   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
485   assert(blob != (const unsigned char *) NULL);
486   assert(blob_length != 0);
487   assert(encode_length != (size_t *) NULL);
488   *encode_length=0;
489   encode=(char *) AcquireQuantumMemory(blob_length/3+4,4*sizeof(*encode));
490   if (encode == (char *) NULL)
491     return((char *) NULL);
492   i=0;
493   for (p=blob; p < (blob+blob_length-2); p+=3)
494   {
495     encode[i++]=Base64[(int) (*p >> 2)];
496     encode[i++]=Base64[(int) (((*p & 0x03) << 4)+(*(p+1) >> 4))];
497     encode[i++]=Base64[(int) (((*(p+1) & 0x0f) << 2)+(*(p+2) >> 6))];
498     encode[i++]=Base64[(int) (*(p+2) & 0x3f)];
499   }
500   remainder=blob_length % 3;
501   if (remainder != 0)
502     {
503       long
504         j;
505
506       unsigned char
507         code[3];
508
509       code[0]='\0';
510       code[1]='\0';
511       code[2]='\0';
512       for (j=0; j < (long) remainder; j++)
513         code[j]=(*p++);
514       encode[i++]=Base64[(int) (code[0] >> 2)];
515       encode[i++]=Base64[(int) (((code[0] & 0x03) << 4)+(code[1] >> 4))];
516       if (remainder == 1)
517         encode[i++]='=';
518       else
519         encode[i++]=Base64[(int) (((code[1] & 0x0f) << 2)+(code[2] >> 6))];
520       encode[i++]='=';
521     }
522   *encode_length=i;
523   encode[i++]='\0';
524   return(encode);
525 }
526 \f
527 /*
528 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
529 %                                                                             %
530 %                                                                             %
531 %                                                                             %
532 %   C h o p P a t h C o m p o n e n t s                                       %
533 %                                                                             %
534 %                                                                             %
535 %                                                                             %
536 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
537 %
538 %  ChopPathComponents() removes the number of specified file components from a
539 %  path.
540 %
541 %  The format of the ChopPathComponents method is:
542 %
543 %      ChopPathComponents(char *path,unsigned long components)
544 %
545 %  A description of each parameter follows:
546 %
547 %    o path:  The path.
548 %
549 %    o components:  The number of components to chop.
550 %
551 */
552 MagickExport void ChopPathComponents(char *path,const unsigned long components)
553 {
554   register long
555     i;
556
557   for (i=0; i < (long) components; i++)
558     GetPathComponent(path,HeadPath,path);
559 }
560 \f
561 /*
562 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
563 %                                                                             %
564 %                                                                             %
565 %                                                                             %
566 %   E x p a n d F i l e n a m e                                               %
567 %                                                                             %
568 %                                                                             %
569 %                                                                             %
570 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
571 %
572 %  ExpandFilename() expands '~' in a path.
573 %
574 %  The format of the ExpandFilename function is:
575 %
576 %      ExpandFilename(char *path)
577 %
578 %  A description of each parameter follows:
579 %
580 %    o path: Specifies a pointer to a character array that contains the
581 %      path.
582 %
583 */
584 MagickExport void ExpandFilename(char *path)
585 {
586   char
587     expand_path[MaxTextExtent];
588
589   if (path == (char *) NULL)
590     return;
591   if (*path != '~')
592     return;
593   (void) CopyMagickString(expand_path,path,MaxTextExtent);
594   if ((*(path+1) == *DirectorySeparator) || (*(path+1) == '\0'))
595     {
596       char
597         *home;
598
599       /*
600         Substitute ~ with $HOME.
601       */
602       (void) CopyMagickString(expand_path,".",MaxTextExtent);
603       (void) ConcatenateMagickString(expand_path,path+1,MaxTextExtent);
604       home=GetEnvironmentValue("HOME");
605       if (home == (char *) NULL)
606         home=GetEnvironmentValue("USERPROFILE");
607       if (home != (char *) NULL)
608         {
609           (void) CopyMagickString(expand_path,home,MaxTextExtent);
610           (void) ConcatenateMagickString(expand_path,path+1,MaxTextExtent);
611           home=DestroyString(home);
612         }
613     }
614   else
615     {
616 #if defined(MAGICKCORE_POSIX_SUPPORT) && !defined(__OS2__)
617       char
618         username[MaxTextExtent];
619
620       register char
621         *p;
622
623       struct passwd
624         *entry;
625
626       /*
627         Substitute ~ with home directory from password file.
628       */
629       (void) CopyMagickString(username,path+1,MaxTextExtent);
630       p=strchr(username,'/');
631       if (p != (char *) NULL)
632         *p='\0';
633       entry=getpwnam(username);
634       if (entry == (struct passwd *) NULL)
635         return;
636       (void) CopyMagickString(expand_path,entry->pw_dir,MaxTextExtent);
637       if (p != (char *) NULL)
638         {
639           (void) ConcatenateMagickString(expand_path,"/",MaxTextExtent);
640           (void) ConcatenateMagickString(expand_path,p+1,MaxTextExtent);
641         }
642 #endif
643     }
644   (void) CopyMagickString(path,expand_path,MaxTextExtent);
645 }
646 \f
647 /*
648 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
649 %                                                                             %
650 %                                                                             %
651 %                                                                             %
652 %   E x p a n d F i l e n a m e s                                             %
653 %                                                                             %
654 %                                                                             %
655 %                                                                             %
656 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
657 %
658 %  ExpandFilenames() checks each argument of the command line vector and
659 %  expands it if they have a wildcard character.  For example, *.jpg might
660 %  expand to:  bird.jpg rose.jpg tiki.jpg.
661 %
662 %  The format of the ExpandFilenames function is:
663 %
664 %      status=ExpandFilenames(int *number_arguments,char ***arguments)
665 %
666 %  A description of each parameter follows:
667 %
668 %    o number_arguments: Specifies a pointer to an integer describing the
669 %      number of elements in the argument vector.
670 %
671 %    o arguments: Specifies a pointer to a text array containing the command
672 %      line arguments.
673 %
674 */
675 MagickExport MagickBooleanType ExpandFilenames(int *number_arguments,
676   char ***arguments)
677 {
678   char
679     *cwd,
680     home_directory[MaxTextExtent],
681     **vector;
682
683   long
684     count,
685     parameters;
686
687   register long
688     i,
689     j;
690
691   unsigned long
692     number_files;
693
694   /*
695     Allocate argument vector.
696   */
697   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
698   assert(number_arguments != (int *) NULL);
699   assert(arguments != (char ***) NULL);
700   vector=(char **) AcquireQuantumMemory((size_t) (*number_arguments+1),
701     sizeof(*vector));
702   if (vector == (char **) NULL)
703     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
704   /*
705     Expand any wildcard filenames.
706   */
707   *home_directory='\0';
708   count=0;
709   for (i=0; i < (long) *number_arguments; i++)
710   {
711     char
712       **filelist,
713       filename[MaxTextExtent],
714       magick[MaxTextExtent],
715       *option,
716       path[MaxTextExtent],
717       subimage[MaxTextExtent];
718
719     MagickBooleanType
720       destroy;
721
722     option=(*arguments)[i];
723     *magick='\0';
724     *path='\0';
725     *filename='\0';
726     *subimage='\0';
727     vector[count++]=ConstantString(option);
728     destroy=MagickTrue;
729     parameters=ParseMagickOption(MagickCommandOptions,MagickFalse,option);
730     if (parameters > 0)
731       {
732         /*
733           Do not expand command option parameters.
734         */
735         for (j=0; j < parameters; j++)
736         {
737           i++;
738           if (i == (long) *number_arguments)
739             break;
740           option=(*arguments)[i];
741           vector[count++]=ConstantString(option);
742         }
743         continue;
744       }
745     if ((*option == '"') || (*option == '\''))
746       continue;
747     GetPathComponent(option,TailPath,filename);
748     GetPathComponent(option,MagickPath,magick);
749     if ((LocaleCompare(magick,"CAPTION") == 0) ||
750         (LocaleCompare(magick,"LABEL") == 0) ||
751         (LocaleCompare(magick,"VID") == 0))
752       continue;
753     if ((IsGlob(filename) == MagickFalse) && (*filename != '@'))
754       continue;
755     if (*filename != '@')
756       {
757         /*
758           Generate file list from wildcard filename (e.g. *.jpg).
759         */
760         GetPathComponent(option,HeadPath,path);
761         GetPathComponent(option,SubimagePath,subimage);
762         ExpandFilename(path);
763         if (*home_directory == '\0')
764           cwd=getcwd(home_directory,MaxTextExtent-1);
765         filelist=ListFiles(*path == '\0' ? home_directory : path,filename,
766           &number_files);
767       }
768     else
769       {
770         char
771           *files;
772
773         ExceptionInfo
774           *exception;
775
776         int
777           number_images;
778
779         /*
780           Generate file list from file list (e.g. @filelist.txt).
781         */
782         exception=AcquireExceptionInfo();
783         files=FileToString(filename+1,~0,exception);
784         exception=DestroyExceptionInfo(exception);
785         if (files == (char *) NULL)
786           continue;
787         StripString(files);
788         filelist=StringToArgv(files,&number_images);
789         files=DestroyString(files);
790         number_files=(unsigned long) number_images;
791         if (filelist != (char **) NULL)
792           {
793             number_files--;
794             for (j=0; j < (long) number_files; j++)
795               filelist[j]=filelist[j+1];
796           }
797         count--;
798       }
799     if (filelist == (char **) NULL)
800       continue;
801     for (j=0; j < (long) number_files; j++)
802       if (IsPathDirectory(filelist[j]) <= 0)
803         break;
804     if (j == (long) number_files)
805       {
806         for (j=0; j < (long) number_files; j++)
807           filelist[j]=DestroyString(filelist[j]);
808         filelist=(char **) RelinquishMagickMemory(filelist);
809         continue;
810       }
811     /*
812       Transfer file list to argument vector.
813     */
814     vector=(char **) ResizeQuantumMemory(vector,(size_t) *number_arguments+
815       count+number_files+1,sizeof(*vector));
816     if (vector == (char **) NULL)
817       return(MagickFalse);
818     for (j=0; j < (long) number_files; j++)
819     {
820       option=filelist[j];
821       parameters=ParseMagickOption(MagickCommandOptions,MagickFalse,option);
822       if (parameters > 0)
823         {
824           long
825             k;
826
827           /*
828             Do not expand command option parameters.
829           */
830           vector[count++]=ConstantString(option);
831           for (k=0; k < parameters; k++)
832           {
833             j++;
834             if (j == (long) number_files)
835               break;
836             option=filelist[j];
837             vector[count++]=ConstantString(option);
838           }
839           continue;
840         }
841       (void) CopyMagickString(filename,path,MaxTextExtent);
842       if (*path != '\0')
843         (void) ConcatenateMagickString(filename,DirectorySeparator,
844           MaxTextExtent);
845       (void) ConcatenateMagickString(filename,filelist[j],MaxTextExtent);
846       filelist[j]=DestroyString(filelist[j]);
847       if (strlen(filename) >= (MaxTextExtent-1))
848         ThrowFatalException(OptionFatalError,"FilenameTruncated");
849       if (IsPathDirectory(filename) <= 0)
850         {
851           char
852             path[MaxTextExtent];
853
854           *path='\0';
855           if (*magick != '\0')
856             {
857               (void) ConcatenateMagickString(path,magick,MaxTextExtent);
858               (void) ConcatenateMagickString(path,":",MaxTextExtent);
859             }
860           (void) ConcatenateMagickString(path,filename,MaxTextExtent);
861           if (*subimage != '\0')
862             {
863               (void) ConcatenateMagickString(path,"[",MaxTextExtent);
864               (void) ConcatenateMagickString(path,subimage,MaxTextExtent);
865               (void) ConcatenateMagickString(path,"]",MaxTextExtent);
866             }
867           if (strlen(path) >= MaxTextExtent)
868             ThrowFatalException(OptionFatalError,"FilenameTruncated");
869           if (destroy != MagickFalse)
870             {
871               count--;
872               vector[count]=DestroyString(vector[count]);
873               destroy=MagickFalse;
874             }
875           vector[count++]=ConstantString(path);
876         }
877     }
878     filelist=(char **) RelinquishMagickMemory(filelist);
879   }
880   vector[count]=(char *) NULL;
881   if (IsEventLogging() != MagickFalse)
882     {
883       char
884         *command_line;
885
886       command_line=AcquireString(vector[0]);
887       for (i=1; i < count; i++)
888       {
889         (void) ConcatenateString(&command_line," {");
890         (void) ConcatenateString(&command_line,vector[i]);
891         (void) ConcatenateString(&command_line,"}");
892       }
893       (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
894         "Command line: %s",command_line);
895       command_line=DestroyString(command_line);
896     }
897   *number_arguments=(int) count;
898   *arguments=vector;
899   return(MagickTrue);
900 }
901 \f
902 /*
903 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
904 %                                                                             %
905 %                                                                             %
906 %                                                                             %
907 %   G e t E x e c u t i o n P a t h                                           %
908 %                                                                             %
909 %                                                                             %
910 %                                                                             %
911 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
912 %
913 %  GetExecutionPath() returns the pathname of the executable that started
914 %  the process.  On success MagickTrue is returned, otherwise MagickFalse.
915 %
916 %  The format of the GetExecutionPath method is:
917 %
918 %      MagickBooleanType GetExecutionPath(char *path,const size_t extent)
919 %
920 %  A description of each parameter follows:
921 %
922 %    o path: the pathname of the executable that started the process.
923 %
924 %    o extent: the maximum extent of the path.
925 %
926 */
927 MagickExport MagickBooleanType GetExecutionPath(char *path,const size_t extent)
928 {
929   char
930     *cwd;
931
932   *path='\0';
933   cwd=getcwd(path,(unsigned long) extent);
934 #if defined(MAGICKCORE_HAVE_GETPID) && defined(MAGICKCORE_HAVE_READLINK) && defined(PATH_MAX)
935   {
936     char
937       link_path[MaxTextExtent],
938       execution_path[PATH_MAX+1];
939
940     ssize_t
941       count;
942
943     (void) FormatMagickString(link_path,MaxTextExtent,"/proc/%ld/exe",
944       (long) getpid());
945     count=readlink(link_path,execution_path,PATH_MAX);
946     if (count == -1)
947       {
948         (void) FormatMagickString(link_path,MaxTextExtent,"/proc/%ld/file",
949           (long) getpid());
950         count=readlink(link_path,execution_path,PATH_MAX);
951       }
952     if ((count > 0) && (count <= (ssize_t) PATH_MAX))
953       {
954         execution_path[count]='\0';
955         (void) CopyMagickString(path,execution_path,extent);
956       }
957   }
958 #endif
959 #if defined(MAGICKCORE_HAVE__NSGETEXECUTABLEPATH)
960   {
961     char
962       executable_path[PATH_MAX << 1],
963       execution_path[PATH_MAX+1];
964
965     uint32_t
966       length;
967
968     length=sizeof(executable_path);
969     if ((_NSGetExecutablePath(executable_path,&length) == 0) &&
970         (realpath(executable_path,execution_path) != (char *) NULL))
971       (void) CopyMagickString(path,execution_path,extent);
972   }
973 #endif
974 #if defined(MAGICKCORE_HAVE_GETEXECNAME)
975   {
976     const char
977       *execution_path;
978
979     execution_path=(const char *) getexecname();
980     if (execution_path != (const char *) NULL)
981       {
982         if (*execution_path != *DirectorySeparator)
983           (void) ConcatenateMagickString(path,DirectorySeparator,extent);
984         (void) ConcatenateMagickString(path,execution_path,extent);
985       }
986   }
987 #endif
988 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
989   NTGetExecutionPath(path,extent);
990 #endif
991 #if defined(__GNU__)
992   {
993     char
994       *program_name,
995       *execution_path;
996
997     long
998       count;
999
1000     count=0;
1001     execution_path=(char *) NULL;
1002     program_name=program_invocation_name;
1003     if (*program_invocation_name != '/')
1004       {
1005         size_t
1006           extent;
1007
1008         extent=strlen(cwd)+strlen(program_name)+1;
1009         program_name=AcquireQuantumMemory(extent,sizeof(*program_name));
1010         if (program_name == (char *) NULL)
1011           program_name=program_invocation_name;
1012         else
1013           count=FormatMagickString(program_name,extent,"%s/%s",cwd,
1014             program_invocation_name);
1015       }
1016     if (count != -1)
1017       {
1018         execution_path=realpath(program_name,NULL);
1019         if (execution_path != (char *) NULL)
1020           (void) CopyMagickString(path,execution_path,extent);
1021       }
1022     if (program_name != program_invocation_name)
1023       program_name=(char *) RelinquishMagickMemory(program_name);
1024     execution_path=(char *) RelinquishMagickMemory(execution_path);
1025   }
1026 #endif
1027   return(IsPathAccessible(path));
1028 }
1029 \f
1030 /*
1031 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1032 %                                                                             %
1033 %                                                                             %
1034 %                                                                             %
1035 %   G e t M a g i c k P a g e S i z e                                         %
1036 %                                                                             %
1037 %                                                                             %
1038 %                                                                             %
1039 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1040 %
1041 %  GetMagickPageSize() returns the memory page size.
1042 %
1043 %  The format of the GetMagickPageSize method is:
1044 %
1045 %      long GetMagickPageSize()
1046 %
1047 */
1048 MagickExport long GetMagickPageSize(void)
1049 {
1050   static long
1051     page_size = -1;
1052
1053   if (page_size > 0)
1054     return(page_size);
1055 #if defined(MAGICKCORE_HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
1056   page_size=sysconf(_SC_PAGE_SIZE);
1057 #else
1058 #if defined(MAGICKCORE_HAVE_GETPAGESIZE)
1059   page_size=getpagesize();
1060 #endif
1061 #endif
1062   if (page_size <= 0)
1063     page_size=16384;
1064   return(page_size);
1065 }
1066 \f
1067 /*
1068 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1069 %                                                                             %
1070 %                                                                             %
1071 %                                                                             %
1072 %   G e t P a t h A t t r i b u t e s                                         %
1073 %                                                                             %
1074 %                                                                             %
1075 %                                                                             %
1076 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1077 %
1078 %  GetPathAttributes() returns attributes (e.g. size of file) about a path.
1079 %
1080 %  The path of the GetPathAttributes method is:
1081 %
1082 %      MagickBooleanType GetPathAttributes(const char *path,void *attributes)
1083 %
1084 %  A description of each parameter follows.
1085 %
1086 %   o  path: the file path.
1087 %
1088 %   o  attributes: the path attributes are returned here.
1089 %
1090 */
1091
1092 #if defined(MAGICKCORE_HAVE__WFOPEN)
1093 static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16)
1094 {
1095   register const unsigned char
1096     *p;
1097
1098   if (utf16 != (wchar_t *) NULL)
1099     {
1100       register wchar_t
1101         *q;
1102
1103       wchar_t
1104         c;
1105
1106       /*
1107         Convert UTF-8 to UTF-16.
1108       */
1109       q=utf16;
1110       for (p=utf8; *p != '\0'; p++)
1111       {
1112         if ((*p & 0x80) == 0)
1113           *q=(*p);
1114         else
1115           if ((*p & 0xE0) == 0xC0)
1116             {
1117               c=(*p);
1118               *q=(c & 0x1F) << 6;
1119               p++;
1120               if ((*p & 0xC0) != 0x80)
1121                 return(0);
1122               *q|=(*p & 0x3F);
1123             }
1124           else
1125             if ((*p & 0xF0) == 0xE0)
1126               {
1127                 c=(*p);
1128                 *q=c << 12;
1129                 p++;
1130                 if ((*p & 0xC0) != 0x80)
1131                   return(0);
1132                 c=(*p);
1133                 *q|=(c & 0x3F) << 6;
1134                 p++;
1135                 if ((*p & 0xC0) != 0x80)
1136                   return(0);
1137                 *q|=(*p & 0x3F);
1138               }
1139             else
1140               return(0);
1141         q++;
1142       }
1143       *q++='\0';
1144       return(q-utf16);
1145     }
1146   /*
1147     Compute UTF-16 string length.
1148   */
1149   for (p=utf8; *p != '\0'; p++)
1150   {
1151     if ((*p & 0x80) == 0)
1152       ;
1153     else
1154       if ((*p & 0xE0) == 0xC0)
1155         {
1156           p++;
1157           if ((*p & 0xC0) != 0x80)
1158             return(0);
1159         }
1160       else
1161         if ((*p & 0xF0) == 0xE0)
1162           {
1163             p++;
1164             if ((*p & 0xC0) != 0x80)
1165               return(0);
1166             p++;
1167             if ((*p & 0xC0) != 0x80)
1168               return(0);
1169          }
1170        else
1171          return(0);
1172   }
1173   return(p-utf8);
1174 }
1175
1176 static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source)
1177 {
1178   size_t
1179     length;
1180
1181   wchar_t
1182     *utf16;
1183
1184   length=UTF8ToUTF16(source,(wchar_t *) NULL);
1185   if (length == 0)
1186     {
1187       register long
1188         i;
1189
1190       /*
1191         Not UTF-8, just copy.
1192       */
1193       length=strlen((const char *) source);
1194       utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16));
1195       if (utf16 == (wchar_t *) NULL)
1196         return((wchar_t *) NULL);
1197       for (i=0; i <= (long) length; i++)
1198         utf16[i]=source[i];
1199       return(utf16);
1200     }
1201   utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16));
1202   if (utf16 == (wchar_t *) NULL)
1203     return((wchar_t *) NULL);
1204   length=UTF8ToUTF16(source,utf16);
1205   return(utf16);
1206 }
1207 #endif
1208
1209 MagickExport MagickBooleanType GetPathAttributes(const char *path,
1210   void *attributes)
1211 {
1212   MagickBooleanType
1213     status;
1214
1215   if (path == (const char *) NULL)
1216     {
1217       errno=EINVAL;
1218       return(MagickFalse);
1219     }
1220 #if !defined(MAGICKCORE_HAVE__WSTAT)
1221   status=stat(path,(struct stat *) attributes) == 0 ? MagickTrue : MagickFalse;
1222 #else
1223   {
1224     wchar_t
1225       *unicode_path;
1226
1227     unicode_path=ConvertUTF8ToUTF16((const unsigned char *) path);
1228     if (unicode_path == (wchar_t *) NULL)
1229       return(MagickFalse);
1230     status=wstat(unicode_path,(struct stat *) attributes) == 0 ? MagickTrue :
1231       MagickFalse;
1232     unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path);
1233   }
1234 #endif
1235   return(status);
1236 }
1237 \f
1238 /*
1239 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1240 %                                                                             %
1241 %                                                                             %
1242 %                                                                             %
1243 %   G e t P a t h C o m p o n e n t                                           %
1244 %                                                                             %
1245 %                                                                             %
1246 %                                                                             %
1247 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1248 %
1249 %  GetPathComponent() returns the parent directory name, filename, basename, or
1250 %  extension of a file path.
1251 %
1252 %  The format of the GetPathComponent function is:
1253 %
1254 %      GetPathComponent(const char *path,PathType type,char *component)
1255 %
1256 %  A description of each parameter follows:
1257 %
1258 %    o path: Specifies a pointer to a character array that contains the
1259 %      file path.
1260 %
1261 %    o type: Specififies which file path component to return.
1262 %
1263 %    o component: the selected file path component is returned here.
1264 %
1265 */
1266 MagickExport void GetPathComponent(const char *path,PathType type,
1267   char *component)
1268 {
1269   char
1270     magick[MaxTextExtent],
1271     *q,
1272     subimage[MaxTextExtent];
1273
1274   register char
1275     *p;
1276
1277   assert(path != (const char *) NULL);
1278   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",path);
1279   assert(component != (char *) NULL);
1280   if (*path == '\0')
1281     {
1282       *component='\0';
1283       return;
1284     }
1285   (void) CopyMagickString(component,path,MaxTextExtent);
1286   *magick='\0';
1287 #if defined(__OS2__)
1288   if (path[1] != ":")
1289 #endif
1290   for (p=component; *p != '\0'; p++)
1291   {
1292     if ((*p == '%') && (*(p+1) == '['))
1293       {
1294         /*
1295           Skip over %[...].
1296         */
1297         for (p++; (*p != ']') && (*p != '\0'); p++) ;
1298         if (*p == '\0')
1299           break;
1300       }
1301     if ((*p == ':') && (IsPathDirectory(path) < 0) &&
1302         (IsPathAccessible(path) == MagickFalse))
1303       {
1304         /*
1305           Look for image format specification (e.g. ps3:image).
1306         */
1307         (void) CopyMagickString(magick,component,(size_t) (p-component+1));
1308         if (IsMagickConflict(magick) != MagickFalse)
1309           *magick='\0';
1310         else
1311           for (q=component; *q != '\0'; q++)
1312             *q=(*++p);
1313         break;
1314       }
1315   }
1316   *subimage='\0';
1317   p=component;
1318   if (*p != '\0')
1319     p=component+strlen(component)-1;
1320   if ((*p == ']') && (strchr(component,'[') != (char *) NULL) &&
1321       (IsPathAccessible(path) == MagickFalse))
1322     {
1323       /*
1324         Look for scene specification (e.g. img0001.pcd[4]).
1325       */
1326       for (q=p-1; q > component; q--)
1327         if (*q == '[')
1328           break;
1329       if (*q == '[')
1330         {
1331           (void) CopyMagickString(subimage,q+1,MaxTextExtent);
1332           subimage[p-q-1]='\0';
1333           if ((IsSceneGeometry(subimage,MagickFalse) == MagickFalse) &&
1334               (IsGeometry(subimage) == MagickFalse))
1335             *subimage='\0';
1336           else
1337             *q='\0';
1338         }
1339     }
1340   p=component;
1341   if (*p != '\0')
1342     for (p=component+strlen(component)-1; p > component; p--)
1343       if (IsBasenameSeparator(*p) != MagickFalse)
1344         break;
1345   switch (type)
1346   {
1347     case MagickPath:
1348     {
1349       (void) CopyMagickString(component,magick,MaxTextExtent);
1350       break;
1351     }
1352     case RootPath:
1353     {
1354       for (p=component+(strlen(component)-1); p > component; p--)
1355       {
1356         if (IsBasenameSeparator(*p) != MagickFalse)
1357           break;
1358         if (*p == '.')
1359           break;
1360       }
1361       if (*p == '.')
1362         *p='\0';
1363       break;
1364     }
1365     case HeadPath:
1366     {
1367       *p='\0';
1368       break;
1369     }
1370     case TailPath:
1371     {
1372       if (IsBasenameSeparator(*p) != MagickFalse)
1373         (void) CopyMagickMemory((unsigned char *) component,
1374           (const unsigned char *) (p+1),strlen(p+1)+1);
1375       break;
1376     }
1377     case BasePath:
1378     {
1379       if (IsBasenameSeparator(*p) != MagickFalse)
1380         (void) CopyMagickString(component,p+1,MaxTextExtent);
1381       for (p=component+(strlen(component)-1); p > component; p--)
1382         if (*p == '.')
1383           {
1384             *p='\0';
1385             break;
1386           }
1387       break;
1388     }
1389     case ExtensionPath:
1390     {
1391       if (IsBasenameSeparator(*p) != MagickFalse)
1392         (void) CopyMagickString(component,p+1,MaxTextExtent);
1393       p=component;
1394       if (*p != '\0')
1395         for (p=component+strlen(component)-1; p > component; p--)
1396           if (*p == '.')
1397             break;
1398       *component='\0';
1399       if (*p == '.')
1400         (void) CopyMagickString(component,p+1,MaxTextExtent);
1401       break;
1402     }
1403     case SubimagePath:
1404     {
1405       (void) CopyMagickString(component,subimage,MaxTextExtent);
1406       break;
1407     }
1408     case CanonicalPath:
1409     case UndefinedPath:
1410       break;
1411   }
1412 }
1413 \f
1414 /*
1415 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1416 %                                                                             %
1417 %                                                                             %
1418 %                                                                             %
1419 %  G e t P a t h C o m p o n e n t s                                          %
1420 %                                                                             %
1421 %                                                                             %
1422 %                                                                             %
1423 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1424 %
1425 %  GetPathComponents() returns a list of path components.
1426 %
1427 %  The format of the GetPathComponents method is:
1428 %
1429 %      char **GetPathComponents(const char *path,
1430 %        unsigned long *number_componenets)
1431 %
1432 %  A description of each parameter follows:
1433 %
1434 %    o path:  Specifies the string to segment into a list.
1435 %
1436 %    o number_components:  return the number of components in the list
1437 %
1438 */
1439 MagickExport char **GetPathComponents(const char *path,
1440   unsigned long *number_components)
1441 {
1442   char
1443     **components;
1444
1445   register const char
1446     *p,
1447     *q;
1448
1449   register long
1450     i;
1451
1452   if (path == (char *) NULL)
1453     return((char **) NULL);
1454   *number_components=1;
1455   for (p=path; *p != '\0'; p++)
1456     if (IsBasenameSeparator(*p))
1457       (*number_components)++;
1458   components=(char **) AcquireQuantumMemory((size_t) *number_components+1UL,
1459     sizeof(*components));
1460   if (components == (char **) NULL)
1461     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1462   p=path;
1463   for (i=0; i < (long) *number_components; i++)
1464   {
1465     for (q=p; *q != '\0'; q++)
1466       if (IsBasenameSeparator(*q))
1467         break;
1468     components[i]=(char *) AcquireQuantumMemory((size_t) (q-p)+MaxTextExtent,
1469       sizeof(*components));
1470     if (components[i] == (char *) NULL)
1471       ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1472     (void) CopyMagickString(components[i],p,(size_t) (q-p+1));
1473     p=q+1;
1474   }
1475   components[i]=(char *) NULL;
1476   return(components);
1477 }
1478 \f
1479 /*
1480 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1481 %                                                                             %
1482 %                                                                             %
1483 %                                                                             %
1484 %  I s P a t h A c c e s s i b l e                                            %
1485 %                                                                             %
1486 %                                                                             %
1487 %                                                                             %
1488 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1489 %
1490 %  IsPathAccessible() returns MagickTrue if the file as defined by the path is
1491 %  accessible.
1492 %
1493 %  The format of the IsPathAccessible method is:
1494 %
1495 %      MagickBooleanType IsPathAccessible(const char *filename)
1496 %
1497 %  A description of each parameter follows.
1498 %
1499 %    o path:  Specifies a path to a file.
1500 %
1501 */
1502 MagickExport MagickBooleanType IsPathAccessible(const char *path)
1503 {
1504   MagickBooleanType
1505     status;
1506
1507   struct stat
1508     attributes;
1509
1510   if ((path == (const char *) NULL) || (*path == '\0'))
1511     return(MagickFalse);
1512   status=GetPathAttributes(path,&attributes);
1513   if (status == MagickFalse)
1514     return(status);
1515   if (S_ISREG(attributes.st_mode) == 0)
1516     return(MagickFalse);
1517   if (access(path,F_OK) != 0)
1518     return(MagickFalse);
1519   return(MagickTrue);
1520 }
1521 \f
1522 /*
1523 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1524 %                                                                             %
1525 %                                                                             %
1526 %                                                                             %
1527 +  I s P a t h D i r e c t o r y                                              %
1528 %                                                                             %
1529 %                                                                             %
1530 %                                                                             %
1531 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1532 %
1533 %  IsPathDirectory() returns -1 if the directory does not exist,  1 is returned
1534 %  if the path represents a directory otherwise 0.
1535 %
1536 %  The format of the IsPathDirectory method is:
1537 %
1538 %      int IsPathDirectory(const char *path)
1539 %
1540 %  A description of each parameter follows.
1541 %
1542 %   o  path:  The directory path.
1543 %
1544 */
1545 static int IsPathDirectory(const char *path)
1546 {
1547   MagickBooleanType
1548     status;
1549
1550   struct stat
1551     attributes;
1552
1553   if ((path == (const char *) NULL) || (*path == '\0'))
1554     return(MagickFalse);
1555   status=GetPathAttributes(path,&attributes);
1556   if (status == MagickFalse)
1557     return(-1);
1558   if (S_ISDIR(attributes.st_mode) == 0)
1559     return(0);
1560   return(1);
1561 }
1562 \f
1563 /*
1564 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1565 %                                                                             %
1566 %                                                                             %
1567 %                                                                             %
1568 %   I s M a g i c k T r u e                                                   %
1569 %                                                                             %
1570 %                                                                             %
1571 %                                                                             %
1572 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1573 %
1574 %  IsMagickTrue() returns MagickTrue if the value is "true", "on", "yes" or
1575 %  "1".
1576 %
1577 %  The format of the IsMagickTrue method is:
1578 %
1579 %      MagickBooleanType IsMagickTrue(const char *value)
1580 %
1581 %  A description of each parameter follows:
1582 %
1583 %    o option: either MagickTrue or MagickFalse depending on the value
1584 %      parameter.
1585 %
1586 %    o value: Specifies a pointer to a character array.
1587 %
1588 */
1589 MagickExport MagickBooleanType IsMagickTrue(const char *value)
1590 {
1591   if (value == (const char *) NULL)
1592     return(MagickFalse);
1593   if (LocaleCompare(value,"true") == 0)
1594     return(MagickTrue);
1595   if (LocaleCompare(value,"on") == 0)
1596     return(MagickTrue);
1597   if (LocaleCompare(value,"yes") == 0)
1598     return(MagickTrue);
1599   if (LocaleCompare(value,"1") == 0)
1600     return(MagickTrue);
1601   return(MagickFalse);
1602 }
1603 \f
1604 /*
1605 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1606 %                                                                             %
1607 %                                                                             %
1608 %                                                                             %
1609 %   L i s t F i l e s                                                         %
1610 %                                                                             %
1611 %                                                                             %
1612 %                                                                             %
1613 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1614 %
1615 %  ListFiles() reads the directory specified and returns a list of filenames
1616 %  contained in the directory sorted in ascending alphabetic order.
1617 %
1618 %  The format of the ListFiles function is:
1619 %
1620 %      char **ListFiles(const char *directory,const char *pattern,
1621 %        long *number_entries)
1622 %
1623 %  A description of each parameter follows:
1624 %
1625 %    o filelist: Method ListFiles returns a list of filenames contained
1626 %      in the directory.  If the directory specified cannot be read or it is
1627 %      a file a NULL list is returned.
1628 %
1629 %    o directory: Specifies a pointer to a text string containing a directory
1630 %      name.
1631 %
1632 %    o pattern: Specifies a pointer to a text string containing a pattern.
1633 %
1634 %    o number_entries:  This integer returns the number of filenames in the
1635 %      list.
1636 %
1637 */
1638
1639 #if defined(__cplusplus) || defined(c_plusplus)
1640 extern "C" {
1641 #endif
1642
1643 static int FileCompare(const void *x,const void *y)
1644 {
1645   register const char
1646     **p,
1647     **q;
1648
1649   p=(const char **) x;
1650   q=(const char **) y;
1651   return(LocaleCompare(*p,*q));
1652 }
1653
1654 #if defined(__cplusplus) || defined(c_plusplus)
1655 }
1656 #endif
1657
1658 static inline int MagickReadDirectory(DIR *directory,struct dirent *entry,
1659   struct dirent **result)
1660 {
1661 #if defined(MAGICKCORE_HAVE_READDIR_R)
1662   return(readdir_r(directory,entry,result));
1663 #else
1664   (void) entry;
1665   errno=0;
1666   *result=readdir(directory);
1667   return(errno);
1668 #endif
1669 }
1670
1671 MagickExport char **ListFiles(const char *directory,const char *pattern,
1672   unsigned long *number_entries)
1673 {
1674   char
1675     **filelist;
1676
1677   DIR
1678     *current_directory;
1679
1680   struct dirent
1681     *buffer,
1682     *entry;
1683
1684   unsigned long
1685     max_entries;
1686
1687   /*
1688     Open directory.
1689   */
1690   assert(directory != (const char *) NULL);
1691   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",directory);
1692   assert(pattern != (const char *) NULL);
1693   assert(number_entries != (unsigned long *) NULL);
1694   *number_entries=0;
1695   current_directory=opendir(directory);
1696   if (current_directory == (DIR *) NULL)
1697     return((char **) NULL);
1698   /*
1699     Allocate filelist.
1700   */
1701   max_entries=2048;
1702   filelist=(char **) AcquireQuantumMemory((size_t) max_entries,
1703     sizeof(*filelist));
1704   if (filelist == (char **) NULL)
1705     {
1706       (void) closedir(current_directory);
1707       return((char **) NULL);
1708     }
1709   /*
1710     Save the current and change to the new directory.
1711   */
1712   buffer=(struct dirent *) AcquireAlignedMemory(1,sizeof(*buffer)+FILENAME_MAX+1);
1713   if (buffer == (struct dirent *) NULL)
1714     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1715   while ((MagickReadDirectory(current_directory,buffer,&entry) == 0) &&
1716          (entry != (struct dirent *) NULL))
1717   {
1718     if (*entry->d_name == '.')
1719       continue;
1720     if ((IsPathDirectory(entry->d_name) > 0) ||
1721 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
1722         (GlobExpression(entry->d_name,pattern,MagickTrue) != MagickFalse))
1723 #else
1724         (GlobExpression(entry->d_name,pattern,MagickFalse) != MagickFalse))
1725 #endif
1726       {
1727         if (*number_entries >= max_entries)
1728           {
1729             /*
1730               Extend the file list.
1731             */
1732             max_entries<<=1;
1733             filelist=(char **) ResizeQuantumMemory(filelist,(size_t)
1734               max_entries,sizeof(*filelist));
1735             if (filelist == (char **) NULL)
1736               break;
1737           }
1738 #if defined(vms)
1739         {
1740           register char
1741             *p;
1742
1743           p=strchr(entry->d_name,';');
1744           if (p)
1745             *p='\0';
1746           if (*number_entries > 0)
1747             if (LocaleCompare(entry->d_name,filelist[*number_entries-1]) == 0)
1748               continue;
1749         }
1750 #endif
1751         filelist[*number_entries]=(char *) AcquireString(entry->d_name);
1752         if (IsPathDirectory(entry->d_name) > 0)
1753           (void) ConcatenateMagickString(filelist[*number_entries],
1754             DirectorySeparator,MaxTextExtent);
1755         (*number_entries)++;
1756       }
1757   }
1758   buffer=(struct dirent *) RelinquishMagickMemory(buffer);
1759   (void) closedir(current_directory);
1760   if (filelist == (char **) NULL)
1761     return((char **) NULL);
1762   /*
1763     Sort filelist in ascending order.
1764   */
1765   qsort((void *) filelist,(size_t) *number_entries,sizeof(*filelist),
1766     FileCompare);
1767   return(filelist);
1768 }
1769 \f
1770 /*
1771 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1772 %                                                                             %
1773 %                                                                             %
1774 %                                                                             %
1775 %  M u l t i l i n e C e n s u s                                              %
1776 %                                                                             %
1777 %                                                                             %
1778 %                                                                             %
1779 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1780 %
1781 %  MultilineCensus() returns the number of lines within a label.  A line is
1782 %  represented by a \n character.
1783 %
1784 %  The format of the MultilineCenus method is:
1785 %
1786 %      unsigned long MultilineCensus(const char *label)
1787 %
1788 %  A description of each parameter follows.
1789 %
1790 %   o  label:  This character string is the label.
1791 %
1792 %
1793 */
1794 MagickExport unsigned long MultilineCensus(const char *label)
1795 {
1796   unsigned long
1797     number_lines;
1798
1799   /*
1800     Determine the number of lines within this label.
1801   */
1802   if (label == (char *) NULL)
1803     return(0);
1804   for (number_lines=1; *label != '\0'; label++)
1805     if (*label == '\n')
1806       number_lines++;
1807   return(number_lines);
1808 }
1809 \f
1810 /*
1811 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1812 %                                                                             %
1813 %                                                                             %
1814 %                                                                             %
1815 %   O p e n M a g i c k S t r e a m                                           %
1816 %                                                                             %
1817 %                                                                             %
1818 %                                                                             %
1819 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1820 %
1821 %  OpenMagickStream() opens the file at the specified path and return the
1822 %  associated stream.
1823 %
1824 %  The path of the OpenMagickStream method is:
1825 %
1826 %      FILE *OpenMagickStream(const char *path,const char *mode)
1827 %
1828 %  A description of each parameter follows.
1829 %
1830 %   o  path: the file path.
1831 %
1832 %   o  mode: the file mode.
1833 %
1834 */
1835 MagickExport FILE *OpenMagickStream(const char *path,const char *mode)
1836 {
1837   FILE
1838     *file;
1839
1840   if ((path == (const char *) NULL) || (mode == (const char *) NULL))
1841     {
1842       errno=EINVAL;
1843       return((FILE *) NULL);
1844     }
1845   file=(FILE *) NULL;
1846 #if defined(MAGICKCORE_HAVE__WFOPEN)
1847   {
1848     wchar_t
1849       *unicode_mode,
1850       *unicode_path;
1851
1852     unicode_path=ConvertUTF8ToUTF16((const unsigned char *) path);
1853     if (unicode_path == (wchar_t *) NULL)
1854       return((FILE *) NULL);
1855     unicode_mode=ConvertUTF8ToUTF16((const unsigned char *) mode);
1856     if (unicode_mode == (wchar_t *) NULL)
1857       {
1858         unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path);
1859         return((FILE *) NULL);
1860       }
1861     file=_wfopen(unicode_path,unicode_mode);
1862     unicode_mode=(wchar_t *) RelinquishMagickMemory(unicode_mode);
1863     unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path);
1864   }
1865 #endif
1866   if (file == (FILE *) NULL)
1867     file=fopen(path,mode);
1868   return(file);
1869 }
1870 \f
1871 /*
1872 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1873 %                                                                             %
1874 %                                                                             %
1875 %                                                                             %
1876 %   S y s t e m C o m m a n d                                                 %
1877 %                                                                             %
1878 %                                                                             %
1879 %                                                                             %
1880 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1881 %
1882 %  SystemCommand() executes the specified command and waits until it
1883 %  terminates.  The returned value is the exit status of the command.
1884 %
1885 %  The format of the SystemCommand method is:
1886 %
1887 %      int SystemCommand(const MagickBooleanType asynchronous,
1888 %        const MagickBooleanType verbose,const char *command,
1889 %        ExceptionInfo *exception)
1890 %
1891 %  A description of each parameter follows:
1892 %
1893 %    o asynchronous: a value other than 0 executes the parent program
1894 %      concurrently with the new child process.
1895 %
1896 %    o verbose: a value other than 0 prints the executed command before it is
1897 %      invoked.
1898 %
1899 %    o command: this string is the command to execute.
1900 %
1901 %    o exception: return any errors here.
1902 %
1903 */
1904 MagickExport int SystemCommand(const MagickBooleanType asynchronous,
1905   const MagickBooleanType verbose,const char *command,ExceptionInfo *exception)
1906 {
1907   char
1908     **arguments,
1909     *shell_command;
1910
1911   int
1912     number_arguments,
1913     status;
1914
1915   PolicyDomain
1916     domain;
1917
1918   PolicyRights
1919     rights;
1920
1921   register long
1922     i;
1923
1924   status=(-1);
1925   arguments=StringToArgv(command,&number_arguments);
1926   if (arguments == (char **) NULL)
1927     return(status);
1928   rights=ExecutePolicyRights;
1929   domain=DelegatePolicyDomain;
1930   if (IsRightsAuthorized(domain,rights,arguments[1]) == MagickFalse)
1931     {
1932       errno=EPERM;
1933       (void) ThrowMagickException(exception,GetMagickModule(),PolicyError,
1934         "NotAuthorized","`%s'",arguments[1]);
1935       for (i=0; i < number_arguments; i++)
1936         arguments[i]=DestroyString(arguments[i]);
1937       arguments=(char **) RelinquishMagickMemory(arguments);
1938       return(-1);
1939     }
1940   if (verbose != MagickFalse)
1941     {
1942       (void) fprintf(stderr,"%s\n",command);
1943       (void) fflush(stderr);
1944     }
1945   shell_command=(char *) command;
1946   if (asynchronous != MagickFalse)
1947     {
1948       shell_command=AcquireString(command);
1949       (void) ConcatenateMagickString(shell_command,"&",MaxTextExtent);
1950     }
1951 #if defined(MAGICKCORE_POSIX_SUPPORT)
1952 #if !defined(MAGICKCORE_HAVE_EXECVP)
1953   status=system(shell_command);
1954 #else
1955   if ((asynchronous != MagickFalse) || (strspn(shell_command,"&;<>|") == 0))
1956     status=system(shell_command);
1957   else
1958     {
1959       pid_t
1960         child_pid;
1961
1962       /*
1963         Call application directly rather than from a shell.
1964       */
1965       child_pid=fork();
1966       if (child_pid == (pid_t) -1)
1967         status=system(command);
1968       else
1969         if (child_pid == 0)
1970           {
1971             status=execvp(arguments[1],arguments+1);
1972             _exit(1);
1973           }
1974         else
1975           {
1976             int
1977               child_status;
1978
1979             pid_t
1980               pid;
1981
1982             child_status=0;
1983             pid=waitpid(child_pid,&child_status,0);
1984             if (pid == -1)
1985               status=(-1);
1986             else
1987               {
1988                 if (WIFEXITED(child_status) != 0)
1989                   status=WEXITSTATUS(child_status);
1990                 else
1991                   if (WIFSIGNALED(child_status))
1992                     status=(-1);
1993               }
1994           }
1995     }
1996 #endif
1997 #elif defined(MAGICKCORE_WINDOWS_SUPPORT)
1998   {
1999     int
2000       mode;
2001
2002     mode=_P_WAIT;
2003     if (asynchronous != MagickFalse)
2004       mode=_P_NOWAIT;
2005     status=spawnvp(mode,arguments[1],(const char **) (arguments+1));
2006   }
2007 #elif defined(macintosh)
2008   status=MACSystemCommand(shell_command);
2009 #elif defined(vms)
2010   status=system(shell_command);
2011 #else
2012 #  error No suitable system() method.
2013 #endif
2014   if (status < 0)
2015     (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,
2016       "`%s' (%d)",command,status);
2017   if (shell_command != command)
2018     shell_command=DestroyString(shell_command);
2019   for (i=0; i < number_arguments; i++)
2020     arguments[i]=DestroyString(arguments[i]);
2021   arguments=(char **) RelinquishMagickMemory(arguments);
2022   return(status);
2023 }