unit.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. /* Copyright (C) 2002-2015 Free Software Foundation, Inc.
  2. Contributed by Andy Vaught
  3. F2003 I/O support contributed by Jerry DeLisle
  4. This file is part of the GNU Fortran runtime library (libgfortran).
  5. Libgfortran is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 3, or (at your option)
  8. any later version.
  9. Libgfortran is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. Under Section 7 of GPL version 3, you are granted additional
  14. permissions described in the GCC Runtime Library Exception, version
  15. 3.1, as published by the Free Software Foundation.
  16. You should have received a copy of the GNU General Public License and
  17. a copy of the GCC Runtime Library Exception along with this program;
  18. see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. <http://www.gnu.org/licenses/>. */
  20. #include "io.h"
  21. #include "fbuf.h"
  22. #include "format.h"
  23. #include "unix.h"
  24. #include <stdlib.h>
  25. #include <string.h>
  26. /* IO locking rules:
  27. UNIT_LOCK is a master lock, protecting UNIT_ROOT tree and UNIT_CACHE.
  28. Concurrent use of different units should be supported, so
  29. each unit has its own lock, LOCK.
  30. Open should be atomic with its reopening of units and list_read.c
  31. in several places needs find_unit another unit while holding stdin
  32. unit's lock, so it must be possible to acquire UNIT_LOCK while holding
  33. some unit's lock. Therefore to avoid deadlocks, it is forbidden
  34. to acquire unit's private locks while holding UNIT_LOCK, except
  35. for freshly created units (where no other thread can get at their
  36. address yet) or when using just trylock rather than lock operation.
  37. In addition to unit's private lock each unit has a WAITERS counter
  38. and CLOSED flag. WAITERS counter must be either only
  39. atomically incremented/decremented in all places (if atomic builtins
  40. are supported), or protected by UNIT_LOCK in all places (otherwise).
  41. CLOSED flag must be always protected by unit's LOCK.
  42. After finding a unit in UNIT_CACHE or UNIT_ROOT with UNIT_LOCK held,
  43. WAITERS must be incremented to avoid concurrent close from freeing
  44. the unit between unlocking UNIT_LOCK and acquiring unit's LOCK.
  45. Unit freeing is always done under UNIT_LOCK. If close_unit sees any
  46. WAITERS, it doesn't free the unit but instead sets the CLOSED flag
  47. and the thread that decrements WAITERS to zero while CLOSED flag is
  48. set is responsible for freeing it (while holding UNIT_LOCK).
  49. flush_all_units operation is iterating over the unit tree with
  50. increasing UNIT_NUMBER while holding UNIT_LOCK and attempting to
  51. flush each unit (and therefore needs the unit's LOCK held as well).
  52. To avoid deadlocks, it just trylocks the LOCK and if unsuccessful,
  53. remembers the current unit's UNIT_NUMBER, unlocks UNIT_LOCK, acquires
  54. unit's LOCK and after flushing reacquires UNIT_LOCK and restarts with
  55. the smallest UNIT_NUMBER above the last one flushed.
  56. If find_unit/find_or_create_unit/find_file/get_unit routines return
  57. non-NULL, the returned unit has its private lock locked and when the
  58. caller is done with it, it must call either unlock_unit or close_unit
  59. on it. unlock_unit or close_unit must be always called only with the
  60. private lock held. */
  61. /* Subroutines related to units */
  62. /* Unit number to be assigned when NEWUNIT is used in an OPEN statement. */
  63. #define GFC_FIRST_NEWUNIT -10
  64. static GFC_INTEGER_4 next_available_newunit = GFC_FIRST_NEWUNIT;
  65. #define CACHE_SIZE 3
  66. static gfc_unit *unit_cache[CACHE_SIZE];
  67. gfc_offset max_offset;
  68. gfc_unit *unit_root;
  69. #ifdef __GTHREAD_MUTEX_INIT
  70. __gthread_mutex_t unit_lock = __GTHREAD_MUTEX_INIT;
  71. #else
  72. __gthread_mutex_t unit_lock;
  73. #endif
  74. /* We use these filenames for error reporting. */
  75. static char stdin_name[] = "stdin";
  76. static char stdout_name[] = "stdout";
  77. static char stderr_name[] = "stderr";
  78. #ifdef HAVE_NEWLOCALE
  79. locale_t c_locale;
  80. #else
  81. /* If we don't have POSIX 2008 per-thread locales, we need to use the
  82. traditional setlocale(). To prevent multiple concurrent threads
  83. doing formatted I/O from messing up the locale, we need to store a
  84. global old_locale, and a counter keeping track of how many threads
  85. are currently doing formatted I/O. The first thread saves the old
  86. locale, and the last one restores it. */
  87. char *old_locale;
  88. int old_locale_ctr;
  89. #ifdef __GTHREAD_MUTEX_INIT
  90. __gthread_mutex_t old_locale_lock = __GTHREAD_MUTEX_INIT;
  91. #else
  92. __gthread_mutex_t old_locale_lock;
  93. #endif
  94. #endif
  95. /* This implementation is based on Stefan Nilsson's article in the
  96. * July 1997 Doctor Dobb's Journal, "Treaps in Java". */
  97. /* pseudo_random()-- Simple linear congruential pseudorandom number
  98. * generator. The period of this generator is 44071, which is plenty
  99. * for our purposes. */
  100. static int
  101. pseudo_random (void)
  102. {
  103. static int x0 = 5341;
  104. x0 = (22611 * x0 + 10) % 44071;
  105. return x0;
  106. }
  107. /* rotate_left()-- Rotate the treap left */
  108. static gfc_unit *
  109. rotate_left (gfc_unit * t)
  110. {
  111. gfc_unit *temp;
  112. temp = t->right;
  113. t->right = t->right->left;
  114. temp->left = t;
  115. return temp;
  116. }
  117. /* rotate_right()-- Rotate the treap right */
  118. static gfc_unit *
  119. rotate_right (gfc_unit * t)
  120. {
  121. gfc_unit *temp;
  122. temp = t->left;
  123. t->left = t->left->right;
  124. temp->right = t;
  125. return temp;
  126. }
  127. static int
  128. compare (int a, int b)
  129. {
  130. if (a < b)
  131. return -1;
  132. if (a > b)
  133. return 1;
  134. return 0;
  135. }
  136. /* insert()-- Recursive insertion function. Returns the updated treap. */
  137. static gfc_unit *
  138. insert (gfc_unit *new, gfc_unit *t)
  139. {
  140. int c;
  141. if (t == NULL)
  142. return new;
  143. c = compare (new->unit_number, t->unit_number);
  144. if (c < 0)
  145. {
  146. t->left = insert (new, t->left);
  147. if (t->priority < t->left->priority)
  148. t = rotate_right (t);
  149. }
  150. if (c > 0)
  151. {
  152. t->right = insert (new, t->right);
  153. if (t->priority < t->right->priority)
  154. t = rotate_left (t);
  155. }
  156. if (c == 0)
  157. internal_error (NULL, "insert(): Duplicate key found!");
  158. return t;
  159. }
  160. /* insert_unit()-- Create a new node, insert it into the treap. */
  161. static gfc_unit *
  162. insert_unit (int n)
  163. {
  164. gfc_unit *u = xcalloc (1, sizeof (gfc_unit));
  165. u->unit_number = n;
  166. #ifdef __GTHREAD_MUTEX_INIT
  167. {
  168. __gthread_mutex_t tmp = __GTHREAD_MUTEX_INIT;
  169. u->lock = tmp;
  170. }
  171. #else
  172. __GTHREAD_MUTEX_INIT_FUNCTION (&u->lock);
  173. #endif
  174. __gthread_mutex_lock (&u->lock);
  175. u->priority = pseudo_random ();
  176. unit_root = insert (u, unit_root);
  177. return u;
  178. }
  179. /* destroy_unit_mutex()-- Destroy the mutex and free memory of unit. */
  180. static void
  181. destroy_unit_mutex (gfc_unit * u)
  182. {
  183. __gthread_mutex_destroy (&u->lock);
  184. free (u);
  185. }
  186. static gfc_unit *
  187. delete_root (gfc_unit * t)
  188. {
  189. gfc_unit *temp;
  190. if (t->left == NULL)
  191. return t->right;
  192. if (t->right == NULL)
  193. return t->left;
  194. if (t->left->priority > t->right->priority)
  195. {
  196. temp = rotate_right (t);
  197. temp->right = delete_root (t);
  198. }
  199. else
  200. {
  201. temp = rotate_left (t);
  202. temp->left = delete_root (t);
  203. }
  204. return temp;
  205. }
  206. /* delete_treap()-- Delete an element from a tree. The 'old' value
  207. * does not necessarily have to point to the element to be deleted, it
  208. * must just point to a treap structure with the key to be deleted.
  209. * Returns the new root node of the tree. */
  210. static gfc_unit *
  211. delete_treap (gfc_unit * old, gfc_unit * t)
  212. {
  213. int c;
  214. if (t == NULL)
  215. return NULL;
  216. c = compare (old->unit_number, t->unit_number);
  217. if (c < 0)
  218. t->left = delete_treap (old, t->left);
  219. if (c > 0)
  220. t->right = delete_treap (old, t->right);
  221. if (c == 0)
  222. t = delete_root (t);
  223. return t;
  224. }
  225. /* delete_unit()-- Delete a unit from a tree */
  226. static void
  227. delete_unit (gfc_unit * old)
  228. {
  229. unit_root = delete_treap (old, unit_root);
  230. }
  231. /* get_external_unit()-- Given an integer, return a pointer to the unit
  232. * structure. Returns NULL if the unit does not exist,
  233. * otherwise returns a locked unit. */
  234. static gfc_unit *
  235. get_external_unit (int n, int do_create)
  236. {
  237. gfc_unit *p;
  238. int c, created = 0;
  239. __gthread_mutex_lock (&unit_lock);
  240. retry:
  241. for (c = 0; c < CACHE_SIZE; c++)
  242. if (unit_cache[c] != NULL && unit_cache[c]->unit_number == n)
  243. {
  244. p = unit_cache[c];
  245. goto found;
  246. }
  247. p = unit_root;
  248. while (p != NULL)
  249. {
  250. c = compare (n, p->unit_number);
  251. if (c < 0)
  252. p = p->left;
  253. if (c > 0)
  254. p = p->right;
  255. if (c == 0)
  256. break;
  257. }
  258. if (p == NULL && do_create)
  259. {
  260. p = insert_unit (n);
  261. created = 1;
  262. }
  263. if (p != NULL)
  264. {
  265. for (c = 0; c < CACHE_SIZE - 1; c++)
  266. unit_cache[c] = unit_cache[c + 1];
  267. unit_cache[CACHE_SIZE - 1] = p;
  268. }
  269. if (created)
  270. {
  271. /* Newly created units have their lock held already
  272. from insert_unit. Just unlock UNIT_LOCK and return. */
  273. __gthread_mutex_unlock (&unit_lock);
  274. return p;
  275. }
  276. found:
  277. if (p != NULL)
  278. {
  279. /* Fast path. */
  280. if (! __gthread_mutex_trylock (&p->lock))
  281. {
  282. /* assert (p->closed == 0); */
  283. __gthread_mutex_unlock (&unit_lock);
  284. return p;
  285. }
  286. inc_waiting_locked (p);
  287. }
  288. __gthread_mutex_unlock (&unit_lock);
  289. if (p != NULL)
  290. {
  291. __gthread_mutex_lock (&p->lock);
  292. if (p->closed)
  293. {
  294. __gthread_mutex_lock (&unit_lock);
  295. __gthread_mutex_unlock (&p->lock);
  296. if (predec_waiting_locked (p) == 0)
  297. destroy_unit_mutex (p);
  298. goto retry;
  299. }
  300. dec_waiting_unlocked (p);
  301. }
  302. return p;
  303. }
  304. gfc_unit *
  305. find_unit (int n)
  306. {
  307. return get_external_unit (n, 0);
  308. }
  309. gfc_unit *
  310. find_or_create_unit (int n)
  311. {
  312. return get_external_unit (n, 1);
  313. }
  314. /* Helper function to check rank, stride, format string, and namelist.
  315. This is used for optimization. You can't trim out blanks or shorten
  316. the string if trailing spaces are significant. */
  317. static bool
  318. is_trim_ok (st_parameter_dt *dtp)
  319. {
  320. /* Check rank and stride. */
  321. if (dtp->internal_unit_desc)
  322. return false;
  323. /* Format strings can not have 'BZ' or '/'. */
  324. if (dtp->common.flags & IOPARM_DT_HAS_FORMAT)
  325. {
  326. char *p = dtp->format;
  327. off_t i;
  328. if (dtp->common.flags & IOPARM_DT_HAS_BLANK)
  329. return false;
  330. for (i = 0; i < dtp->format_len; i++)
  331. {
  332. if (p[i] == '/') return false;
  333. if (p[i] == 'b' || p[i] == 'B')
  334. if (p[i+1] == 'z' || p[i+1] == 'Z')
  335. return false;
  336. }
  337. }
  338. if (dtp->u.p.ionml) /* A namelist. */
  339. return false;
  340. return true;
  341. }
  342. gfc_unit *
  343. get_internal_unit (st_parameter_dt *dtp)
  344. {
  345. gfc_unit * iunit;
  346. gfc_offset start_record = 0;
  347. /* Allocate memory for a unit structure. */
  348. iunit = xcalloc (1, sizeof (gfc_unit));
  349. #ifdef __GTHREAD_MUTEX_INIT
  350. {
  351. __gthread_mutex_t tmp = __GTHREAD_MUTEX_INIT;
  352. iunit->lock = tmp;
  353. }
  354. #else
  355. __GTHREAD_MUTEX_INIT_FUNCTION (&iunit->lock);
  356. #endif
  357. __gthread_mutex_lock (&iunit->lock);
  358. iunit->recl = dtp->internal_unit_len;
  359. /* For internal units we set the unit number to -1.
  360. Otherwise internal units can be mistaken for a pre-connected unit or
  361. some other file I/O unit. */
  362. iunit->unit_number = -1;
  363. /* As an optimization, adjust the unit record length to not
  364. include trailing blanks. This will not work under certain conditions
  365. where trailing blanks have significance. */
  366. if (dtp->u.p.mode == READING && is_trim_ok (dtp))
  367. {
  368. int len;
  369. if (dtp->common.unit == 0)
  370. len = string_len_trim (dtp->internal_unit_len,
  371. dtp->internal_unit);
  372. else
  373. len = string_len_trim_char4 (dtp->internal_unit_len,
  374. (const gfc_char4_t*) dtp->internal_unit);
  375. dtp->internal_unit_len = len;
  376. iunit->recl = dtp->internal_unit_len;
  377. }
  378. /* Set up the looping specification from the array descriptor, if any. */
  379. if (is_array_io (dtp))
  380. {
  381. iunit->rank = GFC_DESCRIPTOR_RANK (dtp->internal_unit_desc);
  382. iunit->ls = (array_loop_spec *)
  383. xmallocarray (iunit->rank, sizeof (array_loop_spec));
  384. dtp->internal_unit_len *=
  385. init_loop_spec (dtp->internal_unit_desc, iunit->ls, &start_record);
  386. start_record *= iunit->recl;
  387. }
  388. /* Set initial values for unit parameters. */
  389. if (dtp->common.unit)
  390. {
  391. iunit->s = open_internal4 (dtp->internal_unit - start_record,
  392. dtp->internal_unit_len, -start_record);
  393. fbuf_init (iunit, 256);
  394. }
  395. else
  396. iunit->s = open_internal (dtp->internal_unit - start_record,
  397. dtp->internal_unit_len, -start_record);
  398. iunit->bytes_left = iunit->recl;
  399. iunit->last_record=0;
  400. iunit->maxrec=0;
  401. iunit->current_record=0;
  402. iunit->read_bad = 0;
  403. iunit->endfile = NO_ENDFILE;
  404. /* Set flags for the internal unit. */
  405. iunit->flags.access = ACCESS_SEQUENTIAL;
  406. iunit->flags.action = ACTION_READWRITE;
  407. iunit->flags.blank = BLANK_NULL;
  408. iunit->flags.form = FORM_FORMATTED;
  409. iunit->flags.pad = PAD_YES;
  410. iunit->flags.status = STATUS_UNSPECIFIED;
  411. iunit->flags.sign = SIGN_SUPPRESS;
  412. iunit->flags.decimal = DECIMAL_POINT;
  413. iunit->flags.delim = DELIM_UNSPECIFIED;
  414. iunit->flags.encoding = ENCODING_DEFAULT;
  415. iunit->flags.async = ASYNC_NO;
  416. iunit->flags.round = ROUND_UNSPECIFIED;
  417. /* Initialize the data transfer parameters. */
  418. dtp->u.p.advance_status = ADVANCE_YES;
  419. dtp->u.p.seen_dollar = 0;
  420. dtp->u.p.skips = 0;
  421. dtp->u.p.pending_spaces = 0;
  422. dtp->u.p.max_pos = 0;
  423. dtp->u.p.at_eof = 0;
  424. /* This flag tells us the unit is assigned to internal I/O. */
  425. dtp->u.p.unit_is_internal = 1;
  426. return iunit;
  427. }
  428. /* free_internal_unit()-- Free memory allocated for internal units if any. */
  429. void
  430. free_internal_unit (st_parameter_dt *dtp)
  431. {
  432. if (!is_internal_unit (dtp))
  433. return;
  434. if (unlikely (is_char4_unit (dtp)))
  435. fbuf_destroy (dtp->u.p.current_unit);
  436. if (dtp->u.p.current_unit != NULL)
  437. {
  438. free (dtp->u.p.current_unit->ls);
  439. free (dtp->u.p.current_unit->s);
  440. destroy_unit_mutex (dtp->u.p.current_unit);
  441. }
  442. }
  443. /* get_unit()-- Returns the unit structure associated with the integer
  444. unit or the internal file. */
  445. gfc_unit *
  446. get_unit (st_parameter_dt *dtp, int do_create)
  447. {
  448. if ((dtp->common.flags & IOPARM_DT_HAS_INTERNAL_UNIT) != 0)
  449. return get_internal_unit (dtp);
  450. /* Has to be an external unit. */
  451. dtp->u.p.unit_is_internal = 0;
  452. dtp->internal_unit_desc = NULL;
  453. return get_external_unit (dtp->common.unit, do_create);
  454. }
  455. /*************************/
  456. /* Initialize everything. */
  457. void
  458. init_units (void)
  459. {
  460. gfc_unit *u;
  461. unsigned int i;
  462. #ifdef HAVE_NEWLOCALE
  463. c_locale = newlocale (0, "C", 0);
  464. #else
  465. #ifndef __GTHREAD_MUTEX_INIT
  466. __GTHREAD_MUTEX_INIT_FUNCTION (&old_locale_lock);
  467. #endif
  468. #endif
  469. #ifndef __GTHREAD_MUTEX_INIT
  470. __GTHREAD_MUTEX_INIT_FUNCTION (&unit_lock);
  471. #endif
  472. if (options.stdin_unit >= 0)
  473. { /* STDIN */
  474. u = insert_unit (options.stdin_unit);
  475. u->s = input_stream ();
  476. u->flags.action = ACTION_READ;
  477. u->flags.access = ACCESS_SEQUENTIAL;
  478. u->flags.form = FORM_FORMATTED;
  479. u->flags.status = STATUS_OLD;
  480. u->flags.blank = BLANK_NULL;
  481. u->flags.pad = PAD_YES;
  482. u->flags.position = POSITION_ASIS;
  483. u->flags.sign = SIGN_SUPPRESS;
  484. u->flags.decimal = DECIMAL_POINT;
  485. u->flags.delim = DELIM_UNSPECIFIED;
  486. u->flags.encoding = ENCODING_DEFAULT;
  487. u->flags.async = ASYNC_NO;
  488. u->flags.round = ROUND_UNSPECIFIED;
  489. u->recl = options.default_recl;
  490. u->endfile = NO_ENDFILE;
  491. u->filename = strdup (stdin_name);
  492. fbuf_init (u, 0);
  493. __gthread_mutex_unlock (&u->lock);
  494. }
  495. if (options.stdout_unit >= 0)
  496. { /* STDOUT */
  497. u = insert_unit (options.stdout_unit);
  498. u->s = output_stream ();
  499. u->flags.action = ACTION_WRITE;
  500. u->flags.access = ACCESS_SEQUENTIAL;
  501. u->flags.form = FORM_FORMATTED;
  502. u->flags.status = STATUS_OLD;
  503. u->flags.blank = BLANK_NULL;
  504. u->flags.position = POSITION_ASIS;
  505. u->flags.sign = SIGN_SUPPRESS;
  506. u->flags.decimal = DECIMAL_POINT;
  507. u->flags.delim = DELIM_UNSPECIFIED;
  508. u->flags.encoding = ENCODING_DEFAULT;
  509. u->flags.async = ASYNC_NO;
  510. u->flags.round = ROUND_UNSPECIFIED;
  511. u->recl = options.default_recl;
  512. u->endfile = AT_ENDFILE;
  513. u->filename = strdup (stdout_name);
  514. fbuf_init (u, 0);
  515. __gthread_mutex_unlock (&u->lock);
  516. }
  517. if (options.stderr_unit >= 0)
  518. { /* STDERR */
  519. u = insert_unit (options.stderr_unit);
  520. u->s = error_stream ();
  521. u->flags.action = ACTION_WRITE;
  522. u->flags.access = ACCESS_SEQUENTIAL;
  523. u->flags.form = FORM_FORMATTED;
  524. u->flags.status = STATUS_OLD;
  525. u->flags.blank = BLANK_NULL;
  526. u->flags.position = POSITION_ASIS;
  527. u->flags.sign = SIGN_SUPPRESS;
  528. u->flags.decimal = DECIMAL_POINT;
  529. u->flags.encoding = ENCODING_DEFAULT;
  530. u->flags.async = ASYNC_NO;
  531. u->flags.round = ROUND_UNSPECIFIED;
  532. u->recl = options.default_recl;
  533. u->endfile = AT_ENDFILE;
  534. u->filename = strdup (stderr_name);
  535. fbuf_init (u, 256); /* 256 bytes should be enough, probably not doing
  536. any kind of exotic formatting to stderr. */
  537. __gthread_mutex_unlock (&u->lock);
  538. }
  539. /* Calculate the maximum file offset in a portable manner.
  540. max will be the largest signed number for the type gfc_offset.
  541. set a 1 in the LSB and keep a running sum, stopping at MSB-1 bit. */
  542. max_offset = 0;
  543. for (i = 0; i < sizeof (max_offset) * 8 - 1; i++)
  544. max_offset = max_offset + ((gfc_offset) 1 << i);
  545. }
  546. static int
  547. close_unit_1 (gfc_unit *u, int locked)
  548. {
  549. int i, rc;
  550. /* If there are previously written bytes from a write with ADVANCE="no"
  551. Reposition the buffer before closing. */
  552. if (u->previous_nonadvancing_write)
  553. finish_last_advance_record (u);
  554. rc = (u->s == NULL) ? 0 : sclose (u->s) == -1;
  555. u->closed = 1;
  556. if (!locked)
  557. __gthread_mutex_lock (&unit_lock);
  558. for (i = 0; i < CACHE_SIZE; i++)
  559. if (unit_cache[i] == u)
  560. unit_cache[i] = NULL;
  561. delete_unit (u);
  562. free (u->filename);
  563. u->filename = NULL;
  564. free_format_hash_table (u);
  565. fbuf_destroy (u);
  566. if (!locked)
  567. __gthread_mutex_unlock (&u->lock);
  568. /* If there are any threads waiting in find_unit for this unit,
  569. avoid freeing the memory, the last such thread will free it
  570. instead. */
  571. if (u->waiting == 0)
  572. destroy_unit_mutex (u);
  573. if (!locked)
  574. __gthread_mutex_unlock (&unit_lock);
  575. return rc;
  576. }
  577. void
  578. unlock_unit (gfc_unit *u)
  579. {
  580. __gthread_mutex_unlock (&u->lock);
  581. }
  582. /* close_unit()-- Close a unit. The stream is closed, and any memory
  583. associated with the stream is freed. Returns nonzero on I/O error.
  584. Should be called with the u->lock locked. */
  585. int
  586. close_unit (gfc_unit *u)
  587. {
  588. return close_unit_1 (u, 0);
  589. }
  590. /* close_units()-- Delete units on completion. We just keep deleting
  591. the root of the treap until there is nothing left.
  592. Not sure what to do with locking here. Some other thread might be
  593. holding some unit's lock and perhaps hold it indefinitely
  594. (e.g. waiting for input from some pipe) and close_units shouldn't
  595. delay the program too much. */
  596. void
  597. close_units (void)
  598. {
  599. __gthread_mutex_lock (&unit_lock);
  600. while (unit_root != NULL)
  601. close_unit_1 (unit_root, 1);
  602. __gthread_mutex_unlock (&unit_lock);
  603. #ifdef HAVE_FREELOCALE
  604. freelocale (c_locale);
  605. #endif
  606. }
  607. /* High level interface to truncate a file, i.e. flush format buffers,
  608. and generate an error or set some flags. Just like POSIX
  609. ftruncate, returns 0 on success, -1 on failure. */
  610. int
  611. unit_truncate (gfc_unit * u, gfc_offset pos, st_parameter_common * common)
  612. {
  613. int ret;
  614. /* Make sure format buffer is flushed. */
  615. if (u->flags.form == FORM_FORMATTED)
  616. {
  617. if (u->mode == READING)
  618. pos += fbuf_reset (u);
  619. else
  620. fbuf_flush (u, u->mode);
  621. }
  622. /* struncate() should flush the stream buffer if necessary, so don't
  623. bother calling sflush() here. */
  624. ret = struncate (u->s, pos);
  625. if (ret != 0)
  626. generate_error (common, LIBERROR_OS, NULL);
  627. else
  628. {
  629. u->endfile = AT_ENDFILE;
  630. u->flags.position = POSITION_APPEND;
  631. }
  632. return ret;
  633. }
  634. /* filename_from_unit()-- If the unit_number exists, return a pointer to the
  635. name of the associated file, otherwise return the empty string. The caller
  636. must free memory allocated for the filename string. */
  637. char *
  638. filename_from_unit (int n)
  639. {
  640. gfc_unit *u;
  641. int c;
  642. /* Find the unit. */
  643. u = unit_root;
  644. while (u != NULL)
  645. {
  646. c = compare (n, u->unit_number);
  647. if (c < 0)
  648. u = u->left;
  649. if (c > 0)
  650. u = u->right;
  651. if (c == 0)
  652. break;
  653. }
  654. /* Get the filename. */
  655. if (u != NULL && u->filename != NULL)
  656. return strdup (u->filename);
  657. else
  658. return (char *) NULL;
  659. }
  660. void
  661. finish_last_advance_record (gfc_unit *u)
  662. {
  663. if (u->saved_pos > 0)
  664. fbuf_seek (u, u->saved_pos, SEEK_CUR);
  665. if (!(u->unit_number == options.stdout_unit
  666. || u->unit_number == options.stderr_unit))
  667. {
  668. #ifdef HAVE_CRLF
  669. const int len = 2;
  670. #else
  671. const int len = 1;
  672. #endif
  673. char *p = fbuf_alloc (u, len);
  674. if (!p)
  675. os_error ("Completing record after ADVANCE_NO failed");
  676. #ifdef HAVE_CRLF
  677. *(p++) = '\r';
  678. #endif
  679. *p = '\n';
  680. }
  681. fbuf_flush (u, u->mode);
  682. }
  683. /* Assign a negative number for NEWUNIT in OPEN statements. */
  684. GFC_INTEGER_4
  685. get_unique_unit_number (st_parameter_open *opp)
  686. {
  687. GFC_INTEGER_4 num;
  688. #ifdef HAVE_SYNC_FETCH_AND_ADD
  689. num = __sync_fetch_and_add (&next_available_newunit, -1);
  690. #else
  691. __gthread_mutex_lock (&unit_lock);
  692. num = next_available_newunit--;
  693. __gthread_mutex_unlock (&unit_lock);
  694. #endif
  695. /* Do not allow NEWUNIT numbers to wrap. */
  696. if (num > GFC_FIRST_NEWUNIT)
  697. {
  698. generate_error (&opp->common, LIBERROR_INTERNAL, "NEWUNIT exhausted");
  699. return 0;
  700. }
  701. return num;
  702. }