stream.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  1. /* Copyright (C) 1989, 2000, 2001 Aladdin Enterprises. All rights reserved.
  2. This file is part of AFPL Ghostscript.
  3. AFPL Ghostscript is distributed with NO WARRANTY OF ANY KIND. No author or
  4. distributor accepts any responsibility for the consequences of using it, or
  5. for whether it serves any particular purpose or works at all, unless he or
  6. she says so in writing. Refer to the Aladdin Free Public License (the
  7. "License") for full details.
  8. Every copy of AFPL Ghostscript must include a copy of the License, normally
  9. in a plain ASCII text file named PUBLIC. The License grants you the right
  10. to copy, modify and redistribute AFPL Ghostscript, but only under certain
  11. conditions described in the License. Among other things, the License
  12. requires that the copyright notice and this notice be preserved on all
  13. copies.
  14. */
  15. /*$Id: stream.c,v 1.15 2001/10/19 21:52:50 raph Exp $ */
  16. /* Stream package for Ghostscript interpreter */
  17. #include "stdio_.h" /* includes std.h */
  18. #include "memory_.h"
  19. #include "gdebug.h"
  20. #include "gpcheck.h"
  21. #include "stream.h"
  22. #include "strimpl.h"
  23. /* Forward declarations */
  24. private int sreadbuf(P2(stream *, stream_cursor_write *));
  25. private int swritebuf(P3(stream *, stream_cursor_read *, bool));
  26. private void stream_compact(P2(stream *, bool));
  27. /* Structure types for allocating streams. */
  28. public_st_stream();
  29. public_st_stream_state(); /* default */
  30. /* GC procedures */
  31. private
  32. ENUM_PTRS_WITH(stream_enum_ptrs, stream *st) return 0;
  33. case 0:
  34. if (st->foreign)
  35. ENUM_RETURN(NULL);
  36. else if (st->cbuf_string.data != 0)
  37. ENUM_RETURN_STRING_PTR(stream, cbuf_string);
  38. else
  39. ENUM_RETURN(st->cbuf);
  40. ENUM_PTR3(1, stream, strm, prev, next);
  41. ENUM_PTR(4, stream, state);
  42. case 5: return ENUM_CONST_STRING(&st->file_name);
  43. ENUM_PTRS_END
  44. private RELOC_PTRS_WITH(stream_reloc_ptrs, stream *st)
  45. {
  46. byte *cbuf_old = st->cbuf;
  47. if (cbuf_old != 0 && !st->foreign) {
  48. long reloc;
  49. if (st->cbuf_string.data != 0) {
  50. RELOC_STRING_VAR(st->cbuf_string);
  51. st->cbuf = st->cbuf_string.data;
  52. } else
  53. RELOC_VAR(st->cbuf);
  54. reloc = cbuf_old - st->cbuf;
  55. /* Relocate the other buffer pointers. */
  56. st->srptr -= reloc;
  57. st->srlimit -= reloc; /* same as swptr */
  58. st->swlimit -= reloc;
  59. }
  60. RELOC_VAR(st->strm);
  61. RELOC_VAR(st->prev);
  62. RELOC_VAR(st->next);
  63. RELOC_VAR(st->state);
  64. RELOC_CONST_STRING_VAR(st->file_name);
  65. }
  66. RELOC_PTRS_END
  67. /* Finalize a stream by closing it. */
  68. /* We only do this for file streams, because other kinds of streams */
  69. /* may attempt to free storage when closing. */
  70. private void
  71. stream_finalize(void *vptr)
  72. {
  73. stream *const st = vptr;
  74. if_debug2('u', "[u]%s 0x%lx\n",
  75. (!s_is_valid(st) ? "already closed:" :
  76. st->is_temp ? "is_temp set:" :
  77. st->file == 0 ? "not file:" :
  78. "closing file:"), (ulong) st);
  79. if (s_is_valid(st) && !st->is_temp && st->file != 0) {
  80. /* Prevent any attempt to free the buffer. */
  81. st->cbuf = 0;
  82. st->cbuf_string.data = 0;
  83. sclose(st); /* ignore errors */
  84. }
  85. }
  86. /* Dummy template for streams that don't have a separate state. */
  87. private const stream_template s_no_template = {
  88. &st_stream_state, 0, 0, 1, 1, 0
  89. };
  90. /* ------ Generic procedures ------ */
  91. /* Allocate a stream and initialize it minimally. */
  92. void
  93. s_init(stream *s, gs_memory_t * mem)
  94. {
  95. s->memory = mem;
  96. s->report_error = s_no_report_error;
  97. s->min_left = 0;
  98. s->error_string[0] = 0;
  99. s->prev = s->next = 0; /* clean for GC */
  100. s->file_name.data = 0; /* ibid. */
  101. s->file_name.size = 0;
  102. s->close_strm = false; /* default */
  103. s->close_at_eod = true; /* default */
  104. }
  105. stream *
  106. s_alloc(gs_memory_t * mem, client_name_t cname)
  107. {
  108. stream *s = gs_alloc_struct(mem, stream, &st_stream, cname);
  109. if_debug2('s', "[s]alloc(%s) = 0x%lx\n",
  110. client_name_string(cname), (ulong) s);
  111. if (s == 0)
  112. return 0;
  113. s_init(s, mem);
  114. return s;
  115. }
  116. /* Allocate a stream state and initialize it minimally. */
  117. void
  118. s_init_state(stream_state *st, const stream_template *template,
  119. gs_memory_t *mem)
  120. {
  121. st->template = template;
  122. st->memory = mem;
  123. st->report_error = s_no_report_error;
  124. st->min_left = 0;
  125. }
  126. stream_state *
  127. s_alloc_state(gs_memory_t * mem, gs_memory_type_ptr_t stype,
  128. client_name_t cname)
  129. {
  130. stream_state *st = gs_alloc_struct(mem, stream_state, stype, cname);
  131. if_debug3('s', "[s]alloc_state %s(%s) = 0x%lx\n",
  132. client_name_string(cname),
  133. client_name_string(stype->sname),
  134. (ulong) st);
  135. if (st)
  136. s_init_state(st, NULL, mem);
  137. return st;
  138. }
  139. /* Standard stream initialization */
  140. void
  141. s_std_init(register stream * s, byte * ptr, uint len, const stream_procs * pp,
  142. int modes)
  143. {
  144. s->template = &s_no_template;
  145. s->cbuf = ptr;
  146. s->srptr = s->srlimit = s->swptr = ptr - 1;
  147. s->swlimit = ptr - 1 + len;
  148. s->end_status = 0;
  149. s->foreign = 0;
  150. s->modes = modes;
  151. s->cbuf_string.data = 0;
  152. s->position = 0;
  153. s->bsize = s->cbsize = len;
  154. s->strm = 0; /* not a filter */
  155. s->is_temp = 0;
  156. s->procs = *pp;
  157. s->state = (stream_state *) s; /* hack to avoid separate state */
  158. s->file = 0;
  159. s->file_name.data = 0; /* in case stream is on stack */
  160. s->file_name.size = 0;
  161. if_debug4('s', "[s]init 0x%lx, buf=0x%lx, len=%u, modes=%d\n",
  162. (ulong) s, (ulong) ptr, len, modes);
  163. }
  164. /* Set the file name of a stream, copying the name. */
  165. /* Return <0 if the copy could not be allocated. */
  166. int
  167. ssetfilename(stream *s, const byte *data, uint size)
  168. {
  169. byte *str =
  170. (s->file_name.data == 0 ?
  171. gs_alloc_string(s->memory, size + 1, "ssetfilename") :
  172. gs_resize_string(s->memory,
  173. (byte *)s->file_name.data, /* break const */
  174. s->file_name.size,
  175. size + 1, "ssetfilename"));
  176. if (str == 0)
  177. return -1;
  178. memcpy(str, data, size);
  179. str[size] = 0;
  180. s->file_name.data = str;
  181. s->file_name.size = size + 1;
  182. return 0;
  183. }
  184. /* Return the file name of a stream, if any. */
  185. /* There is a guaranteed 0 byte after the string. */
  186. int
  187. sfilename(stream *s, gs_const_string *pfname)
  188. {
  189. pfname->data = s->file_name.data;
  190. if (pfname->data == 0) {
  191. pfname->size = 0;
  192. return -1;
  193. }
  194. pfname->size = s->file_name.size - 1; /* omit terminator */
  195. return 0;
  196. }
  197. /* Implement a stream procedure as a no-op. */
  198. int
  199. s_std_null(stream * s)
  200. {
  201. return 0;
  202. }
  203. /* Discard the contents of the buffer when reading. */
  204. void
  205. s_std_read_reset(stream * s)
  206. {
  207. s->srptr = s->srlimit = s->cbuf - 1;
  208. }
  209. /* Discard the contents of the buffer when writing. */
  210. void
  211. s_std_write_reset(stream * s)
  212. {
  213. s->swptr = s->cbuf - 1;
  214. }
  215. /* Flush data to end-of-file when reading. */
  216. int
  217. s_std_read_flush(stream * s)
  218. {
  219. while (1) {
  220. s->srptr = s->srlimit = s->cbuf - 1;
  221. if (s->end_status)
  222. break;
  223. s_process_read_buf(s);
  224. }
  225. return (s->end_status == EOFC ? 0 : s->end_status);
  226. }
  227. /* Flush buffered data when writing. */
  228. int
  229. s_std_write_flush(stream * s)
  230. {
  231. return s_process_write_buf(s, false);
  232. }
  233. /* Indicate that the number of available input bytes is unknown. */
  234. int
  235. s_std_noavailable(stream * s, long *pl)
  236. {
  237. *pl = -1;
  238. return 0;
  239. }
  240. /* Indicate an error when asked to seek. */
  241. int
  242. s_std_noseek(stream * s, long pos)
  243. {
  244. return ERRC;
  245. }
  246. /* Standard stream closing. */
  247. int
  248. s_std_close(stream * s)
  249. {
  250. return 0;
  251. }
  252. /* Standard stream mode switching. */
  253. int
  254. s_std_switch_mode(stream * s, bool writing)
  255. {
  256. return ERRC;
  257. }
  258. /* Standard stream finalization. Disable the stream. */
  259. void
  260. s_disable(register stream * s)
  261. {
  262. s->cbuf = 0;
  263. s->bsize = 0;
  264. s->end_status = EOFC;
  265. s->modes = 0;
  266. s->cbuf_string.data = 0;
  267. /* The pointers in the next two statements should really be */
  268. /* initialized to ([const] byte *)0 - 1, but some very picky */
  269. /* compilers complain about this. */
  270. s->cursor.r.ptr = s->cursor.r.limit = 0;
  271. s->cursor.w.limit = 0;
  272. s->procs.close = s_std_null;
  273. /* Clear pointers for GC */
  274. s->strm = 0;
  275. s->state = (stream_state *) s;
  276. s->template = &s_no_template;
  277. /* Free the file name. */
  278. if (s->file_name.data) {
  279. gs_free_const_string(s->memory, s->file_name.data, s->file_name.size,
  280. "s_disable(file_name)");
  281. s->file_name.data = 0;
  282. s->file_name.size = 0;
  283. }
  284. /****** SHOULD DO MORE THAN THIS ******/
  285. if_debug1('s', "[s]disable 0x%lx\n", (ulong) s);
  286. }
  287. /* Implement flushing for encoding filters. */
  288. int
  289. s_filter_write_flush(register stream * s)
  290. {
  291. int status = s_process_write_buf(s, false);
  292. if (status != 0)
  293. return status;
  294. return sflush(s->strm);
  295. }
  296. /* Close a filter. If this is an encoding filter, flush it first. */
  297. int
  298. s_filter_close(register stream * s)
  299. {
  300. if (s_is_writing(s)) {
  301. int status = s_process_write_buf(s, true);
  302. if (status != 0 && status != EOFC)
  303. return status;
  304. }
  305. return s_std_close(s);
  306. }
  307. /* Disregard a stream error message. */
  308. int
  309. s_no_report_error(stream_state * st, const char *str)
  310. {
  311. return 0;
  312. }
  313. /* Generic procedure structures for filters. */
  314. const stream_procs s_filter_read_procs = {
  315. s_std_noavailable, s_std_noseek, s_std_read_reset,
  316. s_std_read_flush, s_filter_close
  317. };
  318. const stream_procs s_filter_write_procs = {
  319. s_std_noavailable, s_std_noseek, s_std_write_reset,
  320. s_filter_write_flush, s_filter_close
  321. };
  322. /* ------ Implementation-independent procedures ------ */
  323. /* Store the amount of available data in a(n input) stream. */
  324. int
  325. savailable(stream * s, long *pl)
  326. {
  327. return (*(s)->procs.available) (s, pl);
  328. }
  329. /* Return the current position of a stream. */
  330. long
  331. stell(stream * s)
  332. {
  333. /*
  334. * The stream might have been closed, but the position
  335. * is still meaningful in this case.
  336. */
  337. const byte *ptr = (s_is_writing(s) ? s->swptr : s->srptr);
  338. return (ptr == 0 ? 0 : ptr + 1 - s->cbuf) + s->position;
  339. }
  340. /* Set the position of a stream. */
  341. int
  342. spseek(stream * s, long pos)
  343. {
  344. if_debug3('s', "[s]seek 0x%lx to %ld, position was %ld\n",
  345. (ulong) s, pos, stell(s));
  346. return (*(s)->procs.seek) (s, pos);
  347. }
  348. /* Switch a stream to read or write mode. */
  349. /* Return 0 or ERRC. */
  350. int
  351. sswitch(register stream * s, bool writing)
  352. {
  353. if (s->procs.switch_mode == 0)
  354. return ERRC;
  355. return (*s->procs.switch_mode) (s, writing);
  356. }
  357. /* Close a stream, disabling it if successful. */
  358. /* (The stream may already be closed.) */
  359. int
  360. sclose(register stream * s)
  361. {
  362. stream_state *st;
  363. int code = (*s->procs.close) (s);
  364. if (code < 0)
  365. return code;
  366. st = s->state;
  367. if (st != 0) {
  368. stream_proc_release((*release)) = st->template->release;
  369. if (release != 0)
  370. (*release) (st);
  371. if (st != (stream_state *) s && st->memory != 0)
  372. gs_free_object(st->memory, st, "s_std_close");
  373. s->state = (stream_state *) s;
  374. }
  375. s_disable(s);
  376. return code;
  377. }
  378. /*
  379. * Implement sgetc when the buffer may be empty. If the buffer really is
  380. * empty, refill it and then read a byte. Note that filters must read one
  381. * byte ahead, so that they can close immediately after the client reads the
  382. * last data byte if the next thing is an EOD.
  383. */
  384. int
  385. spgetcc(register stream * s, bool close_at_eod)
  386. {
  387. int status, left;
  388. int min_left = sbuf_min_left(s);
  389. while (status = s->end_status,
  390. left = s->srlimit - s->srptr,
  391. left <= min_left && status >= 0
  392. )
  393. s_process_read_buf(s);
  394. if (left <= min_left &&
  395. (left == 0 || (status != EOFC && status != ERRC))
  396. ) {
  397. /* Compact the stream so stell will return the right result. */
  398. stream_compact(s, true);
  399. if (status == EOFC && close_at_eod && s->close_at_eod) {
  400. status = sclose(s);
  401. if (status == 0)
  402. status = EOFC;
  403. s->end_status = status;
  404. }
  405. return status;
  406. }
  407. return *++(s->srptr);
  408. }
  409. /* Implementing sputc when the buffer is full, */
  410. /* by flushing the buffer and then writing the byte. */
  411. int
  412. spputc(register stream * s, byte b)
  413. {
  414. for (;;) {
  415. if (s->end_status)
  416. return s->end_status;
  417. if (!sendwp(s)) {
  418. *++(s->swptr) = b;
  419. return b;
  420. }
  421. s_process_write_buf(s, false);
  422. }
  423. }
  424. /* Push back a character onto a (read) stream. */
  425. /* The character must be the same as the last one read. */
  426. /* Return 0 on success, ERRC on failure. */
  427. int
  428. sungetc(register stream * s, byte c)
  429. {
  430. if (!s_is_reading(s) || s->srptr < s->cbuf || *(s->srptr) != c)
  431. return ERRC;
  432. s->srptr--;
  433. return 0;
  434. }
  435. /* Get a string from a stream. */
  436. /* Return 0 if the string was filled, or an exception status. */
  437. int
  438. sgets(stream * s, byte * buf, uint nmax, uint * pn)
  439. {
  440. stream_cursor_write cw;
  441. int status = 0;
  442. int min_left = sbuf_min_left(s);
  443. cw.ptr = buf - 1;
  444. cw.limit = cw.ptr + nmax;
  445. while (cw.ptr < cw.limit) {
  446. int left;
  447. if ((left = s->srlimit - s->srptr) > min_left) {
  448. s->srlimit -= min_left;
  449. stream_move(&s->cursor.r, &cw);
  450. s->srlimit += min_left;
  451. } else {
  452. uint wanted = cw.limit - cw.ptr;
  453. int c;
  454. stream_state *st;
  455. if (wanted >= s->bsize >> 2 &&
  456. (st = s->state) != 0 &&
  457. wanted >= st->template->min_out_size &&
  458. s->end_status == 0 &&
  459. left == 0
  460. ) {
  461. byte *wptr = cw.ptr;
  462. cw.limit -= min_left;
  463. status = sreadbuf(s, &cw);
  464. cw.limit += min_left;
  465. /*
  466. * We know the stream buffer is empty, so it's safe to
  467. * update position. However, we need to reset the read
  468. * cursor to indicate that there is no data in the buffer.
  469. */
  470. s->srptr = s->srlimit = s->cbuf - 1;
  471. s->position += cw.ptr - wptr;
  472. if (status != 1 || cw.ptr == cw.limit)
  473. break;
  474. }
  475. c = spgetc(s);
  476. if (c < 0) {
  477. status = c;
  478. break;
  479. }
  480. *++(cw.ptr) = c;
  481. }
  482. }
  483. *pn = cw.ptr + 1 - buf;
  484. return (status >= 0 ? 0 : status);
  485. }
  486. /* Write a string on a stream. */
  487. /* Return 0 if the entire string was written, or an exception status. */
  488. int
  489. sputs(register stream * s, const byte * str, uint wlen, uint * pn)
  490. {
  491. uint len = wlen;
  492. int status = s->end_status;
  493. if (status >= 0)
  494. while (len > 0) {
  495. uint count = s->swlimit - s->swptr;
  496. if (count > 0) {
  497. if (count > len)
  498. count = len;
  499. memcpy(s->swptr + 1, str, count);
  500. s->swptr += count;
  501. str += count;
  502. len -= count;
  503. } else {
  504. byte ch = *str++;
  505. status = sputc(s, ch);
  506. if (status < 0)
  507. break;
  508. len--;
  509. }
  510. }
  511. *pn = wlen - len;
  512. return (status >= 0 ? 0 : status);
  513. }
  514. /* Skip ahead a specified distance in a read stream. */
  515. /* Return 0 or an exception code. */
  516. /* Store the number of bytes skipped in *pskipped. */
  517. int
  518. spskip(register stream * s, long nskip, long *pskipped)
  519. {
  520. long n = nskip;
  521. int min_left;
  522. if (nskip < 0 || !s_is_reading(s)) {
  523. *pskipped = 0;
  524. return ERRC;
  525. }
  526. if (s_can_seek(s)) {
  527. long pos = stell(s);
  528. int code = sseek(s, pos + n);
  529. *pskipped = stell(s) - pos;
  530. return code;
  531. }
  532. min_left = sbuf_min_left(s);
  533. while (sbufavailable(s) < n + min_left) {
  534. int code;
  535. n -= sbufavailable(s);
  536. s->srptr = s->srlimit;
  537. if (s->end_status) {
  538. *pskipped = nskip - n;
  539. return s->end_status;
  540. }
  541. code = sgetc(s);
  542. if (code < 0) {
  543. *pskipped = nskip - n;
  544. return code;
  545. }
  546. --n;
  547. }
  548. /* Note that if min_left > 0, n < 0 is possible; this is harmless. */
  549. s->srptr += n;
  550. *pskipped = nskip;
  551. return 0;
  552. }
  553. /* Read a line from a stream. See srdline.h for the specification. */
  554. int
  555. sreadline(stream *s_in, stream *s_out, void *readline_data,
  556. gs_const_string *prompt, gs_string * buf,
  557. gs_memory_t * bufmem, uint * pcount, bool *pin_eol,
  558. bool (*is_stdin)(P1(const stream *)))
  559. {
  560. uint count = *pcount;
  561. /* Most systems define \n as 0xa and \r as 0xd; however, */
  562. /* OS-9 has \n == \r == 0xd and \l == 0xa. The following */
  563. /* code works properly regardless of environment. */
  564. #if '\n' == '\r'
  565. # define LF 0xa
  566. #else
  567. # define LF '\n'
  568. #endif
  569. if (count == 0 && s_out && prompt) {
  570. uint ignore_n;
  571. int ch = sputs(s_out, prompt->data, prompt->size, &ignore_n);
  572. if (ch < 0)
  573. return ch;
  574. }
  575. top:
  576. if (*pin_eol) {
  577. /*
  578. * We're in the middle of checking for a two-character
  579. * end-of-line sequence. If we get an EOF here, stop, but
  580. * don't signal EOF now; wait till the next read.
  581. */
  582. int ch = spgetcc(s_in, false);
  583. if (ch == EOFC) {
  584. *pin_eol = false;
  585. return 0;
  586. } else if (ch < 0)
  587. return ch;
  588. else if (ch != LF)
  589. sputback(s_in);
  590. *pin_eol = false;
  591. return 0;
  592. }
  593. for (;;) {
  594. int ch = sgetc(s_in);
  595. if (ch < 0) { /* EOF or exception */
  596. *pcount = count;
  597. return ch;
  598. }
  599. switch (ch) {
  600. case '\r':
  601. {
  602. #if '\n' == '\r' /* OS-9 or similar */
  603. if (!is_stdin(s_in))
  604. #endif
  605. {
  606. *pcount = count;
  607. *pin_eol = true;
  608. goto top;
  609. }
  610. }
  611. /* falls through */
  612. case LF:
  613. #undef LF
  614. *pcount = count;
  615. return 0;
  616. }
  617. if (count >= buf->size) { /* filled the string */
  618. if (!bufmem) {
  619. sputback(s_in);
  620. *pcount = count;
  621. return 1;
  622. }
  623. {
  624. uint nsize = count + max(count, 20);
  625. byte *ndata = gs_resize_string(bufmem, buf->data, buf->size,
  626. nsize, "sreadline(buffer)");
  627. if (ndata == 0)
  628. return ERRC; /* no better choice */
  629. buf->data = ndata;
  630. buf->size = nsize;
  631. }
  632. }
  633. buf->data[count++] = ch;
  634. }
  635. /*return 0; *//* not reached */
  636. }
  637. /* ------ Utilities ------ */
  638. /*
  639. * Attempt to refill the buffer of a read stream. Only call this if the
  640. * end_status is not EOFC, and if the buffer is (nearly) empty.
  641. */
  642. int
  643. s_process_read_buf(stream * s)
  644. {
  645. int status;
  646. stream_compact(s, false);
  647. status = sreadbuf(s, &s->cursor.w);
  648. s->end_status = (status >= 0 ? 0 : status);
  649. return 0;
  650. }
  651. /*
  652. * Attempt to empty the buffer of a write stream. Only call this if the
  653. * end_status is not EOFC.
  654. */
  655. int
  656. s_process_write_buf(stream * s, bool last)
  657. {
  658. int status = swritebuf(s, &s->cursor.r, last);
  659. stream_compact(s, false);
  660. return (status >= 0 ? 0 : status);
  661. }
  662. /* Move forward or backward in a pipeline. We temporarily reverse */
  663. /* the direction of the pointers while doing this. */
  664. /* (Cf the Deutsch-Schorr-Waite graph marking algorithm.) */
  665. #define MOVE_BACK(curr, prev)\
  666. BEGIN\
  667. stream *back = prev->strm;\
  668. prev->strm = curr; curr = prev; prev = back;\
  669. END
  670. #define MOVE_AHEAD(curr, prev)\
  671. BEGIN\
  672. stream *ahead = curr->strm;\
  673. curr->strm = prev; prev = curr; curr = ahead;\
  674. END
  675. /*
  676. * Read from a stream pipeline. Update end_status for all streams that were
  677. * actually touched. Return the status from the outermost stream: this is
  678. * normally the same as s->end_status, except that if s->procs.process
  679. * returned 1, sreadbuf sets s->end_status to 0, but returns 1.
  680. */
  681. private int
  682. sreadbuf(stream * s, stream_cursor_write * pbuf)
  683. {
  684. stream *prev = 0;
  685. stream *curr = s;
  686. int status;
  687. for (;;) {
  688. stream *strm;
  689. stream_cursor_write *pw;
  690. byte *oldpos;
  691. for (;;) { /* Descend into the recursion. */
  692. stream_cursor_read cr;
  693. stream_cursor_read *pr;
  694. int left;
  695. bool eof;
  696. strm = curr->strm;
  697. if (strm == 0) {
  698. cr.ptr = 0, cr.limit = 0;
  699. pr = &cr;
  700. left = 0;
  701. eof = false;
  702. } else {
  703. pr = &strm->cursor.r;
  704. left = sbuf_min_left(strm);
  705. left = min(left, pr->limit - pr->ptr);
  706. pr->limit -= left;
  707. eof = strm->end_status == EOFC;
  708. }
  709. pw = (prev == 0 ? pbuf : &curr->cursor.w);
  710. if_debug4('s', "[s]read process 0x%lx, nr=%u, nw=%u, eof=%d\n",
  711. (ulong) curr, (uint) (pr->limit - pr->ptr),
  712. (uint) (pw->limit - pw->ptr), eof);
  713. oldpos = pw->ptr;
  714. status = (*curr->procs.process) (curr->state, pr, pw, eof);
  715. pr->limit += left;
  716. if_debug4('s', "[s]after read 0x%lx, nr=%u, nw=%u, status=%d\n",
  717. (ulong) curr, (uint) (pr->limit - pr->ptr),
  718. (uint) (pw->limit - pw->ptr), status);
  719. if (strm == 0 || status != 0)
  720. break;
  721. if (strm->end_status < 0) {
  722. if (strm->end_status != EOFC || pw->ptr == oldpos)
  723. status = strm->end_status;
  724. break;
  725. }
  726. MOVE_AHEAD(curr, prev);
  727. stream_compact(curr, false);
  728. }
  729. /* If curr reached EOD and is a filter stream, close it. */
  730. if (strm != 0 && status == EOFC &&
  731. curr->cursor.r.ptr >= curr->cursor.r.limit &&
  732. curr->close_at_eod
  733. ) {
  734. int cstat = sclose(curr);
  735. if (cstat != 0)
  736. status = cstat;
  737. }
  738. /* Unwind from the recursion. */
  739. curr->end_status = (status >= 0 ? 0 : status);
  740. if (prev == 0)
  741. return status;
  742. MOVE_BACK(curr, prev);
  743. }
  744. }
  745. /* Write to a pipeline. */
  746. private int
  747. swritebuf(stream * s, stream_cursor_read * pbuf, bool last)
  748. {
  749. stream *prev = 0;
  750. stream *curr = s;
  751. int depth = 0; /* # of non-temp streams before curr */
  752. int status;
  753. /*
  754. * The handling of EOFC is a little tricky. There are two
  755. * invariants that keep it straight:
  756. * - We only pass last = true to a stream if either it is
  757. * the first stream in the pipeline, or it is a temporary stream
  758. * below the first stream and the stream immediately above it has
  759. * end_status = EOFC.
  760. */
  761. for (;;) {
  762. for (;;) {
  763. /* Move ahead in the pipeline. */
  764. stream *strm = curr->strm;
  765. stream_cursor_write cw;
  766. stream_cursor_read *pr;
  767. stream_cursor_write *pw;
  768. /*
  769. * We only want to set the last/end flag for
  770. * the top-level stream and any temporary streams
  771. * immediately below it.
  772. */
  773. bool end = last &&
  774. (prev == 0 ||
  775. (depth <= 1 && prev->end_status == EOFC));
  776. if (strm == 0)
  777. cw.ptr = 0, cw.limit = 0, pw = &cw;
  778. else
  779. pw = &strm->cursor.w;
  780. if (prev == 0)
  781. pr = pbuf;
  782. else
  783. pr = &curr->cursor.r;
  784. if_debug5('s',
  785. "[s]write process 0x%lx(%s), nr=%u, nw=%u, end=%d\n",
  786. (ulong)curr,
  787. gs_struct_type_name(curr->state->template->stype),
  788. (uint)(pr->limit - pr->ptr),
  789. (uint)(pw->limit - pw->ptr), end);
  790. status = curr->end_status;
  791. if (status >= 0) {
  792. status = (*curr->procs.process)(curr->state, pr, pw, end);
  793. if_debug5('s',
  794. "[s]after write 0x%lx, nr=%u, nw=%u, end=%d, status=%d\n",
  795. (ulong) curr, (uint) (pr->limit - pr->ptr),
  796. (uint) (pw->limit - pw->ptr), end, status);
  797. if (status == 0 && end)
  798. status = EOFC;
  799. if (status == EOFC || status == ERRC)
  800. curr->end_status = status;
  801. }
  802. if (strm == 0 || (status < 0 && status != EOFC))
  803. break;
  804. if (status != 1) {
  805. /*
  806. * Keep going if we are closing a filter with a sub-stream.
  807. * We know status == 0 or EOFC.
  808. */
  809. if (!end || !strm->is_temp)
  810. break;
  811. }
  812. status = strm->end_status;
  813. if (status < 0)
  814. break;
  815. if (!curr->is_temp)
  816. ++depth;
  817. if_debug1('s', "[s]moving ahead, depth = %d\n", depth);
  818. MOVE_AHEAD(curr, prev);
  819. stream_compact(curr, false);
  820. }
  821. /* Move back in the pipeline. */
  822. curr->end_status = (status >= 0 ? 0 : status);
  823. if (status < 0 || prev == 0) {
  824. /*
  825. * All streams up to here were called with last = true
  826. * and returned 0 or EOFC (so their end_status is now EOFC):
  827. * finish unwinding and then return. Change the status of
  828. * the prior streams to ERRC if the new status is ERRC,
  829. * otherwise leave it alone.
  830. */
  831. while (prev) {
  832. if_debug0('s', "[s]unwinding\n");
  833. MOVE_BACK(curr, prev);
  834. if (status >= 0)
  835. curr->end_status = 0;
  836. else if (status == ERRC)
  837. curr->end_status = ERRC;
  838. }
  839. return status;
  840. }
  841. MOVE_BACK(curr, prev);
  842. if (!curr->is_temp)
  843. --depth;
  844. if_debug1('s', "[s]moving back, depth = %d\n", depth);
  845. }
  846. }
  847. /* Move as much data as possible from one buffer to another. */
  848. /* Return 0 if the input became empty, 1 if the output became full. */
  849. int
  850. stream_move(stream_cursor_read * pr, stream_cursor_write * pw)
  851. {
  852. uint rcount = pr->limit - pr->ptr;
  853. uint wcount = pw->limit - pw->ptr;
  854. uint count;
  855. int status;
  856. if (rcount <= wcount)
  857. count = rcount, status = 0;
  858. else
  859. count = wcount, status = 1;
  860. memmove(pw->ptr + 1, pr->ptr + 1, count);
  861. pr->ptr += count;
  862. pw->ptr += count;
  863. return status;
  864. }
  865. /* If possible, compact the information in a stream buffer to the bottom. */
  866. private void
  867. stream_compact(stream * s, bool always)
  868. {
  869. if (s->cursor.r.ptr >= s->cbuf && (always || s->end_status >= 0)) {
  870. uint dist = s->cursor.r.ptr + 1 - s->cbuf;
  871. memmove(s->cbuf, s->cursor.r.ptr + 1,
  872. (uint) (s->cursor.r.limit - s->cursor.r.ptr));
  873. s->cursor.r.ptr = s->cbuf - 1;
  874. s->cursor.r.limit -= dist; /* same as w.ptr */
  875. s->position += dist;
  876. }
  877. }
  878. /* ------ String streams ------ */
  879. /* String stream procedures */
  880. private int
  881. s_string_available(P2(stream *, long *)),
  882. s_string_read_seek(P2(stream *, long)),
  883. s_string_write_seek(P2(stream *, long)),
  884. s_string_read_process(P4(stream_state *, stream_cursor_read *,
  885. stream_cursor_write *, bool)),
  886. s_string_write_process(P4(stream_state *, stream_cursor_read *,
  887. stream_cursor_write *, bool));
  888. /* Initialize a stream for reading a string. */
  889. void
  890. sread_string(register stream *s, const byte *ptr, uint len)
  891. {
  892. static const stream_procs p = {
  893. s_string_available, s_string_read_seek, s_std_read_reset,
  894. s_std_read_flush, s_std_null, s_string_read_process
  895. };
  896. s_std_init(s, (byte *)ptr, len, &p, s_mode_read + s_mode_seek);
  897. s->cbuf_string.data = (byte *)ptr;
  898. s->cbuf_string.size = len;
  899. s->end_status = EOFC;
  900. s->srlimit = s->swlimit;
  901. }
  902. /* Initialize a reusable stream for reading a string. */
  903. private void
  904. s_string_reusable_reset(stream *s)
  905. {
  906. s->srptr = s->cbuf - 1; /* just reset to the beginning */
  907. s->srlimit = s->srptr + s->bsize; /* might have gotten reset */
  908. }
  909. private int
  910. s_string_reusable_flush(stream *s)
  911. {
  912. s->srptr = s->srlimit = s->cbuf + s->bsize - 1; /* just set to the end */
  913. return 0;
  914. }
  915. void
  916. sread_string_reusable(stream *s, const byte *ptr, uint len)
  917. {
  918. static const stream_procs p = {
  919. s_string_available, s_string_read_seek, s_string_reusable_reset,
  920. s_string_reusable_flush, s_std_null, s_string_read_process
  921. };
  922. sread_string(s, ptr, len);
  923. s->procs = p;
  924. s->close_at_eod = false;
  925. }
  926. /* Return the number of available bytes when reading from a string. */
  927. private int
  928. s_string_available(stream *s, long *pl)
  929. {
  930. *pl = sbufavailable(s);
  931. if (*pl == 0 && s->close_at_eod) /* EOF */
  932. *pl = -1;
  933. return 0;
  934. }
  935. /* Seek in a string being read. Return 0 if OK, ERRC if not. */
  936. private int
  937. s_string_read_seek(register stream * s, long pos)
  938. {
  939. if (pos < 0 || pos > s->bsize)
  940. return ERRC;
  941. s->srptr = s->cbuf + pos - 1;
  942. /* We might be seeking after a reusable string reached EOF. */
  943. s->srlimit = s->cbuf + s->bsize - 1;
  944. return 0;
  945. }
  946. /* Initialize a stream for writing a string. */
  947. void
  948. swrite_string(register stream * s, byte * ptr, uint len)
  949. {
  950. static const stream_procs p = {
  951. s_std_noavailable, s_string_write_seek, s_std_write_reset,
  952. s_std_null, s_std_null, s_string_write_process
  953. };
  954. s_std_init(s, ptr, len, &p, s_mode_write + s_mode_seek);
  955. s->cbuf_string.data = ptr;
  956. s->cbuf_string.size = len;
  957. }
  958. /* Seek in a string being written. Return 0 if OK, ERRC if not. */
  959. private int
  960. s_string_write_seek(register stream * s, long pos)
  961. {
  962. if (pos < 0 || pos > s->bsize)
  963. return ERRC;
  964. s->swptr = s->cbuf + pos - 1;
  965. return 0;
  966. }
  967. /* Since we initialize the input buffer of a string read stream */
  968. /* to contain all of the data in the string, if we are ever asked */
  969. /* to refill the buffer, we should signal EOF. */
  970. private int
  971. s_string_read_process(stream_state * st, stream_cursor_read * ignore_pr,
  972. stream_cursor_write * pw, bool last)
  973. {
  974. return EOFC;
  975. }
  976. /* Similarly, if we are ever asked to empty the buffer, it means that */
  977. /* there has been an overrun (unless we are closing the stream). */
  978. private int
  979. s_string_write_process(stream_state * st, stream_cursor_read * pr,
  980. stream_cursor_write * ignore_pw, bool last)
  981. {
  982. return (last ? EOFC : ERRC);
  983. }
  984. /* ------ Position-tracking stream ------ */
  985. private int
  986. s_write_position_process(P4(stream_state *, stream_cursor_read *,
  987. stream_cursor_write *, bool));
  988. /* Set up a write stream that just keeps track of the position. */
  989. void
  990. swrite_position_only(stream *s)
  991. {
  992. static byte discard_buf[50]; /* size is arbitrary */
  993. swrite_string(s, discard_buf, sizeof(discard_buf));
  994. s->procs.process = s_write_position_process;
  995. }
  996. private int
  997. s_write_position_process(stream_state * st, stream_cursor_read * pr,
  998. stream_cursor_write * ignore_pw, bool last)
  999. {
  1000. pr->ptr = pr->limit; /* discard data */
  1001. return 0;
  1002. }
  1003. /* ------ Filter pipelines ------ */
  1004. /*
  1005. * Add a filter to an output pipeline. The client must have allocated the
  1006. * stream state, if any, using the given allocator. For s_init_filter, the
  1007. * client must have called s_init and s_init_state.
  1008. */
  1009. int
  1010. s_init_filter(stream *fs, stream_state *fss, byte *buf, uint bsize,
  1011. stream *target)
  1012. {
  1013. const stream_template *template = fss->template;
  1014. if (bsize < template->min_in_size)
  1015. return ERRC;
  1016. s_std_init(fs, buf, bsize, &s_filter_write_procs, s_mode_write);
  1017. fs->procs.process = template->process;
  1018. fs->state = fss;
  1019. if (template->init)
  1020. (template->init)(fss);
  1021. fs->strm = target;
  1022. return 0;
  1023. }
  1024. stream *
  1025. s_add_filter(stream **ps, const stream_template *template,
  1026. stream_state *ss, gs_memory_t *mem)
  1027. {
  1028. stream *es;
  1029. stream_state *ess;
  1030. uint bsize = max(template->min_in_size, 256); /* arbitrary */
  1031. byte *buf;
  1032. /*
  1033. * Ensure enough buffering. This may require adding an additional
  1034. * stream.
  1035. */
  1036. if (bsize > (*ps)->bsize && template->process != s_NullE_template.process) {
  1037. stream_template null_template;
  1038. null_template = s_NullE_template;
  1039. null_template.min_in_size = bsize;
  1040. if (s_add_filter(ps, &null_template, NULL, mem) == 0)
  1041. return 0;
  1042. }
  1043. es = s_alloc(mem, "s_add_filter(stream)");
  1044. buf = gs_alloc_bytes(mem, bsize, "s_add_filter(buf)");
  1045. if (es == 0 || buf == 0) {
  1046. gs_free_object(mem, buf, "s_add_filter(buf)");
  1047. gs_free_object(mem, es, "s_add_filter(stream)");
  1048. return 0;
  1049. }
  1050. ess = (ss == 0 ? (stream_state *)es : ss);
  1051. ess->template = template;
  1052. ess->memory = mem;
  1053. es->memory = mem;
  1054. s_init_filter(es, ess, buf, bsize, *ps);
  1055. *ps = es;
  1056. return es;
  1057. }
  1058. /*
  1059. * Close the filters in a pipeline, up to a given target stream, freeing
  1060. * their buffers and state structures.
  1061. */
  1062. int
  1063. s_close_filters(stream **ps, stream *target)
  1064. {
  1065. while (*ps != target) {
  1066. stream *s = *ps;
  1067. gs_memory_t *mem = s->state->memory;
  1068. byte *sbuf = s->cbuf;
  1069. stream *next = s->strm;
  1070. int status = sclose(s);
  1071. stream_state *ss = s->state; /* sclose may set this to s */
  1072. if (status < 0)
  1073. return status;
  1074. if (mem) {
  1075. gs_free_object(mem, sbuf, "s_close_filters(buf)");
  1076. gs_free_object(mem, s, "s_close_filters(stream)");
  1077. if (ss != (stream_state *)s)
  1078. gs_free_object(mem, ss, "s_close_filters(state)");
  1079. }
  1080. *ps = next;
  1081. }
  1082. return 0;
  1083. }
  1084. /* ------ NullEncode/Decode ------ */
  1085. /* Process a buffer */
  1086. private int
  1087. s_Null_process(stream_state * st, stream_cursor_read * pr,
  1088. stream_cursor_write * pw, bool last)
  1089. {
  1090. return stream_move(pr, pw);
  1091. }
  1092. /* Stream template */
  1093. const stream_template s_NullE_template = {
  1094. &st_stream_state, NULL, s_Null_process, 1, 1
  1095. };
  1096. const stream_template s_NullD_template = {
  1097. &st_stream_state, NULL, s_Null_process, 1, 1
  1098. };