home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1996 February / PCWK0296.iso / sharewar / dos / program / gs300sr1 / gs300sr1.exe / ZFILE.C < prev    next >
C/C++ Source or Header  |  1994-07-31  |  24KB  |  774 lines

  1. /* Copyright (C) 1989, 1992, 1993, 1994 Aladdin Enterprises.  All rights reserved.
  2.   
  3.   This file is part of Aladdin Ghostscript.
  4.   
  5.   Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author
  6.   or distributor accepts any responsibility for the consequences of using it,
  7.   or for whether it serves any particular purpose or works at all, unless he
  8.   or she says so in writing.  Refer to the Aladdin Ghostscript Free Public
  9.   License (the "License") for full details.
  10.   
  11.   Every copy of Aladdin Ghostscript must include a copy of the License,
  12.   normally in a plain ASCII text file named PUBLIC.  The License grants you
  13.   the right to copy, modify and redistribute Aladdin Ghostscript, but only
  14.   under certain conditions described in the License.  Among other things, the
  15.   License requires that the copyright notice and this notice be preserved on
  16.   all copies.
  17. */
  18.  
  19. /* zfile.c */
  20. /* Non-I/O file operators */
  21. #include "memory_.h"
  22. #include "string_.h"
  23. #include "ghost.h"
  24. #include "gp.h"
  25. #include "gsstruct.h"            /* for registering root */
  26. #include "errors.h"
  27. #include "oper.h"
  28. #include "estack.h"            /* for filenameforall */
  29. #include "ialloc.h"
  30. #include "ilevel.h"            /* %names only work in Level 2 */
  31. #include "interp.h"            /* gs_errorinfo_put_string prototype */
  32. #include "isave.h"            /* for restore */
  33. #include "iutil.h"
  34. #include "stream.h"
  35. #include "strimpl.h"
  36. #include "gxiodev.h"            /* must come after stream.h */
  37.                     /* and before files.h */
  38. #include "files.h"            /* ditto */
  39. #include "fname.h"            /* ditto */
  40. #include "store.h"
  41.  
  42. /* Import the file_open routine for %os%, which is the default. */
  43. extern iodev_proc_open_file(iodev_os_open_file);
  44.  
  45. /* Forward references: file opening. */
  46. int file_open(P6(const byte *, uint, const char *, uint, ref *, stream **));
  47. stream *file_alloc_stream(P0());
  48.  
  49. /* Forward references: other. */
  50. int file_close_disable(P1(stream *));
  51. private int file_close_file(P1(stream *));
  52. private stream_proc_report_error(filter_report_error);
  53.  
  54. /* Imported from gs.c */
  55. extern char **gs_lib_paths;        /* search path list, */
  56.                     /* terminated by a null pointer */
  57.  
  58. /*
  59.  * Since there can be many file objects referring to the same file/stream,
  60.  * we can't simply free a stream when we close it.  On the other hand,
  61.  * we don't want freed streams to clutter up memory needlessly.
  62.  * Our solution is to retain the freed streams, and reuse them.
  63.  * To prevent an old file object from being able to access a reused stream,
  64.  * we keep a serial number in each stream, and check it against a serial
  65.  * number stored in the file object (as the "size"); when we close a file,
  66.  * we increment its serial number.  If the serial number ever overflows,
  67.  * we leave it at zero, and do not reuse the stream.
  68.  * (This will never happen.)
  69.  *
  70.  * Storage management for this scheme is a little tricky.
  71.  * We maintain an invariant that says that a stream opened at a given
  72.  * save level always uses a stream structure allocated at that level.
  73.  * By doing this, we don't need to keep track separately of streams open
  74.  * at a level vs. streams allocated at a level; this simplifies things.
  75.  */
  76.  
  77. /*
  78.  * The chain of all streams allocated at the current level.
  79.  * We need this so that we can do the right thing for restore.
  80.  * Note that this chain includes both open and closed files.
  81.  */
  82. private ref file_list_ref;        /* t_file */
  83. #define file_list file_list_ref.value.pfile
  84. private ref *file_list_p = &file_list_ref;
  85. private gs_gc_root_t file_list_root;
  86.  
  87. /* File buffer sizes.  For real files, this is arbitrary, */
  88. /* since the C library does its own buffering in addition. */
  89. /* stdout and stderr use smaller buffers, */
  90. /* on the assumption that they are usually not real files. */
  91. /* The buffer size for type 1 encrypted files is NOT arbitrary: */
  92. /* it must be at most 512. */
  93. #define default_buffer_size 512
  94. const uint file_default_buffer_size = default_buffer_size;
  95.  
  96. /* An invalid file object */
  97. stream *invalid_file_entry;    /* exported for zfileio.c */
  98. private gs_gc_root_t invalid_file_root;
  99.  
  100. /* Initialize the file table */
  101. private void
  102. zfile_init(void)
  103. {    stream *s = s_alloc(imemory, "zfile_init");
  104.     /* Initialize the stream for the sake of the GC, */
  105.     /* and so it can act as an empty input stream. */
  106.     sread_string(s, NULL, 0);
  107.     s->next = s->prev = 0;
  108.     s_init_no_id(s);
  109.     invalid_file_entry = s;
  110.     gs_register_struct_root(imemory, &invalid_file_root,
  111.                 (void **)&invalid_file_entry,
  112.                 "invalid_file_entry");
  113.  
  114.     /* Initialize the bookkeeping lists. */
  115.     
  116.     make_file(&file_list_ref, 0, 0, 0);
  117.     gs_register_ref_root(imemory, &file_list_root,
  118.                  (void **)&file_list_p, "file_list");
  119. }
  120.  
  121. /* Make an invalid file object. */
  122. void
  123. make_invalid_file(ref *fp)
  124. {    make_file(fp, 0, ~0, invalid_file_entry);
  125. }
  126.  
  127. /* <name_string> <access_string> file <file> */
  128. int
  129. zfile(register os_ptr op)
  130. {    char file_access[3];
  131.     parsed_file_name pname;
  132.     const byte *astr;
  133.     int code;
  134.     stream *s;
  135.     check_read_type(*op, t_string);
  136.     astr = op->value.const_bytes;
  137.     switch ( r_size(op) )
  138.        {
  139.     case 2:
  140.         if ( astr[1] != '+' )
  141.             return_error(e_invalidfileaccess);
  142.         file_access[1] = '+';
  143.         file_access[2] = 0;
  144.         break;
  145.     case 1:
  146.         file_access[1] = 0;
  147.         break;
  148.     default:
  149.         return_error(e_invalidfileaccess);
  150.        }
  151.     switch ( astr[0] )
  152.        {
  153.     case 'r': case 'w': case 'a':
  154.         break;
  155.     default:
  156.         return_error(e_invalidfileaccess);
  157.        }
  158.     file_access[0] = astr[0];
  159.     code = parse_file_name(op - 1, &pname);
  160.     if ( code < 0 )
  161.         return code;
  162.     if ( pname.iodev == NULL )
  163.         pname.iodev = iodev_default;
  164.     if ( pname.fname == NULL )        /* just a device */
  165.         code = (*pname.iodev->procs.open_device)(pname.iodev,
  166.                     file_access, &s, imemory);
  167.     else                    /* file */
  168.     {    iodev_proc_open_file((*open_file)) =
  169.             pname.iodev->procs.open_file;
  170.         if ( open_file == 0 )
  171.             open_file = iodev_os_open_file;
  172.         code = (*open_file)(pname.iodev, pname.fname, pname.len,
  173.                     file_access, &s, imemory);
  174.     }
  175.     if ( code < 0 )
  176.         return code;
  177.     make_stream_file(op - 1, s, file_access);
  178.     pop(1);
  179.     return code;
  180. }
  181.  
  182. /* ------ Level 2 extensions ------ */
  183.  
  184. /* <string> deletefile - */
  185. int
  186. zdeletefile(register os_ptr op)
  187. {    parsed_file_name pname;
  188.     int code = parse_real_file_name(op, &pname, "deletefile");
  189.     if ( code < 0 )
  190.         return code;
  191.     code = (*pname.iodev->procs.delete_file)(pname.iodev, pname.fname);
  192.     free_file_name(&pname, "deletefile");
  193.     if ( code < 0 )
  194.         return code;
  195.     pop(1);
  196.     return 0;
  197. }
  198.  
  199. /* <template> <proc> <scratch> filenameforall - */
  200. /****** NOT CONVERTED FOR IODEVICES YET ******/
  201. private int file_continue(P1(os_ptr));
  202. private int file_cleanup(P1(os_ptr));
  203. int
  204. zfilenameforall(register os_ptr op)
  205. {    file_enum *pfen;
  206.     int code;
  207.     check_write_type(*op, t_string);
  208.     check_proc(op[-1]);
  209.     check_read_type(op[-2], t_string);
  210.     /* Push a mark, the pattern, the scratch string, the enumerator, */
  211.     /* and the procedure, and invoke the continuation. */
  212.     check_estack(7);
  213.     pfen = gp_enumerate_files_init((char *)op[-2].value.bytes, r_size(op - 2), imemory);
  214.     if ( pfen == 0 )
  215.         return_error(e_VMerror);
  216.     push_mark_estack(es_for, file_cleanup);
  217.     *++esp = op[-2];
  218.     *++esp = *op;
  219.     ++esp;
  220.     make_istruct(esp, 0, pfen);
  221.     *++esp = op[-1];
  222.     pop(3);  op -= 3;
  223.     code = file_continue(op);
  224.     return (code == o_pop_estack ? o_push_estack : code);
  225. }
  226. /* Continuation operator for enumerating files */
  227. private int
  228. file_continue(register os_ptr op)
  229. {    es_ptr pscratch = esp - 2;
  230.     file_enum *pfen = r_ptr(esp - 1, file_enum);
  231.     uint len = r_size(pscratch);
  232.     uint code =
  233.       gp_enumerate_files_next(pfen, (char *)pscratch->value.bytes, len);
  234.     if ( code == ~(uint)0 )        /* all done */
  235.        {    esp -= 4;        /* pop proc, pfen, scratch, mark */
  236.         return o_pop_estack;
  237.        }
  238.     else if ( code > len )        /* overran string */
  239.         return_error(e_rangecheck);
  240.     else
  241.        {    push(1);
  242.         ref_assign(op, pscratch);
  243.         r_set_size(op, code);
  244.         push_op_estack(file_continue);    /* come again */
  245.         *++esp = pscratch[2];    /* proc */
  246.         return o_push_estack;
  247.        }
  248. }
  249. /* Cleanup procedure for enumerating files */
  250. private int
  251. file_cleanup(os_ptr op)
  252. {    gp_enumerate_files_close(r_ptr(esp + 4, file_enum));
  253.     return 0;
  254. }
  255.  
  256. /* <string1> <string2> renamefile - */
  257. int
  258. zrenamefile(register os_ptr op)
  259. {    parsed_file_name pname1, pname2;
  260.     int code = parse_real_file_name(op - 1, &pname1, "renamefile(from)");
  261.     if ( code < 0 )
  262.         return code;
  263.     pname2.fname = 0;
  264.     code = parse_real_file_name(op, &pname2, "renamefile(to)");
  265.     if ( code < 0 || pname1.iodev != pname2.iodev ||
  266.          (code = (*pname1.iodev->procs.rename_file)(pname1.iodev,
  267.                      pname1.fname, pname2.fname)) < 0
  268.        )
  269.     {    if ( code >= 0 )
  270.             code = gs_note_error(e_invalidfileaccess);
  271.     }
  272.     free_file_name(&pname2, "renamefile(to)");
  273.     free_file_name(&pname1, "renamefile(from)");
  274.     if ( code < 0 )
  275.         return code;
  276.     pop(2);
  277.     return 0;
  278. }    
  279.  
  280. /* <file> status <open_bool> */
  281. /* <string> status <pages> <bytes> <ref_time> <creation_time> true */
  282. /* <string> status false */
  283. int
  284. zstatus(register os_ptr op)
  285. {    switch ( r_type(op) )
  286.     {
  287.     case t_file:
  288.         make_bool(op, (s_is_valid(fptr(op)) ? 1 : 0));
  289.         return 0;
  290.     case t_string:
  291.     {    parsed_file_name pname;
  292.         struct stat fstat;
  293.         int code = parse_file_name(op, &pname);
  294.         if ( code < 0 )
  295.             return code;
  296.         code = terminate_file_name(&pname, "status");
  297.         if ( code < 0 )
  298.             return code;
  299.         code = (*pname.iodev->procs.file_status)(pname.iodev,
  300.                 pname.fname, &fstat);
  301.         switch ( code )
  302.         {
  303.         case 0:
  304.             push(4);
  305.             make_int(op - 4, stat_blocks(&fstat));
  306.             make_int(op - 3, fstat.st_size);
  307.             make_int(op - 2, fstat.st_mtime);
  308.             make_int(op - 1, fstat.st_ctime);
  309.             make_bool(op, 1);
  310.             break;
  311.         case e_undefinedfilename:
  312.             make_bool(op, 0);
  313.             code = 0;
  314.         }
  315.         free_file_name(&pname, "status");
  316.         return code;
  317.     }
  318.     default:
  319.         return_error(e_typecheck);
  320.     }
  321. }
  322.  
  323. /* ------ Non-standard extensions ------ */
  324.  
  325. /* <string> findlibfile <found_string> <file> true */
  326. /* <string> findlibfile <string> false */
  327. int
  328. zfindlibfile(register os_ptr op)
  329. {    int code;
  330. #define maxclen 200
  331.     byte cname[maxclen];
  332.     uint clen;
  333.     parsed_file_name pname;
  334.     stream *s;
  335.     check_ostack(2);
  336.     code = parse_file_name(op, &pname);
  337.     if ( code < 0 )
  338.         return code;
  339.     if ( pname.iodev == NULL )
  340.         pname.iodev = iodev_default;
  341.     if ( pname.iodev != iodev_default )
  342.     {    /* Non-OS devices don't have search paths (yet). */
  343.         code = (*pname.iodev->procs.open_file)(pname.iodev,
  344.                     pname.fname, pname.len, "r", &s,
  345.                     imemory);
  346.         if ( code < 0 )
  347.         {    push(1);
  348.             make_false(op);
  349.             return 0;
  350.         }
  351.         make_stream_file(op + 1, s, "r");
  352.     }
  353.     else
  354.     {    byte *cstr;
  355.         code = lib_file_open(pname.fname, pname.len, cname, maxclen,
  356.                      &clen, op + 1);
  357.         if ( code == e_VMerror )
  358.           return code;
  359.         if ( code < 0 )
  360.         {    push(1);
  361.             make_false(op);
  362.             return 0;
  363.         }
  364.         cstr = ialloc_string(clen, "findlibfile");
  365.         if ( cstr == 0 )
  366.             return_error(e_VMerror);
  367.         memcpy(cstr, cname, clen);
  368.         make_string(op, a_all, clen, cstr);
  369.     }
  370.     push(2);
  371.     make_true(op);
  372.     return 0;
  373. }
  374.  
  375. /* ------ Initialization procedure ------ */
  376.  
  377. op_def zfile_op_defs[] = {
  378.     {"1deletefile", zdeletefile},
  379.     {"2file", zfile},
  380.     {"3filenameforall", zfilenameforall},
  381.     {"1findlibfile", zfindlibfile},
  382.     {"2renamefile", zrenamefile},
  383.     {"1status", zstatus},
  384.         /* Internal operators */
  385.     {"0%file_continue", file_continue},
  386.     op_def_end(zfile_init)
  387. };
  388.  
  389. /* ------ Stream opening ------ */
  390.  
  391. /* Make a t_file reference to a stream. */
  392. void
  393. make_stream_file(ref *pfile, stream *s, const char *access)
  394. {    uint attrs =
  395.         (access[1] == '+' ? a_write + a_read + a_execute : 0) |
  396.         imemory_local_attr((gs_ref_memory_t *)s->memory);
  397.     if ( access[0] == 'r' )
  398.     {    make_file(pfile, attrs | (a_read | a_execute), s->read_id, s);
  399.         s->write_id = 0;
  400.     }
  401.     else
  402.     {    make_file(pfile, attrs | a_write, s->write_id, s);
  403.         s->read_id = 0;
  404.     }
  405. }
  406.  
  407. /* Open an OS-level file (like fopen), using the search paths if necessary. */
  408. /* Note that it overwrites the file name; the 'const' on bname is a lie. */
  409. /* Note also that it does not automatically look in the current */
  410. /* directory first (or at all): this is like Unix, and unlike MS-DOS. */
  411. private int
  412. lib_file_fopen(gx_io_device *iodev, const char *bname,
  413.   const char *ignore_access, FILE **pfile)
  414. {    char fmode[3];            /* r, [b], null */
  415.     int len = strlen(bname);
  416.     char **ppath;
  417.     strcpy(fmode, "r");
  418.     strcat(fmode, gp_fmode_binary_suffix);
  419.     if ( gp_file_name_is_absolute(bname, len) )
  420.       return (*iodev->procs.fopen)(iodev, bname, fmode, pfile);
  421.     /* Go through the list of search paths */
  422.     for ( ppath = gs_lib_paths; *ppath != 0; ppath++ )
  423.        {    char *path = *ppath;
  424.         for ( ; ; )
  425.            {    /* Find the end of the next path */
  426.             char *npath = path;
  427.             uint plen;
  428.             const char *cstr;
  429.             int code;
  430.             int up, i;
  431.             while ( *npath != 0 && *npath != gp_file_name_list_separator )
  432.                 npath++;
  433.             plen = npath - path;
  434.             cstr = gp_file_name_concat_string(path, plen,
  435.                               (const char *)bname,
  436.                               len);
  437.             /* Concatenate the prefix, combiner, and file name. */
  438.             up = plen + strlen(cstr);
  439. #define wbname ((char *)bname)        /* break const */
  440.             for ( i = len + 1; --i >= 0; )
  441.                 wbname[i + up] = wbname[i];
  442.             memcpy(wbname, (byte *)path, plen);
  443.             memcpy(wbname + plen, cstr, strlen(cstr));
  444.             code = (*iodev->procs.fopen)(iodev, bname, fmode,
  445.                              pfile);
  446.             if ( code >= 0 )
  447.                 return code;
  448.             /* strcpy isn't guaranteed to work for overlapping */
  449.             /* source and destination, so: */
  450.             for ( i = 0; (wbname[i] = wbname[i + up]) != 0; i++ )
  451.               ;
  452. #undef wbname
  453.             if ( !*npath ) break;
  454.             path = npath + 1;
  455.            }
  456.        }
  457.     return_error(e_undefinedfilename);
  458. }
  459. /* The startup code calls this to open @-files. */
  460. FILE *
  461. lib_fopen(const char *bname)
  462. {    FILE *file = NULL;
  463.     int code = lib_file_fopen(iodev_default, bname, "r", &file);
  464.     return (code < 0 ? NULL : file);
  465. }
  466.  
  467. /* Open a file stream on an OS file and create a file object, */
  468. /* using the search paths. */
  469. /* The startup code calls this to open the initialization file gs_init.ps. */
  470. int
  471. lib_file_open(const char *fname, uint len, byte *cname, uint max_clen,
  472.   uint *pclen, ref *pfile)
  473. {    stream *s;
  474.     int code = file_open_stream(fname, len, "r",
  475.                     default_buffer_size, &s, lib_file_fopen);
  476.     char *bname;
  477.     uint blen;
  478.     if ( code < 0 ) return code;
  479.     /* Get the name from the stream buffer. */
  480.     bname = (char *)s->cbuf;
  481.     blen = strlen(bname);
  482.     if ( blen > max_clen )
  483.     {    sclose(s);
  484.         return_error(e_limitcheck);
  485.     }
  486.     memcpy(cname, bname, blen);
  487.     *pclen = blen;
  488.     make_stream_file(pfile, s, "r");
  489.     return 0;
  490. }
  491.  
  492. /* Open a file stream that reads a string. */
  493. /* (This is currently used only by gs_run_string and the ccinit feature.) */
  494. /* The string must be allocated in non-garbage-collectable (foreign) space. */
  495. int
  496. file_read_string(const byte *str, uint len, ref *pfile)
  497. {    register stream *s = file_alloc_stream();
  498.     if ( s == 0 )
  499.         return_error(e_VMerror);
  500.     sread_string(s, str, len);
  501.     s->foreign = 1;
  502.     s->write_id = 0;
  503.     make_file(pfile, a_readonly | ilocal_attr, s->read_id, s);
  504.     s->save_close = s->procs.close;
  505.     s->procs.close = file_close_disable;
  506.     return 0;
  507. }
  508.  
  509. /* Open a file stream, optionally on an OS file. */
  510. /* Return 0 if successful, error code if not. */
  511. /* On a successful return, the C file name is in the stream buffer. */
  512. /* If fname==0, set up the file entry, stream, and buffer, */
  513. /* but don't open an OS file or initialize the stream. */
  514. int
  515. file_open_stream(const char *fname, uint len, const char *file_access,
  516.   uint buffer_size, stream **ps, iodev_proc_fopen_t fopen_proc)
  517. {    byte *buffer;
  518.     register stream *s;
  519.     if ( buffer_size == 0 )
  520.       buffer_size = default_buffer_size;
  521.     if ( len >= buffer_size )
  522.       return_error(e_limitcheck);    /* we copy the file name into the buffer */
  523.     /* Allocate the stream first, since it persists */
  524.     /* even after the file has been closed. */
  525.       s = file_alloc_stream();
  526.     if ( s == 0 )
  527.         return_error(e_VMerror);
  528.     /* Allocate the buffer. */
  529.     buffer = ialloc_bytes(buffer_size, "file_open(buffer)");
  530.     if ( buffer == 0 )
  531.         return_error(e_VMerror);
  532.     if ( fname != 0 )
  533.        {    /* Copy the name (so we can terminate it with a zero byte.) */
  534.         char *file_name = (char *)buffer;
  535.         char fmode[4];        /* r/w/a, [+], [b], null */
  536.         FILE *file;
  537.         int code;
  538.         memcpy(file_name, fname, len);
  539.         file_name[len] = 0;        /* terminate string */
  540.         /* Open the file, always in binary mode. */
  541.         strcpy(fmode, file_access);
  542.         strcat(fmode, gp_fmode_binary_suffix);
  543.         /****** iodev_default IS QUESTIONABLE ******/
  544.         code = (*fopen_proc)(iodev_default, file_name, fmode, &file);
  545.         if (code < 0 )
  546.         {    ifree_object(buffer, "file_open(buffer)");
  547.             return code;
  548.         }
  549.         /* Set up the stream. */
  550.         switch ( *file_access )
  551.         {
  552.         case 'a':
  553.             sappend_file(s, file, buffer, buffer_size);
  554.             break;
  555.         case 'r':
  556.             sread_file(s, file, buffer, buffer_size);
  557.             break;
  558.         case 'w':
  559.             swrite_file(s, file, buffer, buffer_size);
  560.         }
  561.         s->save_close = s->procs.close;
  562.         s->procs.close = file_close_file;
  563.        }
  564.     else                /* save the buffer and size */
  565.        {    s->cbuf = buffer;
  566.         s->bsize = s->cbsize = buffer_size;
  567.        }
  568.     *ps = s;
  569.     return 0;
  570. }
  571.  
  572. /* Open a file stream for a filter. */
  573. int
  574. filter_open(const char *file_access, uint buffer_size, ref *pfile,
  575.   const stream_procs _ds *procs, const stream_template *template,
  576.   const stream_state *st, stream **ps)
  577. {    stream *s;
  578.     uint ssize = gs_struct_type_size(template->stype);
  579.     stream_state *sst = 0;
  580.     int code;
  581.     if ( template->stype != &st_stream_state )
  582.     {    sst = s_alloc_state(imemory, template->stype,
  583.                     "filter_open(stream_state)");
  584.         if ( sst == 0 )
  585.           return_error(e_VMerror);
  586.     }
  587.     code = file_open_stream((char *)0, 0, file_access,
  588.                 buffer_size, &s, (iodev_proc_fopen_t)0);
  589.     if ( code < 0 )
  590.     {    ifree_object(sst, "filter_open(stream_state)");
  591.         return code;
  592.     }
  593.     s_std_init(s, s->cbuf, s->bsize, procs,
  594.            (*file_access == 'r' ? s_mode_read : s_mode_write));
  595.     make_stream_file(pfile, s, file_access);
  596.     s->procs.process = template->process;
  597.     s->save_close = s->procs.close;
  598.     s->procs.close = file_close_file;
  599.     if ( sst == 0 )
  600.     {    /* This stream doesn't have any state of its own. */
  601.         /* Hack: use the stream itself as the state. */
  602.         sst = (stream_state *)s;
  603.     }
  604.     else if ( st != 0 )    /* might not have client parameters */
  605.         memcpy(sst, st, ssize);
  606.     s->state = sst;
  607.     sst->template = template;
  608.     sst->memory = imemory;
  609.     sst->report_error = filter_report_error;
  610.     if ( template->init != 0 )
  611.     {    code = (*template->init)(sst);
  612.         if ( code < 0 )
  613.         {    ifree_object(sst, "filter_open(stream_state)");
  614.             ifree_object(s->cbuf, "filter_open(buffer)");
  615.             return code;
  616.         }
  617.     }
  618.     *ps = s;
  619.     return 0;
  620. }
  621.  
  622. /* Report an error by storing it in $error.errorinfo. */
  623. private int
  624. filter_report_error(stream_state *st, const char *str)
  625. {    if_debug1('s', "[s]stream error: %s\n", str);
  626.     return gs_errorinfo_put_string(str);
  627. }
  628.  
  629. /* Ensure a minimum size for a stream. */
  630. int
  631. file_ensure_buf(stream *s, uint min_size)
  632. {    byte *nbuf;
  633.     gs_memory_t *mem = s->state->memory;
  634.     if ( s->bsize == 0 /* stream is closed */ || s->bsize >= min_size )
  635.       return 0;
  636.     nbuf = gs_alloc_bytes(mem, min_size, "file_ensure_buf(new)");
  637.     if ( nbuf == 0 )
  638.       return_error(e_VMerror);
  639.     /* Copy the data from the old buffer to the new one. */
  640.     memcpy(nbuf, s->cbuf, s->cbsize);
  641.     s->srptr = (const byte *)(nbuf + (s->srptr - s->cbuf));
  642.     s->swptr = nbuf + (s->swptr - s->cbuf);    /* = srlimit */
  643.     s->swlimit = nbuf + min_size;
  644.     gs_free_object(mem, s->cbuf, "file_ensure_buf(old)");
  645.     s->cbuf = nbuf;
  646.     s->bsize = s->cbsize = min_size;
  647.     return 0;
  648. }
  649.  
  650. /* Allocate and return a file stream. */
  651. /* Return 0 if the allocation failed. */
  652. /* The stream is initialized to an invalid state, so the caller need not */
  653. /* worry about cleaning up if a later step in opening the stream fails. */
  654. stream *
  655. file_alloc_stream(void)
  656. {    stream *s;
  657.     /* Look first for a free stream allocated at this level. */
  658.     s = file_list;
  659.     while ( s != 0 )
  660.     {    if ( !s_is_valid(s) && s->read_id != 0 /* i.e. !overflowed */
  661.              && s->memory == imemory
  662.            )
  663.         {    s->strm_is_temp = 0;    /* not a temp stream */
  664.             return s;
  665.         }
  666.         s = s->next;
  667.     }
  668.     s = s_alloc(imemory, "file_open(stream)");
  669.     if ( s == 0 )
  670.         return 0;
  671.     s_init_ids(s);
  672.     s->strm_is_temp = 0;        /* not a temp stream */
  673.     /* Disable the stream now (in case we can't open the file, */
  674.     /* or a filter init procedure fails) so that `restore' won't */
  675.     /* crash when it tries to close open files. */
  676.     s_disable(s);
  677.     /* Add s to the list of files. */
  678.     if ( file_list != 0 )
  679.         file_list->prev = s;
  680.     s->next = file_list;
  681.     s->prev = 0;
  682.     file_list = s;
  683.     return s;
  684. }
  685.  
  686. /* ------ Stream closing ------ */
  687.  
  688. /* Finish closing a file stream.  This used to check whether it was */
  689. /* currentfile, but we don't have to do this any longer. */
  690. /* This replaces the close procedure for the std* streams, */
  691. /* which cannot actually be closed. */
  692. /* This is exported for ziodev.c. */
  693. int
  694. file_close_finish(stream *s)
  695. {    return 0;
  696. }
  697.  
  698. /* Close a file stream, but don't deallocate the buffer. */
  699. /* This replaces the close procedure for %lineedit and %statementedit. */
  700. /* (This is WRONG: these streams should allocate a new buffer each time */
  701. /* they are opened, but that would overstress the allocator right now.) */
  702. /* This is exported for ziodev.c. */
  703. /* This also replaces the close procedure for the string-reading */
  704. /* stream created for gs_run_string. */
  705. int
  706. file_close_disable(stream *s)
  707. {    int code = (*s->save_close)(s);
  708.     if ( code )
  709.         return code;
  710.     /* Increment the IDs to prevent further access. */
  711.     s->read_id = s->write_id = (s->read_id | s->write_id) + 1;
  712.     return file_close_finish(s);
  713. }
  714.  
  715. /* Close a file stream.  This replaces the close procedure in the stream */
  716. /* for normal (OS) files and for filters. */
  717. private int
  718. file_close_file(stream *s)
  719. {    stream *stemp = (s->strm_is_temp ? s->strm : 0);
  720.     gs_memory_t *mem = s->memory;
  721.     int code = file_close_disable(s);
  722.     if ( code )
  723.         return code;
  724.     gs_free_object(mem, s->cbuf, "file_close(buffer)");
  725.     /* Check for temporary streams created for filters. */
  726.     /* In the case of a procedure-based filter, */
  727.     /* there may be two of them. */
  728.     if ( stemp != 0 )
  729.     {    stream *snext = stemp->strm;
  730.         if ( snext != 0 )
  731.         {    gs_memory_t *smem = snext->memory;
  732.             gs_free_object(smem, stemp->cbuf,
  733.                        "file_close(2nd buffer)");
  734.             gs_free_object(smem, stemp,
  735.                        "file_close(2nd temp stream)");
  736.             stemp = snext;
  737.         }
  738.         mem = stemp->memory;
  739.         gs_free_object(mem, stemp, "file_close(temp stream)");
  740.     }
  741.     return 0;
  742. }
  743.  
  744. /* Close a file object. */
  745. /* This is exported only for gsmain.c. */
  746. int
  747. file_close(ref *pfile)
  748. {    if ( sclose(fptr(pfile)) )
  749.         return_error(e_ioerror);
  750.     return 0;
  751. }
  752.  
  753. /* ------ Memory management ------ */
  754.  
  755. /* Arrange to save the current file list at a save. */
  756. void
  757. file_save(void)
  758. {    ref_mark_old(&file_list_ref);
  759.     ref_save(NULL, &file_list_ref, "file_save");
  760.     make_file(&file_list_ref, 0, 0, 0);
  761. }
  762.  
  763. /* Close inaccessible files just before a restore. */
  764. void
  765. file_restore(const alloc_save_t *save)
  766. {    stream *s = file_list;
  767.     while ( s != 0 )
  768.     {    if ( s_is_valid(s) )
  769.             sclose(s);
  770.         s = s->next;
  771.     }
  772.     file_list = 0;
  773. }
  774.