Debian Codegraph @

libgcobol/gfileio.cc

raw
1 /*
2 * Copyright (c) 2021-2025 Symas Corporation
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 * * Neither the name of the Symas Corporation nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include <err.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34
35 #include <cctype>
36 #include <cerrno>
37 #include <cmath>
38 #include <cstdio>
39 #include <cstdlib>
40 #include <cstring>
41 #include <ctime>
42
43 #include <algorithm>
44 #include <vector>
45
46 #include "config.h"
47 #include "libgcobol-fp.h"
48
49 #include "ec.h"
50 #include "io.h"
51 #include "common-defs.h"
52 #include "gcobolio.h"
53 #include "libgcobol.h"
54 #include "gfileio.h"
55 #include "charmaps.h"
56
57 #include <sys/mman.h>
58 #include <sys/stat.h>
59 #include <sys/types.h>
60
61 #pragma GCC diagnostic ignored "-Wunused-result"
62
63 /* Ordinary error-handling flow:
64
65 file->errnum is always set to the value of the system ferror() function
66 file->io_status is always set to the COBOL specific value established
67 by the __gg__file_status_word function.
68
69 When __gg__file_status_word is called with (FsErrno), it returns a value
70 based on the value of errno. Otherwise it returns the value it was called
71 with.
72
73 So, after each operation, if we can figure out the COBOL response, we set
74 file->io_status t to that value. Otherwise, we set it to FsErrno and
75 let __gg__file_status_word establish the file->io_status_t value.
76
77 */
78
79 /* Incomplete notes on file organization, written at the time I reworked
80 ORGANIZATION IS SEQUENTIAL
81
82 GnucCOBOL: Defaults to ORGANIZATION IS SEQUENTIAL
83 GCOBOL: Defaults to ORGANIZATION IS LINE SEQUENTIAL
84
85 SEQUENTIAL Where min/max record sizes are equal:
86 All records are output verbatim
87 SEQUENTIAL Where FD min/max record sizes are not the same
88 A 4-byte preamble is prepended to each record.
89 SEQUENTIAL Where FD record-clause is FORMAT 1
90 [RECORD CONTAINS 10 CHARACTERS]
91 Just like sequential: The sizes of the FD records determine
92 whether or not preambles are issued. GnuCOBOL issues a warning
93 if an FD record size is greater than the record-clause size
94 SEQUENTIAL Where FD record-clause is FORMAT 2 [RECORD VARYING]
95 When all FD records are the same size: No preamble
96 When all FD records are different sizes: Preamble
97 SEQUENTIAL Where FD record-clause is FORMAT 2 [RECORD VARYING 70 TO 72]
98 When all FD records are the same size: No preamble
99 When all FD records are different sizes: Preamble
100 SEQUENTIAL Where FD record-clause is FORMAT 2 [RECORD VARYING DEPENDING ON]
101 There is always a preamble
102 SEQUENTIAL Where FD record-clause is FORMAT 3
103 [RECORD CONTAINS I TO J CHARACTERS]
104 There is always a preamble
105
106 */
107
108 extern "C"
109 void
110 __gg__handle_error(const char *function, const char *msg)
111 {
112 if(0)
113 {
114 fflush(stdout);
115 char ach[1024];
116 snprintf(ach, sizeof(ach), "%s(): %s", function, msg);
117 perror(ach);
118 }
119 }
120
121 static bool
122 handle_ferror(cblc_file_t *file, const char *function, const char *msg)
123 {
124 // This routine gets called after an operation that might result in a
125 // failure, or in an end-of-file
126 bool retval = false; // Indicates no error
127 file->errnum = ferror(file->file_pointer);
128
129 // First, check for an end-of-file
130 if( file->file_pointer )
131 {
132 if( feof(file->file_pointer) )
133 {
134 // This is an end-of-file, which has its own COBOL status code, so it
135 // is error-ish:
136 retval = true;
137 file->io_status = FsEofSeq; // "10"
138 file->prior_read_location = -1;
139 }
140 else if( ferror(file->file_pointer) )
141 {
142 // There was some kind of actionable error:
143 retval = true;
144 // Optionally tell the world of our troubles:
145 if(0)
146 {
147 fflush(stdout);
148 char ach[1024];
149 snprintf(ach, sizeof(ach), "%s(): %s", function, msg);
150 perror(ach);
151 }
152
153 // Set up for the next I/O operation by clearing out the error condition
154 clearerr(file->file_pointer);
155 }
156 }
157 else
158 {
159 // There is no file pointer. The most likely cause an attempt to open a
160 // file that doesn't exist.
161 fprintf(stderr, "%s(): called with NULL file->file_pointer\n", __func__);
162 abort();
163 return true;
164 }
165 return retval;
166 }
167
168 static bool
169 handle_errno(cblc_file_t *file, const char *function, const char *msg)
170 {
171 // This routine gets called after an operation that resulted in a
172 // errno failure
173 bool retval = false; // Indicates no error
174 file->errnum = errno;
175
176 if( errno )
177 {
178 // There was some kind of actionable error:
179 retval = true;
180 // Optionally tell the world of our troubles:
181 if(0)
182 {
183 fflush(stdout);
184 char ach[1024];
185 snprintf(ach, sizeof(ach), "%s(): %s", function, msg);
186 perror(ach);
187 }
188 }
189 return retval;
190 }
191
192 static
193 char *
194 get_filename( const cblc_file_t *file,
195 int is_quoted)
196 {
197 static size_t fname_size = MINIMUM_ALLOCATION_SIZE;
198 static char *fname = static_cast<char *>(malloc(MINIMUM_ALLOCATION_SIZE));
199 massert(fname);
200 fname = internal_to_console(&fname,
201 &fname_size,
202 file->filename,
203 strlen(file->filename));
204
205 if( !is_quoted )
206 {
207 // We have been given something that might be the name of an
208 // environment variable that contains the filename:
209 const char *p_from_environment = getenv(fname);
210 if( p_from_environment )
211 {
212 if( strlen(p_from_environment)+1 > fname_size )
213 {
214 fname_size = strlen(p_from_environment)+1;
215 free(fname);
216 fname = static_cast<char *>(malloc(fname_size));
217 massert(fname);
218 }
219 strcpy(fname, p_from_environment);
220 }
221 }
222
223 if(*fname)
224 {
225 // COBOL strings are space-filled to the right, so we have to get rid
226 // of any spaces out there. If somebody *wants* a filename space-filled
227 // to the right, well, at this juncture I am not prepared to be complicit
228 // in that particular flavor of lunacy.
229 size_t n = strlen(fname)-1;
230 // Note the conditional that terminates the loop when n goes from zero
231 // to a huge positive number in the event that the string is all SPACES
232 while( n < strlen(fname) && fname[n] == ascii_space )
233 {
234 fname[n--] = '\0';
235 }
236 }
237 return fname;
238 }
239
240 static void
241 establish_status(cblc_file_t *file, long read_location)
242 {
243 // Call this routine with fs->errnum already set to errno.
244 //
245 // Establish file->io_status with either FsErrno or a specific value
246 // before calling this routine
247
248 // Some operations have some state associated with them:
249 file->prior_read_location = read_location;
250
251 // When this routine is called, file->io_status has been explicitly set to
252 // a COBOL status (in which case it will be left alone), or it is still
253 // at FsErrno, which means that errno will be used to translate to a COBOL
254 // status word.
255 file->io_status = __gg__file_status_word(file->io_status, file->errnum);
256 __gg__int128_to_field(file->status,
257 file->io_status,
258 0,
259 truncation_e,
260 NULL);
261 // Set the EC-EXCEPTION according to the status code
262 __gg__set_exception_file(file);
263 }
264
265 extern "C"
266 void
267 __gg__set_user_status(cblc_field_t *ustatus, cblc_file_t *file)
268 {
269 __gg__int128_to_field(ustatus,
270 file->io_status,
271 0,
272 truncation_e,
273 NULL);
274 }
275
276 static long
277 max_value(const cblc_field_t *key)
278 {
279 long retval;
280 if( key->digits )
281 {
282 retval = (long)__gg__power_of_ten(key->digits)-1 ;
283 }
284 else
285 {
286 switch( key->capacity )
287 {
288 case 1:
289 retval = 99;
290 break;
291 case 2:
292 retval = 9999;
293 break;
294 default:
295 retval = 999999999;
296 break;
297 }
298 }
299 return retval;
300 }
301
302 extern "C"
303 void
304 __gg__file_init(
305 cblc_file_t *file,
306 const char *name,
307 size_t symbol_table_index,
308 cblc_field_t **keys,
309 int *key_numbers,
310 int *uniques,
311 cblc_field_t *default_record,
312 cblc_field_t *password,
313 cblc_field_t *user_status,
314 cblc_field_t *vsam_status,
315 cblc_field_t *record_length,
316 cblc_field_t *status,
317 size_t reserve,
318 int org,
319 int padding,
320 int access,
321 int optional,
322 size_t record_area_min,
323 size_t record_area_max)
324 {
325 if( !(file->flags & file_flag_initialized_e) )
326 {
327 file->name = strdup(name);
328 file->symbol_table_index = symbol_table_index;
329 file->filename = NULL ;
330 file->file_pointer = NULL ;
331 file->keys = keys;
332 file->key_numbers = key_numbers;
333 file->uniques = uniques;
334 file->default_record = default_record;
335 file->password = password ;
336 file->user_status = user_status ;
337 file->vsam_status = vsam_status ;
338 file->record_length = record_length ;
339 file->status = status ;
340 file->reserve = reserve ;
341 file->org = (cbl_file_org_t)org ;
342 file->padding = padding ;
343 file->access = (cbl_file_access_t)access ;
344 file->errnum = 0 ;
345 file->io_status = FsSuccess ;
346 file->delimiter = internal_newline ;
347 file->flags = file_flag_none_e;
348 file->flags |= (optional ? file_flag_optional_e : file_flag_none_e)
349 + file_flag_initialized_e;
350 file->record_area_min = record_area_min;
351 file->record_area_max = record_area_max;
352 file->prior_read_location = 0;
353 file->prior_op = file_op_none;
354
355 if( file->access == file_inaccessible_e )
356 {
357 file->access = file_access_seq_e;
358 }
359 }
360 }
361
362 enum relative_file_mode
363 {
364 // MicroFocus uses a zero-byte prefix, and a two-byte postfix. The
365 // final byte is 0x0A for a valid record.
366 rfm_microfocus_e,
367 };
368
369 enum indexed_file_mode
370 {
371 // Data file is the same as rfm_microfocus. We use maps and multimaps for
372 // the keys, in an extravaganza of expedience.
373 ifm_dubner_e,
374 };
375
376 struct relative_file_parameters
377 {
378 long preamble_size;
379 long payload_size;
380 long postamble_size;
381 long record_size;
382 long file_size;
383 long key_value;
384 long record_position;
385 long flag_position;
386 long current_file_position;
387 int fd;
388 bool inside_existing_file;
389 };
390
391 #define IGNORE_LIMITS false
392 #define RESPECT_LIMITS true
393 #define DONT_INIT_KEY false
394 #define INIT_KEY true
395
396 static bool
397 relative_file_parameters_get( struct relative_file_parameters &rfp, // OUTPUT
398 relative_file_mode rfm, // INPUTS
399 cblc_file_t *file,
400 bool respect_limits,
401 bool initialize_key,
402 bool is_random)
403 {
404 bool retval = false; // False means "okay"
405 switch(rfm)
406 {
407 // Note that the rfm is a nice idea, but at this point is not really being
408 // used.
409 case rfm_microfocus_e:
410 {
411 if( file->record_area_min == file->record_area_max )
412 {
413 // Set MicroFocus-specific sizes:
414 rfp.preamble_size = 0;
415 rfp.payload_size = (long)file->record_area_max;
416 rfp.postamble_size = 2;
417 }
418 else
419 {
420 rfp.preamble_size = 8;
421 rfp.payload_size = (long)file->record_area_max;
422 rfp.postamble_size = 0;
423 }
424 rfp.record_size = rfp.preamble_size
425 + rfp.payload_size
426 + rfp.postamble_size;
427
428 // We need to know the current file size:
429 errno = 0;
430 file->errnum = 0;
431 rfp.fd = fileno(file->file_pointer);
432 if( rfp.fd == -1 )
433 {
434 file->io_status = FsErrno;
435 handle_errno(file, __func__, "fileno() error" );
436 retval = true;
437 goto done;
438 }
439
440 struct stat file_status;
441 errno = 0;
442 file->errnum = 0;
443 if( fstat(rfp.fd, &file_status) == -1 )
444 {
445 file->io_status = FsErrno;
446 handle_errno(file, __func__, "fstat() error");
447 retval = true;
448 goto done;
449 }
450 rfp.file_size = file_status.st_size;
451
452 rfp.current_file_position = ftell(file->file_pointer);
453 if( handle_ferror(file, __func__, "ftell() error") )
454 {
455 file->io_status = FsErrno;
456 retval = true;
457 goto done;
458 }
459
460 if( !is_random )
461 {
462 rfp.key_value = rfp.current_file_position/rfp.record_size + 1;
463 rfp.record_position = (rfp.key_value-1) * rfp.record_size;
464 rfp.inside_existing_file
465 = rfp.record_position + rfp.record_size <= rfp.file_size;
466 }
467 else
468 {
469 // Pick up the relative_key value:
470 if( initialize_key )
471 {
472 rfp.key_value = rfp.current_file_position/rfp.record_size + 1;
473 }
474 else
475 {
476 int rdigits;
477 if( !file->keys[0] )
478 {
479 warnx("%s(): %s file->keys[0] is NULL, and it shouldn't be\n",
480 __func__,
481 file->name);
482 if( !file->keys[0] )
483 {
484 __gg__abort("relative_file_parameters_get(): file->keys is empty");
485 }
486 }
487 rfp.key_value = (long)__gg__binary_value_from_field(&rdigits,
488 file->keys[0]);
489 }
490
491 rfp.record_position = (rfp.key_value-1) * rfp.record_size;
492 if( rfp.record_position < 0 )
493 {
494 // The record can't be found before the beginning of the file
495 file->io_status = FsNotFound; // "23"
496 retval = true;
497 goto done;
498 }
499
500 rfp.inside_existing_file
501 = rfp.record_position + rfp.record_size <= rfp.file_size;
502
503 if( respect_limits
504 && !rfp.inside_existing_file
505 && file->mode_char == 'r')
506 {
507 // This is a READ operation, but the targeted location is not inside
508 // the file
509 file->io_status = FsNotFound; // "23"
510 retval = true;
511 goto done;
512 }
513 }
514
515 // For Microfocus, the flag is the final byte of the record:
516 rfp.flag_position = rfp.record_position + rfp.record_size - 1;
517
518 break;
519 }
520
521 default:
522 warnx("%s(): Unhandled relative_file_mode %d", __func__, rfm);
523 exit(1);
524 break;
525 }
526 done:
527 if( retval )
528 {
529 establish_status(file, -1);
530 }
531 return retval;
532 }
533
534 static void
535 relative_file_delete_varying(cblc_file_t *file, bool is_random)
536 {
537 file->errnum = 0;
538 file->io_status = FsErrno;
539
540 size_t payload_length;
541
542 unsigned char *stash = static_cast<unsigned char *>(malloc(file->default_record->capacity));
543 massert(stash);
544 memcpy(stash, file->default_record->data, file->default_record->capacity);
545 long starting_pos = ftell(file->file_pointer);
546
547 if( !file->file_pointer )
548 {
549 // Attempting to delete in a file that isn't open
550 file->io_status = FsNoDelete; // "49"
551 goto done;
552 }
553
554 if( file->mode_char != '+' )
555 {
556 // We have to be in I-O mode
557 file->io_status = FsNoDelete; // "49"
558 goto done;
559 }
560
561 relative_file_parameters rfp;
562 if( relative_file_parameters_get( rfp,
563 rfm_microfocus_e,
564 file,
565 RESPECT_LIMITS,
566 DONT_INIT_KEY,
567 is_random) )
568 {
569 goto done;
570 }
571
572 if( !is_random )
573 {
574 // Check that the prior operation was a successful read:
575 if( file->prior_read_location < 0)
576 {
577 file->io_status = FsNoRead; // "43"
578 goto done;
579 }
580
581 // Turn that valid record into an empty one:
582 fseek(file->file_pointer, file->prior_read_location, SEEK_SET);
583 if( handle_ferror(file, __func__, "fseek() error") )
584 {
585 goto done;
586 }
587
588 payload_length = 0;
589 fwrite(&payload_length, 8, 1, file->file_pointer);
590 if( handle_ferror(file, __func__, "fwrite() error") )
591 {
592 goto done;
593 }
594 }
595 else
596 {
597 // We are doing a random access:
598
599 // Let's check to make sure the slot for this record is currently
600 // occupied:
601
602 errno = 0;
603 file->errnum = 0;
604
605 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
606 if( handle_ferror(file, __func__, "fseek() error") )
607 {
608 goto done;
609 }
610
611 fread(&payload_length, 8, 1, file->file_pointer);
612 if( handle_ferror(file, __func__, "fread() error") )
613 {
614 goto done;
615 }
616
617 if( !payload_length )
618 {
619 // There isn't a record there for us to delete, which is an error
620 file->io_status = FsNotFound; // "23"
621 goto done;
622 }
623
624 // Turn that valid record into an empty one:
625 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
626 if( handle_ferror(file, __func__, "fseek() error") )
627 {
628 goto done;
629 }
630
631 payload_length = 0;
632 fwrite(&payload_length, 8, 1, file->file_pointer);
633 if( handle_ferror(file, __func__, "fwrite() error") )
634 {
635 goto done;
636 }
637 }
638
639 done:
640 memcpy(file->default_record->data, stash, file->default_record->capacity);
641 free(stash);
642 fseek(file->file_pointer, starting_pos, SEEK_SET);
643 file->prior_op = file_op_delete;
644 establish_status(file, -1);
645 }
646
647 static void
648 relative_file_delete(cblc_file_t *file, bool is_random)
649 {
650 if( file->record_area_min != file->record_area_max )
651 {
652 return relative_file_delete_varying(file, is_random);
653 }
654
655 file->errnum = 0;
656 file->io_status = FsErrno;
657
658 char record_marker;
659
660 unsigned char *stash = static_cast<unsigned char *>(malloc(file->default_record->capacity));
661 massert(stash);
662 memcpy(stash, file->default_record->data, file->default_record->capacity);
663
664 long starting_pos = ftell(file->file_pointer);
665
666 if( !file->file_pointer )
667 {
668 // Attempting to delete in a file that isn't open
669 file->io_status = FsNoDelete; // "49"
670 goto done;
671 }
672
673 if( file->mode_char != '+' )
674 {
675 // We have to be in I-O mode
676 file->io_status = FsNoDelete; // "49"
677 goto done;
678 }
679
680 relative_file_parameters rfp;
681 if( relative_file_parameters_get( rfp,
682 rfm_microfocus_e,
683 file,
684 RESPECT_LIMITS,
685 DONT_INIT_KEY,
686 is_random) )
687 {
688 goto done;
689 }
690
691 if( !is_random )
692 {
693 // Check that the prior operation was a successful read:
694 if( file->prior_read_location < 0)
695 {
696 file->io_status = FsNoRead; // "43"
697 goto done;
698 }
699
700 // Turn that valid record into an empty one:
701 record_marker = 0x00;
702 errno = 0;
703 file->errnum = 0;
704 if( pwrite( rfp.fd,
705 &record_marker,
706 1,
707 file->prior_read_location
708 + rfp.record_size - 1 ) == -1 )
709 {
710 handle_errno(file, __func__, "pwrite() error");
711 goto done;
712 }
713 }
714 else
715 {
716 // We are doing a random access:
717
718 // Let's check to make sure the slot for this record is currently
719 // occupied:
720
721 errno = 0;
722 file->errnum = 0;
723 ssize_t presult = pread(rfp.fd, &record_marker, 1, rfp.flag_position);
724 if( presult < 0 )
725 {
726 handle_errno(file, __func__, "pread() error");
727 goto done;
728 }
729
730 if( presult == 0 || record_marker != internal_newline )
731 {
732 // There isn't a record there for us to delete, which is an error
733 file->io_status = FsNotFound; // "23"
734 goto done;
735 }
736
737 // We now clobber the 0x0A record marker:
738 record_marker = 0x00;
739 errno = 0;
740 file->errnum = 0;
741 if( pwrite(rfp.fd, &record_marker, 1, rfp.flag_position) == -1 )
742 {
743 file->errnum = errno;
744 handle_ferror(file, __func__, "pwrite() error");
745 goto done;
746 }
747 }
748
749 done:
750 memcpy(file->default_record->data, stash, file->default_record->capacity);
751 free(stash);
752 fseek(file->file_pointer, starting_pos, SEEK_SET);
753 file->prior_op = file_op_delete;
754 establish_status(file, -1);
755 }
756
757 static std::vector<unsigned char>
758 file_indexed_make_key(cblc_file_t *file, int key_number)
759 {
760 std::vector<unsigned char> retval;
761 int index = 0;
762 while( file->key_numbers[index] != -1 ) // -1 is the guardrail
763 {
764 if( file->key_numbers[index] == key_number )
765 {
766 unsigned char *location = file->keys[index]->data;
767 for(size_t i=0; i<file->keys[index]->capacity; i++ )
768 {
769 retval.push_back(*location++);
770 }
771 }
772 index += 1;
773 }
774 return retval;
775 }
776
777 static long
778 file_indexed_first_position(cblc_file_t *file, int key_number)
779 {
780 // We need to find the file position for the given key:
781 long retval = -1;
782
783 // Pick up our structure for this key_number
784 file_index_t *file_index = &file->supplemental->indexes[key_number];
785
786 // Build the key value for the given key_number
787 std::vector<unsigned char> key = file_indexed_make_key(file, key_number);
788
789 // Find the pair of pointers to the first and last matches
790 std::pair < std::multimap<std::vector<unsigned char>, long>::iterator,
791 std::multimap<std::vector<unsigned char>, long>::iterator> ret;
792 ret = file_index->key_to_position.equal_range(key);
793 file_index->current_iterator = ret.first;
794 file_index->ending_iterator = ret.second;
795
796 if( ret.first != ret.second )
797 {
798 // There is one or more entries that match the key. We are returning
799 // the location from the first. We leave "recent_indicator" as the one
800 // we found.
801 retval = ret.first->second;
802 }
803 return retval;
804 }
805
806 static int
807 read_an_indexed_record( cblc_file_t *file,
808 long max_bytes,
809 long &record_length,
810 int &flag)
811 {
812 int retval = 2; // zero is okay; 1 is EOF, 2 is an ERROR
813 size_t bytes_read;
814 size_t bytes_to_read;
815
816 // Call this routine with the file positioned at the record to read
817
818 // We need to read in the four-byte preamble plus record_area_min bytes
819 // of the record to be deleted. We need those bytes in order to calculate
820 // all of the keys of indexes that might have to be removed:
821
822 unsigned char ach[4];
823 bytes_read = fread(ach, 1, 4, file->file_pointer);
824 file->errnum = ferror(file->file_pointer);
825 if( feof(file->file_pointer) || bytes_read < 4 )
826 {
827 clearerr(file->file_pointer);
828 retval = 1; // Flag the EOF
829 goto done;
830 }
831 if( handle_ferror(file, __func__, "fread() error") )
832 {
833 goto done;
834 }
835
836 record_length = static_cast<long>(ach[0])<<8;
837 record_length += ach[1];
838 if(ach[2] != 0)
839 {
840 warnx("Bad file format in read_an_indexed_record(). "
841 "Third byte should be zero");
842 abort();
843 }
844
845 flag = ach[3];
846
847 bytes_to_read = record_length;
848 if( record_length > max_bytes )
849 {
850 // The record length in the file is too big for us to read into our
851 // record area.
852
853 // Read as many bytes as we can:
854 bytes_to_read = max_bytes;
855 }
856
857 file->errnum = 0;
858 bytes_read = fread(file->default_record->data,
859 1,
860 bytes_to_read,
861 file->file_pointer);
862 if( handle_ferror(file, __func__, "fread() error") )
863 {
864 goto done;
865 }
866 if( bytes_read != bytes_to_read)
867 {
868 // Weird. We couldn't read a minimal number of bytes
869 goto done;
870 }
871
872 if( record_length > max_bytes )
873 {
874 // The record length in the file was too big. So, we read what we could.
875 // Now we need to adjust the file pointer to skip past the bytes we weren't
876 // able to read:
877 fseek(file->file_pointer, record_length - max_bytes, SEEK_CUR);
878 if( handle_ferror(file, __func__, "fseek() error") )
879 {
880 goto done;
881 }
882 }
883 retval = 0; // Indicate that all is well
884 done:
885 return retval;
886 }
887
888 struct position_state_t
889 {
890 int recent_key;
891 long starting_position;
892 std::vector<std::multimap<std::vector<unsigned char>, long>::iterator> currents;
893 std::vector<std::multimap<std::vector<unsigned char>, long>::iterator> endings;
894 };
895
896 static void
897 position_state_preserve(cblc_file_t *file, position_state_t &state)
898 {
899 state.recent_key = file->recent_key;
900 state.starting_position = ftell(file->file_pointer);
901 if( handle_ferror(file, __func__, "ftell() error") )
902 {
903 exit(1);
904 }
905 for(size_t i=1; i<file->supplemental->indexes.size(); i++)
906 {
907 state.currents.push_back(file->supplemental->indexes[i].current_iterator);
908 state.endings.push_back (file->supplemental->indexes[i].ending_iterator );
909 }
910 }
911
912 static void
913 position_state_restore(cblc_file_t *file, const position_state_t &state)
914 {
915 file->recent_key = state.recent_key;
916 fseek(file->file_pointer, state.starting_position, SEEK_SET);
917 if( handle_ferror(file, __func__, "fseek() error") )
918 {
919 exit(1);
920 }
921 for(size_t i=1; i<file->supplemental->indexes.size(); i++)
922 {
923 // Remember that key numbers range from 1 to N, whilst the vector we
924 // we created to stash the iterators started at zero.
925 file->supplemental->indexes[i].current_iterator = state.currents[i-1];
926 file->supplemental->indexes[i].ending_iterator = state.endings[i-1];
927 }
928 }
929
930 static void
931 indexed_file_delete(cblc_file_t *file, bool is_random)
932 {
933 file->errnum = 0;
934 file->io_status = FsErrno;
935
936 long fpos;
937 unsigned char *stash = NULL;
938 long record_length;
939 int flag;
940 file_hole_t new_hole;
941 position_state_t position_state;
942
943 if( !file->file_pointer )
944 {
945 // Attempting to delete in a file that isn't open
946 file->io_status = FsNoDelete; // "49"
947 goto done;
948 }
949
950 if( file->mode_char != '+' )
951 {
952 // We have to be in I-O mode
953 file->io_status = FsNoDelete; // "49"
954 goto done;
955 }
956
957 if( !is_random && file->prior_read_location == -1 )
958 {
959 // When the access mode is sequential, the prior operation shall have been a
960 // successful read statement. It is that record which is removed. Not
961 // meeting that requirement gets its own error code:
962 file->io_status = FsNoRead; // "43"
963 goto done;
964 }
965
966 // For both sequential and random access, we need to read the record to be
967 // deleted into the record area. It could be I am being overly didactic, but
968 // my reading of the ISO spec indicates that there has to be a successful read
969 // of the record in sequential mode, but I don't see a requirement that the]
970 // programmer leave the record area untouched before trying to delete it.
971
972 // Likewise, for random access, the primary key has to be valid, but I see
973 // no requirement that the alternate keys be valid. We need the alternate
974 // keys in place in order to delete them from the indexes.
975
976 // The requirements for a delete are that both the file position indicator
977 // and the record area itself are unchanged by the delete operation.
978
979 // So, we save the current record area:
980 stash = static_cast<unsigned char *>(malloc(file->record_area_max));
981 massert(stash);
982 memcpy(stash, file->default_record->data, file->record_area_max);
983
984 // And the position state of our file
985 position_state_preserve(file, position_state);
986
987 if( !is_random )
988 {
989 // For sequential, re-read the recent successful read:
990 fpos = file->prior_read_location;
991 }
992 else
993 {
994 // We are doing a random read. Figure out the position from the primary
995 // key:
996 fpos = file_indexed_first_position(file, 1);
997 if( fpos == -1 )
998 {
999 // The primary key does not exist
1000 file->io_status = FsNotFound; // "23"
1001 goto done;
1002 }
1003 }
1004
1005 // Read the record to be deleted into the record area:
1006 fseek(file->file_pointer, fpos, SEEK_SET);
1007 if( handle_ferror(file, __func__, "fseek() error") )
1008 {
1009 goto done;
1010 }
1011 if( read_an_indexed_record( file,
1012 file->record_area_max,
1013 record_length,
1014 flag) )
1015 {
1016 goto done;
1017 }
1018
1019 // The record we just read *has* to be a good record:
1020 if( flag != 1 )
1021 {
1022 warnx("Bad file format in indexed_file_delete(). "
1023 "Fourth byte should be one");
1024 abort();
1025 }
1026
1027 // Because we are deleting it, we need to remove it from all of the indexes.
1028 // Given our indexes, we need to scan all of them looking for the matching
1029 // fpos value. And then we have to start over again, because the deletion
1030 // changes the tree that implements the multimap. If speed becomes an issue,
1031 // a bandaid fix would be to create a multi-map of fpos to iterator.
1032
1033 // The real fix is a real database, but somewhere before that we need to
1034 // really design an indexed file system, instead of this business of putting
1035 // it on a stick an banging a few nails through it.
1036
1037 for(size_t key_number=1;
1038 key_number<file->supplemental->indexes.size();
1039 key_number++)
1040 {
1041 file_index_t *file_index = &file->supplemental->indexes[key_number];
1042 if( file->supplemental->uniques[key_number] )
1043 {
1044 // This key does not allow duplicates, so we don't have to scan for it,
1045 // because we know we have to delete it.
1046 file_indexed_first_position(file, key_number);
1047 file_index->key_to_position.erase(file_index->current_iterator);
1048 // and continue to the next key number
1049 continue;
1050 }
1051 else
1052 {
1053 // This particular key allows duplicates
1054
1055 // We have to scan the entire index for keys that point to our fpos. When
1056 // we find one, we check to see if the keys match. If the keys don't
1057 // match, then we have to remove the existing one from the index.
1058
1059 bool deleting = true;
1060 while(deleting)
1061 {
1062 deleting = false;
1063 std::multimap<std::vector<unsigned char>, long>::iterator it
1064 = file_index->key_to_position.begin();
1065 while( it != file_index->key_to_position.end() )
1066 {
1067 if( it->second == fpos )
1068 {
1069 // We have found an index that points to our record.
1070 // It needs to be deleted.
1071 file_index->key_to_position.erase(it);
1072 deleting = true;
1073 break;
1074 }
1075
1076 it++;
1077 }
1078 }
1079 }
1080 }
1081
1082 // We need to turn this record into a hole by changing the fourth byte from
1083 // one to zero
1084
1085 fseek(file->file_pointer, fpos+3, SEEK_SET);
1086 if( handle_ferror(file, __func__, "fseek() error") )
1087 {
1088 goto done;
1089 }
1090 fputc(0, file->file_pointer);
1091 if( handle_ferror(file, __func__, "fputc() error") )
1092 {
1093 goto done;
1094 }
1095
1096 // We just created a hole; put it in the list:
1097 new_hole.location = fpos;
1098 new_hole.size = record_length;
1099 file->supplemental->holes.push_back(new_hole);
1100
1101 done:
1102 if( stash )
1103 {
1104 // Restore the stashed record area:
1105 memcpy(file->default_record->data, stash, file->record_area_min);
1106 free(stash);
1107 stash = NULL;
1108 file->prior_op = file_op_delete;
1109 position_state_restore(file, position_state);
1110 }
1111
1112 file->prior_op = file_op_delete;
1113 establish_status(file, -1);
1114 }
1115
1116 static void
1117 __io__file_delete(cblc_file_t *file, bool is_random)
1118 {
1119 switch(file->org)
1120 {
1121 case file_relative_e:
1122 relative_file_delete(file, is_random);
1123 break;
1124
1125 case file_indexed_e:
1126 indexed_file_delete(file, is_random);
1127 break;
1128
1129 default:
1130 warnx("%s(): Unhandled file organization", __func__);
1131 exit(1);
1132 break;
1133 }
1134
1135 if( file->io_status < FhNotOkay )
1136 {
1137 file->flags |= file_flag_existed_e;
1138 }
1139 }
1140
1141 static void
1142 indexed_file_start( cblc_file_t *file,
1143 int relop,
1144 int key_number,
1145 size_t length)
1146 {
1147 static const int first_key = 1;
1148 //fprintf(stderr, " length is %ld\n", length);
1149 file->io_status = FsNotFound; // "23"
1150
1151 size_t length_of_key = 0;
1152 bool direction_reverse;
1153 std::multimap<std::vector<unsigned char>, long>::iterator it;
1154 file_index_t *file_index;
1155 std::vector<unsigned char> the_key;
1156
1157 if( key_number == -1 )
1158 {
1159 // This is FIRST:
1160 file_index = &file->supplemental->indexes[first_key];
1161 if( file_index->key_to_position.size() )
1162 {
1163 it = file_index->key_to_position.begin();
1164 file->io_status = FsErrno;
1165 key_number = first_key;
1166 }
1167 goto done;
1168 }
1169 if( key_number == -2 )
1170 {
1171 // This is LAST:
1172 file_index = &file->supplemental->indexes[first_key];
1173 if( file_index->key_to_position.size() )
1174 {
1175 it = file_index->key_to_position.end();
1176 it--;
1177 file->io_status = FsErrno;
1178 key_number = first_key;
1179 }
1180 goto done;
1181 }
1182
1183 // Pick up our file index for this key number
1184 file_index = &file->supplemental->indexes[key_number];
1185
1186 // We are going to need the key from the existing record:
1187 the_key = file_indexed_make_key(file, key_number);
1188 length_of_key = the_key.size();
1189
1190 // Make sure the length parameter is within the size of the actual key
1191 if( length < 1 || length > length_of_key )
1192 {
1193 file->io_status = FsNotFound; // "23"
1194 goto done;
1195 }
1196
1197 direction_reverse = (relop==lt_op || relop==le_op);
1198
1199 if( direction_reverse )
1200 {
1201 // We will do a forward search for the biggest index that is smaller than
1202 // the key.
1203 std::multimap<std::vector<unsigned char>, long>::iterator bestie =
1204 file_index->key_to_position.end();
1205 it = file_index->key_to_position.begin();
1206 while( it != file_index->key_to_position.end() )
1207 {
1208 const unsigned char *the_index = it->first.data();
1209
1210 // Do the comparison:
1211 int result = 0;
1212
1213 for(size_t i=0; i<length; i++)
1214 {
1215 result = the_index[i] - the_key[i] ;
1216 if( result )
1217 {
1218 break;
1219 }
1220 }
1221
1222 if( result > 0 )
1223 {
1224 // The index is bigger than the key, so, for better or for worse, we
1225 // are done looking.
1226 break;
1227 }
1228
1229 if( result == 0 )
1230 {
1231 // The index and key are equal
1232 if( relop == le_op )
1233 {
1234 // We have equal, and we were looking for equality. Set a conditional
1235 // winner, and then keep looking in case there are more indexes that
1236 // are equal to the key
1237 bestie = it;
1238 file->io_status = FsErrno;
1239 }
1240 }
1241 else // if( result < 0 )
1242 {
1243 // The index is less than the key.
1244 if( relop == lt_op
1245 || relop == le_op )
1246 {
1247 // This is a conditional winner, so we flag it as such and keep going,
1248 // because there might be more indexes that are bigger than this one
1249 // but less than the key
1250 bestie = it;
1251 file->io_status = FsErrno;
1252 }
1253 }
1254 // At this point, the index is less than the key, so we keep looking:
1255 it++;
1256 }
1257 if( file->io_status == FsErrno )
1258 {
1259 // We found something
1260 it = bestie;
1261 }
1262 }
1263 else
1264 {
1265 // We are doing a forward search for the first index entry that matches
1266 // the criterion.
1267
1268 it = file_index->key_to_position.begin();
1269 while( it != file_index->key_to_position.end() )
1270 {
1271 const unsigned char *the_index = it->first.data();
1272
1273 // Do the comparison:
1274 int result = 0;
1275
1276 for(size_t i=0; i<length; i++)
1277 {
1278 result = the_index[i] - the_key[i] ;
1279 if( result )
1280 {
1281 break;
1282 }
1283 }
1284
1285 if( result == 0 )
1286 {
1287 // The index and key are equal
1288 if( relop == eq_op
1289 || relop == ge_op )
1290 {
1291 // We have equal, and we were looking for equality:
1292 file->io_status = FsErrno;
1293 goto done;
1294 }
1295 else
1296 {
1297 // The operation is gt_op, so we fall through and keep looking
1298 }
1299 }
1300 else if( result > 0 )
1301 {
1302 // The the index is bigger than the key
1303 if( relop == eq_op )
1304 {
1305 // The index is bigger than the key, so we will never find
1306 // equality.
1307 goto done;
1308 }
1309 // At the point, the operation has to be ge_op or gt_op, so our
1310 // criterion is satisfied
1311 file->io_status = FsErrno;
1312 goto done;
1313 }
1314 // At this point, the index is less than the key, so we keep looking:
1315 it++;
1316 }
1317 // We went through the whole index without finding anything.
1318 }
1319 done:
1320 if( file->io_status == FsErrno )
1321 {
1322 // The it iterator points to a valid found index:
1323 file_index->current_iterator = it;
1324 file_index->ending_iterator = file_index->key_to_position.end();
1325
1326 fseek(file->file_pointer, it->second, SEEK_SET);
1327 handle_ferror(file, __func__, "fseek() error");
1328
1329 file->recent_key = key_number;
1330 }
1331 }
1332
1333 static long
1334 relative_file_start(cblc_file_t *file,
1335 int first_last_key,
1336 int relop)
1337 {
1338 long fpos = -1;
1339 relative_file_parameters rfp;
1340 int rdigits;
1341 long total_record_length;
1342 if( relative_file_parameters_get( rfp,
1343 rfm_microfocus_e,
1344 file,
1345 IGNORE_LIMITS,
1346 INIT_KEY,
1347 true) )
1348 {
1349 goto done;
1350 }
1351 total_record_length
1352 = rfp.preamble_size + rfp.payload_size + rfp.postamble_size;
1353 if( first_last_key == -1 )
1354 {
1355 // This is FIRST. Search forward from the beginning
1356 rfp.key_value = 1;
1357 relop = ge_op;
1358 }
1359 else if( first_last_key == -2 )
1360 {
1361 // This is LAST. Search reverse from the end
1362 rfp.key_value = rfp.file_size / total_record_length;
1363 relop = le_op;
1364 }
1365 else
1366 {
1367 rfp.key_value = (long)__gg__binary_value_from_field(&rdigits,
1368 file->keys[0]);
1369 }
1370
1371 bool forward;
1372 switch( relop )
1373 {
1374 case eq_op:
1375 case ge_op:
1376 forward = true;
1377 break;
1378 case le_op:
1379 forward = false;
1380 break;
1381 case gt_op:
1382 rfp.key_value += 1;
1383 forward = true;
1384 break;
1385 case lt_op:
1386 rfp.key_value -= 1;
1387 forward = false;
1388 break;
1389 default:
1390 warnx("%s(): relop is %d, which we don't know how to handle",
1391 __func__,
1392 relop);
1393 exit(1);
1394 break;
1395 }
1396
1397 if( forward )
1398 {
1399 // We are searching forward, so we want the key_value to be 1 or more
1400 rfp.key_value = std::max( rfp.key_value, (long)1);
1401 }
1402 else
1403 {
1404 // We are searching backward, so we want the rfp.key_value to be at most
1405 // the last possible record based on the file size:
1406 rfp.key_value = std::min( rfp.key_value,
1407 rfp.file_size / total_record_length);
1408 }
1409
1410 // Let's initialize for searching for a valid record:
1411 rfp.record_position = (rfp.key_value-1) * total_record_length;
1412 rfp.flag_position = rfp.record_position + rfp.record_size - 1;
1413
1414 // And let the searching begin:
1415
1416 while( rfp.record_position >= 0
1417 && rfp.record_position+total_record_length <= rfp.file_size )
1418 {
1419 char record_marker;
1420 ssize_t presult = pread(rfp.fd, &record_marker, 1, rfp.flag_position);
1421 if( presult < 0 )
1422 {
1423 handle_errno(file, __func__, "pread() error");
1424 goto done;
1425 }
1426 if( presult == 0 )
1427 {
1428 // end of file
1429 goto done;
1430 }
1431 if( record_marker == internal_newline )
1432 {
1433 // The record is a valid one
1434 fpos = rfp.record_position;
1435 goto done;
1436 }
1437 // That position in the file did not have valid data in it. Move on to the
1438 // next record
1439 if( forward )
1440 {
1441 rfp.key_value += 1;
1442 rfp.record_position += total_record_length;
1443 rfp.flag_position += total_record_length;
1444 }
1445 else
1446 {
1447 rfp.key_value -= 1;
1448 rfp.record_position -= total_record_length;
1449 rfp.flag_position -= total_record_length;
1450 }
1451 }
1452
1453 if( fpos == -1)
1454 {
1455 // We didn't find a valid record
1456 file->io_status = FsNotFound; // "23"
1457 goto done;
1458 }
1459
1460 // Position the file at the requested record:
1461 done:
1462 if( fpos >= 0)
1463 {
1464 fseek(file->file_pointer, fpos, SEEK_SET);
1465 if( handle_ferror(file, __func__, "fseek() error") )
1466 {
1467 goto done;
1468 }
1469 // It's unclear to me whether or not START is supposed to update keys like
1470 // this
1471 // Update the key with the one we found
1472 // __gg__int128_to_field(file->keys[0],
1473 // rfp.key_value,
1474 // 0,
1475 // truncation_e,
1476 // NULL);
1477 }
1478
1479 return fpos;
1480 }
1481
1482
1483 static void
1484 __io__file_start( cblc_file_t *file,
1485 int relop,
1486 int first_last_key,
1487 size_t length)
1488 {
1489 // According to IBM Language Reference 6.3, whether or not 'key' is specified,
1490 // the value used is from the RELATIVE KEY clause. See page 421 "Relative
1491 // Files" "Whether or not the KEY phrase is specified, the key data item used
1492 // in the comparison is the RELATIVE KEY data item."
1493 file->errnum = 0;
1494 file->io_status = FsErrno;
1495 long fpos = -1;
1496
1497 bool okay;
1498
1499 if( !file->file_pointer )
1500 {
1501 // Attempting to START a file that isn't open
1502 if( file->flags & file_flag_optional_e )
1503 {
1504 file->io_status = FsNotFound; // "23"
1505 }
1506 else
1507 {
1508 file->io_status = FsReadNotOpen; // "47"
1509 }
1510 goto done;
1511 }
1512
1513 okay = (file->org == file_indexed_e || file->org == file_relative_e)
1514 && ( file->access == file_access_seq_e
1515 || file->access == file_access_dyn_e)
1516 && (file->mode_char == 'r' || file->mode_char == '+') ;
1517 if( !okay )
1518 {
1519 file->io_status = FsReadNotOpen; // "47"
1520 goto done;
1521 }
1522
1523 if( file->org == file_relative_e )
1524 {
1525 fpos = relative_file_start(file, first_last_key, relop);
1526 }
1527 else
1528 {
1529 // first_last_key is the key_number
1530 indexed_file_start(file, relop, first_last_key, length);
1531 if( file->io_status == FsErrno )
1532 {
1533 fpos = 0;
1534 }
1535 }
1536
1537 done:
1538 if( file->io_status == FsErrno )
1539 {
1540 file->flags |= file_flag_existed_e;
1541 }
1542
1543 file->prior_op = file_op_start;
1544 establish_status(file, fpos);
1545 if( file->io_status < FhNotOkay )
1546 {
1547 file->flags |= file_flag_existed_e;
1548 }
1549 }
1550
1551 static void
1552 sequential_file_rewrite( cblc_file_t *file, size_t length )
1553 {
1554 // Handles sequential files
1555
1556 file->errnum = 0;
1557 file->io_status = FsErrno;
1558
1559 long starting_position = -1;
1560 bool okay;
1561 size_t bytes_to_write;
1562
1563 if( !file->file_pointer )
1564 {
1565 // Attempting to read a file that isn't open
1566 file->io_status = FsNoDelete; // "49"
1567 goto done;
1568 }
1569
1570 okay = (file->mode_char == '+');
1571
1572 if( !okay )
1573 {
1574 file->io_status = FsNoDelete; // "49"
1575 goto done;
1576 }
1577
1578 starting_position = ftell(file->file_pointer);
1579 // Check for EOF before calling ferror, which clears feof
1580 if( feof( file->file_pointer) )
1581 {
1582 // Trying to do a rewrite at the end-of-file position has its own code:
1583 file->io_status = FsNoRead; // "43"
1584 goto done;
1585 }
1586 if( handle_ferror(file, __func__, "ftell() error") )
1587 {
1588 goto done;
1589 }
1590
1591 if( file->prior_read_location == -1 )
1592 {
1593 // The prior operation was not a successful read:
1594 file->io_status = FsNoRead; // "43"
1595 goto done;
1596 }
1597
1598 fseek(file->file_pointer, file->prior_read_location, SEEK_SET);
1599 if( handle_ferror(file, __func__, "fseek() error") )
1600 {
1601 goto done;
1602 }
1603
1604 size_t existing_size;
1605 if( file->record_area_min != file->record_area_max )
1606 {
1607 // Because of the different sizes, we are expecting a preamble:
1608
1609 // An error at this point is either an error, or a true end-of-file.
1610 unsigned char preamble[4];
1611 size_t characters_read = fread(preamble, 1, 4, file->file_pointer);
1612 if( handle_ferror(file, __func__, "fread() error") )
1613 {
1614 // This also comes back true for an ordinary end-of-file
1615 goto done;
1616 }
1617
1618 if( characters_read != 4 )
1619 {
1620 // If the preamble is incomplete, treat that as an EOF
1621 file->io_status = FsEofSeq; // "10"
1622 file->prior_read_location = -1;
1623 goto done;
1624 }
1625
1626 // Extract the count of bytes in the record from the preamble
1627 existing_size = ((size_t)preamble[0]<<8) + preamble[1];
1628 }
1629 else
1630 {
1631 // Because the min and max are the same, we figure on writing that many
1632 // characters:
1633 existing_size = file->record_area_max;
1634 }
1635
1636 // We need to make sure that the number of bytes we've been asked
1637 // to write is valid:
1638
1639 // By default, we write what we've been asked to write.
1640 bytes_to_write = length;
1641
1642 // But that can be overridden by a depending_on from the
1643 // FILE-CONTROL paragraph:
1644
1645 if( file->record_length )
1646 {
1647 int rdigits;
1648 bytes_to_write = (size_t)__gg__binary_value_from_field(
1649 &rdigits,
1650 file->record_length);
1651 }
1652
1653 if( bytes_to_write < file->record_area_min
1654 || bytes_to_write > file->record_area_max
1655 || bytes_to_write != existing_size )
1656 {
1657 file->io_status = FsBoundWrite; // "44"
1658 goto done;
1659 }
1660
1661 if( file->record_area_min != file->record_area_max )
1662 {
1663 const unsigned char preamble[4] =
1664 {
1665 (unsigned char)(bytes_to_write>>8),
1666 (unsigned char)(bytes_to_write),
1667 0,
1668 0
1669 };
1670
1671 fwrite( preamble,
1672 4,
1673 1,
1674 file->file_pointer);
1675 if( handle_ferror(file, __func__, "fwrite() error") )
1676 {
1677 goto done;
1678 }
1679 }
1680
1681 fwrite( file->default_record->data,
1682 bytes_to_write,
1683 1,
1684 file->file_pointer );
1685 if( handle_ferror(file, __func__, "fwrite() error") )
1686 {
1687 goto done;
1688 }
1689
1690 done:
1691 // Per the standard, return the file location pointer back to whence it came:
1692 fseek(file->file_pointer, starting_position, SEEK_SET);
1693 handle_ferror(file, __func__, "fseek() error");
1694 file->prior_op = file_op_rewrite;
1695 establish_status(file, starting_position);
1696 }
1697
1698 static void
1699 relative_file_rewrite_varying( cblc_file_t *file, bool is_random )
1700 {
1701 file->errnum = 0;
1702 file->io_status = FsErrno;
1703
1704 long starting_position = -1;
1705 relative_file_parameters rfp;
1706 size_t payload_size;
1707
1708 if( !file->file_pointer )
1709 {
1710 // Attempting to rewrite a file that isn't open
1711 file->io_status = FsNoDelete; // "49"
1712 goto done;
1713 }
1714
1715 if( file->mode_char != '+' )
1716 {
1717 file->io_status = FsNoDelete; // "49"
1718 goto done;
1719 }
1720
1721 starting_position = ftell(file->file_pointer);
1722 // Check for EOF before calling ferror, which clears feof
1723 if( feof( file->file_pointer) )
1724 {
1725 // Trying to do a rewrite at the end-of-file position has its own code:
1726 file->io_status = FsNoRead; // "43"
1727 goto done;
1728 }
1729 if( handle_ferror(file, __func__, "ftell() error") )
1730 {
1731 goto done;
1732 }
1733
1734 if( !is_random )
1735 {
1736 // The access mode is sequential, so we can leverage
1737 // sequential_file_rewrite
1738 rfp.record_position = starting_position;
1739 goto do_the_write;
1740 }
1741 else
1742 {
1743 // This is like a write, except the place we are putting
1744 // it has to be occupied instead of empty.
1745 if( relative_file_parameters_get( rfp,
1746 rfm_microfocus_e,
1747 file,
1748 RESPECT_LIMITS,
1749 DONT_INIT_KEY,
1750 is_random) )
1751 {
1752 goto done;
1753 }
1754
1755 do_the_write:
1756 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
1757 if( handle_ferror(file, __func__, "fseek() error") )
1758 {
1759 goto done;
1760 }
1761 fread(&payload_size, 8, 1, file->file_pointer);
1762 if( handle_ferror(file, __func__, "fread() error") )
1763 {
1764 goto done;
1765 }
1766
1767 if( !payload_size )
1768 {
1769 // The record is not empty:
1770 file->io_status = FsNotFound; // "23"
1771 goto done;
1772 }
1773
1774 payload_size = file->default_record->capacity;
1775 if( payload_size < file->record_area_min
1776 || payload_size > file->record_area_max)
1777 {
1778 file->io_status = FsBoundWrite; // "44"
1779 goto done;
1780 }
1781
1782 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
1783 if( handle_ferror(file, __func__, "fseek() error") )
1784 {
1785 goto done;
1786 }
1787 // We can overwrite the valid record:
1788 fwrite( &payload_size,
1789 8,
1790 1,
1791 file->file_pointer );
1792 if( handle_ferror(file, __func__, "fwrite() error") )
1793 {
1794 goto done;
1795 }
1796
1797 fwrite( file->default_record->data,
1798 file->default_record->capacity,
1799 1,
1800 file->file_pointer );
1801 if( handle_ferror(file, __func__, "fwrite() error") )
1802 {
1803 goto done;
1804 }
1805 }
1806
1807 done:
1808 // Per the standard, return the file location pointer back to whence it came:
1809 fseek(file->file_pointer, starting_position, SEEK_SET);
1810 handle_ferror(file, __func__, "fseek() error");
1811 file->prior_op = file_op_rewrite;
1812 establish_status(file, starting_position);
1813 }
1814
1815 static void
1816 relative_file_rewrite( cblc_file_t *file, size_t length, bool is_random )
1817 {
1818 if( file->record_area_min != file->record_area_max )
1819 {
1820 return relative_file_rewrite_varying(file, is_random);
1821 }
1822
1823 file->errnum = 0;
1824 file->io_status = FsErrno;
1825
1826 long starting_position = -1;
1827 relative_file_parameters rfp;
1828
1829 if( !file->file_pointer )
1830 {
1831 // Attempting to rewrite a file that isn't open
1832 file->io_status = FsNoDelete; // "49"
1833 goto done;
1834 }
1835
1836 if( file->mode_char != '+' )
1837 {
1838 file->io_status = FsNoDelete; // "49"
1839 goto done;
1840 }
1841
1842 starting_position = ftell(file->file_pointer);
1843 // Check for EOF before calling ferror, which clears feof
1844 if( feof( file->file_pointer) )
1845 {
1846 // Trying to do a rewrite at the end-of-file position has its own code:
1847 file->io_status = FsNoRead; // "43"
1848 goto done;
1849 }
1850 if( handle_ferror(file, __func__, "ftell() error") )
1851 {
1852 goto done;
1853 }
1854
1855 if(!is_random)
1856 {
1857 // The access mode is sequential, so we can leverage
1858 // sequential_file_rewrite
1859 sequential_file_rewrite(file, length);
1860 goto done;
1861 }
1862 else
1863 {
1864 // This is like a write, except the place we are putting
1865 // it has to be occupied instead of empty.
1866 char record_marker;
1867 if( relative_file_parameters_get( rfp,
1868 rfm_microfocus_e,
1869 file,
1870 RESPECT_LIMITS,
1871 DONT_INIT_KEY,
1872 is_random) )
1873 {
1874 goto done;
1875 }
1876
1877 ssize_t presult = pread(rfp.fd, &record_marker, 1, rfp.flag_position);
1878 if( presult < 0 )
1879 {
1880 handle_errno(file, __func__, "pread() error");
1881 goto done;
1882 }
1883
1884 if( presult == 0 || record_marker != internal_newline )
1885 {
1886 // The record is not specified:
1887 file->io_status = FsNotFound; // "23"
1888 goto done;
1889 }
1890
1891 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
1892 if( handle_ferror(file, __func__, "fseek() error") )
1893 {
1894 goto done;
1895 }
1896
1897 // We can overwrite the valid record:
1898 fwrite( file->default_record->data,
1899 file->default_record->capacity,
1900 1,
1901 file->file_pointer );
1902 if( handle_ferror(file, __func__, "fwrite() error") )
1903 {
1904 goto done;
1905 }
1906 }
1907
1908 done:
1909 // Per the standard, return the file location pointer back to whence it came:
1910 fseek(file->file_pointer, starting_position, SEEK_SET);
1911 handle_ferror(file, __func__, "fseek() error");
1912 file->prior_op = file_op_rewrite;
1913 establish_status(file, starting_position);
1914 }
1915
1916 static bool
1917 file_indexed_update_indices(cblc_file_t *file,
1918 long record_position,
1919 bool dupes_okay = false)
1920 {
1921 // We have a record in the file->record_area.
1922
1923 bool okay = true;
1924
1925 // We have to do this in two passes.
1926
1927 // First, we check to see that for all keys flagged as unique, that
1928 // the key doesn't already exist:
1929
1930 for(size_t key_number=1;
1931 key_number<file->supplemental->indexes.size();
1932 key_number++)
1933 {
1934 if( file->supplemental->uniques[key_number] )
1935 {
1936 // This key has to be unique:
1937 std::vector<unsigned char>key_value =
1938 file_indexed_make_key(file, key_number);
1939 file_index_t *file_index = &file->supplemental->indexes[key_number];
1940 std::multimap<std::vector<unsigned char>, long>::const_iterator it =
1941 file_index->key_to_position.find(key_value);
1942 if( it != file_index->key_to_position.end() )
1943 {
1944 // This key is already in the index
1945 if( !dupes_okay || it->second != record_position )
1946 {
1947 // We have a key violation:
1948 file->io_status = FsDupWrite; // "22"
1949 okay = false;
1950 break;
1951 }
1952 }
1953 }
1954 }
1955
1956 if( okay )
1957 {
1958 // There were no key violations, so we can do the second pass, which inserts
1959 // the keys into the indexes.
1960 for(size_t key_number=1;
1961 key_number<file->supplemental->indexes.size();
1962 key_number++)
1963 {
1964 file_index_t *file_index = &file->supplemental->indexes[key_number];
1965 // But we don't want the key to end up in here twice, which we have to
1966 // avoid when updating the indexes after a REWRITE
1967
1968 bool safe_to_insert = true;
1969 file_indexed_first_position(file, key_number);
1970 while( file_index->current_iterator != file_index->ending_iterator )
1971 {
1972 if( file_index->current_iterator->second == record_position)
1973 {
1974 safe_to_insert = false;
1975 break;
1976 }
1977 file_index->current_iterator++;
1978 }
1979
1980 if( safe_to_insert )
1981 {
1982 std::vector<unsigned char>key_value =
1983 file_indexed_make_key(file, key_number);
1984 std::pair<std::vector<unsigned char>, long>
1985 to_insert(key_value, record_position);
1986 file_index->key_to_position.insert(to_insert);
1987 }
1988 }
1989 }
1990 return okay;
1991 }
1992
1993 static void
1994 indexed_file_rewrite( cblc_file_t *file, size_t /*length*/, bool is_random )
1995 {
1996 file->errnum = 0;
1997 file->io_status = FsErrno;
1998
1999 long fpos = -1;
2000 position_state_t position_state;
2001 long record_length;
2002
2003 if( !file->file_pointer )
2004 {
2005 // Attempting to work on a file that isn't open
2006 file->io_status = FsNoDelete; // "49"
2007 goto done;
2008 }
2009
2010 if( file->mode_char != '+' )
2011 {
2012 // For an indexed_file REWRITE, the mode has to be '+'
2013 file->io_status = FsNoDelete; // "49"
2014 goto done;
2015 }
2016
2017 // We need to preserve the file position state
2018 position_state_preserve(file, position_state);
2019
2020 if( !is_random )
2021 {
2022 // In the case of sequential access, the prior operation needed to be a
2023 // successful read:
2024 if( file->prior_read_location == -1 )
2025 {
2026 // The prior operation was not a successful read:
2027 file->io_status = FsNoRead; // "43"
2028 goto done;
2029 }
2030
2031 // The prior read was successful. Let's see if the primary key has changed
2032 fpos = file_indexed_first_position(file, 1);
2033 if( fpos != file->prior_read_location )
2034 {
2035 // Between the successful read and this attempt at a rewrite, somebody
2036 // changed the primary key in the record. This gets its own special error
2037 // code
2038 file->io_status = FsKeySeq; // "21"
2039 goto done;
2040 }
2041 }
2042 else
2043 {
2044 // It's not a sequential read, so it's got to be random. Let's determine
2045 // that the primary key is valid:
2046 fpos = file_indexed_first_position(file, 1);
2047 if( fpos == -1 )
2048 {
2049 file->io_status = FsNotFound; // "23"
2050 goto done;
2051 }
2052 }
2053
2054 // We need to know the record length:
2055 fseek(file->file_pointer, fpos, SEEK_SET);
2056 if( handle_ferror(file, __func__, "fseek() error") )
2057 {
2058 fpos = -1;
2059 goto done;
2060 }
2061
2062 unsigned char preamble[4];
2063 fread(preamble, 1, 4, file->file_pointer);
2064 if( handle_ferror(file, __func__, "fread() error") )
2065 {
2066 fpos = -1;
2067 goto done;
2068 }
2069 record_length = (preamble[0]<<8) + preamble[1];
2070 // Note that after the read, the file position is at the beginning of the
2071 // record.
2072
2073 // We know we have a good primary key. It points to fpos.
2074
2075 // We now need to check any alternate keys flagged as unique. We need to
2076 // make sure that any such key this record has already points to fpos.
2077
2078 // If it points somewhere else, then our attempt to rewrite the record would
2079 // end up that key pointing to two different records, which means a failure:
2080
2081 for(size_t key_number=2;
2082 key_number<file->supplemental->indexes.size();
2083 key_number++)
2084 {
2085 if( file->supplemental->uniques[key_number] )
2086 {
2087 // This particular alternative index does not allow duplicates
2088 long altfpos = file_indexed_first_position(file, key_number);
2089 if( altfpos != -1 && altfpos != fpos )
2090 {
2091 // This alternate key would create a duplicate index entry where none
2092 // such are allowed:
2093 file->io_status = FsDupWrite; // "22"
2094 goto done;
2095 }
2096 }
2097 }
2098
2099 // At this point we know we are going to write the record, because there will
2100 // be no key violations. But because an alternate key might have changed, we
2101 // we have to scan for all such and remove them from the indexes:
2102 for(size_t key_number=2;
2103 key_number<file->supplemental->indexes.size();
2104 key_number++)
2105 {
2106 if( !file->supplemental->uniques[key_number] )
2107 {
2108 // This particular alternative index allows duplicates
2109 file_index_t *file_index = &file->supplemental->indexes[key_number];
2110
2111 // We have to scan the entire index for keys that point to our fpos. When
2112 // we find one, we check to see if the keys match. If the keys don't
2113 // match, then we have to remove the existing one from the index.
2114
2115 std::vector<unsigned char> the_key
2116 = file_indexed_make_key(file, key_number);
2117 bool deleting = true;
2118 while(deleting)
2119 {
2120 deleting = false;
2121 std::multimap<std::vector<unsigned char>, long>::iterator it
2122 = file_index->key_to_position.begin();
2123 while( it != file_index->key_to_position.end() )
2124 {
2125 if( it->second == fpos )
2126 {
2127 // We have found an index entry that points to our record. If the
2128 // index's key doesn't match our calculated key, we need to delete
2129 // it.
2130 const unsigned char *the_index = it->first.data();
2131 int result = 0;
2132 for(size_t i=0; i<the_key.size(); i++)
2133 {
2134 result = the_key[i] - the_index[i];
2135 if( result )
2136 {
2137 break;
2138 }
2139 }
2140 if(result)
2141 {
2142 // We found an index that needs to be deleted
2143 file_index->key_to_position.erase(it);
2144 deleting = true;
2145 break;
2146 }
2147 }
2148 it++;
2149 }
2150 }
2151 }
2152 }
2153
2154 // To recap: The primary key is valid, and any remaining alternative keys
2155 // are already pointing to fpos, and if a new one gets entered, it won't
2156 // conflict with any existing key flagged as unique.
2157
2158 // We can now write the data out, at the given location:
2159
2160 fwrite( file->default_record->data,
2161 1,
2162 record_length,
2163 file->file_pointer );
2164 if( handle_ferror(file, __func__, "fwrite() error") )
2165 {
2166 goto done;
2167 }
2168
2169 // And it is safe to update the keys:
2170 file_indexed_update_indices(file,
2171 fpos,
2172 true); // Set to true to indicate that might
2173 // // occur and should be ignored
2174
2175 done:
2176 // Per the standard, return thefile location pointer back to whence it came:
2177 if( fpos != -1 )
2178 {
2179 position_state_restore(file, position_state);
2180 }
2181 file->prior_op = file_op_rewrite;
2182 establish_status(file, fpos);
2183 file->prior_read_location = -1;
2184 }
2185
2186 static void
2187 __io__file_rewrite(cblc_file_t *file, size_t length, bool is_random)
2188 {
2189 switch(file->org)
2190 {
2191 case file_relative_e:
2192 relative_file_rewrite(file, length, is_random);
2193 break;
2194
2195 case file_sequential_e:
2196 sequential_file_rewrite(file, length);
2197 break;
2198
2199 case file_indexed_e:
2200 indexed_file_rewrite(file, length, is_random);
2201 break;
2202
2203 default:
2204 warnx("%s(): Unhandled file organization", __func__);
2205 exit(1);
2206 break;
2207 }
2208 if( file->io_status < FhNotOkay )
2209 {
2210 file->flags |= file_flag_existed_e;
2211 }
2212 }
2213
2214 static void
2215 relative_file_write_varying(cblc_file_t *file,
2216 const unsigned char *location,
2217 size_t length,
2218 bool is_random)
2219 {
2220 // This routine handles variable-length writes to RELATIVE files
2221 file->errnum = 0;
2222 file->io_status = FsErrno;
2223
2224 long necessary_file_size;
2225 size_t payload_length;
2226
2227 relative_file_parameters rfp;
2228
2229 if( is_random )
2230 {
2231 if( relative_file_parameters_get( rfp,
2232 rfm_microfocus_e,
2233 file,
2234 IGNORE_LIMITS,
2235 DONT_INIT_KEY,
2236 is_random) )
2237 {
2238 goto done;
2239 }
2240
2241 // If the file isn't big enough, we need to expand it:
2242 necessary_file_size = rfp.record_position
2243 + rfp.record_size;
2244 if( rfp.file_size < necessary_file_size )
2245 {
2246 // Position the file position indicator to the very end of the file
2247 fseek(file->file_pointer, 0, SEEK_END);
2248 if( handle_ferror(file, __func__, "fseek() error") )
2249 {
2250 goto done;
2251 }
2252
2253 // Expand the file to the necessary length:
2254 while( rfp.file_size++ < necessary_file_size-1 )
2255 {
2256 fputc(0, file->file_pointer);
2257 if( handle_ferror(file, __func__, "fputc() error [2]") )
2258 {
2259 goto done;
2260 }
2261 }
2262 }
2263
2264 // Position the file pointer at the slot:
2265 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
2266 if( handle_ferror(file, __func__, "fseek() error") )
2267 {
2268 goto done;
2269 }
2270
2271 fread(&payload_length, 8, 1, file->file_pointer);
2272 if( handle_ferror(file, __func__, "fread() error") )
2273 {
2274 goto done;
2275 }
2276
2277 if( payload_length != 0 )
2278 {
2279 // The slot has something in it already:
2280 file->io_status = FsDupWrite; // "22"
2281 goto done;
2282 }
2283
2284 // Position the file pointer at the slot:
2285 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
2286 if( handle_ferror(file, __func__, "fseek() error") )
2287 {
2288 goto done;
2289 }
2290 }
2291 else
2292 {
2293 // We need to do a sequential write:
2294 if( file->mode_char == 'a' )
2295 {
2296 // Position the file pointer at the end:
2297 fseek(file->file_pointer, 0, SEEK_END);
2298 if( handle_ferror(file, __func__, "fseek() error") )
2299 {
2300 goto done;
2301 }
2302 }
2303 }
2304
2305 // Write out the record.
2306 // We need a length.
2307
2308 if( file->record_length )
2309 {
2310 // df
2311 int rdigits;
2312 length = (size_t)__gg__binary_value_from_field( &rdigits,
2313 file->record_length);
2314 }
2315
2316 payload_length = length;
2317
2318 if( payload_length < file->record_area_min
2319 || payload_length > file->record_area_max)
2320 {
2321 file->io_status = FsBoundWrite; // "44"
2322 goto done;
2323 }
2324
2325 fwrite(&payload_length, 8, 1, file->file_pointer);
2326 if( handle_ferror(file, __func__, "fwrite() error") )
2327 {
2328 goto done;
2329 }
2330
2331 fwrite(location, 1, payload_length, file->file_pointer);
2332 if( handle_ferror(file, __func__, "fwrite() error") )
2333 {
2334 goto done;
2335 }
2336
2337 while( payload_length < file->record_area_max )
2338 {
2339 fputc(internal_space, file->file_pointer);
2340 if( handle_ferror(file, __func__, "fputc() error") )
2341 {
2342 goto done;
2343 }
2344 payload_length += 1;
2345 }
2346
2347 if( is_random )
2348 {
2349 // Per the COBOL specification, put the file position back to where
2350 // it was when we started this exercise:
2351 fseek(file->file_pointer, rfp.current_file_position, SEEK_SET);
2352 if( handle_ferror(file, __func__, "fseek(starting_pos) error") )
2353 {
2354 goto done;
2355 }
2356 }
2357
2358 done:
2359 file->prior_op = file_op_write;
2360 establish_status(file, -1);
2361 }
2362
2363 static void
2364 relative_file_write(cblc_file_t *file,
2365 const unsigned char *location,
2366 size_t length,
2367 bool is_random)
2368 {
2369 // This routine handles writes to RELATIVE files
2370
2371 if( file->record_area_min != file->record_area_max )
2372 {
2373 return relative_file_write_varying(file, location, length, is_random);
2374 }
2375
2376 file->errnum = 0;
2377 file->io_status = FsErrno;
2378
2379 long necessary_file_size;
2380 const unsigned char achPostamble[] = {internal_cr, internal_newline};
2381
2382 relative_file_parameters rfp;
2383
2384 if( is_random )
2385 {
2386 if( relative_file_parameters_get( rfp,
2387 rfm_microfocus_e,
2388 file,
2389 IGNORE_LIMITS,
2390 DONT_INIT_KEY,
2391 is_random) )
2392 {
2393 goto done;
2394 }
2395
2396 necessary_file_size = rfp.record_position
2397 + rfp.preamble_size
2398 + rfp.payload_size
2399 + rfp.postamble_size;
2400 if( rfp.file_size < necessary_file_size )
2401 {
2402 // Position the file position indicator to the very end of the file
2403 fseek(file->file_pointer, 0, SEEK_END);
2404 if( handle_ferror(file, __func__, "fseek() error") )
2405 {
2406 goto done;
2407 }
2408
2409 // Expand the file to the necessary length:
2410 while( rfp.file_size++ < necessary_file_size-1 )
2411 {
2412 fputc(0, file->file_pointer);
2413 if( handle_ferror(file, __func__, "fputc() error [2]") )
2414 {
2415 goto done;
2416 }
2417 }
2418 }
2419 // Let's check to make sure the slot for this record is currently available:
2420 char record_marker;
2421 ssize_t presult = pread(rfp.fd, &record_marker, 1, rfp.flag_position);
2422 if( presult < 0 )
2423 {
2424 handle_errno(file, __func__, "pread() error");
2425 goto done;
2426 }
2427
2428 if( presult == 1 && record_marker == internal_newline )
2429 {
2430 // The slot has something in it already:
2431 file->io_status = FsDupWrite; // "22"
2432 goto done;
2433 }
2434 // Either the record is available, or else the write is taking place at the
2435 // end of the current file size.
2436
2437 // Position the file pointer at the slot:
2438 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
2439 if( handle_ferror(file, __func__, "fseek() error") )
2440 {
2441 goto done;
2442 }
2443 }
2444 else
2445 {
2446 // We need to do a sequential write:
2447 if( file->mode_char == 'a' )
2448 {
2449 // Position the file pointer at the end:
2450 fseek(file->file_pointer, 0, SEEK_END);
2451 if( handle_ferror(file, __func__, "fseek() error") )
2452 {
2453 goto done;
2454 }
2455 }
2456 }
2457
2458 // Write out the data:
2459 fwrite(location, length, 1, file->file_pointer);
2460 if( handle_ferror(file, __func__, "fwrite() error") )
2461 {
2462 goto done;
2463 }
2464
2465 if( file->record_area_max > length )
2466 {
2467 size_t padding = file->record_area_max - length;
2468 while(padding--)
2469 {
2470 fputc(internal_space, file->file_pointer);
2471 }
2472 }
2473
2474 // Write out the rfm_microfocus "valid record" postamble:
2475 fwrite(achPostamble, 1, 2, file->file_pointer);
2476 if( handle_ferror(file, __func__, "fwrite() error") )
2477 {
2478 goto done;
2479 }
2480
2481 if( is_random )
2482 {
2483 // Per the COBOL specification, put the file position back to where
2484 // it was when we started this exercise:
2485 fseek(file->file_pointer, rfp.current_file_position, SEEK_SET);
2486 if( handle_ferror(file, __func__, "fseek(starting_pos) error") )
2487 {
2488 goto done;
2489 }
2490 }
2491
2492 done:
2493 file->prior_op = file_op_write;
2494 establish_status(file, -1);
2495 }
2496
2497 static void
2498 sequential_file_write(cblc_file_t *file,
2499 const unsigned char *location,
2500 size_t length,
2501 int after,
2502 int lines)
2503 {
2504 // This code handles SEQUENTIAL and LINE SEQUENTIAl
2505 char ch = '\0';
2506 size_t characters_to_write;
2507
2508 int lcount;
2509
2510 if( lines < -1 )
2511 {
2512 // We are using -666 for a form feed
2513 ch = internal_ff; // Form feed
2514 lcount = 1;
2515 }
2516 else if( lines == -1 )
2517 {
2518 // -1 is a flag that no vertical control is requested
2519 lcount = 0;
2520 }
2521 else if( lines == 0 )
2522 {
2523 lcount = 1;
2524 ch = internal_return;
2525 }
2526 else /* if( lines > 0 ) */
2527 {
2528 lcount = lines;
2529 ch = internal_newline;
2530 }
2531
2532 // By default, we write out the number of characters in the record area
2533 characters_to_write = length;
2534
2535 // That gets overridden if there is a record_length
2536 if( file->record_length )
2537 {
2538 int rdigits;
2539 characters_to_write = (int)__gg__binary_value_from_field(
2540 &rdigits,
2541 file->record_length);
2542 }
2543
2544 if( file->org == file_line_sequential_e )
2545 {
2546 // If file-sequential, then trailing spaces are removed:
2547 while( characters_to_write > 0
2548 && location[characters_to_write-1] == internal_space )
2549 {
2550 characters_to_write -= 1;
2551 }
2552 }
2553
2554 if( after && file->org == file_line_sequential_e && ch == internal_newline )
2555 {
2556 // In general, we terminate every line with a newline. Because this
2557 // line is supposed to start with a newline, we decrement the line
2558 // counter by one if we had already sent one.
2559 if( lcount && ( file->recent_char == internal_newline
2560 || file->recent_char == internal_ff) )
2561 {
2562 lcount -= 1;
2563 }
2564 }
2565
2566 if( after )
2567 {
2568 while(lcount--)
2569 {
2570 fputc(ch, file->file_pointer);
2571 if( handle_ferror(file, __func__, "fputc() error [3]") )
2572 {
2573 goto done;
2574 }
2575 file->recent_char = ch;
2576 }
2577 // That might have been a formfeed; switch back to newline:
2578 ch = internal_newline;
2579 }
2580
2581 switch(file->org)
2582 {
2583 case file_line_sequential_e:
2584 if( characters_to_write )
2585 {
2586 fwrite( location,
2587 characters_to_write,
2588 1,
2589 file->file_pointer);
2590 if( handle_ferror(file, __func__, "fwrite() error") )
2591 {
2592 goto done;
2593 }
2594 }
2595 file->recent_char = '\0';
2596 break;
2597
2598 case file_sequential_e:
2599 if( characters_to_write )
2600 {
2601 // File sequential records can start off with a four-byte
2602 // preamble.
2603
2604 if( characters_to_write < file->record_area_min
2605 || characters_to_write > file->record_area_max)
2606 {
2607 file->io_status = FsBoundWrite; // "44"
2608 goto done;
2609 }
2610
2611 if( file->record_area_min != file->record_area_max )
2612 {
2613 // Because of the min/max mismatch, we require a preamble:
2614 // The first two bytes are the big-endian character count
2615 const unsigned char preamble[4] =
2616 {
2617 (unsigned char)(characters_to_write>>8),
2618 (unsigned char)(characters_to_write),
2619 0,
2620 0
2621 };
2622
2623 fwrite( preamble,
2624 4,
2625 1,
2626 file->file_pointer);
2627 if( handle_ferror(file, __func__, "fwrite() error") )
2628 {
2629 goto done;
2630 }
2631 }
2632
2633 fwrite( location,
2634 characters_to_write,
2635 1,
2636 file->file_pointer);
2637 if( handle_ferror(file, __func__, "fwrite() error") )
2638 {
2639 goto done;
2640 }
2641 }
2642 file->recent_char = '\0';
2643 break;
2644
2645 default:
2646 fprintf(stderr,
2647 "%s(): Unhandled cbl_file_org_t %d\n",
2648 __func__,
2649 file->org);
2650 exit(1);
2651 break;
2652 }
2653
2654 if( after && lines>0 && file->org == file_line_sequential_e )
2655 {
2656 // Special case: when AFTER NON-ZERO lines, we stick a newline on the
2657 // end of this record:
2658 fputc(ch, file->file_pointer);
2659 if( handle_ferror(file, __func__, "fputc() error [4]") )
2660 {
2661 goto done;
2662 }
2663 file->recent_char = internal_newline;
2664 }
2665
2666 if( !after )
2667 {
2668 // We did the output BEFORE, so now it's time to send some internal_newlines
2669 while(lcount--)
2670 {
2671 fputc(ch, file->file_pointer);
2672 if( handle_ferror(file, __func__, "fputc() error [5]") )
2673 {
2674 goto done;
2675 }
2676 file->recent_char = ch;
2677 }
2678 }
2679
2680 done:
2681 file->prior_op = file_op_write;
2682 establish_status(file, -1);
2683 }
2684
2685 static void
2686 indexed_file_write( cblc_file_t *file,
2687 const unsigned char *location,
2688 size_t length,
2689 bool is_random)
2690 {
2691 // This routine handles FILE WRITE to INDEXED files
2692
2693 // Each record starts with a four-byte preamble. The first two bytes are
2694 // a big-endian binary value indicating the length of the record (not
2695 // including the preamble). The third byte is zero; the fourth byte is zero
2696 // for a deleted record and one for an active record.
2697
2698 file->errnum = 0;
2699 file->io_status = FsErrno;
2700 long position_to_write;
2701
2702 int key_number = 1; // We are concerned with the primary key:
2703 // Pick up our structure for the primary_key
2704 file_index_t *file_index = &file->supplemental->indexes[key_number];
2705
2706 // Check to make sure the WRITE is consistent with the mode:
2707 if( !is_random )
2708 {
2709 // sequential mode is OUTPUT or EXTEND. We can only add things at the end
2710 if( file->mode_char != 'w' && file->mode_char != 'a' )
2711 {
2712 file->io_status = FsNoWrite; // "48"
2713 goto done;
2714 }
2715
2716 if( file_index->key_to_position.size() == 0 )
2717 {
2718 // We are dealing with an empty file, so we'll be writing at
2719 // starting_position, which is set to the end
2720 }
2721 else
2722 {
2723 // The primary key for a new record in an indexed file in sequential
2724 // access mode has to be greater than the biggest existing one:
2725
2726 std::multimap<std::vector<unsigned char>, long>::const_reverse_iterator
2727 last_element = file_index->key_to_position.crbegin();
2728 std::vector<unsigned char> biggest_key = last_element->first;
2729
2730 std::vector<unsigned char> new_key = file_indexed_make_key( file,
2731 key_number);
2732
2733 // Quick & dirty comparison to make sure our new key is greater than
2734 // the biggest_key:
2735 bool okay = (memcmp(new_key.data(), biggest_key.data(), new_key.size() ) > 0);
2736 if( !okay )
2737 {
2738 // Create out-of-sequence INVALID KEY condition
2739 file->io_status = FsKeySeq; // "21"
2740 goto done;
2741 }
2742 // We are allowed to do the write. Because this is "w" or "a",
2743 // it will be at the end
2744 }
2745 }
2746 else
2747 {
2748 // Because access is random or dynamic the mode has to be OUTPUT or I-O
2749 if( file->mode_char != 'w' && file->mode_char != '+' )
2750 {
2751 file->io_status = FsNoWrite; // "48"
2752 goto done;
2753 }
2754
2755 // We are allowed to do the write, but only if there will be no key
2756 // violations as a result:
2757
2758 for(size_t keynum=1;
2759 keynum<file->supplemental->indexes.size();
2760 keynum++)
2761 {
2762 if( file->supplemental->uniques[keynum] )
2763 {
2764 long record_position = file_indexed_first_position(file, keynum);
2765 if( record_position != -1 )
2766 {
2767 // No can do, because we already have a unique key with that value
2768 file->io_status = FsDupWrite; // "22"
2769 goto done;
2770 }
2771 }
2772 }
2773
2774 // This record is not in the data file; figure out where to put it
2775 if( file->mode_char == '+' )
2776 {
2777 // This is a '+' for I-O, so we can write into a hole.
2778
2779 // See if we have a hole that is the right size:
2780 bool found_hole = false;
2781 for( size_t i=0; i<file->supplemental->holes.size(); i++ )
2782 {
2783 if( file->supplemental->holes[i].size == length )
2784 {
2785 // We found a hole, and we're going to use it
2786
2787 // Pick up the position
2788 position_to_write = file->supplemental->holes[i].location;
2789
2790 // Get rid of the hole we just filled:
2791 file->supplemental->holes[i] = file->supplemental->holes.back();
2792 file->supplemental->holes.pop_back();
2793
2794 // Position the file, ready to write:
2795 fseek(file->file_pointer, position_to_write, SEEK_SET);
2796 if( handle_ferror(file, __func__, "fseek() error") )
2797 {
2798 goto done;
2799 }
2800 found_hole = true;
2801 break;
2802 }
2803 }
2804 if( !found_hole )
2805 {
2806 // There is no hole, so make sure we are writing at the end
2807 fseek(file->file_pointer, 0, SEEK_END);
2808 if( handle_ferror(file, __func__, "fseek() error") )
2809 {
2810 goto done;
2811 }
2812 }
2813 }
2814 }
2815
2816 // The file is positioned for where the write is to take place. And we know
2817 // that there will be no key violation when we update the indices.
2818
2819 position_to_write = ftell(file->file_pointer);
2820 if( handle_ferror(file, __func__, "ftell() error") )
2821 {
2822 goto done;
2823 }
2824
2825 // We are currently located where the new data must be written.
2826 unsigned char ach[4];
2827 ach[0] = (unsigned char)(length>>8);
2828 ach[1] = (unsigned char)length;
2829 ach[2] = 0;
2830 ach[3] = 1;
2831
2832 // Write out the preamble:
2833 fwrite(ach, 4, 1, file->file_pointer);
2834 if( handle_ferror(file, __func__, "fwrite() error") )
2835 {
2836 goto done;
2837 }
2838
2839 // Write out the data:
2840 fwrite(location, length, 1, file->file_pointer);
2841 if( handle_ferror(file, __func__, "fwrite() error") )
2842 {
2843 goto done;
2844 }
2845
2846 file_indexed_update_indices(file, position_to_write);
2847
2848 done:
2849 file->prior_op = file_op_write;
2850 establish_status(file, -1);
2851 }
2852
2853 static void
2854 __io__file_write( cblc_file_t *file,
2855 const unsigned char *location,
2856 size_t length,
2857 int after,
2858 int lines,
2859 int is_random )
2860 {
2861 // After an epic discussion with Marty, a determination has been made to
2862 // ignore the IBM and ISO specifications, and treat an unadorned WRITE as
2863 // if it were the same as WRITE xxx BEFORE 1 LINE
2864
2865 file->errnum = 0;
2866 file->io_status = FsErrno;
2867
2868 if( !file->file_pointer )
2869 {
2870 // Attempting to write a file that isn't open
2871 file->io_status = FsNoWrite; // "48"
2872 goto done;
2873 }
2874
2875 switch( file->access )
2876 {
2877 case file_access_seq_e:
2878 if( file->mode_char != 'w' && file->mode_char != 'a' )
2879 {
2880 // File is open, but not in OUTPUT or EXTEND mode
2881 file->io_status = FsNoWrite; // "48"
2882 goto done;
2883 }
2884 break;
2885
2886 case file_access_rnd_e:
2887 case file_access_dyn_e:
2888 if( file->mode_char != 'w' && file->mode_char != '+' )
2889 {
2890 // File is open, but not in I-O or OUTPUT or
2891 file->io_status = FsNoWrite; // "48"
2892 goto done;
2893 }
2894 break;
2895
2896 default:
2897 warnx("%s(): Thanks for playing. Next contestant, please", __func__);
2898 abort();
2899 break;
2900 }
2901
2902 if( file->record_length )
2903 {
2904 int rdigits;
2905 length = (size_t)__gg__binary_value_from_field( &rdigits,
2906 file->record_length);
2907 }
2908
2909 switch(file->org)
2910 {
2911 case file_line_sequential_e:
2912 case file_sequential_e:
2913 sequential_file_write(file, location, length, after, lines);
2914 break;
2915
2916 case file_relative_e:
2917 {
2918 relative_file_write(file, location, length, is_random);
2919 break;
2920 }
2921
2922 case file_indexed_e:
2923 {
2924 indexed_file_write(file, location, length, is_random);
2925 break;
2926 }
2927
2928 default:
2929 fprintf(stderr, "%s(): Unhandled cbl_file_org_t %d\n",
2930 __func__,
2931 file->org);
2932 exit(1);
2933 break;
2934 }
2935 done:
2936 file->prior_op = file_op_write;
2937 establish_status(file, -1);
2938 if( file->io_status < FhNotOkay )
2939 {
2940 file->flags |= file_flag_existed_e;
2941 }
2942 }
2943
2944 static void
2945 line_sequential_file_read( cblc_file_t *file)
2946 {
2947 file->errnum = 0;
2948 file->io_status = FsErrno;
2949 size_t characters_read = 0;
2950 size_t remaining;
2951 bool hit_eof;
2952
2953 // According to IBM:
2954
2955 // Characters are read one at a time until:
2956 // - A delimiter is reached. It is discarded, and the
2957 // record area is filled with spaces.
2958 // - The entire record area is filled. If the next unread
2959 // character is the delimiter, it is discarded. Otherwise,
2960 // it becomes the first character read by the next READ
2961 // - EOF is encountered; the remainder of the record area
2962 // is filled with spaces.
2963
2964 // This contradicts the ISO/IEC 2014 standard, which says
2965 // in section 14.9.29.3, paragraph 14) on page 554 that excess
2966 // characters are discarded, and too-short records have
2967 // characters to the right as undefined. I'm going with IBM,
2968 // it makes more sense to me.
2969
2970 // We first stage the data into the record area.
2971 int ch;
2972
2973 long fpos = ftell(file->file_pointer);
2974 if( handle_ferror(file, __func__, "ftell() error") )
2975 {
2976 fpos = -1;
2977 goto done;
2978 }
2979
2980 hit_eof = false;
2981 while( characters_read < file->record_area_max )
2982 {
2983 ch = fgetc(file->file_pointer);
2984 file->errnum = ferror(file->file_pointer);
2985 if( ch == file->delimiter )
2986 {
2987 break;
2988 }
2989 if( ch == EOF )
2990 {
2991 hit_eof = true;
2992 clearerr(file->file_pointer);
2993 break;
2994 }
2995 if( handle_ferror(file, __func__, "fgetc() error") )
2996 {
2997 fpos = -1;
2998 goto done;
2999 }
3000 file->default_record->data[characters_read] = (char)ch;
3001 characters_read += 1;
3002 }
3003 remaining = characters_read;
3004 while(remaining < file->record_area_max )
3005 {
3006 // Space fill shorty records
3007 file->default_record->data[remaining++] = internal_space;
3008 }
3009
3010 if( hit_eof && !characters_read)
3011 {
3012 // We got an end-of-file without characters
3013 file->io_status = FsEofSeq; // "10"
3014 file->prior_read_location = -1;
3015 }
3016 else if( hit_eof )
3017 {
3018 // We got an end-of-file whilst reading characters
3019 // Override the FsEofSeq. We'll get an actual EOF if the programmer
3020 // does another READ:
3021 file->io_status = FsErrno;
3022 }
3023 else if (characters_read < file->record_area_max)
3024 {
3025 // Just discard an early record delimiter
3026 file->io_status = FsRecordLength; // "04"
3027 }
3028 else // We filled the whole record area. Look ahead one character
3029 {
3030 #ifdef POSSIBLY_IBM
3031 // In this code, unread characters before the internal_newline
3032 // are read next time. See page 133 of the IBM Language Reference
3033 // Manual: "If the first unread character is the record delimiter, it
3034 // is discarded. Otherwise, the first unread character becomes the first
3035 // character read by the next READ statement."
3036 ch = fgetc(file->file_pointer);
3037 file->errnum = ferror();
3038 // If that next character isn't a delimiter, put it back:
3039 if( ch != file->delimiter && ch != EOF)
3040 {
3041 ungetc(ch, file->file_pointer);
3042 }
3043 else if( handle_ferror(file->file_pointer, __func__, "fgetc() error") )
3044 {
3045 fpos = -1;
3046 goto done;
3047 }
3048 #else
3049 // In this code, extra characters before the internal_newline
3050 // are read next time are discarded. GnuCOBOL works this way, and
3051 // the Michael Coughlin "Beginning COBOL" examples require this mode.
3052 // The ISO/IEC 2014 standard is silent on the question of LINE
3053 // SEQUENTIAL; it describes only SEQUENTIAL.
3054 for(;;)
3055 {
3056 ch = fgetc(file->file_pointer);
3057 file->errnum = ferror(file->file_pointer);
3058 // We can't use handle_ferror() directly, because an EOF is
3059 // a legitimate way to end the last line.
3060 if( ch == file->delimiter || ch == EOF)
3061 {
3062 clearerr(file->file_pointer);
3063 break;
3064 }
3065 if( ferror(file->file_pointer)
3066 && handle_ferror(file, __func__, "fgetc() error") )
3067 {
3068 fpos = -1;
3069 goto done;
3070 }
3071 file->io_status = FsRecordLength; // "04"
3072 }
3073 #endif
3074 }
3075
3076 if( file->record_length )
3077 {
3078 __gg__int128_to_field(file->record_length,
3079 characters_read,
3080 0,
3081 truncation_e,
3082 NULL);
3083 }
3084 done:
3085 file->prior_op = file_op_read;
3086 establish_status(file, fpos);
3087 }
3088
3089 static size_t
3090 sequential_file_read( cblc_file_t *file)
3091 {
3092 unsigned char preamble[4];
3093 size_t characters_read;
3094 size_t bytes_in_record;
3095 size_t bytes_to_read;
3096 long fpos;
3097
3098 file->errnum = 0;
3099
3100 if( file->io_status >= FsEofSeq ) // "10"
3101 {
3102 // There is a special error code for trying to read a file after an error
3103 // or after an EOF has been encountered
3104 file->io_status = FsReadError; // "46"
3105 fpos = -1;
3106 goto done;
3107 }
3108
3109 file->io_status = FsErrno;
3110
3111 fpos = ftell(file->file_pointer);
3112 if( handle_ferror(file, __func__, "ftell() error") )
3113 {
3114 fpos = -1;
3115 goto done;
3116 }
3117
3118 if( file->record_area_min != file->record_area_max )
3119 {
3120 // Because of the different sizes, we are expecting a preamble:
3121
3122 // An error at this point is either an error, or a true end-of-file.
3123 characters_read = fread(preamble, 1, 4, file->file_pointer);
3124 if( handle_ferror(file, __func__, "fread() error") )
3125 {
3126 // This also comes back true for an ordinary end-of-file
3127 fpos = -1;
3128 goto done;
3129 }
3130
3131 if( characters_read != 4 )
3132 {
3133 // If the preamble is incomplete, treat that as an EOF
3134 file->io_status = FsEofSeq; // "10"
3135 file->prior_read_location = -1;
3136 fpos = -1;
3137 goto done;
3138 }
3139
3140 // Extract the count of bytes in the record from the preamble
3141 bytes_in_record = ((size_t)preamble[0]<<8) + preamble[1];
3142 }
3143 else
3144 {
3145 // Because the min and max are the same, we figure on reading that many
3146 // characters:
3147 bytes_in_record = file->record_area_max;
3148 }
3149
3150
3151 // We are now going to read that many bytes from the file into the record area
3152 // Let's make sure that bogus input doesn't cause us to fall off the end of
3153 // the world:
3154 bytes_to_read = std::min( bytes_in_record,
3155 file->record_area_max);
3156
3157 characters_read = fread(file->default_record->data,
3158 1,
3159 bytes_to_read,
3160 file->file_pointer);
3161 if( handle_ferror(file, __func__, "fread() error") )
3162 {
3163 fpos = -1;
3164 goto done;
3165 }
3166 if( characters_read < bytes_in_record )
3167 {
3168 memset(file->default_record->data, internal_space, bytes_to_read);
3169 file->io_status = FsEofSeq; // "10"
3170 fpos = -1;
3171 goto done;
3172 }
3173
3174 // Let the caller know if we got too few or too many characters
3175 if( bytes_in_record < file->record_area_min
3176 || bytes_in_record > file->record_area_max )
3177 {
3178 file->io_status = FsRecordLength; // "04"
3179 }
3180
3181 if( bytes_in_record > file->record_area_max )
3182 {
3183 // Let's fix the misalignment
3184 fseek(file->file_pointer,
3185 bytes_in_record - file->record_area_max,
3186 SEEK_CUR);
3187 }
3188
3189 if( file->record_length )
3190 {
3191 __gg__int128_to_field(file->record_length,
3192 characters_read,
3193 0,
3194 truncation_e,
3195 NULL);
3196 }
3197 done:
3198 file->prior_op = file_op_read;
3199 establish_status(file, fpos);
3200 return characters_read;
3201 }
3202
3203 static void
3204 relative_file_read_varying( cblc_file_t *file,
3205 int where)
3206 {
3207 // where -2 PREVIOUS
3208 // where -1 NEXT
3209 // where 0 who the hell knows
3210 // where 1 or more: random read
3211
3212 bool is_random = where > 0;
3213
3214 file->errnum = 0;
3215 file->io_status = FsErrno;
3216
3217 relative_file_parameters rfp;
3218
3219 size_t characters_read = 0;
3220 long fpos = -1;
3221 size_t payload_length;
3222
3223 if( where >= 1 )
3224 {
3225 if( relative_file_parameters_get( rfp,
3226 rfm_microfocus_e,
3227 file,
3228 RESPECT_LIMITS,
3229 DONT_INIT_KEY,
3230 is_random) )
3231 {
3232 goto done;
3233 }
3234
3235 if( rfp.record_position >= rfp.file_size )
3236 {
3237 // We're falling off the end of the file, which means our key doesn't
3238 // exist
3239 file->io_status = FsNotFound; // "23"
3240 goto done;
3241 }
3242
3243 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
3244 if( handle_ferror(file, __func__, "fseek() error") )
3245 {
3246 goto done;
3247 }
3248 }
3249 else if( where == -1)
3250 {
3251 // This is a sequential NEXT read of a RELATIVE file
3252 if( relative_file_parameters_get( rfp,
3253 rfm_microfocus_e,
3254 file,
3255 IGNORE_LIMITS,
3256 INIT_KEY,
3257 is_random) )
3258 {
3259 goto done;
3260 }
3261 }
3262 else
3263 {
3264 warnx("Whatever are we doing here?");
3265 abort();
3266 }
3267
3268 // We are now poised to read a record,
3269 for(;;)
3270 {
3271 if( !rfp.inside_existing_file )
3272 {
3273 file->io_status = FsEofSeq; // "10"
3274 file->prior_read_location = -1;
3275 goto done;
3276 }
3277
3278 fread(&payload_length, 8, 1, file->file_pointer);
3279 if( handle_ferror(file, __func__, "fread() error") )
3280 {
3281 fpos = -1;
3282 goto done;
3283 }
3284
3285 if( payload_length )
3286 {
3287 // We have a good record to read:
3288
3289 // Read the characters into the record area:
3290 fread(file->default_record->data,
3291 1,
3292 file->record_area_max,
3293 file->file_pointer);
3294 if( handle_ferror(file, __func__, "fread() error") )
3295 {
3296 goto done;
3297 }
3298 // Having read that that data, set up for a subsequent delete/rewrite.
3299 // Set fpos to the current_file_position, and then update the current
3300 // file position.
3301 fpos = rfp.current_file_position;
3302
3303 // We need to change the file position pointer to point to the next
3304 // record.
3305
3306 rfp.current_file_position += rfp.record_size;
3307 fseek(file->file_pointer,
3308 rfp.current_file_position,
3309 SEEK_SET);
3310 if( handle_ferror(file, __func__, "fseek() error") )
3311 {
3312 fpos = -1;
3313 goto done;
3314 }
3315
3316 break;
3317 }
3318 else
3319 {
3320 // There isn't a record in this slot
3321 if( where == -1 )
3322 {
3323 // But we are in next_record mode. It is our duty and obligation
3324 // to skip merrily through the file looking for the next valid
3325 // record for the lazy bums who called us.
3326 rfp.record_position += rfp.record_size;
3327 rfp.flag_position += rfp.record_size;
3328 rfp.inside_existing_file
3329 = rfp.record_position + rfp.record_size <= rfp.file_size;
3330 rfp.key_value = 1 + rfp.record_position
3331 / (rfp.preamble_size
3332 + rfp.payload_size
3333 + rfp.postamble_size);
3334
3335 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
3336 if( handle_ferror(file, __func__, "fseek() error") )
3337 {
3338 goto done;
3339 }
3340 rfp.current_file_position = rfp.record_position;
3341 continue;
3342 }
3343 break;
3344 }
3345 }
3346
3347 characters_read = payload_length;
3348 if( characters_read == 0 )
3349 {
3350 file->io_status = FsNotFound; // "23"
3351 goto done;
3352 }
3353 else
3354 {
3355 if( where < 0 )
3356 {
3357 // We did a FORMAT 1 read, so we need to update the key, if there is one
3358 if( file->keys[0] )
3359 {
3360 long max_key = max_value(file->keys[0]);
3361 if( rfp.key_value >= max_key )
3362 {
3363 // This is an oddball COBOL error: A sequential read would result in
3364 // reading a record whose relative record number is too big for
3365 // file->key to hold
3366 file->io_status = FsEofRel; // "14"
3367 goto done;
3368 }
3369 __gg__int128_to_field(file->keys[0],
3370 rfp.key_value,
3371 0,
3372 truncation_e,
3373 NULL);
3374 }
3375 }
3376 }
3377 done:
3378 if( file->record_length )
3379 {
3380 __gg__int128_to_field(file->record_length,
3381 payload_length,
3382 0,
3383 truncation_e,
3384 NULL);
3385 }
3386 file->prior_op = file_op_read;
3387 establish_status(file, fpos);
3388 }
3389
3390 static void
3391 relative_file_read( cblc_file_t *file,
3392 int where)
3393 {
3394 // where -2 means PREVIOUS
3395 // where -1 means NEXT
3396 // where 0 means random read, based on the key
3397
3398 if( file->record_area_min != file->record_area_max )
3399 {
3400 return relative_file_read_varying(file, where);
3401 }
3402
3403 bool is_random = where > 0;
3404
3405 file->errnum = 0;
3406 file->io_status = FsErrno;
3407
3408 relative_file_parameters rfp;
3409
3410 size_t characters_read = 0;
3411 long fpos = -1;
3412
3413 if( where >= 1 )
3414 {
3415 if( relative_file_parameters_get( rfp,
3416 rfm_microfocus_e,
3417 file,
3418 RESPECT_LIMITS,
3419 DONT_INIT_KEY,
3420 is_random) )
3421 {
3422 goto done;
3423 }
3424
3425 if( rfp.record_position >= rfp.file_size )
3426 {
3427 // We're falling off the end of the file, which means our key doesn't
3428 // exist
3429 file->io_status = FsNotFound; // "23"
3430 goto done;
3431 }
3432
3433 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
3434 if( handle_ferror(file, __func__, "fseek() error") )
3435 {
3436 goto done;
3437 }
3438 }
3439 else if( where == -1)
3440 {
3441 // This is a sequential NEXT read of a RELATIVE file
3442 if( relative_file_parameters_get( rfp,
3443 rfm_microfocus_e,
3444 file,
3445 IGNORE_LIMITS,
3446 INIT_KEY,
3447 is_random) )
3448 {
3449 goto done;
3450 }
3451 }
3452 else
3453 {
3454 warnx("Whatever are we doing here?");
3455 abort();
3456 }
3457
3458 // The following code is predicated on rfm_microfocus_e.
3459
3460 // We are now poised to read a record, provided the flag byte is
3461 // indicates this is a good record
3462 for(;;)
3463 {
3464 if( !rfp.inside_existing_file )
3465 {
3466 file->io_status = FsEofSeq; // "10"
3467 file->prior_read_location = -1;
3468 goto done;
3469 }
3470 char record_marker;
3471 if( pread(rfp.fd, &record_marker, 1, rfp.flag_position) <= 0)
3472 {
3473 goto done;
3474 }
3475 if(record_marker == internal_newline)
3476 {
3477 // We have a good record to read:
3478
3479 // We need to change the file_position_pointer to reflect any
3480 // preamble:
3481 if( rfp.preamble_size )
3482 {
3483 fseek(file->file_pointer, rfp.preamble_size, SEEK_CUR);
3484 if( handle_ferror(file, __func__, "fseek() error") )
3485 {
3486 goto done;
3487 }
3488 }
3489 // Read the characters into the record area:
3490 characters_read = fread(file->default_record->data,
3491 1,
3492 file->record_area_max,
3493 file->file_pointer);
3494 if( handle_ferror(file, __func__, "fread() error") )
3495 {
3496 goto done;
3497 }
3498 // Having read that that data, set up for a subsequent delete/rewrite.
3499 // Set fpos to the current_file_position, and then update the current
3500 // file position.
3501 fpos = rfp.current_file_position;
3502
3503 // We need to change the file position pointer to point to the next
3504 // record.
3505
3506 rfp.current_file_position += rfp.record_size;
3507 fseek(file->file_pointer,
3508 rfp.current_file_position,
3509 SEEK_SET);
3510 if( handle_ferror(file, __func__, "fseek() error") )
3511 {
3512 fpos = -1;
3513 goto done;
3514 }
3515
3516 break;
3517 }
3518 else
3519 {
3520 // There isn't a record in this slot
3521 if( where == -1 )
3522 {
3523 // But we are in next_record mode. It is our duty and obligation
3524 // to skip merrily through the file looking for the next valid
3525 // record for the lazy bums who called us.
3526 rfp.record_position += rfp.record_size;
3527 rfp.flag_position += rfp.record_size;
3528 rfp.inside_existing_file
3529 = rfp.record_position + rfp.record_size <= rfp.file_size;
3530 rfp.key_value = 1 + rfp.record_position
3531 / (rfp.preamble_size
3532 + rfp.payload_size
3533 + rfp.postamble_size);
3534
3535 fseek(file->file_pointer, rfp.record_position, SEEK_SET);
3536 if( handle_ferror(file, __func__, "fseek() error") )
3537 {
3538 goto done;
3539 }
3540 rfp.current_file_position = rfp.record_position;
3541 continue;
3542 }
3543 break;
3544 }
3545 }
3546
3547 if( characters_read == 0 )
3548 {
3549 file->io_status = FsNotFound; // "23"
3550 goto done;
3551 }
3552 else
3553 {
3554 if( where < 0 )
3555 {
3556 // We did a FORMAT 1 read, so we need to update the key, if there is one
3557 if( file->keys[0] )
3558 {
3559 long max_key = max_value(file->keys[0]);
3560 if( rfp.key_value >= max_key )
3561 {
3562 // This is an oddball COBOL error: A sequential read would result in
3563 // reading a record whose relative record number is too big for
3564 // file->key to hold
3565 file->io_status = FsEofRel; // "14"
3566 goto done;
3567 }
3568 __gg__int128_to_field(file->keys[0],
3569 rfp.key_value,
3570 0,
3571 truncation_e,
3572 NULL);
3573 }
3574 }
3575 }
3576 done:
3577 if( file->record_length )
3578 {
3579 __gg__int128_to_field(file->record_length,
3580 characters_read,
3581 0,
3582 truncation_e,
3583 NULL);
3584 }
3585 file->prior_op = file_op_read;
3586 establish_status(file, fpos);
3587 }
3588
3589 static void
3590 indexed_file_read( cblc_file_t *file,
3591 int key_number)
3592 {
3593 long record_length;
3594 int flag;
3595 int read_res;
3596
3597 if( key_number == 0 )
3598 {
3599 // This is an implicit next
3600 key_number = -1;
3601 }
3602
3603 size_t characters_read = 0;
3604 file_index_t *file_index;
3605 long fpos = -1;
3606
3607 if( key_number >= 1 )
3608 {
3609 // It is meat and potatoes time. We need to pick up the first record
3610 // with the specified key:
3611 file->errnum = 0;
3612 file->io_status = FsErrno;
3613
3614 file->recent_key = key_number;
3615 file_index = &file->supplemental->indexes[key_number];
3616 fpos = file_indexed_first_position(file, key_number);
3617 if( fpos == -1 )
3618 {
3619 file->io_status = FsNotFound; // "23"
3620 goto done;
3621 }
3622 fpos = file_indexed_first_position(file, key_number);
3623 file_index->current_iterator++;
3624 }
3625 else if( key_number == -1 )
3626 {
3627 // We are ready to do a sequential read of an INDEXED file
3628
3629 // There is a special code for trying to read after a preceding unsuccessful
3630 // statement:
3631
3632 if( file->io_status >= FsEofSeq ) // "10"
3633 {
3634 file->io_status = FsReadError; // "46"
3635 goto done;
3636 }
3637
3638 file->errnum = 0;
3639 file->io_status = FsErrno;
3640
3641 file_index = &file->supplemental->indexes[file->recent_key];
3642
3643 // When you arrive here, the current_indicator points to the iterator
3644 // *after* the prior successful read
3645 if( file_index->current_iterator == file_index->key_to_position.end() )
3646 {
3647 // We have hit the end of keys
3648 file->io_status = FsEofSeq; // "10"
3649 file->prior_read_location = -1;
3650 goto done;
3651 }
3652
3653 // cppcheck-suppress derefInvalidIteratorRedundantCheck
3654 fpos = file_index->current_iterator->second;
3655
3656 if( file_index->current_iterator == file_index->key_to_position.end() )
3657 {
3658 __gg__abort("indexed_file_read(): fell off of file_index->key_to_position");
3659 }
3660 file_index->current_iterator++;
3661 }
3662 else if( key_number == -2 )
3663 {
3664 // We are ready to do a sequential read PREVIOUS of an INDEXED file
3665
3666 // There is a special code for trying to read after a preceding unsuccessful
3667 // statement:
3668 if( file->io_status >= FsEofSeq ) // "10"
3669 {
3670 file->io_status = FsReadError; // "46"
3671 goto done;
3672 }
3673
3674 file->errnum = 0;
3675 file->io_status = FsErrno;
3676
3677 file_index = &file->supplemental->indexes[file->recent_key];
3678
3679 /* We need to do a little thinking. After an OPEN or START,
3680 * file_index->current_iterator points to the next record to read for
3681 * either a READ NEXT or READ PREVIOUS.
3682 *
3683 * But after a READ, a subsequent READ PREVIOUS needs to back the iterator
3684 * down by 2 to get the correct record.
3685 */
3686
3687 if( file->prior_op == file_op_read )
3688 {
3689 // We just read record 10, so the iterator points to 11. We need to back
3690 // it down to 9, if we can. (There might not be enough records)
3691
3692 // We know we can back it down at least one record
3693 file_index->current_iterator--; // Make it point back to 10
3694 if( file_index->current_iterator == file_index->key_to_position.begin() )
3695 {
3696 // but we can't back it down another
3697 file->io_status = FsEofSeq; // "10"
3698 file->prior_read_location = -1;
3699 goto done;
3700 }
3701 file_index->current_iterator--; // Make it point back to 9
3702 }
3703 else if( file->prior_op == file_op_delete )
3704 {
3705 if( file->prior_read_location == -1 )
3706 {
3707 // The prior operation deleted the record we are set up to read.
3708 // Let's finesse the positioning.
3709 if( file_index->current_iterator == file_index->key_to_position.end() )
3710 {
3711 // We have hit the end of the keys.
3712 file->io_status = FsEofSeq; // "10"
3713 file->prior_read_location = -1;
3714 goto done;
3715 }
3716 file_index->current_iterator--;
3717 }
3718 }
3719 else
3720 {
3721 // This must be after an OPEN or START. Check to make sure that the
3722 // file isn't actually empty
3723
3724 if( file_index->current_iterator == file_index->key_to_position.end() )
3725 {
3726 // We have hit the end of the keys.
3727 file->io_status = FsEofSeq; // "10"
3728 file->prior_read_location = -1;
3729 goto done;
3730 }
3731 }
3732
3733 // We are ready to proceed
3734
3735 // cppcheck-suppress derefInvalidIteratorRedundantCheck
3736 fpos = file_index->current_iterator->second;
3737 if( file_index->current_iterator == file_index->key_to_position.end() )
3738 {
3739 __gg__abort("indexed_file_read(): fell off of file_index->key_to_position");
3740 }
3741 file_index->current_iterator++;
3742 }
3743
3744 // fpos is where the data are:
3745 fseek(file->file_pointer, fpos, SEEK_SET);
3746 if( handle_ferror(file, __func__, "fseek() error") )
3747 {
3748 fpos = -1;
3749 goto done;
3750 }
3751
3752 read_res = read_an_indexed_record(file,
3753 file->record_area_max,
3754 record_length,
3755 flag);
3756 if( read_res )
3757 {
3758 // We hit an end of file or an error
3759 fpos = -1;
3760 goto done;
3761 }
3762
3763 if(flag != 1)
3764 {
3765 warnx("The file isn't right; key number %d found a deleted record",
3766 key_number);
3767 abort();
3768 }
3769
3770 characters_read = record_length;
3771
3772 done:
3773 if( file->record_length )
3774 {
3775 __gg__int128_to_field(file->record_length,
3776 characters_read,
3777 0,
3778 truncation_e,
3779 NULL);
3780 }
3781 file->prior_op = file_op_read;
3782 establish_status(file, fpos);
3783 }
3784
3785 static void
3786 __io__file_read(cblc_file_t *file,
3787 int where)
3788 {
3789 // where = -2 means PREVIOUS
3790 // where = -1 means NEXT
3791 // where = 1 or more means key N, where N is one-based
3792
3793 file->errnum = 0;
3794
3795 if( !(file->flags & file_flag_existed_e)
3796 && (file->flags & file_flag_optional_e))
3797 {
3798 // Trying to read a file that didn't exist during file_open.
3799 if( file->org == file_sequential_e || file->org == file_line_sequential_e )
3800 {
3801 if( file->io_status < FhNotOkay )
3802 {
3803 // This is a format 1 read
3804 file->io_status = FsEofSeq; // "10"
3805 }
3806 else
3807 {
3808 file->io_status = FsReadError; // "46"
3809 }
3810 file->prior_op = file_op_read;
3811 establish_status(file, -1);
3812 return;
3813 }
3814 else
3815 {
3816 // The indexed or relative file didn't exist, so set an INVALID KEY
3817 // condition:
3818 if( where <= 0 )
3819 {
3820 if( file->io_status < FhNotOkay )
3821 {
3822 // This is a format 1 read
3823 file->io_status = FsEofSeq; // "10"
3824 }
3825 else
3826 {
3827 file->io_status = FsReadError; // "46"
3828 }
3829 file->prior_op = file_op_read;
3830 establish_status(file, -1);
3831 }
3832 else
3833 {
3834 // This is a format 2 read
3835 file->io_status = FsNotFound; // "23"
3836 file->prior_op = file_op_read;
3837 establish_status(file, -1);
3838 }
3839 return;
3840 }
3841 }
3842
3843 if( !file->file_pointer )
3844 {
3845 // Attempting to read a file that isn't open
3846 file->io_status = FsReadNotOpen; // "47"
3847 file->prior_op = file_op_read;
3848 establish_status(file, -1);
3849 return;
3850 }
3851
3852 if( file->mode_char != 'r' && file->mode_char != '+' )
3853 {
3854 // The file is open, but not in INPUT or I-O mode:
3855 file->io_status = FsReadNotOpen; // "47"
3856 file->prior_op = file_op_read;
3857 establish_status(file, -1);
3858 return;
3859 }
3860
3861 switch(file->org)
3862 {
3863 case file_line_sequential_e:
3864 {
3865 line_sequential_file_read(file);
3866 break;
3867 }
3868
3869 case file_sequential_e:
3870 {
3871 sequential_file_read(file);
3872 break;
3873 }
3874
3875 case file_relative_e:
3876 {
3877 relative_file_read(file, where);
3878 break;
3879 }
3880
3881 case file_indexed_e:
3882 {
3883 indexed_file_read(file, where);
3884 break;
3885 }
3886
3887 default:
3888 fprintf(stderr,
3889 "%s(): Unhandled cbl_file_org_t %d\n",
3890 __func__,
3891 file->org);
3892 exit(1);
3893 break;
3894 }
3895 if( file->io_status < FhNotOkay )
3896 {
3897 file->flags |= file_flag_existed_e;
3898 }
3899 }
3900
3901 static void
3902 file_indexed_open(cblc_file_t *file)
3903 {
3904 // The file was supposed to be open when you got here.
3905 if( !file->file_pointer )
3906 {
3907 __gg__abort("file_indexed_open(): file_pointer is NULL");
3908 }
3909
3910 file->supplemental = new supplemental_t;
3911
3912 // We need one multimap for each key. Whenever we are told about a key, it'll
3913 // be by key_number. key_number 1 is by convention the primary key. There
3914 // will be no key_number zero, so we are going to start our vector of indexes
3915 // with an empty placeholder:
3916
3917 unsigned char *stash = NULL;
3918
3919 file_index_t file_index;
3920 file->supplemental->indexes.push_back(file_index);
3921 file->supplemental->uniques.push_back(0);
3922
3923 // Add one entry to the indexes for each key number:
3924 int current_key_number = 0;
3925 size_t index = 0;
3926 while(file->key_numbers[index] != -1)
3927 {
3928 if( file->key_numbers[index] != current_key_number )
3929 {
3930 file->supplemental->indexes.push_back(file_index);
3931 current_key_number = file->key_numbers[index];
3932 file->supplemental->uniques.push_back(file->uniques[index]);
3933 }
3934 index += 1;
3935 }
3936
3937 // To build indexes, we need to be at the beginning:
3938 fseek(file->file_pointer, 0, SEEK_SET);
3939 if( handle_ferror(file, __func__, "fseek() after fopen() failed") )
3940 {
3941 goto done;
3942 }
3943
3944 switch( file->mode_char )
3945 {
3946 case 'w':
3947 // OUTPUT mode causes an empty file to be created, so the indices
3948 // are empty as well
3949 break;
3950
3951 case 'r':
3952 case 'a':
3953 case '+':
3954 if( file->flags & file_flag_existed_e )
3955 {
3956 // We need to open the file for reading, and build the
3957 // maps for each index:
3958 static size_t fname_size = MINIMUM_ALLOCATION_SIZE;
3959 static char *fname = static_cast<char *>(malloc(fname_size));
3960 massert(fname);
3961
3962 internal_to_console(&fname,
3963 &fname_size,
3964 file->filename, strlen(file->filename));
3965
3966 // We are going to scan through the entire file, building index
3967 // entries for each record.
3968
3969 // It should already be at the beginning:
3970 if( ftell(file->file_pointer) != 0 )
3971 {
3972 __gg__abort("file_indexed_open():"
3973 " file_pointer should be at the beginning");
3974 }
3975
3976 // Stash the existing record area:
3977 stash = static_cast<unsigned char *>(malloc(file->record_area_max));
3978 massert(stash);
3979 memcpy( stash,
3980 file->default_record->data,
3981 file->record_area_max);
3982
3983 for(;;)
3984 {
3985 // Remember where we are right now:
3986 long record_length;
3987 int flag;
3988 long record_position = ftell(file->file_pointer);
3989 if( handle_ferror(file, __func__, "ftell() error") )
3990 {
3991 goto done;
3992 }
3993
3994 int read_result = read_an_indexed_record( file,
3995 file->record_area_max,
3996 record_length,
3997 flag);
3998 if( read_result == 1 )
3999 {
4000 // Don't panic; it's just an end-of-file
4001 break;
4002 }
4003 else if( read_result > 1 )
4004 {
4005 // It was an error of some kind
4006 goto done;
4007 }
4008
4009 if( flag == 1 )
4010 {
4011 // We have a good record in our record area:
4012
4013 if( !file_indexed_update_indices(file, record_position) )
4014 {
4015 // There must have been a duplicate UNIQUE index, or some other
4016 // problem.
4017 goto done;
4018 }
4019 }
4020 else
4021 {
4022 // This is a hole in the file; make it available for a WRITE or
4023 // EXTEND
4024 file_hole_t hole = {record_position, (size_t)record_length};
4025 file->supplemental->holes.push_back(hole);
4026 }
4027 }
4028
4029 file->io_status = FsErrno;
4030 fseek(file->file_pointer, 0, SEEK_SET);
4031 if( handle_ferror(file, __func__, "fseek() after fopen() failed") )
4032 {
4033 goto done;
4034 }
4035 }
4036 break;
4037
4038 default:
4039 warnx( "%s(): This is weird. mode_char is '%c' (%d)?\n",
4040 __func__,
4041 file->mode_char,
4042 file->mode_char);
4043 __gg__abort("file_indexed_open(): Unknown mode_char");
4044 break;
4045 }
4046 done:
4047 // We need to initialize the iterators for every index:
4048 for( size_t i=1; i<file->supplemental->indexes.size(); i++ )
4049 {
4050 file->supplemental->indexes[i].current_iterator =
4051 file->supplemental->indexes[i].key_to_position.begin();
4052 file->supplemental->indexes[i].ending_iterator =
4053 file->supplemental->indexes[i].key_to_position.end();
4054 }
4055 file->recent_key = 1;
4056
4057 if( stash )
4058 {
4059 // Restore the original record area:
4060 memcpy( file->default_record->data,
4061 stash,
4062 file->record_area_max);
4063 free(stash);
4064 }
4065
4066 fseek(file->file_pointer, 0, SEEK_SET);
4067 handle_ferror(file, __func__, "fseek() error");
4068
4069 }
4070
4071 static void
4072 file_indexed_close(cblc_file_t *file)
4073 {
4074 delete file->supplemental;
4075 file->supplemental = NULL;
4076 }
4077
4078 extern "C"
4079 void
4080 __gg__file_reopen(cblc_file_t *file, int mode_char)
4081 {
4082 // This is a useful, although scary, little helper. The file must not be
4083 // open. The file->filename must be valid, as must the file_name_quoted_e flag.
4084 // You can see it used in __gg__file_open. You can also see it in
4085 // __gg__sort_workfile, where the workfile is passed as open for read, and
4086 // which needs to be closed and reopened first in "r" and then "w" modes.
4087
4088 // Note that when closing for reopening, you must simply use fclose() and not
4089 // __gg__file_close(). The second one does bookkeeping and cleanup that is
4090 // not appropriate here.
4091
4092 bool the_file_exists;
4093 bool random_access_mode;
4094 char achMode[3];
4095
4096 // Stash the mode_char for later analysis during READ and WRITE operations
4097 file->mode_char = mode_char;
4098 char *trimmed_name;
4099 trimmed_name = get_filename(file, !!(file->flags & file_name_quoted_e));
4100 if( !trimmed_name[0] )
4101 {
4102 bool all_spaces = true;
4103 for(size_t i=0; i<strlen(file->filename); i++)
4104 {
4105 if( file->filename[i] != internal_space )
4106 {
4107 all_spaces = false;
4108 }
4109 break;
4110 }
4111 if( all_spaces )
4112 {
4113 warnx("Warning: %s specified with a filename that is all spaces",
4114 file->name);
4115 file->io_status = FsNameError; // "31"
4116 goto done;
4117 }
4118
4119 static size_t fname_size = MINIMUM_ALLOCATION_SIZE;
4120 static char *fname = static_cast<char *>(malloc(fname_size));
4121 massert(fname)
4122 internal_to_console(&fname,
4123 &fname_size,
4124 file->filename,
4125 strlen(file->filename));
4126 warnx( "%s(): There is no environment variable named \"%s\"\n",
4127 __func__,
4128 fname);
4129 file->io_status = FsNoFile; // "35"
4130 goto done;
4131 }
4132
4133 // achMode is the mode string that gets passed down below to fopen().
4134 random_access_mode = ( file->access == file_access_rnd_e
4135 || file->access == file_access_dyn_e);
4136 the_file_exists = access(trimmed_name, F_OK) == 0;
4137 file->flags |= the_file_exists ? file_flag_existed_e : file_flag_none_e ;
4138
4139 // We have four operations: INPUT (r) OUTPUT (w) I-O (+) and EXTEND (a)
4140 // INPUT and I-O and EXTEND have different results based on is_optional
4141 // and whether or not the file exists.
4142 // Various modification take place if random_access_mode is true
4143
4144 if( the_file_exists )
4145 {
4146 switch(mode_char)
4147 {
4148 case 'r':
4149 // OPEN INPUT
4150 // We need a vanilla read-only file:
4151 strcpy(achMode, "r");
4152 break;
4153
4154 case 'w':
4155 // OPEN OUTPUT
4156 // This syntax means create a new file, or overwrite an existing
4157 // one. For files with random access mode, we need to be
4158 // able to read as well as write, because we have to be able
4159 // to ascertain that a record slot is empty in the event that
4160 // the programmer tries to write to the same slot twice:
4161 if( random_access_mode )
4162 {
4163 strcpy(achMode, "w+");
4164 }
4165 else
4166 {
4167 strcpy(achMode, "w");
4168 }
4169 break;
4170
4171 case 'a':
4172 // EXTEND is for sequential files:
4173 strcpy(achMode, "a");
4174 break;
4175
4176 case '+':
4177 // I-O
4178 // We need to be able to read and write the existing file.
4179 strcpy(achMode, "r+");
4180 break;
4181
4182 default:
4183 fprintf(stderr,
4184 "%s(): We were given an unknown mode_char %d\n",
4185 __func__,
4186 mode_char);
4187 exit(1);
4188 break;
4189 }
4190 }
4191 else
4192 {
4193 // The file *doesn't* exist
4194 switch(mode_char)
4195 {
4196 case 'r':
4197 // OPEN INPUT, but the file doesn't exist:
4198 if( file->flags & file_flag_optional_e )
4199 {
4200 // This is a weird condition. OPTIONAL means "flag it as sort of
4201 // open but the first read causes AT END or INVALID KEY condition.
4202 file->io_status = FsUnavail; // "05"
4203 goto done;
4204 }
4205 else
4206 {
4207 file->io_status = FsNoFile; // "35"
4208 goto done;
4209 }
4210 break;
4211
4212 case 'w':
4213 // OPEN OUTPUT
4214 // This syntax means create a new file, or overwrite an existing
4215 // one. For files with random access mode, we need to be
4216 // able to read as well as write, because we have to be able
4217 // to ascertain that a record slot is empty in the event that
4218 // the programmer tries to write to the same slot twice:
4219 if( random_access_mode )
4220 {
4221 strcpy(achMode, "w+");
4222 }
4223 else
4224 {
4225 strcpy(achMode, "w");
4226 }
4227 break;
4228
4229 case 'a':
4230 // EXTEND
4231 if( file->flags & file_flag_optional_e )
4232 {
4233 if( random_access_mode )
4234 {
4235 // For files that might be sequential or random:
4236 strcpy(achMode, "a+");
4237 }
4238 else
4239 {
4240 // For pure sequential files, we just do a straight "a"
4241 strcpy(achMode, "a");
4242 }
4243 file->io_status = FsUnavail; // "05"
4244 }
4245 else
4246 {
4247 // Trying to extend a non-optional non-existing file is against the rules
4248 file->io_status = FsNoFile; // "35"
4249 goto done;
4250 }
4251 break;
4252
4253 case '+':
4254 // I-O
4255 if( file->flags & file_flag_optional_e )
4256 {
4257 // We need to be able to read and write a new file.
4258 strcpy(achMode, "w+");
4259 file->io_status = FsUnavail; // "05"
4260 }
4261 else
4262 {
4263 file->io_status = FsNoFile; // "35"
4264 goto done;
4265 }
4266 break;
4267
4268 default:
4269 fprintf(stderr,
4270 "%s(): We were given an unknown mode_char %d\n",
4271 __func__,
4272 mode_char);
4273 exit(1);
4274 break;
4275 }
4276 }
4277
4278 file->file_pointer = fopen(trimmed_name, achMode);
4279 if( file->file_pointer == NULL )
4280 {
4281 file->errnum = errno;
4282 // We were unable to open the file
4283 switch(mode_char)
4284 {
4285 case 'r':
4286 case 'a':
4287 case '+':
4288 file->io_status = FsNoFile; // "35"
4289 goto done;
4290 break;
4291
4292 case 'w':
4293 file->io_status = FsOsError; // "30"
4294 goto done;
4295 break;
4296 }
4297 }
4298 file->errnum = ferror(file->file_pointer);
4299
4300 // If this was a OPEN EXTEND, we want the file positioned at the
4301 // the very end (which it won't be when achMode is "r+"
4302 if( mode_char == 'a' )
4303 {
4304 fseek(file->file_pointer, 0, SEEK_END);
4305 if( handle_ferror(file, __func__, "fseek() after fopen() failed") )
4306 {
4307 goto done;
4308 }
4309 }
4310 if( file->org == file_indexed_e )
4311 {
4312 file_indexed_open(file);
4313 }
4314 file->recent_char = '\0';
4315
4316 done:
4317 file->prior_op = file_op_open;
4318 }
4319
4320 static void
4321 __io__file_open(cblc_file_t *file,
4322 char *filename,
4323 int mode_char,
4324 int is_quoted)
4325 {
4326 // Filename is a pointer to a malloc() buffer.
4327
4328 // The complication: A filename can be literal text, it can be from a COBOL
4329 // alphanumeric variable, or it can be the name of an environment variable
4330 // that contains the actual name of the file. The consequence is that if
4331 // you want to call __gg__file_open from anywhere except the parser_file_open
4332 // routine, then you had best really know what you are doing.
4333
4334 file->errnum = 0;
4335 file->io_status = FsErrno;
4336 if( file->file_pointer )
4337 {
4338 // The file is already open:
4339 file->io_status = FsIsOpen; // "41" 14.9.26.3 Paragraph 1
4340 }
4341 else
4342 {
4343 // filename is the result of a strdup or malloc. We will free() it at
4344 // file close time.
4345 file->filename = filename;
4346 file->flags &= ~file_name_quoted_e;
4347 file->flags |= is_quoted ? file_name_quoted_e : file_flag_none_e;
4348
4349 __gg__file_reopen(file, mode_char);
4350 }
4351 file->prior_op = file_op_open;
4352 establish_status(file, -1);
4353 }
4354
4355 static void
4356 __io__file_close( cblc_file_t *file, int how )
4357 {
4358 // We are forcing line-sequential files to end with a newline:
4359
4360 // if( file->org == file_line_sequential_e
4361 // && ( file->mode_char == 'w' || file->mode_char == 'a' )
4362 // && file->recent_char != internal_newline )
4363 // {
4364 // int ch = internal_newline;
4365 // fputc(ch, file->file_pointer);
4366 // if( handle_ferror(file, __func__, "fputc() error [6]") )
4367 // {
4368 // goto done;
4369 // }
4370 // file->recent_char = ch;
4371 // }
4372
4373 errno = 0;
4374 file->io_status = FsErrno;
4375 long fpos = -1;
4376 if( !file->file_pointer )
4377 {
4378 // Attempting to close a file that isn't open:
4379 file->io_status = FsCloseNotOpen; // "42" 14.9.6.3 Paragraph 1
4380 goto done;
4381 }
4382
4383 if( how == file_close_reel_unit_e )
4384 {
4385 // Closing a REEL unit. Leave the file open, and return "07"
4386 file->io_status = FsNotaTape; // "07"
4387
4388 // We have to leave the file position alone:
4389 fpos = ftell(file->file_pointer);
4390 goto done;
4391 }
4392
4393 if( fclose(file->file_pointer) != 0 )
4394 {
4395 handle_ferror(file, __func__, "fclose() error");
4396 }
4397 file->file_pointer = NULL;
4398
4399 if( file->org == file_indexed_e )
4400 {
4401 file_indexed_close(file);
4402 }
4403
4404 // The filename can be from a COBOL alphanumeric variable, which means it can
4405 // between a file_close and a subsequent file_open. So, we get rid of it
4406 // here
4407 free(file->filename);
4408 file->filename = NULL;
4409
4410 done:
4411 file->prior_op = file_op_close;
4412 establish_status(file, fpos);
4413 }
4414
4415 static cblc_file_t *stashed;
4416
4417 cblc_file_t *
4418 __gg__file_stashed()
4419 {
4420 return stashed;
4421 }
4422
4423 extern "C"
4424 void
4425 __gg__file_stash( cblc_file_t *file )
4426 {
4427 ::stashed = file;
4428 }
4429
4430 /*
4431 * The following constitutes a proposal for a public API to gcobol I/O.
4432 *
4433 * The class gcobol_io_t would be in a public header file that
4434 * would be used by any library that provides an I/O
4435 * implementation. Additionally, that header would be where
4436 * cblc_file_t is defined, and where the valid file status values
4437 * (and relops) are enumerated.
4438 *
4439 * The library contructs the class, providing its own pointers,
4440 * and supplies a known function, gcobol_fileops, to return
4441 * it. gcobol-compiled programs call the functions, or others
4442 * supplied by a different implementation, through the pointers.
4443 *
4444 * This design makes it possible to run the same code, unaltered,
4445 * simply by relinking.
4446 *
4447 * This design is commonly used, and is similar to the one used in
4448 * GnuCOBOL. One difference is that the file status is captured
4449 * in the cblc_file_t, whereas in GnuCOBOL it is the return value.
4450 *
4451 * There is no provision for using more than one implemetation at
4452 * a time in the same program, as would be needed for CODE-SET
4453 * support. To achieve that in C++ without dynamic linking, there
4454 * would have to be a set of known implementations, each with its
4455 * own namespace, in which gcobol_fileops would be defined.
4456 */
4457
4458 class gcobol_io_t {
4459 public:
4460 static const char constexpr marquee[64] = "libgcobol: gfileio.cc";
4461
4462 typedef void (open_t)( cblc_file_t *file,
4463 char *filename,
4464 int mode_char,
4465 int is_quoted );
4466 typedef void (close_t)( cblc_file_t *file,
4467 int how );
4468 typedef void (start_t)( cblc_file_t *file,
4469 int relop, // needs enum
4470 int first_last_key,
4471 size_t length );
4472 typedef void (read_t)( cblc_file_t *file,
4473 int where );
4474 typedef void (write_t)( cblc_file_t *file,
4475 const unsigned char *location,
4476 size_t length,
4477 int after,
4478 int lines,
4479 int is_random );
4480 typedef void (rewrite_t)( cblc_file_t *file,
4481 size_t length, bool is_random );
4482 typedef void (delete_t)( cblc_file_t *file,
4483 bool is_random );
4484
4485 open_t *Open;
4486 close_t *Close;
4487 start_t *Start;
4488 read_t *Read;
4489 write_t *Write;
4490 rewrite_t *Rewrite;
4491 delete_t *Delete;
4492
4493 gcobol_io_t()
4494 : Open(NULL)
4495 , Close(NULL)
4496 , Start(NULL)
4497 , Read(NULL)
4498 , Write(NULL)
4499 , Rewrite(NULL)
4500 , Delete(NULL)
4501 {}
4502
4503 gcobol_io_t( open_t *Open,
4504 close_t *Close,
4505 start_t *Start,
4506 read_t *Read,
4507 write_t *Write,
4508 rewrite_t *Rewrite,
4509 delete_t *Delete )
4510 : Open(Open)
4511 , Close(Close)
4512 , Start(Start)
4513 , Read(Read)
4514 , Write(Write)
4515 , Rewrite(Rewrite)
4516 , Delete(Delete)
4517 {}
4518
4519 #if FILE_IO_IMPLEMENTED
4520 int read_next();
4521 int fildelete();
4522 void ioinit();
4523 void ioexit();
4524 int iofork();
4525 int iosync();
4526 int commit();
4527 int rollback();
4528 int iounlock();
4529 char * ioversion();
4530 #endif
4531 };
4532
4533
4534 // Our implementation returns this populated structure
4535
4536 gcobol_io_t*
4537 gcobol_fileops() {
4538 return new gcobol_io_t( __io__file_open,
4539 __io__file_close,
4540 __io__file_start,
4541 __io__file_read,
4542 __io__file_write,
4543 __io__file_rewrite,
4544 __io__file_delete );
4545 }
4546
4547 /*
4548 * To use this structure, whether our gcobolio.so or another, initialize with:
4549 *
4550 * gcobol_io_t * gfile = gcobol_filops(file);
4551 *
4552 * That means every gcobol binary expects to be linked to a library
4553 * that supplies gcobol_fileops(). By default, we link to ours.
4554 *
4555 * Then, in libgcobol, replace direct calls with calls through fileops.
4556 * That is, instead of
4557 *
4558 * __gg__file_open("foo", "r", false );
4559 * use
4560 * gfile->Open("foo", "r", false );
4561 *
4562 * You'll probably want some kind of trampoline to avoid the need to
4563 * generate the Gimple to call through a pointer to a structure:
4564 */
4565
4566 /*
4567 * I/O via interface
4568 */
4569 static gcobol_io_t * gcobol_io = NULL;
4570
4571 static gcobol_io_t *
4572 gcobol_io_funcs() {
4573 if( ! gcobol_io )
4574 {
4575 gcobol_io = gcobol_fileops();
4576 if( !gcobol_io )
4577 {
4578 __gg__abort("gcobol_io_funcs(): gcobol_io is NULL");
4579 }
4580 }
4581 return gcobol_io;
4582 }
4583
4584 extern "C"
4585 void
4586 __gg__file_open(cblc_file_t *file,
4587 char *filename,
4588 int mode_char,
4589 int is_quoted)
4590 {
4591 gcobol_io_t *functions = gcobol_io_funcs();
4592 functions->Open(file, filename, mode_char, is_quoted);
4593 }
4594
4595 extern "C"
4596 void
4597 __gg__file_close( cblc_file_t *file, int how )
4598 {
4599 gcobol_io_t *functions = gcobol_io_funcs();
4600 functions->Close(file, how);
4601 }
4602
4603 extern "C"
4604 void
4605 __gg__file_start( cblc_file_t *file,
4606 int relop,
4607 int first_last_key,
4608 size_t length)
4609 {
4610 gcobol_io_t *functions = gcobol_io_funcs();
4611 functions->Start(file, relop, first_last_key, length);
4612 }
4613
4614 extern "C"
4615 void
4616 __gg__file_read(cblc_file_t *file,
4617 int where)
4618 {
4619 gcobol_io_t *functions = gcobol_io_funcs();
4620 functions->Read(file, where);
4621 }
4622
4623 extern "C"
4624 void
4625 __gg__file_write( cblc_file_t *file,
4626 unsigned char *location,
4627 size_t length,
4628 int after,
4629 int lines,
4630 int is_random )
4631 {
4632 gcobol_io_t *functions = gcobol_io_funcs();
4633 functions->Write(file, location, length, after, lines, is_random);
4634 }
4635
4636 extern "C"
4637 void
4638 __gg__file_rewrite(cblc_file_t *file, size_t length, bool is_random)
4639 {
4640 gcobol_io_t *functions = gcobol_io_funcs();
4641 functions->Rewrite(file, length, is_random);
4642 }
4643
4644 extern "C"
4645 void
4646 __gg__file_delete(cblc_file_t *file, bool is_random)
4647 {
4648 gcobol_io_t *functions = gcobol_io_funcs();
4649 functions->Delete(file, is_random);
4650 }
4651
4652 /* end interface functions */
4653