2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % U U TTTTT IIIII L IIIII TTTTT Y Y %
10 % UUU T IIIII LLLLL IIIII T Y %
13 % MagickCore Utility Methods %
20 % Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
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. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42 #include "MagickCore/studio.h"
43 #include "MagickCore/property.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/color.h"
46 #include "MagickCore/exception.h"
47 #include "MagickCore/exception-private.h"
48 #include "MagickCore/geometry.h"
49 #include "MagickCore/list.h"
50 #include "MagickCore/log.h"
51 #include "MagickCore/magick-private.h"
52 #include "MagickCore/memory_.h"
53 #include "MagickCore/nt-base-private.h"
54 #include "MagickCore/option.h"
55 #include "MagickCore/policy.h"
56 #include "MagickCore/resource_.h"
57 #include "MagickCore/semaphore.h"
58 #include "MagickCore/signature-private.h"
59 #include "MagickCore/statistic.h"
60 #include "MagickCore/string_.h"
61 #include "MagickCore/string-private.h"
62 #include "MagickCore/token.h"
63 #include "MagickCore/token-private.h"
64 #include "MagickCore/utility.h"
65 #include "MagickCore/utility-private.h"
66 #if defined(MAGICKCORE_HAVE_PROCESS_H)
69 #if defined(MAGICKCORE_HAVE_MACH_O_DYLD_H)
70 #include <mach-o/dyld.h>
77 Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
83 IsPathDirectory(const char *);
86 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
90 % A c q u i r e U n i q u e F i l e n a m e %
94 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
96 % AcquireUniqueFilename() replaces the contents of path by a unique path name.
98 % The format of the AcquireUniqueFilename method is:
100 % MagickBooleanType AcquireUniqueFilename(char *path)
102 % A description of each parameter follows.
104 % o path: Specifies a pointer to an array of characters. The unique path
105 % name is returned in this array.
108 MagickExport MagickBooleanType AcquireUniqueFilename(char *path)
113 file=AcquireUniqueFileResource(path);
121 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
125 % A c q u i r e U n i q u e S ym b o l i c L i n k %
129 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
131 % AcquireUniqueSymbolicLink() creates a unique symbolic link to the specified
132 % source path and returns MagickTrue on success otherwise MagickFalse. If the
133 % symlink() method fails or is not available, a unique file name is generated
134 % and the source file copied to it. When you are finished with the file, use
135 % RelinquishUniqueFilename() to destroy it.
137 % The format of the AcquireUniqueSymbolicLink method is:
139 % MagickBooleanType AcquireUniqueSymbolicLink(const char *source,
142 % A description of each parameter follows.
144 % o source: the source path.
146 % o destination: the destination path.
150 static inline size_t MagickMin(const size_t x,const size_t y)
157 MagickExport MagickBooleanType AcquireUniqueSymbolicLink(const char *source,
177 assert(source != (const char *) NULL);
178 assert(destination != (char *) NULL);
179 #if defined(MAGICKCORE_HAVE_SYMLINK)
180 (void) AcquireUniqueFilename(destination);
181 (void) RelinquishUniqueFileResource(destination);
182 if (*source == *DirectorySeparator)
184 if (symlink(source,destination) == 0)
193 if (getcwd(path,MaxTextExtent) == (char *) NULL)
195 (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);
196 (void) ConcatenateMagickString(path,source,MaxTextExtent);
197 if (symlink(path,destination) == 0)
201 destination_file=AcquireUniqueFileResource(destination);
202 if (destination_file == -1)
204 source_file=open_utf8(source,O_RDONLY | O_BINARY,0);
205 if (source_file == -1)
207 (void) close(destination_file);
208 (void) RelinquishUniqueFileResource(destination);
211 quantum=(size_t) MagickMaxBufferExtent;
212 if ((fstat(source_file,&attributes) == 0) && (attributes.st_size != 0))
213 quantum=MagickMin((size_t) attributes.st_size,MagickMaxBufferExtent);
214 buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer));
215 if (buffer == (unsigned char *) NULL)
217 (void) close(source_file);
218 (void) close(destination_file);
219 (void) RelinquishUniqueFileResource(destination);
224 count=(ssize_t) read(source_file,buffer,quantum);
227 length=(size_t) count;
228 count=(ssize_t) write(destination_file,buffer,length);
229 if ((size_t) count != length)
231 (void) close(destination_file);
232 (void) close(source_file);
233 buffer=(unsigned char *) RelinquishMagickMemory(buffer);
234 (void) RelinquishUniqueFileResource(destination);
238 (void) close(destination_file);
239 (void) close(source_file);
240 buffer=(unsigned char *) RelinquishMagickMemory(buffer);
245 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
249 % A p p e n d I m a g e F o r m a t %
253 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
255 % AppendImageFormat() appends the image format type to the filename. If an
256 % extension to the file already exists, it is first removed.
258 % The format of the AppendImageFormat method is:
260 % void AppendImageFormat(const char *format,char *filename)
262 % A description of each parameter follows.
264 % o format: Specifies a pointer to an array of characters. This the
265 % format of the image.
267 % o filename: Specifies a pointer to an array of characters. The unique
268 % file name is returned in this array.
271 MagickExport void AppendImageFormat(const char *format,char *filename)
274 extension[MaxTextExtent],
277 assert(format != (char *) NULL);
278 assert(filename != (char *) NULL);
279 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename);
280 if ((*format == '\0') || (*filename == '\0'))
282 if (LocaleCompare(filename,"-") == 0)
285 message[MaxTextExtent];
287 (void) FormatLocaleString(message,MaxTextExtent,"%s:%s",format,filename);
288 (void) CopyMagickString(filename,message,MaxTextExtent);
291 GetPathComponent(filename,ExtensionPath,extension);
292 if ((LocaleCompare(extension,"Z") == 0) ||
293 (LocaleCompare(extension,"bz2") == 0) ||
294 (LocaleCompare(extension,"gz") == 0) ||
295 (LocaleCompare(extension,"wmz") == 0) ||
296 (LocaleCompare(extension,"svgz") == 0))
298 GetPathComponent(filename,RootPath,root);
299 (void) CopyMagickString(filename,root,MaxTextExtent);
300 GetPathComponent(filename,RootPath,root);
301 (void) FormatLocaleString(filename,MaxTextExtent,"%s.%s.%s",root,format,
305 GetPathComponent(filename,RootPath,root);
306 (void) FormatLocaleString(filename,MaxTextExtent,"%s.%s",root,format);
310 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
314 % B a s e 6 4 D e c o d e %
318 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
320 % Base64Decode() decodes Base64-encoded text and returns its binary
321 % equivalent. NULL is returned if the text is not valid Base64 data, or a
322 % memory allocation failure occurs.
324 % The format of the Base64Decode method is:
326 % unsigned char *Base64Decode(const char *source,length_t *length)
328 % A description of each parameter follows:
330 % o source: A pointer to a Base64-encoded string.
332 % o length: the number of bytes decoded.
335 MagickExport unsigned char *Base64Decode(const char *source,size_t *length)
350 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
351 assert(source != (char *) NULL);
352 assert(length != (size_t *) NULL);
354 decode=(unsigned char *) AcquireQuantumMemory(strlen(source)/4+4,
356 if (decode == (unsigned char *) NULL)
357 return((unsigned char *) NULL);
360 for (p=source; *p != '\0'; p++)
362 if (isspace((int) ((unsigned char) *p)) != 0)
367 if (q == (char *) NULL)
369 decode=(unsigned char *) RelinquishMagickMemory(decode);
370 return((unsigned char *) NULL); /* non-Base64 character */
376 decode[i]=(q-Base64) << 2;
382 decode[i++]|=(q-Base64) >> 4;
383 decode[i]=((q-Base64) & 0x0f) << 4;
389 decode[i++]|=(q-Base64) >> 2;
390 decode[i]=((q-Base64) & 0x03) << 6;
396 decode[i++]|=(q-Base64);
403 Verify Base-64 string has proper terminal characters.
409 decode=(unsigned char *) RelinquishMagickMemory(decode);
410 return((unsigned char *) NULL);
422 Unrecognized '=' character.
424 decode=(unsigned char *) RelinquishMagickMemory(decode);
425 return((unsigned char *) NULL);
429 for ( ; *p != '\0'; p++)
430 if (isspace((int) ((unsigned char) *p)) == 0)
434 decode=(unsigned char *) RelinquishMagickMemory(decode);
435 return((unsigned char *) NULL);
441 for ( ; *p != '\0'; p++)
442 if (isspace((int) ((unsigned char) *p)) == 0)
444 decode=(unsigned char *) RelinquishMagickMemory(decode);
445 return((unsigned char *) NULL);
447 if ((int) decode[i] != 0)
449 decode=(unsigned char *) RelinquishMagickMemory(decode);
450 return((unsigned char *) NULL);
460 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
464 % B a s e 6 4 E n c o d e %
468 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
470 % Base64Encode() encodes arbitrary binary data to Base64 encoded format as
471 % described by the "Base64 Content-Transfer-Encoding" section of RFC 2045 and
472 % returns the result as a null-terminated ASCII string. NULL is returned if
473 % a memory allocation failure occurs.
475 % The format of the Base64Encode method is:
477 % char *Base64Encode(const unsigned char *blob,const size_t blob_length,
478 % size_t *encode_length)
480 % A description of each parameter follows:
482 % o blob: A pointer to binary data to encode.
484 % o blob_length: the number of bytes to encode.
486 % o encode_length: The number of bytes encoded.
489 MagickExport char *Base64Encode(const unsigned char *blob,
490 const size_t blob_length,size_t *encode_length)
495 register const unsigned char
504 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
505 assert(blob != (const unsigned char *) NULL);
506 assert(blob_length != 0);
507 assert(encode_length != (size_t *) NULL);
509 encode=(char *) AcquireQuantumMemory(blob_length/3+4,4*sizeof(*encode));
510 if (encode == (char *) NULL)
511 return((char *) NULL);
513 for (p=blob; p < (blob+blob_length-2); p+=3)
515 encode[i++]=Base64[(int) (*p >> 2)];
516 encode[i++]=Base64[(int) (((*p & 0x03) << 4)+(*(p+1) >> 4))];
517 encode[i++]=Base64[(int) (((*(p+1) & 0x0f) << 2)+(*(p+2) >> 6))];
518 encode[i++]=Base64[(int) (*(p+2) & 0x3f)];
520 remainder=blob_length % 3;
532 for (j=0; j < (ssize_t) remainder; j++)
534 encode[i++]=Base64[(int) (code[0] >> 2)];
535 encode[i++]=Base64[(int) (((code[0] & 0x03) << 4)+(code[1] >> 4))];
539 encode[i++]=Base64[(int) (((code[1] & 0x0f) << 2)+(code[2] >> 6))];
548 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
552 % C h o p P a t h C o m p o n e n t s %
556 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
558 % ChopPathComponents() removes the number of specified file components from a
561 % The format of the ChopPathComponents method is:
563 % ChopPathComponents(char *path,size_t components)
565 % A description of each parameter follows:
569 % o components: The number of components to chop.
572 MagickPrivate void ChopPathComponents(char *path,const size_t components)
577 for (i=0; i < (ssize_t) components; i++)
578 GetPathComponent(path,HeadPath,path);
582 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
586 % E x p a n d F i l e n a m e %
590 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
592 % ExpandFilename() expands '~' in a path.
594 % The format of the ExpandFilename function is:
596 % ExpandFilename(char *path)
598 % A description of each parameter follows:
600 % o path: Specifies a pointer to a character array that contains the
604 MagickPrivate void ExpandFilename(char *path)
607 expand_path[MaxTextExtent];
609 if (path == (char *) NULL)
613 (void) CopyMagickString(expand_path,path,MaxTextExtent);
614 if ((*(path+1) == *DirectorySeparator) || (*(path+1) == '\0'))
620 Substitute ~ with $HOME.
622 (void) CopyMagickString(expand_path,".",MaxTextExtent);
623 (void) ConcatenateMagickString(expand_path,path+1,MaxTextExtent);
624 home=GetEnvironmentValue("HOME");
625 if (home == (char *) NULL)
626 home=GetEnvironmentValue("USERPROFILE");
627 if (home != (char *) NULL)
629 (void) CopyMagickString(expand_path,home,MaxTextExtent);
630 (void) ConcatenateMagickString(expand_path,path+1,MaxTextExtent);
631 home=DestroyString(home);
636 #if defined(MAGICKCORE_POSIX_SUPPORT) && !defined(__OS2__)
638 username[MaxTextExtent];
647 Substitute ~ with home directory from password file.
649 (void) CopyMagickString(username,path+1,MaxTextExtent);
650 p=strchr(username,'/');
651 if (p != (char *) NULL)
653 entry=getpwnam(username);
654 if (entry == (struct passwd *) NULL)
656 (void) CopyMagickString(expand_path,entry->pw_dir,MaxTextExtent);
657 if (p != (char *) NULL)
659 (void) ConcatenateMagickString(expand_path,"/",MaxTextExtent);
660 (void) ConcatenateMagickString(expand_path,p+1,MaxTextExtent);
664 (void) CopyMagickString(path,expand_path,MaxTextExtent);
668 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
672 % E x p a n d F i l e n a m e s %
676 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
678 % ExpandFilenames() checks each argument of the given argument array, and
679 % expands it if they have a wildcard character.
681 % Any coder prefix (EG: 'coder:filename') or read modifier postfix (EG:
682 % 'filename[...]') are ignored during the file the expansion, but will be
683 % included in the final argument. If no filename matching the meta-character
684 % 'glob' is found the original argument is returned.
686 % For example, an argument of '*.gif[20x20]' will be replaced by the list
687 % 'abc.gif[20x20]', 'foobar.gif[20x20]', 'xyzzy.gif[20x20]'
688 % if such filenames exist, (in the current directory in this case).
690 % Meta-characters handled...
691 % @ read a list of filenames (no further expansion performed)
692 % ~ At start of filename expands to HOME environemtn variable
693 % * matches any string including an empty string
694 % ? matches by any single character
696 % WARNING: filenames starting with '.' (hidden files in a UNIX file system)
697 % will never be expanded. Attempting to epand '.*' will produce no change.
699 % Expansion is ignored for coders "label:" "caption:" "pango:" and "vid:".
700 % Which provide their own '@' meta-character handling.
702 % You can see the results of the expansion using "Configure" log
706 % The returned list should be freed using DestroyStringList().
708 % However the strings in the original pointed to argv are not
709 % freed (TO BE CHECKED). So a copy of the original pointer (and count)
710 % should be kept separate if they need to be freed later.
713 % The format of the ExpandFilenames function is:
715 % status=ExpandFilenames(int *number_arguments,char ***arguments)
717 % A description of each parameter follows:
719 % o number_arguments: Specifies a pointer to an integer describing the
720 % number of elements in the argument vector.
722 % o arguments: Specifies a pointer to a text array containing the command
726 MagickExport MagickBooleanType ExpandFilenames(int *number_arguments,
731 home_directory[MaxTextExtent],
746 Allocate argument vector.
748 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
749 assert(number_arguments != (int *) NULL);
750 assert(arguments != (char ***) NULL);
751 vector=(char **) AcquireQuantumMemory((size_t) (*number_arguments+1),
753 if (vector == (char **) NULL)
754 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
756 Expand any wildcard filenames.
758 *home_directory='\0';
760 for (i=0; i < (ssize_t) *number_arguments; i++)
764 filename[MaxTextExtent],
765 magick[MaxTextExtent],
768 subimage[MaxTextExtent];
773 option=(*arguments)[i];
778 vector[count++]=ConstantString(option);
780 parameters=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
784 Do not expand command option parameters.
786 for (j=0; j < parameters; j++)
789 if (i == (ssize_t) *number_arguments)
791 option=(*arguments)[i];
792 vector[count++]=ConstantString(option);
796 if ((*option == '"') || (*option == '\''))
798 GetPathComponent(option,TailPath,filename);
799 GetPathComponent(option,MagickPath,magick);
800 if ((LocaleCompare(magick,"CAPTION") == 0) ||
801 (LocaleCompare(magick,"LABEL") == 0) ||
802 (LocaleCompare(magick,"PANGO") == 0) ||
803 (LocaleCompare(magick,"VID") == 0))
805 if ((IsGlob(filename) == MagickFalse) && (*option != '@'))
810 Generate file list from wildcard filename (e.g. *.jpg).
812 GetPathComponent(option,HeadPath,path);
813 GetPathComponent(option,SubimagePath,subimage);
814 ExpandFilename(path);
815 if (*home_directory == '\0')
816 directory=getcwd(home_directory,MaxTextExtent-1);
818 filelist=ListFiles(*path == '\0' ? home_directory : path,filename,
833 Generate file list from file list (e.g. @filelist.txt).
835 exception=AcquireExceptionInfo();
836 files=FileToString(option+1,~0,exception);
837 exception=DestroyExceptionInfo(exception);
838 if (files == (char *) NULL)
840 filelist=StringToArgv(files,&length);
841 if (filelist == (char **) NULL)
843 files=DestroyString(files);
844 filelist[0]=DestroyString(filelist[0]);
845 for (j=0; j < (ssize_t) (length-1); j++)
846 filelist[j]=filelist[j+1];
847 number_files=(size_t) length-1;
849 if (filelist == (char **) NULL)
851 for (j=0; j < (ssize_t) number_files; j++)
852 if (IsPathDirectory(filelist[j]) <= 0)
854 if (j == (ssize_t) number_files)
856 for (j=0; j < (ssize_t) number_files; j++)
857 filelist[j]=DestroyString(filelist[j]);
858 filelist=(char **) RelinquishMagickMemory(filelist);
862 Transfer file list to argument vector.
864 vector=(char **) ResizeQuantumMemory(vector,(size_t) *number_arguments+
865 count+number_files+1,sizeof(*vector));
866 if (vector == (char **) NULL)
868 for (j=0; j < (ssize_t) number_files; j++)
871 parameters=ParseCommandOption(MagickCommandOptions,MagickFalse,option);
878 Do not expand command option parameters.
880 vector[count++]=ConstantString(option);
881 for (k=0; k < parameters; k++)
884 if (j == (ssize_t) number_files)
887 vector[count++]=ConstantString(option);
891 (void) CopyMagickString(filename,path,MaxTextExtent);
893 (void) ConcatenateMagickString(filename,DirectorySeparator,
895 (void) ConcatenateMagickString(filename,filelist[j],MaxTextExtent);
896 filelist[j]=DestroyString(filelist[j]);
897 if (strlen(filename) >= (MaxTextExtent-1))
898 ThrowFatalException(OptionFatalError,"FilenameTruncated");
899 if (IsPathDirectory(filename) <= 0)
907 (void) ConcatenateMagickString(path,magick,MaxTextExtent);
908 (void) ConcatenateMagickString(path,":",MaxTextExtent);
910 (void) ConcatenateMagickString(path,filename,MaxTextExtent);
911 if (*subimage != '\0')
913 (void) ConcatenateMagickString(path,"[",MaxTextExtent);
914 (void) ConcatenateMagickString(path,subimage,MaxTextExtent);
915 (void) ConcatenateMagickString(path,"]",MaxTextExtent);
917 if (strlen(path) >= (MaxTextExtent-1))
918 ThrowFatalException(OptionFatalError,"FilenameTruncated");
919 if (destroy != MagickFalse)
922 vector[count]=DestroyString(vector[count]);
925 vector[count++]=ConstantString(path);
928 filelist=(char **) RelinquishMagickMemory(filelist);
930 vector[count]=(char *) NULL;
931 if (IsEventLogging() != MagickFalse)
936 command_line=AcquireString(vector[0]);
937 for (i=1; i < count; i++)
939 (void) ConcatenateString(&command_line," {");
940 (void) ConcatenateString(&command_line,vector[i]);
941 (void) ConcatenateString(&command_line,"}");
943 (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
944 "Command line: %s",command_line);
945 command_line=DestroyString(command_line);
947 *number_arguments=(int) count;
953 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
957 % G e t E x e c u t i o n P a t h %
961 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
963 % GetExecutionPath() returns the pathname of the executable that started
964 % the process. On success MagickTrue is returned, otherwise MagickFalse.
966 % The format of the GetExecutionPath method is:
968 % MagickBooleanType GetExecutionPath(char *path,const size_t extent)
970 % A description of each parameter follows:
972 % o path: the pathname of the executable that started the process.
974 % o extent: the maximum extent of the path.
977 MagickPrivate MagickBooleanType GetExecutionPath(char *path,const size_t extent)
983 directory=getcwd(path,(unsigned long) extent);
985 #if defined(MAGICKCORE_HAVE_GETPID) && defined(MAGICKCORE_HAVE_READLINK) && defined(PATH_MAX)
988 link_path[MaxTextExtent],
989 execution_path[PATH_MAX+1];
994 (void) FormatLocaleString(link_path,MaxTextExtent,"/proc/%.20g/exe",
996 count=readlink(link_path,execution_path,PATH_MAX);
999 (void) FormatLocaleString(link_path,MaxTextExtent,"/proc/%.20g/file",
1001 count=readlink(link_path,execution_path,PATH_MAX);
1003 if ((count > 0) && (count <= (ssize_t) PATH_MAX))
1005 execution_path[count]='\0';
1006 (void) CopyMagickString(path,execution_path,extent);
1010 #if defined(MAGICKCORE_HAVE__NSGETEXECUTABLEPATH)
1013 executable_path[PATH_MAX << 1],
1014 execution_path[PATH_MAX+1];
1019 length=sizeof(executable_path);
1020 if ((_NSGetExecutablePath(executable_path,&length) == 0) &&
1021 (realpath(executable_path,execution_path) != (char *) NULL))
1022 (void) CopyMagickString(path,execution_path,extent);
1025 #if defined(MAGICKCORE_HAVE_GETEXECNAME)
1030 execution_path=(const char *) getexecname();
1031 if (execution_path != (const char *) NULL)
1033 if (*execution_path != *DirectorySeparator)
1034 (void) ConcatenateMagickString(path,DirectorySeparator,extent);
1035 (void) ConcatenateMagickString(path,execution_path,extent);
1039 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
1040 NTGetExecutionPath(path,extent);
1042 #if defined(__GNU__)
1052 execution_path=(char *) NULL;
1053 program_name=program_invocation_name;
1054 if (*program_invocation_name != '/')
1059 extent=strlen(directory)+strlen(program_name)+2;
1060 program_name=AcquireQuantumMemory(extent,sizeof(*program_name));
1061 if (program_name == (char *) NULL)
1062 program_name=program_invocation_name;
1064 count=FormatLocaleString(program_name,extent,"%s/%s",directory,
1065 program_invocation_name);
1069 execution_path=realpath(program_name,NULL);
1070 if (execution_path != (char *) NULL)
1071 (void) CopyMagickString(path,execution_path,extent);
1073 if (program_name != program_invocation_name)
1074 program_name=(char *) RelinquishMagickMemory(program_name);
1075 execution_path=(char *) RelinquishMagickMemory(execution_path);
1078 return(IsPathAccessible(path));
1082 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1086 % G e t M a g i c k P a g e S i z e %
1090 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1092 % GetMagickPageSize() returns the memory page size.
1094 % The format of the GetMagickPageSize method is:
1096 % ssize_t GetMagickPageSize()
1099 MagickPrivate ssize_t GetMagickPageSize(void)
1106 #if defined(MAGICKCORE_HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
1107 page_size=(ssize_t) sysconf(_SC_PAGE_SIZE);
1109 #if defined(MAGICKCORE_HAVE_GETPAGESIZE)
1110 page_size=(ssize_t) getpagesize();
1119 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1123 % G e t P a t h A t t r i b u t e s %
1127 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1129 % GetPathAttributes() returns attributes (e.g. size of file) about a path.
1131 % The path of the GetPathAttributes method is:
1133 % MagickBooleanType GetPathAttributes(const char *path,void *attributes)
1135 % A description of each parameter follows.
1137 % o path: the file path.
1139 % o attributes: the path attributes are returned here.
1142 MagickExport MagickBooleanType GetPathAttributes(const char *path,
1148 if (path == (const char *) NULL)
1151 return(MagickFalse);
1153 status=stat_utf8(path,(struct stat *) attributes) == 0 ? MagickTrue :
1159 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1163 % G e t P a t h C o m p o n e n t %
1167 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1169 % GetPathComponent() returns the parent directory name, filename, basename, or
1170 % extension of a file path.
1172 % The component string pointed to must have at least MaxTextExtent space
1173 % for the results to be stored.
1175 % The format of the GetPathComponent function is:
1177 % GetPathComponent(const char *path,PathType type,char *component)
1179 % A description of each parameter follows:
1181 % o path: Specifies a pointer to a character array that contains the
1184 % o type: Specififies which file path component to return.
1186 % o component: the selected file path component is returned here.
1189 MagickExport void GetPathComponent(const char *path,PathType type,
1193 magick[MaxTextExtent],
1195 subimage[MaxTextExtent];
1200 assert(path != (const char *) NULL);
1201 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",path);
1202 assert(component != (char *) NULL);
1208 (void) CopyMagickString(component,path,MaxTextExtent);
1210 #if defined(__OS2__)
1213 for (p=component; *p != '\0'; p++)
1215 if ((*p == '%') && (*(p+1) == '['))
1220 for (p++; (*p != ']') && (*p != '\0'); p++) ;
1224 if ((*p == ':') && (IsPathDirectory(path) < 0) &&
1225 (IsPathAccessible(path) == MagickFalse))
1228 Look for image format specification (e.g. ps3:image).
1230 (void) CopyMagickString(magick,component,(size_t) (p-component+1));
1231 if (IsMagickConflict(magick) != MagickFalse)
1234 for (q=component; *q != '\0'; q++)
1242 p=component+strlen(component)-1;
1243 if ((*p == ']') && (strchr(component,'[') != (char *) NULL) &&
1244 (IsPathAccessible(path) == MagickFalse))
1247 Look for scene specification (e.g. img0001.pcd[4]).
1249 for (q=p-1; q > component; q--)
1254 (void) CopyMagickString(subimage,q+1,MaxTextExtent);
1255 subimage[p-q-1]='\0';
1256 if ((IsSceneGeometry(subimage,MagickFalse) == MagickFalse) &&
1257 (IsGeometry(subimage) == MagickFalse))
1265 for (p=component+strlen(component)-1; p > component; p--)
1266 if (IsBasenameSeparator(*p) != MagickFalse)
1272 (void) CopyMagickString(component,magick,MaxTextExtent);
1277 for (p=component+(strlen(component)-1); p > component; p--)
1279 if (IsBasenameSeparator(*p) != MagickFalse)
1295 if (IsBasenameSeparator(*p) != MagickFalse)
1296 (void) CopyMagickMemory((unsigned char *) component,
1297 (const unsigned char *) (p+1),strlen(p+1)+1);
1302 if (IsBasenameSeparator(*p) != MagickFalse)
1303 (void) CopyMagickString(component,p+1,MaxTextExtent);
1304 for (p=component+(strlen(component)-1); p > component; p--)
1314 if (IsBasenameSeparator(*p) != MagickFalse)
1315 (void) CopyMagickString(component,p+1,MaxTextExtent);
1318 for (p=component+strlen(component)-1; p > component; p--)
1323 (void) CopyMagickString(component,p+1,MaxTextExtent);
1328 (void) CopyMagickString(component,subimage,MaxTextExtent);
1338 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1342 % G e t P a t h C o m p o n e n t s %
1346 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1348 % GetPathComponents() returns a list of path components.
1350 % The format of the GetPathComponents method is:
1352 % char **GetPathComponents(const char *path,
1353 % size_t *number_componenets)
1355 % A description of each parameter follows:
1357 % o path: Specifies the string to segment into a list.
1359 % o number_components: return the number of components in the list
1362 MagickPrivate char **GetPathComponents(const char *path,
1363 size_t *number_components)
1375 if (path == (char *) NULL)
1376 return((char **) NULL);
1377 *number_components=1;
1378 for (p=path; *p != '\0'; p++)
1379 if (IsBasenameSeparator(*p))
1380 (*number_components)++;
1381 components=(char **) AcquireQuantumMemory((size_t) *number_components+1UL,
1382 sizeof(*components));
1383 if (components == (char **) NULL)
1384 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1386 for (i=0; i < (ssize_t) *number_components; i++)
1388 for (q=p; *q != '\0'; q++)
1389 if (IsBasenameSeparator(*q))
1391 components[i]=(char *) AcquireQuantumMemory((size_t) (q-p)+MaxTextExtent,
1392 sizeof(**components));
1393 if (components[i] == (char *) NULL)
1394 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1395 (void) CopyMagickString(components[i],p,(size_t) (q-p+1));
1398 components[i]=(char *) NULL;
1403 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1407 % I s P a t h A c c e s s i b l e %
1411 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1413 % IsPathAccessible() returns MagickTrue if the file as defined by the path is
1416 % The format of the IsPathAccessible method is:
1418 % MagickBooleanType IsPathAccessible(const char *filename)
1420 % A description of each parameter follows.
1422 % o path: Specifies a path to a file.
1425 MagickExport MagickBooleanType IsPathAccessible(const char *path)
1433 if ((path == (const char *) NULL) || (*path == '\0'))
1434 return(MagickFalse);
1435 status=GetPathAttributes(path,&attributes);
1436 if (status == MagickFalse)
1438 if (S_ISREG(attributes.st_mode) == 0)
1439 return(MagickFalse);
1440 if (access_utf8(path,F_OK) != 0)
1441 return(MagickFalse);
1446 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1450 + I s P a t h D i r e c t o r y %
1454 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1456 % IsPathDirectory() returns -1 if the directory does not exist, 1 is returned
1457 % if the path represents a directory otherwise 0.
1459 % The format of the IsPathDirectory method is:
1461 % int IsPathDirectory(const char *path)
1463 % A description of each parameter follows.
1465 % o path: The directory path.
1468 static int IsPathDirectory(const char *path)
1476 if ((path == (const char *) NULL) || (*path == '\0'))
1477 return(MagickFalse);
1478 status=GetPathAttributes(path,&attributes);
1479 if (status == MagickFalse)
1481 if (S_ISDIR(attributes.st_mode) == 0)
1487 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1491 % L i s t F i l e s %
1495 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1497 % ListFiles() reads the directory specified and returns a list of filenames
1498 % contained in the directory sorted in ascending alphabetic order.
1500 % The format of the ListFiles function is:
1502 % char **ListFiles(const char *directory,const char *pattern,
1503 % ssize_t *number_entries)
1505 % A description of each parameter follows:
1507 % o filelist: Method ListFiles returns a list of filenames contained
1508 % in the directory. If the directory specified cannot be read or it is
1509 % a file a NULL list is returned.
1511 % o directory: Specifies a pointer to a text string containing a directory
1514 % o pattern: Specifies a pointer to a text string containing a pattern.
1516 % o number_entries: This integer returns the number of filenames in the
1521 #if defined(__cplusplus) || defined(c_plusplus)
1525 static int FileCompare(const void *x,const void *y)
1531 p=(const char **) x;
1532 q=(const char **) y;
1533 return(LocaleCompare(*p,*q));
1536 #if defined(__cplusplus) || defined(c_plusplus)
1540 static inline int MagickReadDirectory(DIR *directory,struct dirent *entry,
1541 struct dirent **result)
1543 #if defined(MAGICKCORE_HAVE_READDIR_R)
1544 return(readdir_r(directory,entry,result));
1548 *result=readdir(directory);
1553 MagickPrivate char **ListFiles(const char *directory,const char *pattern,
1554 size_t *number_entries)
1572 assert(directory != (const char *) NULL);
1573 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",directory);
1574 assert(pattern != (const char *) NULL);
1575 assert(number_entries != (size_t *) NULL);
1577 current_directory=opendir(directory);
1578 if (current_directory == (DIR *) NULL)
1579 return((char **) NULL);
1584 filelist=(char **) AcquireQuantumMemory((size_t) max_entries,
1586 if (filelist == (char **) NULL)
1588 (void) closedir(current_directory);
1589 return((char **) NULL);
1592 Save the current and change to the new directory.
1594 buffer=(struct dirent *) AcquireMagickMemory(sizeof(*buffer)+
1596 if (buffer == (struct dirent *) NULL)
1597 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1598 while ((MagickReadDirectory(current_directory,buffer,&entry) == 0) &&
1599 (entry != (struct dirent *) NULL))
1601 if (*entry->d_name == '.')
1603 if ((IsPathDirectory(entry->d_name) > 0) ||
1604 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
1605 (GlobExpression(entry->d_name,pattern,MagickTrue) != MagickFalse))
1607 (GlobExpression(entry->d_name,pattern,MagickFalse) != MagickFalse))
1610 if (*number_entries >= max_entries)
1613 Extend the file list.
1616 filelist=(char **) ResizeQuantumMemory(filelist,(size_t)
1617 max_entries,sizeof(*filelist));
1618 if (filelist == (char **) NULL)
1626 p=strchr(entry->d_name,';');
1629 if (*number_entries > 0)
1630 if (LocaleCompare(entry->d_name,filelist[*number_entries-1]) == 0)
1634 filelist[*number_entries]=(char *) AcquireString(entry->d_name);
1635 (*number_entries)++;
1638 buffer=(struct dirent *) RelinquishMagickMemory(buffer);
1639 (void) closedir(current_directory);
1640 if (filelist == (char **) NULL)
1641 return((char **) NULL);
1643 Sort filelist in ascending order.
1645 qsort((void *) filelist,(size_t) *number_entries,sizeof(*filelist),
1651 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1655 % M a g i c k D e l a y %
1659 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1661 % MagickDelay() suspends program execution for the number of milliseconds
1664 % The format of the Delay method is:
1666 % void MagickDelay(const MagickSizeType milliseconds)
1668 % A description of each parameter follows:
1670 % o milliseconds: Specifies the number of milliseconds to delay before
1674 MagickPrivate void MagickDelay(const MagickSizeType milliseconds)
1676 if (milliseconds == 0)
1678 #if defined(MAGICKCORE_HAVE_NANOSLEEP)
1683 timer.tv_sec=(time_t) (milliseconds/1000);
1684 timer.tv_nsec=(milliseconds % 1000)*1000*1000;
1685 (void) nanosleep(&timer,(struct timespec *) NULL);
1687 #elif defined(MAGICKCORE_HAVE_USLEEP)
1688 usleep(1000*milliseconds);
1689 #elif defined(MAGICKCORE_HAVE_SELECT)
1694 timer.tv_sec=(long) milliseconds/1000;
1695 timer.tv_usec=(long) (milliseconds % 1000)*1000;
1696 (void) select(0,(XFD_SET *) NULL,(XFD_SET *) NULL,(XFD_SET *) NULL,&timer);
1698 #elif defined(MAGICKCORE_HAVE_POLL)
1699 (void) poll((struct pollfd *) NULL,0,(int) milliseconds);
1700 #elif defined(MAGICKCORE_WINDOWS_SUPPORT)
1701 Sleep((long) milliseconds);
1707 timer=milliseconds/1000.0;
1710 #elif defined(__BEOS__)
1711 snooze(1000*milliseconds);
1713 # error "Time delay method not defined."
1718 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1722 % M u l t i l i n e C e n s u s %
1726 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1728 % MultilineCensus() returns the number of lines within a label. A line is
1729 % represented by a \n character.
1731 % The format of the MultilineCenus method is:
1733 % size_t MultilineCensus(const char *label)
1735 % A description of each parameter follows.
1737 % o label: This character string is the label.
1740 MagickExport size_t MultilineCensus(const char *label)
1746 Determine the number of lines within this label.
1748 if (label == (char *) NULL)
1750 for (number_lines=1; *label != '\0'; label++)
1753 return(number_lines);
1757 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1761 % S y s t e m C o m m a n d %
1765 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1767 % SystemCommand() executes the specified command and waits until it
1768 % terminates. The returned value is the exit status of the command.
1770 % The format of the SystemCommand method is:
1772 % int SystemCommand(const MagickBooleanType asynchronous,
1773 % const MagickBooleanType verbose,const char *command,
1774 % ExceptionInfo *exception)
1776 % A description of each parameter follows:
1778 % o asynchronous: a value other than 0 executes the parent program
1779 % concurrently with the new child process.
1781 % o verbose: a value other than 0 prints the executed command before it is
1784 % o command: this string is the command to execute.
1786 % o exception: return any errors here.
1789 MagickExport int SystemCommand(const MagickBooleanType asynchronous,
1790 const MagickBooleanType verbose,const char *command,ExceptionInfo *exception)
1810 arguments=StringToArgv(command,&number_arguments);
1811 if (arguments == (char **) NULL)
1813 rights=ExecutePolicyRights;
1814 domain=DelegatePolicyDomain;
1815 if (IsRightsAuthorized(domain,rights,arguments[1]) == MagickFalse)
1818 (void) ThrowMagickException(exception,GetMagickModule(),PolicyError,
1819 "NotAuthorized","'%s'",arguments[1]);
1820 for (i=0; i < (ssize_t) number_arguments; i++)
1821 arguments[i]=DestroyString(arguments[i]);
1822 arguments=(char **) RelinquishMagickMemory(arguments);
1825 if (verbose != MagickFalse)
1827 (void) FormatLocaleFile(stderr,"%s\n",command);
1828 (void) fflush(stderr);
1830 shell_command=(char *) command;
1831 if (asynchronous != MagickFalse)
1833 shell_command=AcquireString(command);
1834 (void) ConcatenateMagickString(shell_command,"&",MaxTextExtent);
1836 #if defined(MAGICKCORE_POSIX_SUPPORT)
1837 #if !defined(MAGICKCORE_HAVE_EXECVP)
1838 status=system(shell_command);
1840 if ((asynchronous != MagickFalse) ||
1841 (strpbrk(shell_command,"&;<>|") != (char *) NULL))
1842 status=system(shell_command);
1849 Call application directly rather than from a shell.
1851 child_pid=(pid_t) fork();
1852 if (child_pid == (pid_t) -1)
1853 status=system(command);
1857 status=execvp(arguments[1],arguments+1);
1869 pid=(pid_t) waitpid(child_pid,&child_status,0);
1874 if (WIFEXITED(child_status) != 0)
1875 status=WEXITSTATUS(child_status);
1877 if (WIFSIGNALED(child_status))
1883 #elif defined(MAGICKCORE_WINDOWS_SUPPORT)
1884 status=NTSystemCommand(shell_command);
1885 #elif defined(macintosh)
1886 status=MACSystemCommand(shell_command);
1888 status=system(shell_command);
1890 # error No suitable system() method.
1893 (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,
1894 "'%s' (%d)",command,status);
1895 if (shell_command != command)
1896 shell_command=DestroyString(shell_command);
1897 for (i=0; i < (ssize_t) number_arguments; i++)
1898 arguments[i]=DestroyString(arguments[i]);
1899 arguments=(char **) RelinquishMagickMemory(arguments);