1 /* Copyright (C) 2001-2012 Artifex Software, Inc.
2    All Rights Reserved.
3 
4    This software is provided AS-IS with no warranty, either express or
5    implied.
6 
7    This software is distributed under license and may not be copied,
8    modified or distributed except as expressly authorized under the terms
9    of the license contained in the file LICENSE in this distribution.
10 
11    Refer to licensing information at http://www.artifex.com or contact
12    Artifex Software, Inc.,  7 Mt. Lassen Drive - Suite A-134, San Rafael,
13    CA  94903, U.S.A., +1(415)492-9861, for further information.
14 */
15 
16 
17 /* Interface to platform-specific routines */
18 /* Requires gsmemory.h */
19 
20 #ifndef gp_INCLUDED
21 #  define gp_INCLUDED
22 
23 #include "gstypes.h"
24 #include "gscdefs.h"		/* for gs_serialnumber */
25 /*
26  * This file defines the interface to ***ALL*** platform-specific routines,
27  * with the exception of the thread/synchronization interface (gpsync.h)
28  * and getenv (gpgetenv.h).  The implementations are in gp_*.c files
29  * specific to each platform.  We try very hard to keep this list short!
30  */
31 /*
32  * gp_getenv is declared in a separate file because a few places need it
33  * and don't want to include any of the other gs definitions.
34  */
35 #include "gpgetenv.h"
36 /*
37  * The prototype for gp_readline is in srdline.h, since it is shared with
38  * stream.h.
39  */
40 #include "srdline.h"
41 
42 /*
43  * int64_t is used in the 64 bits file access.
44  */
45 #include "stdint_.h"
46 
47 /* ------ Initialization/termination ------ */
48 
49 /*
50  * This routine is called early in the initialization.
51  * It should do as little as possible.  In particular, it should not
52  * do things like open display connections: that is the responsibility
53  * of the display device driver.
54  */
55 void gp_init(void);
56 
57 /*
58  * This routine is called just before the program exits (normally or
59  * abnormally).  It too should do as little as possible.
60  */
61 void gp_exit(int exit_status, int code);
62 
63 /*
64  * Exit the program.  Normally this just calls the `exit' library procedure,
65  * but it does something different on a few platforms.
66  */
67 void gp_do_exit(int exit_status);
68 
69 /* ------ Miscellaneous ------ */
70 
71 /*
72  * Get the string corresponding to an OS error number.
73  * If no string is available, return NULL.  The caller may assume
74  * the string is allocated statically and permanently.
75  */
76 const char *gp_strerror(int);
77 
78 /*
79  * Get the system default paper size, which is usually letter for
80  * countries using the imperial system, and a4 for countries
81  * using the metric system.
82  *
83  * If there is no default paper size, set *ptr = 0 (if *plen > 0),
84  * set *plen = 1, and return 1.
85  *
86  * If there is a default paper size and the length len of the value
87  * (not counting the terminating \0) is less than *plen,
88  * copy the value to ptr, set *plen = len + 1, and return 0.
89  *
90  * If there is a default paper size and len >= *plen, set *plen = len + 1,
91  * don't store anything at ptr, and return -1.
92  *
93  * Note that *plen is the size of the buffer, not the length of the string:
94  * because of the terminating \0, the maximum string length is 1 less than
95  * the size of the buffer.
96  *
97  * The use of ptr and plen as described above are the same as gp_getenv.
98  */
99 int gp_defaultpapersize(char *ptr, int *plen);
100 
101 /*
102  * Return a serialnumber. Clients that want to can modify the appropriate
103  * gp_***.c file(s) for their platform and Digital Rights Management (DRM)
104  * of choice. Default handlers for common platforms use info from the OS
105  * and unsupported or old platforms simply return GS_SERIALNUMBER.
106  */
107 int gp_serialnumber(void);
108 
109 /* ------ Date and time ------ */
110 
111 /*
112  * Read the current time (in seconds since an implementation-defined epoch)
113  * into ptm[0], and fraction (in nanoseconds) into ptm[1].
114  */
115 void gp_get_realtime(long ptm[2]);
116 
117 /*
118  * Read the current user CPU time (in seconds) into ptm[0],
119  * and fraction (in nanoseconds) into ptm[1].
120  */
121 void gp_get_usertime(long ptm[2]);
122 
123 /* ------ Reading lines from stdin ------ */
124 
125 /*
126  * These routines are intended to provide an abstract interface to GNU
127  * readline or to other packages that offer enhanced line-reading
128  * capability.
129  */
130 
131 /*
132  * Allocate a state structure for line reading.  This is called once at
133  * initialization.  *preadline_data is an opaque pointer that is passed
134  * back to gp_readline and gp_readline_finit.
135  */
136 int gp_readline_init(void **preadline_data, gs_memory_t *mem);
137 
138 /*
139  * See srdline.h for the definition of sreadline_proc.
140  */
141 int gp_readline(stream *s_in, stream *s_out, void *readline_data,
142                 gs_const_string *prompt, gs_string *buf,
143                 gs_memory_t *bufmem, uint *pcount, bool *pin_eol,
144                 bool (*is_stdin)(const stream *));
145 
146 /*
147  * Free a readline state.
148  */
149 void gp_readline_finit(void *readline_data);
150 
151 /* ------ Reading from stdin, unbuffered if possible ------ */
152 
153 /* Read bytes from stdin, using unbuffered if possible.
154  * Store up to len bytes in buf.
155  * Returns number of bytes read, or 0 if EOF, or -ve if error.
156  * If unbuffered is NOT possible, fetch 1 byte if interactive
157  * is non-zero, or up to len bytes otherwise.
158  * If unbuffered is possible, fetch at least 1 byte (unless error or EOF)
159  * and any additional bytes that are available without blocking.
160  */
161 int gp_stdin_read(char *buf, int len, int interactive, FILE *f);
162 
163 /* ------ Screen management ------ */
164 
165 /*
166  * The following are only relevant for X Windows.
167  */
168 
169 /* Get the environment variable that specifies the display to use. */
170 const char *gp_getenv_display(void);
171 
172 /* ------ File naming and accessing ------ */
173 
174 /*
175  * Define the maximum size of a file name returned by gp_open_scratch_file
176  * or gp_open_printer.  (This should really be passed as an additional
177  * parameter, but it would break too many clients to make this change now.)
178  * Note that this is the size of the buffer, not the maximum number of
179  * characters: the latter is one less, because of the terminating \0.
180  */
181 #define gp_file_name_sizeof 260 /* == MAX_PATH on Windows */
182 
183 /* Define the character used for separating file names in a list. */
184 extern const char gp_file_name_list_separator;
185 
186 /* Define the default scratch file name prefix. */
187 extern const char gp_scratch_file_name_prefix[];
188 
189 /* Define the name of the null output file. */
190 extern const char gp_null_file_name[];
191 
192 /* Define the name that designates the current directory. */
193 extern const char gp_current_directory_name[];
194 
195 /* Define the string to be concatenated with the file mode */
196 /* for opening files without end-of-line conversion. */
197 /* This is always either "" or "b". */
198 extern const char gp_fmode_binary_suffix[];
199 
200 /* Define the file modes for binary reading or writing. */
201 /* (This is just a convenience: they are "r" or "w" + the suffix.) */
202 extern const char gp_fmode_rb[];
203 extern const char gp_fmode_wb[];
204 
205 /**
206  * gp_open_scratch_file: Create a scratch file.
207  * @mem: Memory pointer
208  * @prefix: Name prefix.
209  * @fname: Where to store filename of newly created file.
210  * @mode: File access mode (in fopen syntax).
211  *
212  * Creates a scratch (temporary) file in the filesystem. The exact
213  * location and name of the file is platform dependent, but in general
214  * uses @prefix as a prefix. If @prefix is not absolute, then choose
215  * an appropriate system directory, usually as determined from
216  * gp_gettmpdir(), followed by a path as returned from a system call.
217  *
218  * Implementations should make sure that
219  *
220  * Return value: Opened file object, or NULL on error.
221  **/
222 FILE *gp_open_scratch_file(const gs_memory_t *mem,
223                            const char        *prefix,
224                                  char         fname[gp_file_name_sizeof],
225                            const char        *mode);
226 
227 /* Open a file with the given name, as a stream of uninterpreted bytes. */
228 FILE *gp_fopen(const char *fname, const char *mode);
229 
230 /* Force given file into binary mode (no eol translations, etc) */
231 /* if 2nd param true, text mode if 2nd param false */
232 int gp_setmode_binary(FILE * pfile, bool mode);
233 
234 typedef enum {
235     gp_combine_small_buffer = -1,
236     gp_combine_cant_handle = 0,
237     gp_combine_success = 1
238 } gp_file_name_combine_result;
239 
240 /*
241  * Combine a file name with a prefix.
242  * Concatenates two paths and reduce parten references and current
243  * directory references from the concatenation when possible.
244  * The trailing zero byte is being added.
245  * Various platforms may share this code.
246  */
247 gp_file_name_combine_result gp_file_name_combine(const char *prefix, uint plen,
248             const char *fname, uint flen, bool no_sibling, char *buffer, uint *blen);
249 
250 /* -------------- Helpers for gp_file_name_combine_generic ------------- */
251 /* Platforms, which do not call gp_file_name_combine_generic, */
252 /* must stub the helpers against linkage problems. */
253 
254 /* Return length of root prefix of the file name, or zero. */
255 /*	unix:   length("/")	    */
256 /*	Win:    length("c:/") or length("//computername/cd:/")  */
257 /*	mac:	length("volume:")    */
258 /*	VMS:	length("device:[root.]["	    */
259 uint gp_file_name_root(const char *fname, uint len);
260 
261 /* Check whether a part of file name starts (ends) with a separator. */
262 /* Must return the length of the separator.*/
263 /* If the 'len' is negative, must search in backward direction. */
264 /*	unix:   '/'	    */
265 /*	Win:    '/' or '\'  */
266 /*	mac:	':' except "::"	    */
267 /*	VMS:	smart - see the implementation   */
268 uint gs_file_name_check_separator(const char *fname, int len, const char *item);
269 
270 /* Check whether a part of file name is a parent reference. */
271 /*	unix, Win:  equal to ".."	*/
272 /*	mac:	equal to ":"		*/
273 /*	VMS:	equal to "."		*/
274 bool gp_file_name_is_parent(const char *fname, uint len);
275 
276 /* Check if a part of file name is a current directory reference. */
277 /*	unix, Win:  equal to "."	*/
278 /*	mac:	equal to ""		*/
279 /*	VMS:	equal to ""		*/
280 bool gp_file_name_is_current(const char *fname, uint len);
281 
282 /* Returns a string for referencing the current directory. */
283 /*	unix, Win:  "."	    */
284 /*	mac:	":"	    */
285 /*	VMS:	""          */
286 const char *gp_file_name_current(void);
287 
288 /* Returns a string for separating a file name item. */
289 /*	unix, Win:  "/"	    */
290 /*	mac:	":"	    */
291 /*	VMS:	"]"	    */
292 const char *gp_file_name_separator(void);
293 
294 /* Returns a string for separating a directory item. */
295 /*	unix, Win:  "/"	    */
296 /*	mac:	":"	    */
297 /*	VMS:	"."	    */
298 const char *gp_file_name_directory_separator(void);
299 
300 /* Returns a string for representing a parent directory reference. */
301 /*	unix, Win:  ".."    */
302 /*	mac:	":"	    */
303 /*	VMS:	"."	    */
304 const char *gp_file_name_parent(void);
305 
306 /* Answer whether the platform allows parent refenences. */
307 /*	unix, Win, Mac: yes */
308 /*	VMS:	no.         */
309 bool gp_file_name_is_partent_allowed(void);
310 
311 /* Answer whether an empty item is meanful in file names on the platform. */
312 /*	unix, Win:  no	    */
313 /*	mac:	yes	    */
314 /*	VMS:	yes         */
315 bool gp_file_name_is_empty_item_meanful(void);
316 
317 /* Read a 'resource' stored in a special database indexed by a 32 bit  */
318 /* 'type' and 16 bit 'id' in an extended attribute of a file. The is   */
319 /* primarily for accessing fonts on MacOS, which classically used this */
320 /* format. Presumedly a 'nop' on systems that don't support Apple HFS. */
321 int gp_read_macresource(byte *buf, const char *fname,
322                                      const uint type, const ushort id);
323 
324 /* ------ persistent cache interface ------ */
325 
326 /*
327  * This is used for access to data cached between invocations of
328  * Ghostscript. It is generally used for saving reusable data that
329  * is expensive to compute. Concurrent access by multiple instances
330  * is safe. Because of this care should be taken to use a new data
331  * type when the format of the cached data changes.
332  *
333  * Generic data buffers are stored under a combination of type and
334  * key. It is up the to client to interpret the data buffer appropriately.
335  * An insert overwrites any previous entry under that type and key.
336  * A query if successful uses the passed callback to allocate a buffer
337  * and fills it with the retrieved data. The caller is thus responsible
338  * for the buffer's memory management.
339  *
340  * See zmisc.c for postscript test operators and an example implementation.
341  */
342 
343 /* return 0 on successful insert, non-zero otherwise */
344 int gp_cache_insert(int type, byte *key, int keylen, void *buffer, int buflen);
345 
346 /* return the length of the buffer on success, a negative value otherwise */
347 typedef void *(*gp_cache_alloc)(void *userdata, int bytes);
348 int gp_cache_query(int type, byte* key, int keylen, void **buffer,
349     gp_cache_alloc alloc, void *userdata);
350 
351 /* cache data types */
352 #define GP_CACHE_TYPE_TEST 0
353 #define GP_CACHE_TYPE_FONTMAP 1
354 
355 /* ------ Printer accessing ------ */
356 
357 /*
358  * Open a connection to a printer.  A null file name means use the standard
359  * printer connected to the machine, if any.  Note that this procedure is
360  * called only if the original file name (normally the value of the
361  * OutputFile device parameter) was an ordinary file (not stdout, a pipe, or
362  * other %filedevice%file name): stdout is handled specially, and other
363  * values of filedevice are handled by calling the fopen procedure
364  * associated with that kind of "file".
365  *
366  * Note that if the file name is null (0-length) and a default printer is
367  * available, the file name may be replaced with the name of a scratch file
368  * for spooling.  If the file name is null and no default printer is
369  * available, this procedure returns 0.
370  */
371 FILE *gp_open_printer(const gs_memory_t *mem,
372                             char         fname[gp_file_name_sizeof],
373                             int          binary_mode);
374 
375 /*
376  * Close the connection to the printer.  Note that this is only called
377  * if the original file name was an ordinary file (not stdout, a pipe,
378  * or other %filedevice%file name): stdout is handled specially, and other
379  * values of filedevice are handled by calling the fclose procedure
380  * associated with that kind of "file".
381  */
382 void gp_close_printer(const gs_memory_t *mem,
383                             FILE        *pfile,
384                       const char        *fname);
385 
386 /* ------ File enumeration ------ */
387 
388 #ifndef file_enum_DEFINED	/* also defined in iodev.h */
389 #  define file_enum_DEFINED
390 typedef struct file_enum_s file_enum;
391 #endif
392 
393 /*
394  * Begin an enumeration.  pat is a C string that may contain *s or ?s.
395  * The implementor should copy the string to a safe place.
396  * If the operating system doesn't support correct, arbitrarily placed
397  * *s and ?s, the implementation should modify the string so that it
398  * will return a conservative superset of the request, and then use
399  * the string_match procedure to select the desired subset.  E.g., if the
400  * OS doesn't implement ? (single-character wild card), any consecutive
401  * string of ?s should be interpreted as *.  Note that \ can appear in
402  * the pattern also, as a quoting character.
403  */
404 file_enum *gp_enumerate_files_init(const char *pat, uint patlen,
405                                    gs_memory_t * memory);
406 
407 /*
408  * Return the next file name in the enumeration.  The client passes in
409  * a scratch string and a max length.  If the name of the next file fits,
410  * the procedure returns the length.  If it doesn't fit, the procedure
411  * returns max length +1.  If there are no more files, the procedure
412  * returns -1.
413  */
414 uint gp_enumerate_files_next(file_enum * pfen, char *ptr, uint maxlen);
415 
416 /*
417  * Clean up a file enumeration.  This is only called to abandon
418  * an enumeration partway through: ...next should do it if there are
419  * no more files to enumerate.  This should deallocate the file_enum
420  * structure and any subsidiary structures, strings, buffers, etc.
421  */
422 void gp_enumerate_files_close(file_enum * pfen);
423 
424 /* ------ Font enumeration ------ */
425 
426 /* This is used to query the native os for a list of font names and
427  * corresponding paths. The general idea is to save the hassle of
428  * building a custom fontmap file
429  */
430 
431 /* allocate and initialize the iterator
432    returns a pointer to its local state or NULL on failure */
433 void *gp_enumerate_fonts_init(gs_memory_t *mem);
434 
435 /* get the next element in the font enumeration
436    Takes a pointer to its local state and pointers in which to
437    return C strings. The string 'name' is the font name, 'path'
438    is the access path for the font resource. The returned strings
439    are only safe to reference until until the next call.
440    Returns 0 when no more fonts are available, a positive value
441    on success, or negative value on error. */
442 int gp_enumerate_fonts_next(void *enum_state, char **fontname, char **path);
443 
444 /* clean up and deallocate the iterator */
445 void gp_enumerate_fonts_free(void *enum_state);
446 
447 /* --------- 64 bit file access ----------- */
448 
449 /* The following functions are analogues of ones with
450    same name without the "_64" suffix.
451    They perform same function with allowing big files
452    (over 4 gygabytes length).
453 
454    If the platform does not allow big files,
455    these functions are mapped to regular file i/o functions.
456    On 64 bits platforms they work same as
457    regular file i/o functions.
458 
459    We continue using the old file i/o functions
460    because most files do not need 64 bits access.
461    The upgrading of old code to the new 64 bits access
462    to be done step by step on real necessity,
463    with replacing old function names with
464    new function names through code,
465    together with providing the int64_t type for storing
466    file offsets in intermediate structures and variables.
467 
468    We assume that the result of 64 bits variant of 'ftell'
469    can be represented in int64_t on all platforms,
470    rather the result type of the native 64 bits function is
471    compiler dependent (__off_t on Linux, _off_t on Cygwin,
472    __int64 on Windows).
473  */
474 
475 FILE *gp_fopen_64(const char *filename, const char *mode);
476 
477 FILE *gp_open_scratch_file_64(const gs_memory_t *mem,
478                               const char        *prefix,
479                                     char         fname[gp_file_name_sizeof],
480                               const char        *mode);
481 FILE *gp_open_printer_64(const gs_memory_t *mem,
482                                char         fname[gp_file_name_sizeof],
483                                int          binary_mode);
484 
485 int64_t gp_ftell_64(FILE *strm);
486 
487 int gp_fseek_64(FILE *strm, int64_t offset, int origin);
488 
489 /* We don't define gp_fread_64, gp_fwrite_64,
490    because (1) known platforms allow regular fread, fwrite
491    to be applied to a file opened with O_LARGEFILE,
492    fopen64, etc.; (2) Ghostscript code does not
493    perform writing/reading a long (over 4gb) block
494    in one operation.
495  */
496 
497 #endif /* gp_INCLUDED */
498