Debian Codegraph @

libgcobol/libgcobol.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 #include <algorithm>
31 #include <cctype>
32 #include <cstdio>
33 #include <cstdlib>
34 #include <cstring>
35 #include <ctime>
36 #include <set>
37 #include <stack>
38 #include <string>
39 #include <unordered_map>
40 #include <vector>
41
42 #include <dirent.h>
43 #include <dlfcn.h>
44 #include <err.h>
45 #include <fcntl.h>
46 #include <fenv.h>
47 #include <math.h> // required for fpclassify(3), not in cmath
48 #include <setjmp.h>
49 #include <signal.h>
50 #include <syslog.h>
51 #include <unistd.h>
52 #include <stdarg.h>
53 #if __has_include(<errno.h>)
54 # include <errno.h> // for program_invocation_short_name
55 #endif
56
57 #include "config.h"
58 #include "libgcobol-fp.h"
59
60 #include "ec.h"
61 #include "common-defs.h"
62 #include "io.h"
63 #include "gcobolio.h"
64 #include "libgcobol.h"
65 #include "gfileio.h"
66 #include "charmaps.h"
67 #include "valconv.h"
68 #include <sys/mman.h>
69 #include <sys/resource.h>
70 #include <sys/stat.h>
71 #include <sys/types.h>
72 #include <sys/time.h>
73 #include <execinfo.h>
74 #include "exceptl.h"
75
76 /* BSD extension. */
77 #if !defined(LOG_PERROR)
78 #define LOG_PERROR 0
79 #endif
80
81 #if !defined (HAVE_STRFROMF32)
82 # if __FLT_MANT_DIG__ == 24 && __FLT_MAX_EXP__ == 128
83 static int
84 strfromf32 (char *s, size_t n, const char *f, float v)
85 {
86 return snprintf (s, n, f, (double) v);
87 }
88 # else
89 # error "It looks like float on this platform is not IEEE754"
90 # endif
91 #endif
92
93 #if !defined (HAVE_STRFROMF64)
94 # if __DBL_MANT_DIG__ == 53 && __DBL_MAX_EXP__ == 1024
95 static int
96 strfromf64 (char *s, size_t n, const char *f, double v)
97 {
98 return snprintf (s, n, f, v);
99 }
100 # else
101 # error "It looks like double on this platform is not IEEE754"
102 # endif
103 #endif
104
105 // Enable Declarative tracing via "match_declarative" environment variable.
106 #if defined(MATCH_DECLARATIVE) || true
107 # undef MATCH_DECLARATIVE
108 # define MATCH_DECLARATIVE getenv("match_declarative")
109 #else
110 # define MATCH_DECLARATIVE (nullptr)
111 #endif
112
113 // This couldn't be defined in symbols.h because it conflicts with a LEVEL66
114 // in parse.h
115 #define LEVEL66 (66)
116 #define LEVEL88 (88)
117
118 // These global variables are returned when the functions
119 // EXCEPTION-FILE
120 // EXCEPTION-LOCATION
121 // EXCEPTION-STATEMENT
122 // EXCEPTION-STATUS
123 // are called
124
125 // These global values are established as the COBOL program executes
126 int __gg__exception_code = 0 ;
127 int __gg__exception_file_status = 0 ;
128 const char *__gg__exception_file_name = NULL ;
129 const char *__gg__exception_program_id = NULL ;
130 const char *__gg__exception_section = NULL ;
131 const char *__gg__exception_paragraph = NULL ;
132 const char *__gg__exception_source_file = NULL ;
133 int __gg__exception_line_number = 0 ;
134 const char *__gg__exception_statement = NULL ;
135 int __gg__default_compute_error = 0 ;
136 int __gg__rdigits = 0 ;
137 int __gg__nop = 0 ;
138 int __gg__main_called = 0 ;
139
140 // During SORT operations, we don't want the end-of-file condition, which
141 // happens as a matter of course, from setting the EOF exception condition.
142 // Setting this variable to 'true' suppresses the error condition.
143 static bool sv_suppress_eof_ec = false;
144
145 // What follows are arrays that are used by features like INSPECT, STRING,
146 // UNSTRING, and, particularly, arithmetic_operation. These features are
147 // characterized by having unknown, and essentially unlimited, numbers of
148 // variables. Consider, for example, ADD A B C D ... TO L M N O ...
149
150 // Although originally implemented with malloc/free, that's terribly inefficient
151 // on its face; arithmetic is done frequently. The next step was to malloc
152 // buffers just once, and have them grow as needed, but that resulted in a lot
153 // of code being laid down, because it meant checking each buffer size at
154 // run-time, and laying down the code to be executed if the size was inadequate.
155 //
156 // The current solution is to make the pointers to the arrays of values global,
157 // and initialize them with space for MIN_FIELD_BLOCK_SIZE values. Thus, at
158 // compile time, we can ignore all tests for fewer than MIN_FIELD_BLOCK_SIZE
159 // (which is generally the case). Only when N is greater than the MIN do we
160 // have to check the current run-time size and, if necessary, expand the buffer
161 // with realloc.
162 size_t __gg__arithmetic_rounds_size = 0 ;
163 int * __gg__arithmetic_rounds = NULL ;
164
165 size_t __gg__fourplet_flags_size = 0 ;
166 int * __gg__fourplet_flags = NULL ;
167
168 static size_t treeplet_1_size = 0 ;
169 cblc_field_t ** __gg__treeplet_1f = NULL ;
170 size_t * __gg__treeplet_1o = NULL ;
171 size_t * __gg__treeplet_1s = NULL ;
172
173 static size_t treeplet_2_size = 0 ;
174 cblc_field_t ** __gg__treeplet_2f = NULL ;
175 size_t * __gg__treeplet_2o = NULL ;
176 size_t * __gg__treeplet_2s = NULL ;
177
178 static size_t treeplet_3_size = 0 ;
179 cblc_field_t ** __gg__treeplet_3f = NULL ;
180 size_t * __gg__treeplet_3o = NULL ;
181 size_t * __gg__treeplet_3s = NULL ;
182
183 static size_t treeplet_4_size = 0 ;
184 cblc_field_t ** __gg__treeplet_4f = NULL ;
185 size_t * __gg__treeplet_4o = NULL ;
186 size_t * __gg__treeplet_4s = NULL ;
187
188
189 // This value is increased every time PROCEDURE DIVISION is processed. It is
190 // used to keep track of local variables.
191 size_t __gg__unique_prog_id = 0 ;
192
193 // Whenever an exception status is set, a snapshot of the current statement
194 // location information are established in the "last_exception..." variables.
195 // This is in accordance with the ISO requirements of "14.6.13.1.1 General" that
196 // describe how a "last exception status" is maintained.
197 // other "location" information
198 static int last_exception_code;
199 static const char *last_exception_program_id;
200 static const char *last_exception_section;
201 static const char *last_exception_paragraph;
202 static const char *last_exception_source_file;
203 static int last_exception_line_number;
204 static const char *last_exception_statement;
205 // These variables are similar, and are established when an exception is
206 // raised for a file I-O operation.
207 static cblc_file_prior_op_t last_exception_file_operation;
208 static file_status_t last_exception_file_status;
209 static const char *last_exception_file_name;
210
211 static int sv_from_raise_statement = 0;
212
213 typedef void (*PFUNC)();
214 static std::unordered_map<int, char ***> accessible_programs;
215 static std::unordered_map<int, PFUNC **> accessible_pointers;
216
217 #define ARG_LIMIT 512
218 char *__gg__call_parameter_signature = NULL;
219 int __gg__call_parameter_count = A_ZILLION;
220 size_t __gg__call_parameter_lengths[ARG_LIMIT];
221
222 // This is used for managing ENTRY statements in COBOL routines
223 void *__gg__entry_location = NULL;
224
225 // This is the current value at the back of the PERFORM <PROC> stack of
226 // procedure signatures. Said another way: When the exit address at
227 // the end of a paragraph matches this value address, then it is time to pop
228 // the return address off of the stack. It's in this fashion that we implements
229 // nested PERFORM PROC statements.
230 void *__gg__exit_address = NULL;
231
232 /*
233 * ec_status_t represents the runtime exception condition status for
234 * any statement. There are 4 states:
235 * 1. initial, all zeros
236 * 2. updated, copy global EC state for by Declarative and/or default
237 * 3. matched, Declarative found, isection nonzero
238 * 4. handled, where handled == type
239 *
240 * If the statement includes some kind of ON ERROR
241 * clause that covers it, the generated code does not raise an EC.
242 *
243 * The status is updated by __gg_match_exception if it runs, else
244 * __gg__check_fatal_exception.
245 *
246 * If a Declarative is matched, its section number is passed to handled_by(),
247 * which does two things:
248 * 1. sets isection to record the declarative
249 * 2. for a nonfatal EC, sets handled, indication no further action is needed
250 *
251 * A Declarative may use RESUME, which clears ec_status, which is a "handled" state.
252 *
253 * Default processing ensures return to initial state.
254 */
255 class ec_status_t {
256 public:
257 struct file_status_t {
258 size_t ifile;
259 cblc_file_prior_op_t operation;
260 cbl_file_mode_t mode;
261 cblc_field_t *user_status;
262 const char * filename;
263 file_status_t()
264 : ifile(0)
265 , operation(file_op_none)
266 , mode(file_mode_none_e)
267 , user_status(nullptr)
268 , filename(nullptr)
269 {}
270 explicit file_status_t( const cblc_file_t *file )
271 : ifile(file->symbol_table_index)
272 , operation(file->prior_op)
273 , mode(cbl_file_mode_t(file->mode_char))
274 , user_status(file->user_status)
275 , filename(file->filename)
276 {}
277 const char * op_str() const {
278 switch( operation ) {
279 case file_op_none: return "none";
280 case file_op_open: return "open";
281 case file_op_close: return "close";
282 case file_op_start: return "start";
283 case file_op_read: return "read";
284 case file_op_write: return "write";
285 case file_op_rewrite: return "rewrite";
286 case file_op_delete: return "delete";
287 }
288 return "???";
289 }
290 };
291 private:
292 char msg[132];
293 ec_type_t type, handled;
294 size_t isection;
295 cbl_enabled_exceptions_t enabled;
296 cbl_declaratives_t declaratives;
297 struct file_status_t file;
298 public:
299 int lineno;
300 const char *source_file;
301 cbl_name_t statement; // e.g., "ADD"
302
303 ec_status_t()
304 : type(ec_none_e)
305 , handled(ec_none_e)
306 , isection(0)
307 , lineno(0)
308 , source_file(NULL)
309 {
310 msg[0] = statement[0] = '\0';
311 }
312
313 bool is_fatal() const;
314 ec_status_t& update();
315
316 bool is_enabled() const { return enabled.match(type); }
317 bool is_enabled( ec_type_t ec) const { return enabled.match(ec); }
318 ec_status_t& handled_by( size_t declarative_section ) {
319 isection = declarative_section;
320 // A fatal exception remains unhandled unless RESUME clears it.
321 if( ! is_fatal() ) {
322 handled = type;
323 }
324 return *this;
325 }
326 ec_status_t& clear() {
327 handled = type = ec_none_e;
328 isection = 0;
329 lineno = 0;
330 msg[0] = statement[0] = '\0';
331 return *this;
332 }
333 bool unset() const { return isection == 0 && lineno == 0; }
334
335 void reset_environment() const;
336 ec_status_t& copy_environment();
337
338 // Return the EC's type if it is *not* handled.
339 ec_type_t unhandled() const {
340 bool was_handled = ec_cmp(type, handled);
341 return was_handled? ec_none_e : type;
342 }
343
344 bool done() const { return unhandled() == ec_none_e; }
345
346 const file_status_t& file_status() const { return file; }
347
348 const char * exception_location() {
349 snprintf(msg, sizeof(msg), "%s:%d: '%s'", source_file, lineno, statement);
350 return msg;
351 }
352 };
353
354 /*
355 * Capture the global EC status at the beginning of Declarative matching. While
356 * executing the Declarative, push the current status on a stack. When the
357 * Declarative returns, restore EC status from the stack.
358 *
359 * If the Declarative includes a RESUME statement, it clears the on-stack
360 * status, thus avoiding any default handling.
361 */
362 static ec_status_t ec_status;
363 static std::stack<ec_status_t> ec_stack;
364
365 static cbl_enabled_exceptions_t enabled_ECs;
366 static cbl_declaratives_t declaratives;
367
368 static const ec_descr_t *
369 local_ec_type_descr( ec_type_t type ) {
370 auto p = std::find( __gg__exception_table, __gg__exception_table_end, type );
371 if( p == __gg__exception_table_end )
372 {
373 warnx("%s:%d: no such EC value %08x", __func__, __LINE__, type);
374 __gg__abort("Fell off the end of the __gg__exception_table");
375 }
376 return p;
377 }
378
379 cblc_file_t * __gg__file_stashed();
380
381 #pragma GCC diagnostic push
382 #pragma GCC diagnostic ignored "-Wunused-function"
383 // Keep this debugging function around for when it is needed
384 static const char *
385 local_ec_type_str( ec_type_t type ) {
386 if( type == ec_none_e ) return "EC-NONE";
387 auto p = local_ec_type_descr(type);
388 return p->name;
389 }
390 #pragma GCC diagnostic pop
391
392 bool
393 ec_status_t::is_fatal() const {
394 auto descr = local_ec_type_descr(type);
395 return descr->disposition == ec_category_fatal_e;
396 }
397
398 ec_status_t&
399 ec_status_t::update() {
400 handled = ec_none_e;
401 type = ec_type_t(__gg__exception_code);
402 source_file = __gg__exception_source_file;
403 lineno = __gg__exception_line_number;
404 if( __gg__exception_statement ) {
405 snprintf(statement, sizeof(statement), "%s", __gg__exception_statement);
406 }
407 cblc_file_t *stashed = __gg__file_stashed();
408 this->file = stashed? file_status_t(stashed) : file_status_t();
409
410 if( type != ec_none_e && MATCH_DECLARATIVE ) {
411 warnx( "ec_status_t::update:%d: EC %s by %s (handled %s) " , __LINE__,
412 local_ec_type_str(type),
413 __gg__exception_statement? statement : "<none>",
414 local_ec_type_str(handled) );
415 }
416
417 this->enabled = ::enabled_ECs;
418 this->declaratives = ::declaratives;
419
420 return *this;
421 }
422
423 ec_status_t&
424 ec_status_t::copy_environment() {
425 this->enabled = ::enabled_ECs;
426 this->declaratives = ::declaratives;
427 return *this;
428 }
429
430 void
431 ec_status_t::reset_environment() const {
432 ::enabled_ECs = enabled;
433 ::declaratives = declaratives;
434 }
435
436
437 // This is the default truncation mode
438 static cbl_truncation_mode truncation_mode = trunc_std_e;
439
440 extern "C"
441 void
442 __gg__set_truncation_mode(cbl_truncation_mode trunc_mode)
443 {
444 truncation_mode = trunc_mode;
445 }
446
447 struct program_state
448 {
449 // These are the run-time values of these characters.
450
451 // They are always in source_code space; they get converted to native
452 // when they are used.
453 int rt_decimal_point;
454 int rt_decimal_separator;
455 int rt_quote_character;
456 int rt_low_value_character;
457 int rt_high_value_character;
458 char *rt_currency_signs[256];
459 const unsigned short *rt_collation; // Points to a table of 256 values;
460 char *rt_program_name;
461
462 program_state()
463 {
464 // IBM defaults to the \" QUOTE compiler option. quote_character must
465 // be set to \' when the APOST compiler option is in effect
466
467 // rt_currency_signs provides for replacing a PICTURE currency "symbol"
468 // with a character string referred to in the language specification as
469 // a "sign". The string can be an arbitrary length, allowing the
470 // replacement of, as an example, the currency <symbol> "$" with the
471 // <sign> "USD"
472
473 rt_decimal_point = ascii_period ;
474 rt_decimal_separator = ascii_comma ;
475 rt_quote_character = ascii_dquote ; // Change this with APOST
476 rt_low_value_character = DEGENERATE_LOW_VALUE ;
477 rt_high_value_character = DEGENERATE_HIGH_VALUE ;
478
479 // Set all the currency_sign pointers to NULL:
480
481 memset(rt_currency_signs, 0, sizeof(rt_currency_signs));
482
483 // The default collating sequence:
484 if( internal_is_ebcdic )
485 {
486 rt_collation = __gg__cp1140_to_cp1252_values;
487 }
488 else
489 {
490 rt_collation = __gg__one_to_one_values;
491 }
492 rt_program_name = NULL;
493 }
494
495 program_state(const program_state &ps)
496 {
497 rt_decimal_point = ps.rt_decimal_point ;
498 rt_decimal_separator = ps.rt_decimal_separator ;
499 rt_quote_character = ps.rt_quote_character ;
500 rt_low_value_character = ps.rt_low_value_character ;
501 // Note throughout the code that there is special processing for the
502 // high-value character. In EBCDIC 0xFF doesn't map to ASCII 0xFF, so
503 // we are forced to avoid converting EBCDIC 0xFF.
504 rt_high_value_character = ps.rt_high_value_character ;
505 rt_collation = ps.rt_collation ;
506
507 for( int i=0; i<256; i++ )
508 {
509 if( ps.rt_currency_signs[i] )
510 {
511 rt_currency_signs[i] = strdup(ps.rt_currency_signs[i]);
512 }
513 else
514 {
515 rt_currency_signs[i] = NULL;
516 }
517 }
518
519 rt_program_name = ps.rt_program_name ;
520 }
521
522 ~program_state()
523 {
524 for(int symbol=0; symbol<256; symbol++)
525 {
526 if( rt_currency_signs[symbol] )
527 {
528 free(rt_currency_signs[symbol]);
529 rt_currency_signs[symbol] = NULL;
530 }
531 }
532 }
533 };
534
535 static std::vector<program_state> program_states;
536 #define collated(a) (program_states.back().rt_collation[(unsigned int)(a&0xFF)])
537 #define program_name (program_states.back().rt_program_name)
538 // #define decimal_point (program_states.back().rt_decimal_point)
539 // #define decimal_separator (program_states.back().rt_decimal_separator)
540 // #define quote_character (program_states.back().rt_quote_character)
541 // #define low_value_character (program_states.back().rt_low_value_character)
542 // #define high_value_character (program_states.back().rt_high_value_character)
543 // #define currency_signs(a) (program_states.back().rt_currency_signs[(a)])
544 #define currency_signs(a) (__gg__currency_signs[(a)])
545
546 #ifdef DEBUG_MALLOC
547 void *malloc(size_t a)
548 {
549 void *retval = malloc(a);
550 fprintf(stderr, " --malloc(%p)-- ", retval);
551 return retval;
552 }
553 #endif
554
555 void
556 __gg__abort(const char *msg)
557 {
558 fprintf(stderr, "%s: %s\n", program_name, msg);
559 abort();
560 }
561
562 void
563 __gg__mabort()
564 {
565 __gg__abort("Memory allocation error\n");
566 }
567
568 extern "C"
569 char
570 __gg__get_decimal_point()
571 {
572 return __gg__decimal_point;
573 }
574
575 extern "C"
576 char
577 __gg__get_decimal_separator()
578 {
579 return __gg__decimal_separator;
580 }
581
582 extern "C"
583 char *
584 __gg__get_default_currency_string()
585 {
586 return currency_signs(__gg__default_currency_sign);
587 }
588
589 extern "C"
590 void
591 __gg__resize_int_p( size_t *size,
592 int **block,
593 size_t new_size)
594 {
595 if( new_size > *size )
596 {
597 *size = new_size;
598 *block = static_cast<int *>(realloc(*block, new_size * sizeof(int)));
599 }
600 }
601
602 extern "C"
603 void
604 __gg__resize_treeplet(int ngroup,
605 size_t new_size)
606 {
607 switch( ngroup )
608 {
609 case 1:
610 if( new_size > treeplet_1_size )
611 {
612 treeplet_1_size = new_size;
613 __gg__treeplet_1f = static_cast<cblc_field_t **>(realloc(__gg__treeplet_1f, new_size * sizeof(cblc_field_t *)));
614 __gg__treeplet_1o = static_cast<size_t *>(realloc(__gg__treeplet_1o, new_size * sizeof(size_t)));
615 __gg__treeplet_1s = static_cast<size_t *>(realloc(__gg__treeplet_1s, new_size * sizeof(size_t)));
616 }
617 break;
618 case 2:
619 if( new_size > treeplet_2_size )
620 {
621 treeplet_2_size = new_size;
622 __gg__treeplet_2f = static_cast<cblc_field_t **>(realloc(__gg__treeplet_2f, new_size * sizeof(cblc_field_t *)));
623 __gg__treeplet_2o = static_cast<size_t *>(realloc(__gg__treeplet_2o, new_size * sizeof(size_t)));
624 __gg__treeplet_2s = static_cast<size_t *>(realloc(__gg__treeplet_2s, new_size * sizeof(size_t)));
625 }
626 break;
627 case 3:
628 if( new_size > treeplet_3_size )
629 {
630 treeplet_3_size = new_size;
631 __gg__treeplet_3f = static_cast<cblc_field_t **>(realloc(__gg__treeplet_3f, new_size * sizeof(cblc_field_t *)));
632 __gg__treeplet_3o = static_cast<size_t *>(realloc(__gg__treeplet_3o, new_size * sizeof(size_t)));
633 __gg__treeplet_3s = static_cast<size_t *>(realloc(__gg__treeplet_3s, new_size * sizeof(size_t)));
634 }
635 break;
636 case 4:
637 if( new_size > treeplet_4_size )
638 {
639 treeplet_4_size = new_size;
640 __gg__treeplet_4f = static_cast<cblc_field_t **>(realloc(__gg__treeplet_4f, new_size * sizeof(cblc_field_t *)));
641 __gg__treeplet_4o = static_cast<size_t *>(realloc(__gg__treeplet_4o, new_size * sizeof(size_t)));
642 __gg__treeplet_4s = static_cast<size_t *>(realloc(__gg__treeplet_4s, new_size * sizeof(size_t)));
643 }
644 break;
645 }
646 }
647
648 static void
649 initialize_program_state()
650 {
651 // This routine gets called exactly once for a COBOL executable
652 program_state initial_value = {};
653 program_states.push_back(initial_value);
654 __gg__currency_signs = program_states.back().rt_currency_signs;
655
656 // This is where we initialize the various tables that have
657 // MIN_FIELD_BLOCK_SIZE elements:
658
659 __gg__resize_int_p(&__gg__arithmetic_rounds_size,
660 &__gg__arithmetic_rounds,
661 MIN_FIELD_BLOCK_SIZE );
662 __gg__resize_int_p(&__gg__fourplet_flags_size,
663 &__gg__fourplet_flags,
664 MIN_FIELD_BLOCK_SIZE );
665 __gg__resize_treeplet(1, MIN_FIELD_BLOCK_SIZE);
666 __gg__resize_treeplet(2, MIN_FIELD_BLOCK_SIZE);
667 __gg__resize_treeplet(3, MIN_FIELD_BLOCK_SIZE);
668 __gg__resize_treeplet(4, MIN_FIELD_BLOCK_SIZE);
669 }
670
671 extern "C"
672 void
673 __gg__set_program_name(char *progname)
674 {
675 program_name = progname;
676 }
677
678 extern "C"
679 void
680 __gg__push_program_state()
681 {
682 // Duplicate the state at the back of the stack
683 program_states.push_back(program_states.back());
684 __gg__currency_signs = program_states.back().rt_currency_signs;
685 }
686
687 extern "C"
688 void
689 __gg__pop_program_state()
690 {
691 program_states.pop_back();
692
693 // #define decimal_point (program_states.back().rt_decimal_point)
694 // #define decimal_separator (program_states.back().rt_decimal_separator)
695 // #define quote_character (program_states.back().rt_quote_character)
696 // #define low_value_character (program_states.back().rt_low_value_character)
697 // #define high_value_character (program_states.back().rt_high_value_character)
698
699 __gg__decimal_point = program_states.back().rt_decimal_point ;
700 __gg__decimal_separator = program_states.back().rt_decimal_separator ;
701 __gg__quote_character = program_states.back().rt_quote_character ;
702 __gg__low_value_character = program_states.back().rt_low_value_character ;
703 __gg__high_value_character = program_states.back().rt_high_value_character ;
704 __gg__currency_signs = program_states.back().rt_currency_signs ;
705
706 }
707
708 static
709 int
710 cstrncmp( char const * const left_,
711 char const * const right_,
712 size_t count)
713 {
714 const char *left = left_;
715 const char *right = right_;
716 // This is the version of strncmp() that uses the current collation
717
718 // It also is designed to handle strings with embedded NUL characters, so
719 // it treats NULs like any other characters.
720 int retval = 0;
721 while( count-- )
722 {
723 unsigned char chl = *left++;
724 unsigned char chr = *right++;
725 retval = chl - chr;
726 if( retval )
727 {
728 break;
729 }
730 }
731 return retval;
732 }
733
734 extern "C"
735 void
736 __gg__decimal_point_is_comma()
737 {
738 program_states.back().rt_decimal_point = ascii_comma ;
739 program_states.back().rt_decimal_separator = ascii_period ;
740 __gg__decimal_point = ascii_comma ;
741 __gg__decimal_separator = ascii_period ;
742 }
743
744 extern "C"
745 void
746 __gg__init_program_state()
747 {
748 // This routine gets called at DATA DIVISION time.
749
750 // We need to make sure that the program_states vector has at least one
751 // entry in it. This happens when we are the very first PROGRAM-ID called
752 // in this module.
753 if( program_states.empty() )
754 {
755 initialize_program_state();
756 }
757 }
758
759 static int
760 var_is_refmod( const cblc_field_t *var )
761 {
762 return (var->attr & refmod_e) != 0;
763 }
764
765 extern "C"
766 __int128
767 __gg__power_of_ten(int n)
768 {
769 // 2** 64 = 1.8E19
770 // 2**128 = 3.4E38
771 __int128 retval = 1;
772 static const int MAX_POWER = 19 ;
773 static const __int128 pos[MAX_POWER+1] =
774 {
775 1ULL, // 00
776 10ULL, // 01
777 100ULL, // 02
778 1000ULL, // 03
779 10000ULL, // 04
780 100000ULL, // 05
781 1000000ULL, // 06
782 10000000ULL, // 07
783 100000000ULL, // 08
784 1000000000ULL, // 09
785 10000000000ULL, // 10
786 100000000000ULL, // 11
787 1000000000000ULL, // 12
788 10000000000000ULL, // 13
789 100000000000000ULL, // 14
790 1000000000000000ULL, // 15
791 10000000000000000ULL, // 16
792 100000000000000000ULL, // 17
793 1000000000000000000ULL, // 18
794 10000000000000000000ULL, // 19
795 };
796 if( n < 0 || n>MAX_POWER*2) // The most we can handle is 10**38
797 {
798 fprintf(stderr,
799 "Trying to raise 10 to %d as an int128, which we can't do.\n",
800 n);
801 fprintf(stderr, "The problem is in %s.\n", __func__);
802 abort();
803 }
804 if( n <= MAX_POWER )
805 {
806 // Up to 10**18 we do directly:
807 retval = pos[n];
808 }
809 else
810 {
811 // 19 through 38:
812 retval = pos[n/2];
813 retval *= retval;
814 if( n & 1 )
815 {
816 retval *= 10;
817 }
818 }
819 return retval;
820 }
821
822 extern "C"
823 __int128
824 __gg__scale_by_power_of_ten_1(__int128 value, int N)
825 {
826 // This routine is called when the result of the scaling is not allowed to
827 // have non-zero rdigits. __gg__rdigits is set to 1 when the result is
828 // in the bad zone. The ultimate caller needs to examine __gg__rdigits to
829 // decide what to do about it.
830
831 // This is a separate routine because of the performance hit caused by the
832 // value % pot operation, which is needed only when certain EC checking is
833 // turned on.
834 if( N > 0 )
835 {
836 __gg__rdigits = 0;
837 value *= __gg__power_of_ten(N);
838 }
839 else if( N < 0)
840 {
841 // We throwing away the N rightmost digits. Use __gg__rdigits
842 // to let the calling chain know they were non-zero:
843 __int128 pot = __gg__power_of_ten(-N);
844 if( value % pot)
845 {
846 __gg__rdigits = 1;
847 }
848 else
849 {
850 __gg__rdigits = 0;
851 }
852
853 value /= pot;
854 }
855 else
856 {
857 // N is zero
858 __gg__rdigits = 0;
859 }
860 return value;
861 }
862
863 extern "C"
864 __int128
865 __gg__scale_by_power_of_ten_2(__int128 value, int N)
866 {
867 if( N > 0 )
868 {
869 value *= __gg__power_of_ten(N);
870 }
871 else if( N < 0)
872 {
873 value /= __gg__power_of_ten(-N);
874 }
875 return value;
876 }
877
878 extern "C"
879 bool
880 __gg__binary_to_string(char *result, int digits, __int128 value)
881 {
882 // The result is not terminated, because this routine is used
883 // to put information directly into cblc_field_t::data
884 // Our caller has to keep track of whether value was negative.
885
886 // Note that this routine operates in the source code-set space; that is
887 // the result comes back with zero as an ASCII 0x30, not an EBCDIC 0xF0
888
889 if( value < 0 )
890 {
891 value = -value;
892 }
893 result += digits-1 ;
894 while( digits-- )
895 {
896 *result-- = value%10 + ascii_zero;
897 value /= 10;
898 }
899 // Should value be non-zero, it means we potentially have a size error
900 return value != 0;
901 }
902
903 extern "C"
904 bool
905 __gg__binary_to_string_internal(char *result, int digits, __int128 value)
906 {
907 // The result is not terminated, because this routine is used
908 // to put information directly into cblc_field_t::data
909 // Our caller has to keep track of whether value was negative.
910
911 // Note that this routine operates in the source code-set space; that is
912 // the result comes back with zero as an ASCII 0x30, not an EBCDIC 0xF0
913
914 if( value < 0 )
915 {
916 value = -value;
917 }
918 result += digits-1 ;
919 while( digits-- )
920 {
921 *result-- = (value%10) + internal_zero;
922 value /= 10;
923 }
924 // Should value be non-zero, it means we potentially have a size error
925 return value != 0;
926 }
927
928 static bool
929 value_is_too_big(const cblc_field_t *var,
930 __int128 value,
931 int source_rdigits)
932 {
933 // This routine is in support of arithmetic ON SIZE ERROR. It returns
934 // TRUE if var hasn't enough bytes to hold the decimal representation
935 // of value:
936 bool retval = false;
937
938 if( !(var->attr & intermediate_e) )
939 {
940 if( value < 0 )
941 {
942 value = -value;
943 }
944 if( var->digits )
945 {
946 // I don't know how to describe this calculation. I came up with the
947 // equation by working a few examples. For instance, if value is 12345 and
948 // source_rdigits is two, then we are trying to cram 123.45 into 99v99999
949 // and we have a size error. So, digits is 7, rdigits is 5 and source_rdigits
950 // 2. That means we compare 12345 with 10^(7 - 5 + 2), which is 12345 versus
951 // 10000, which is too big, which means we have a size error.
952 retval =
953 value >= __gg__power_of_ten( var->digits - var->rdigits + source_rdigits);
954 }
955 else
956 {
957 // var->digits is zero. We are dealing with a binary-style number that
958 // fills the whole of the value
959 if( !( var->type == FldNumericBin5
960 || var->type == FldPointer
961 || var->type == FldIndex) )
962 {
963 __gg__abort("value_is_too_big() was given a type it doesn't know about");
964 }
965 if( var->capacity < 16 )
966 {
967 __int128 max_possible = 1;
968 max_possible = max_possible << (var->capacity * 8);
969 retval = value >= max_possible;
970 }
971 }
972 }
973
974 return retval;
975 }
976
977 static void
978 binary_to_big_endian( unsigned char *dest,
979 int bytes,
980 __int128 value
981 )
982 {
983 if( value < 0 )
984 {
985 memset(dest, 0xFF, bytes);
986 }
987 else
988 {
989 memset(dest, 0x00, bytes);
990 }
991
992 dest += bytes-1;
993 while( bytes-- )
994 {
995 *dest-- = (unsigned char) value;
996 value >>= 8;
997 }
998 }
999
1000 static void
1001 binary_to_little_endian( unsigned char *dest,
1002 int bytes,
1003 __int128 value
1004 )
1005 {
1006 if( value < 0 )
1007 {
1008 memset(dest, 0xFF, bytes);
1009 }
1010 else
1011 {
1012 memset(dest, 0x00, bytes);
1013 }
1014 memcpy(dest, &value, bytes);
1015 }
1016
1017 static void
1018 turn_sign_bit_on(unsigned char *location)
1019 {
1020 if( internal_is_ebcdic )
1021 {
1022 *location &= ~NUMERIC_DISPLAY_SIGN_BIT;
1023 }
1024 else
1025 {
1026 *location |= NUMERIC_DISPLAY_SIGN_BIT;
1027 }
1028 }
1029
1030 static void
1031 turn_sign_bit_off(unsigned char *location)
1032 {
1033 if( internal_is_ebcdic )
1034 {
1035 *location |= NUMERIC_DISPLAY_SIGN_BIT;
1036 }
1037 else
1038 {
1039 *location &= ~NUMERIC_DISPLAY_SIGN_BIT;
1040 }
1041 }
1042
1043 static bool
1044 is_sign_bit_on(char ch)
1045 {
1046 bool retval;
1047 if( (unsigned char)ch == 0xFF || ch == 0x00 )
1048 {
1049 // Don't let HIGH-VALUE or LOW_VALUE confuse sign detection
1050 retval = false;
1051 }
1052 else
1053 {
1054 if( internal_is_ebcdic )
1055 {
1056 retval = (ch & NUMERIC_DISPLAY_SIGN_BIT) == 0;
1057 }
1058 else
1059 {
1060 retval = (ch & NUMERIC_DISPLAY_SIGN_BIT) != 0;
1061 }
1062 }
1063 return retval;
1064 }
1065
1066 extern "C"
1067 void
1068 __gg__string_to_alpha_edited_ascii( char *dest,
1069 const char *source,
1070 int slength,
1071 const char *picture)
1072 {
1073 char *dupe = static_cast<char *>(malloc(slength));
1074 massert(dupe);
1075 memcpy(dupe, source, slength);
1076 ascii_to_internal_str(dupe, slength);
1077 __gg__string_to_alpha_edited(dest, dupe, slength, picture);
1078 free(dupe);
1079 }
1080
1081 static __int128
1082 int128_to_int128_rounded( cbl_round_t rounded,
1083 __int128 value,
1084 __int128 factor,
1085 __int128 remainder,
1086 int *compute_error)
1087 {
1088 // value is signed, and is scaled to the target
1089 GCOB_FP128 fpart = ((GCOB_FP128)remainder) / ((GCOB_FP128)factor);
1090 __int128 retval = value;
1091
1092 if(rounded == nearest_even_e
1093 && fpart != GCOB_FP128_LITERAL (-0.5)
1094 && fpart != GCOB_FP128_LITERAL (0.5))
1095 {
1096 // "bankers rounding" has been requested.
1097 //
1098 // Since the fraction is not 0.5, this is an ordinary rounding
1099 // problem
1100 rounded = nearest_away_from_zero_e;
1101 }
1102
1103 switch(rounded)
1104 {
1105 case truncation_e:
1106 break;
1107
1108 case nearest_away_from_zero_e:
1109 {
1110 // This is ordinary rounding, like you learned in grade school
1111 // 0.0 through 0.4 becomes 0
1112 // 0.5 through 0.9 becomes 1
1113 if( value < 0 )
1114 {
1115 if( fpart <= GCOB_FP128_LITERAL(-0.5) )
1116 {
1117 retval -= 1;
1118 }
1119 }
1120 else
1121 {
1122 if( fpart >= GCOB_FP128_LITERAL(0.5) )
1123 {
1124 retval += 1;
1125 }
1126 }
1127 break;
1128 }
1129
1130 case away_from_zero_e:
1131 {
1132 // zero stays zero, otherwise head for the next number away from zero
1133 if( value < 0 )
1134 {
1135 if( fpart != 0 )
1136 {
1137 retval -= 1;
1138 }
1139 }
1140 else
1141 {
1142 if( fpart != 0 )
1143 {
1144 retval += 1;
1145 }
1146 }
1147 break;
1148 }
1149
1150 case nearest_toward_zero_e:
1151 {
1152 // 0.0 through 0.5 becomes 0
1153 // 0.6 through 0.9 becomes 1
1154 if( value < 0 )
1155 {
1156 if( fpart < GCOB_FP128_LITERAL(-0.5) )
1157 {
1158 retval -= 1;
1159 }
1160 }
1161 else
1162 {
1163 if( fpart > GCOB_FP128_LITERAL(0.5) )
1164 {
1165 retval += 1;
1166 }
1167 }
1168 break;
1169 }
1170
1171 case toward_greater_e:
1172 {
1173 if( value > 0 )
1174 {
1175 if( fpart != 0 )
1176 {
1177 retval += 1;
1178 }
1179 }
1180 break;
1181 }
1182
1183 case toward_lesser_e:
1184 {
1185 if( value < 0 )
1186 {
1187 if(fpart != 0)
1188 {
1189 retval -= 1;
1190 }
1191 }
1192 break;
1193 }
1194
1195 case nearest_even_e:
1196 {
1197 // This is "banker's rounding"
1198 // 3.4 -> 3.0
1199 // 3.5 -> 4.0
1200 // 3.6 -> 4.0
1201
1202 // 4.4 -> 4.0
1203 // 4.5 -> 4.0
1204 // 4.6 -> 5.0
1205
1206 // We know that the fractional part is 0.5 or -0.5, and we know that
1207 // we want 3 to become 4 and for 4 to stay 4.
1208
1209 if( value < 0 )
1210 {
1211 if( retval & 1 )
1212 {
1213 retval -= 1;
1214 }
1215 }
1216 else
1217 {
1218 if( retval & 1 )
1219 {
1220 retval += 1;
1221 }
1222 }
1223 break;
1224 }
1225
1226 case prohibited_e:
1227 {
1228 if( fpart != 0 )
1229 {
1230 *compute_error |= compute_error_truncate;
1231 }
1232
1233 break;
1234 }
1235
1236 default:
1237 abort();
1238 break;
1239 }
1240 return retval;
1241 }
1242
1243 static __int128
1244 f128_to_i128_rounded( cbl_round_t rounded,
1245 GCOB_FP128 value,
1246 int *compute_error)
1247 {
1248 // value is signed, and is scaled to the target
1249 GCOB_FP128 ipart;
1250 GCOB_FP128 fpart = FP128_FUNC(modf)(value, &ipart);
1251 __int128 retval = (__int128)ipart;
1252
1253 if(rounded == nearest_even_e
1254 && fpart != GCOB_FP128_LITERAL (-0.5)
1255 && fpart != GCOB_FP128_LITERAL (0.5))
1256 {
1257 // "bankers rounding" has been requested.
1258 //
1259 // Since the fraction is not 0.5, this is an ordinary rounding
1260 // problem
1261 rounded = nearest_away_from_zero_e;
1262 }
1263
1264 switch(rounded)
1265 {
1266 case truncation_e:
1267 break;
1268
1269 case nearest_away_from_zero_e:
1270 {
1271 // This is ordinary rounding, like you learned in grade school
1272 // 0.0 through 0.4 becomes 0
1273 // 0.5 through 0.9 becomes 1
1274 if( value < 0 )
1275 {
1276 if( fpart <= GCOB_FP128_LITERAL (-0.5) )
1277 {
1278 retval -= 1;
1279 }
1280 }
1281 else
1282 {
1283 if( fpart >= GCOB_FP128_LITERAL (0.5) )
1284 {
1285 retval += 1;
1286 }
1287 }
1288 break;
1289 }
1290
1291 case away_from_zero_e:
1292 {
1293 // zero stays zero, otherwise head for the next number away from zero
1294 if( value < 0 )
1295 {
1296 if( fpart != 0 )
1297 {
1298 retval -= 1;
1299 }
1300 }
1301 else
1302 {
1303 if( fpart != 0 )
1304 {
1305 retval += 1;
1306 }
1307 }
1308 break;
1309 }
1310
1311 case nearest_toward_zero_e:
1312 {
1313 // 0.0 through 0.5 becomes 0
1314 // 0.6 through 0.9 becomes 1
1315 if( value < 0 )
1316 {
1317 if( fpart < GCOB_FP128_LITERAL (-0.5) )
1318 {
1319 retval -= 1;
1320 }
1321 }
1322 else
1323 {
1324 if( fpart > GCOB_FP128_LITERAL (0.5) )
1325 {
1326 retval += 1;
1327 }
1328 }
1329 break;
1330 }
1331
1332 case toward_greater_e:
1333 {
1334 if( value > 0 )
1335 {
1336 if( fpart != 0 )
1337 {
1338 retval += 1;
1339 }
1340 }
1341 break;
1342 }
1343
1344 case toward_lesser_e:
1345 {
1346 if( value < 0 )
1347 {
1348 if(fpart != 0)
1349 {
1350 retval -= 1;
1351 }
1352 }
1353 break;
1354 }
1355
1356 case nearest_even_e:
1357 {
1358 // This is "banker's rounding"
1359 // 3.4 -> 3.0
1360 // 3.5 -> 4.0
1361 // 3.6 -> 4.0
1362
1363 // 4.4 -> 4.0
1364 // 4.5 -> 4.0
1365 // 4.6 -> 5.0
1366
1367 // We know that the fractional part is 0.5 or -0.5, and we know that
1368 // we want 3 to become 4 and for 4 to stay 4.
1369
1370 if( value < 0 )
1371 {
1372 if( retval & 1 )
1373 {
1374 retval -= 1;
1375 }
1376 }
1377 else
1378 {
1379 if( retval & 1 )
1380 {
1381 retval += 1;
1382 }
1383 }
1384 break;
1385 }
1386
1387 case prohibited_e:
1388 {
1389 if( fpart != 0 )
1390 {
1391 *compute_error |= compute_error_truncate;
1392 }
1393
1394 break;
1395 }
1396
1397 default:
1398 abort();
1399 break;
1400 }
1401 return retval;
1402 }
1403
1404 static void
1405 int128_to_field(cblc_field_t *var,
1406 unsigned char *location,
1407 size_t length,
1408 __int128 value,
1409 int source_rdigits,
1410 enum cbl_round_t rounded,
1411 int *compute_error)
1412 {
1413 // This routine takes a numerical value, and scales and converts it to the
1414 // target field type.
1415
1416 // It operates in the source codeset space, and converts the final result
1417 // to the native codeset space
1418
1419 switch( var->type )
1420 {
1421 case FldFloat:
1422 {
1423 switch( var->capacity )
1424 {
1425 case 4:
1426 {
1427 float tvalue = (float)value;
1428 tvalue /= (float)__gg__power_of_ten(source_rdigits);
1429 *PTRCAST(float, location) = tvalue;
1430 break;
1431 }
1432
1433 case 8:
1434 {
1435 double tvalue = (double)value;
1436 tvalue /= (double)__gg__power_of_ten(source_rdigits);
1437 *PTRCAST(double, location) = tvalue;
1438 break;
1439 }
1440
1441 case 16:
1442 {
1443 // It turns out we have a problem. The IEEE 754 quadruple-precision
1444 // binary representation can handle up to 33 digits exactly, and can
1445 // handle at most 36 digits. I decided to implement fixed-point
1446 // values to 38 places (which is what an __int128 can hold), and as a
1447 // result, at this point in the code we can be asking the compiler to
1448 // turn a 38-digit __int128 into a _Float128.
1449
1450 // This caused a problem that I noticed in COMPUTE var = (2/3)*3.
1451
1452 // The default is truncation, and so the PIC 9V9999 result should be
1453 // 1.9999.
1454
1455 // At this point in the code, the 128-bit value was the
1456 // 38-digit 19999999999999999999999999999999999998
1457
1458 // So, I then converted that to a _Float128, and the conversion
1459 // routine properly did the best it could and returned exactly
1460 // 2E37
1461
1462 // The problem: This rounded the number up from 1.9999...., and so
1463 // the truncation resulted in 2.0000 when we wanted 1.9999
1464
1465 // The solution: Throw away digits on the right to make sure there
1466 // are no more than 33 significant digits.
1467
1468 bool isneg = value < 0;
1469 if(isneg)
1470 {
1471 value = -value;
1472 }
1473
1474 static __int128 ten33 = __gg__power_of_ten(33);
1475
1476 while( value >= ten33 )
1477 {
1478 // Lop off the rightmost digits until the result has no more than
1479 // 33 digits.
1480 value /= 10;
1481 source_rdigits -= 1;
1482 }
1483
1484 if(isneg)
1485 {
1486 value = -value;
1487 }
1488 GCOB_FP128 tvalue = (GCOB_FP128 )value;
1489 tvalue /= (GCOB_FP128 )__gg__power_of_ten(source_rdigits);
1490 // *(_Float128 *)location = tvalue;
1491 // memcpy because *(_Float128 *) requires a 16-byte boundary.
1492 memcpy(location, &tvalue, 16);
1493 break;
1494 }
1495 }
1496 break;
1497 }
1498
1499 default:
1500 {
1501 int target_rdigits = var->rdigits;
1502 if( var->attr & intermediate_e && var->type == FldNumericBin5)
1503 {
1504 // The target is an intermediate, meaning that we want to
1505 // Make sure our intermediate target has just enough digits and rdigits
1506 // to hold the value we've been given:
1507 target_rdigits = source_rdigits;
1508 var->rdigits = target_rdigits;
1509 var->digits = MAX_FIXED_POINT_DIGITS;
1510 }
1511 else if( var->attr & scaled_e )
1512 {
1513 // Our target is scaled. No matter which way we are going, the result
1514 // going into memory has no decimal places.
1515 target_rdigits = 0;
1516
1517 // We have some additional scaling of value to do to make things line up.
1518
1519 if( var->rdigits >= 0 )
1520 {
1521 // Our target is something like PPPPPP999, meaning that var->actual_length
1522 // is 3, and var->rdigits is 6.
1523
1524 // By rights, our caller should have given us something like 123 with
1525 // source_rdigits of 9. So, we multiply by 10**9 to put the 123 just
1526 // to the left of the decimal point, so that they line up with the
1527 // target_rdigits of zero we are targeting:
1528 source_rdigits -= var->digits + var->rdigits;
1529 if(source_rdigits < 0)
1530 {
1531 // We overshot
1532 value *= __gg__power_of_ten(-source_rdigits);
1533 source_rdigits = 0;
1534 }
1535 }
1536 else
1537 {
1538 // Our target is something like 999PPPPPP, so there is a ->digits
1539 // of 3 and var->rdigits of -6.
1540
1541 // If our caller gave us 123000000, we need to effectively divide
1542 // it by 1000000 to line up the 123 with where we want it to go:
1543
1544 source_rdigits += (-var->rdigits);
1545 }
1546 // Either way, we now have everything aligned for the remainder of the
1547 // processing to work:
1548 }
1549
1550 // Convert the scale of value to match the scale of var
1551 if( source_rdigits < target_rdigits )
1552 {
1553 // The source (value), has fewer rdigits than the target (var)
1554
1555 // Multiply value by ten until the source_rdigits matches the
1556 // target_rdigits. No rounding will be necessary
1557 value *= __gg__power_of_ten(target_rdigits - source_rdigits);
1558 source_rdigits = target_rdigits;
1559 }
1560
1561 if( source_rdigits > target_rdigits )
1562 {
1563 // The source(value) has more rdigits than the target (var)
1564
1565 // Extract those extra digits; we'll need them for rounding:
1566 __int128 factor = __gg__power_of_ten(source_rdigits - target_rdigits);
1567
1568 __int128 remainder = value % factor;
1569 value /= factor;
1570 source_rdigits = target_rdigits;
1571
1572 value = int128_to_int128_rounded( rounded,
1573 value,
1574 factor,
1575 remainder,
1576 compute_error);
1577 }
1578
1579 // The documentation for ROUNDED MODE PHOHIBITED says that if the value
1580 // doesn't fit into the target, "...the content of the resultant
1581 // identifier is unchanged"
1582
1583 if( compute_error && *compute_error && rounded == prohibited_e )
1584 {
1585 // This is the case where we are not supposed to do anything
1586 }
1587 else
1588 {
1589 // Value is now scaled to the target's target_rdigits
1590 bool size_error = false;
1591
1592 int is_negative = value < 0 ;
1593
1594 if( !(var->attr & signable_e) && is_negative )
1595 {
1596 if(false)
1597 {
1598 // I believe the COBOL spec allows for throwing INCOMPATIBLE-DATA
1599 // errors. <sound effect: can being kicked down road>
1600 printf( "runtime exception: assigning negative "
1601 "value to unsigned variable %s\n",
1602 var->name);
1603 }
1604 // Take the absolute value of value
1605 value = -value;
1606 is_negative = false;
1607 }
1608
1609 // And now we put value where it belongs
1610 switch( var->type )
1611 {
1612 case FldGroup:
1613 case FldAlphanumeric:
1614 // This is sort of a Hail Mary play. We aren't supposed to do this
1615 // conversion if rdigits is non-zero. But we shouldn't have gotten
1616 // here if rdigits is non-zero. So, we'll just go with the flow.
1617
1618 // Note that sending a signed value to an alphanumeric strips off
1619 // any plus or minus signs.
1620 size_error = __gg__binary_to_string_internal(
1621 PTRCAST(char, location),
1622 length, value);
1623 break;
1624
1625 case FldNumericDisplay:
1626 if( var->attr & signable_e )
1627 {
1628 // Things get exciting when a numeric-display value is signable
1629
1630 if( var->attr & separate_e )
1631 {
1632 // Whether positive or negative, a sign there will be:
1633 char sign_ch = is_negative ? internal_minus : internal_plus ;
1634 if( var->attr & leading_e )
1635 {
1636 // The sign character goes into the first location
1637 size_error =
1638 __gg__binary_to_string_internal(PTRCAST(char, location+1),
1639 length-1, value);
1640 location[0] = sign_ch;
1641 }
1642 else
1643 {
1644 // The sign character goes into the last location
1645 size_error =
1646 __gg__binary_to_string_internal(PTRCAST(char, location),
1647 length-1, value);
1648 location[length-1] = sign_ch;
1649 }
1650 }
1651 else
1652 {
1653 // The sign information is not separate, so we put it into
1654 // the number
1655 size_error =
1656 __gg__binary_to_string_internal(PTRCAST(char, location),
1657 length, value);
1658
1659 if( size_error && is_negative )
1660 {
1661 // If all of the digits are zero, then the result is zero, and
1662 // we have to kill the is_negative flag:
1663 is_negative = false;
1664 for(size_t i=0; i<length; i++)
1665 {
1666 if( location[i] != internal_zero )
1667 {
1668 is_negative = true;
1669 break;
1670 }
1671 }
1672 }
1673
1674 if( is_negative )
1675 {
1676 if( var->attr & leading_e )
1677 {
1678 // The sign bit goes into the first digit:
1679 turn_sign_bit_on(&location[0]);
1680 }
1681 else
1682 {
1683 // The sign bit goes into the last digit:
1684 turn_sign_bit_on(&location[length-1]);
1685 }
1686 }
1687 }
1688 }
1689 else
1690 {
1691 // It's a simple positive number
1692 size_error = __gg__binary_to_string_internal( PTRCAST(char,
1693 location),
1694 length, value);
1695 }
1696
1697 break;
1698
1699 case FldNumericEdited:
1700 {
1701 if( value == 0 && (var->attr & blank_zero_e) )
1702 {
1703 memset(location, internal_space, length);
1704 }
1705 else
1706 {
1707 char ach[512];
1708
1709 // At this point, value is scaled to the target's rdigits
1710
1711 size_error = __gg__binary_to_string(ach, var->digits, value);
1712 ach[var->digits] = NULLCH;
1713
1714 // Convert that string according to the PICTURE clause
1715 size_error |= __gg__string_to_numeric_edited(
1716 PTRCAST(char, location),
1717 ach,
1718 target_rdigits,
1719 is_negative,
1720 var->picture);
1721 ascii_to_internal_str( PTRCAST(char, location), var->capacity);
1722 }
1723
1724 break;
1725 }
1726
1727 case FldNumericBinary:
1728 binary_to_big_endian( location,
1729 length,
1730 value);
1731 size_error = value_is_too_big(var, value, source_rdigits);
1732 break;
1733
1734 case FldNumericBin5:
1735 case FldIndex:
1736 case FldLiteralN:
1737 case FldPointer:
1738 // Weirdly, this might be a figurative constant, hopefully usually
1739 // ZERO. Everything but HIGH-VALUE will end up zero. HIGH-VALUE
1740 // will become one, but it is, apparently harmless. The HIGH-VALUE
1741 // must get processed separately elsewhere. As the author, it would
1742 // be nice if I knew -- but I don't.
1743 binary_to_little_endian(location,
1744 length,
1745 value);
1746 size_error = value_is_too_big(var, value, source_rdigits);
1747 break;
1748
1749 case FldAlphaEdited:
1750 {
1751 char ach[128];
1752 size_error = __gg__binary_to_string(ach, length, value);
1753 ach[length] = NULLCH;
1754
1755 // Convert that string according to the PICTURE clause
1756 __gg__string_to_alpha_edited(
1757 PTRCAST(char, location),
1758 ach,
1759 strlen(ach),
1760 var->picture);
1761 break;
1762 }
1763
1764 case FldPacked:
1765 {
1766 static const unsigned char bin2pd[100] =
1767 {
1768 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
1769 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
1770 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
1771 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
1772 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
1773 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
1774 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
1775 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
1776 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
1777 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
1778 } ;
1779
1780 // Convert the binary value to packed decimal.
1781
1782 // Set the destination bytes to zero
1783 memset(location, 0, length);
1784 unsigned char sign_nybble = 0;
1785 if( !(var->attr & packed_no_sign_e) )
1786 {
1787 // This is COMP-3 packed decimal, so we need to make room to the
1788 // right of the final decimal digit for the sign nybble:
1789 value *= 10;
1790 // Figure out what the sign nybble is going to be, and make the
1791 // the value positive:
1792 if(var->attr & signable_e)
1793 {
1794 if(value < 0)
1795 {
1796 sign_nybble = 0x0D;
1797 value = -value;
1798 }
1799 else
1800 {
1801 sign_nybble = 0x0C;
1802 }
1803 }
1804 else
1805 {
1806 sign_nybble = 0x0F;
1807 if(value < 0)
1808 {
1809 value = -value;
1810 }
1811 }
1812 }
1813 // ploc points to the current rightmost byte of the location:
1814 unsigned char *ploc = location + length -1 ;
1815
1816 // Build the target from right to left, so that the result is
1817 // big-endian:
1818 while( value && ploc >= location )
1819 {
1820 *ploc-- = bin2pd[value%100];
1821 value /= 100;
1822 }
1823
1824 // We can put the sign nybble into place at this point. Note that
1825 // for COMP-6 numbers the sign_nybble value is zero, so the next
1826 // operation is harmless.
1827 location[length -1] |= sign_nybble;
1828
1829 // If we still have value left, we have a size error
1830 if( value )
1831 {
1832 size_error = true;
1833 }
1834 else
1835 {
1836 if( ( sign_nybble && !(var->digits&1) )
1837 || ( !sign_nybble && (var->digits&1) ) )
1838 {
1839 // This is either
1840 // comp-3 with an even number of digits, or
1841 // comp-6 with an odd number of digits.
1842 // Either way, the first byte of the target has to have a high
1843 // nybble of zero. If it's non-zero, then we have a size error:
1844 if( location[0] & 0xF0 )
1845 {
1846 size_error = true;
1847 }
1848 }
1849 }
1850 // And we're done.
1851 break;
1852 }
1853
1854 default:
1855 fprintf(stderr, "can't convert in %s() %s %d\n",
1856 __func__,
1857 var->name,
1858 var->type);
1859 abort();
1860 break;
1861 }
1862 if( compute_error )
1863 {
1864 *compute_error |= size_error ? compute_error_truncate : 0;
1865 }
1866 }
1867 }
1868 break;
1869 }
1870 }
1871
1872 static __int128
1873 edited_to_binary( char *ps_,
1874 int length,
1875 int *rdigits)
1876 {
1877 const unsigned char *ps = const_cast<const unsigned char *>(PTRCAST(unsigned char, ps_));
1878 // This routine is used for converting NumericEdited strings to
1879 // binary.
1880
1881 // Numeric edited strings can have all kinds of crap in them: spaces,
1882 // slashes, dollar signs...you name it. It might have a minus sign at
1883 // the beginning or end, or it might have CR or DB at the end.
1884
1885 // We are going to look for a minus sign, D (or d) and use that to flag the
1886 // result as negative. We are going to look for a decimal point and count up
1887 // the numerical digits to the right of it. And we are going to pretend
1888 // that nothing else matters.
1889
1890 int hyphen = 0;
1891 *rdigits = 0;
1892
1893 // index into the ps string
1894 int index = 0;
1895
1896 // Create a delta_r for counting digits to the right of
1897 // any decimal point. If and when we encounter a decimal point,
1898 // we'll set this to one, otherwise it'll stay zero.
1899 int delta_r = 0;
1900
1901 __int128 result = 0;
1902
1903 // We need to check the last two characters. If CR or DB, then the result
1904 // is negative:
1905 if( length >= 2)
1906 {
1907 if(((ps[length-2]&0xFF) == internal_D || (ps[length-2]&0xFF) == internal_d )
1908 &&((ps[length-1]&0xFF) == internal_B || (ps[length-1]&0xFF) == internal_b))
1909 {
1910 hyphen = 1;
1911 }
1912 else if( ((ps[length-2]&0xFF) == internal_C
1913 || (ps[length-2]&0xFF) == internal_c)
1914 && ((ps[length-1]&0xFF) == internal_R
1915 || (ps[length-1]&0xFF) == internal_r) )
1916 {
1917 hyphen = 1;
1918 }
1919 }
1920
1921 while( index < length )
1922 {
1923 unsigned char ch = ps[index++] & 0xFF;
1924 if( ch == ascii_to_internal(__gg__decimal_point) )
1925 {
1926 delta_r = 1;
1927 continue;
1928 }
1929 if( ch == internal_minus )
1930 {
1931 hyphen = 1;
1932 continue;
1933 }
1934
1935 if( internal_0 <= ch && ch <= internal_9 )
1936 {
1937 result *= 10;
1938 // In both EBCDIC and ASCII, this works:
1939 result += ch & 0x0F ;
1940 *rdigits += delta_r ;
1941 continue;
1942 }
1943 }
1944
1945 if( hyphen )
1946 {
1947 result = -result;
1948 }
1949 return result;
1950 }
1951
1952 static
1953 __int128
1954 big_endian_to_binary_signed(
1955 const unsigned char *psource,
1956 int capacity
1957 )
1958 {
1959 // This subroutine takes a big-endian value of "capacity" bytes and
1960 // converts it to a signed INT128. The highest order bit of the big-endian
1961 // value determines whether or not the highest-order bits of the INT128
1962 // return value are off or on.
1963
1964 __int128 retval;
1965 if( *psource >= 128 )
1966 {
1967 retval = -1;
1968 }
1969 else
1970 {
1971 retval = 0;
1972 }
1973
1974 // move the bytes of psource into retval, flipping them end-to-end
1975 unsigned char *dest = PTRCAST(unsigned char, &retval);
1976 while(capacity > 0)
1977 {
1978 *dest++ = psource[--capacity];
1979 }
1980 return retval;
1981 }
1982
1983 static
1984 __int128
1985 little_endian_to_binary_signed(
1986 const unsigned char *psource,
1987 int capacity
1988 )
1989 {
1990 // This subroutine takes a little-endian value of "capacity" bytes and
1991 // converts it to a signed INT128. The highest order bit of the little-endian
1992 // value determines whether or not the highest-order bits of the INT128
1993 // return value are off or on.
1994
1995 __int128 result;
1996
1997 // Set all the bits of the result based on the sign of the source:
1998 if( psource[capacity-1] >= 128 )
1999 {
2000 result = -1;
2001 }
2002 else
2003 {
2004 result = 0;
2005 }
2006
2007 // Copy the low-order bytes into place:
2008 memcpy(&result, psource, capacity);
2009 return result;
2010 }
2011
2012 static
2013 __int128
2014 little_endian_to_binary_unsigned(
2015 const unsigned char *psource,
2016 int capacity
2017 )
2018 {
2019 __int128 result = 0;
2020
2021 // Copy the low-order bytes into place:
2022 memcpy(&result, psource, capacity);
2023 return result;
2024 }
2025
2026 static
2027 __int128
2028 big_endian_to_binary_unsigned(
2029 const unsigned char *psource,
2030 int capacity
2031 )
2032 {
2033 // This subroutine takes an unsigned big-endian value of "capacity" bytes and
2034 // converts it to an INT128.
2035
2036 __int128 retval = 0 ;
2037
2038 // move the bytes of psource into retval, flipping them end-to-end
2039 unsigned char *dest = PTRCAST(unsigned char, &retval);
2040 while(capacity > 0)
2041 {
2042 *dest++ = psource[--capacity];
2043 }
2044 return retval;
2045 }
2046
2047 static
2048 __int128
2049 get_binary_value_local( int *rdigits,
2050 const cblc_field_t *resolved_var,
2051 unsigned char *resolved_location,
2052 size_t resolved_length)
2053 {
2054 __int128 retval = 0;
2055
2056 unsigned char ch;
2057 switch( resolved_var->type )
2058 {
2059 #if 1
2060 case FldLiteralA :
2061 fprintf(stderr, "%s(): is trying to handle a FldLiteralA\n", __func__);
2062 abort();
2063 // // Read the data area as a dirty string:
2064 // retval = __gg__dirty_to_binary_internal( (const char *)resolved_location,
2065 // resolved_length,
2066 // rdigits );
2067 break;
2068 #endif
2069
2070 case FldGroup :
2071 case FldAlphanumeric :
2072 // Read the data area as a dirty string:
2073 retval = __gg__dirty_to_binary_internal( PTRCAST(const char,
2074 resolved_location),
2075 resolved_length,
2076 rdigits );
2077 break;
2078
2079 case FldNumericDisplay :
2080 if( resolved_location[resolved_length-1] == DEGENERATE_HIGH_VALUE )
2081 {
2082 // This is a degenerate case, which violates the language
2083 // specification, but nonetheless seems to be a thing. By
2084 // default, HIGH-VALUE is usually assumed to be 0xFF. This is
2085 // not necessarily true; HIGH-VALUE can be changed by the
2086 // SPECIAL-NAMES ALPHABET clause. Furthermore, by definition,
2087 // HIGH-VALUE applies *only* to text literals. However, there
2088 // seems to be code out in the universe that wants to be able
2089 // to compare NumericDisplay values that have been set to
2090 // HIGH-VALUE. Consider, for example, code that reads from
2091 // a disk file which sets the input field to HIGH-VALUE upon
2092 // an end-of-file condition.
2093
2094 // This code detects that particular condition, and sets the
2095 // resulting binary number to the maximum possible positive
2096 // value.
2097
2098 // Turn all the bits on
2099 memset( &retval, 0xFF, sizeof(retval) );
2100
2101 // Make it positive by turning off the highest order bit:
2102 (PTRCAST(unsigned char, &retval))[sizeof(retval)-1] = 0x3F;
2103 *rdigits = resolved_var->rdigits;
2104 }
2105 else
2106 {
2107 // Pick up the sign byte, and force our value to be positive
2108 unsigned char *sign_byte_location;
2109 if( (resolved_var->attr & separate_e )
2110 && (resolved_var->attr & leading_e ) )
2111 {
2112 sign_byte_location = resolved_location;
2113 ch = *sign_byte_location;
2114 *sign_byte_location = internal_plus;
2115 }
2116 else if( (resolved_var->attr & separate_e)
2117 && !(resolved_var->attr & leading_e ) )
2118 {
2119 sign_byte_location = resolved_location + resolved_length - 1;
2120 ch = *sign_byte_location;
2121 *sign_byte_location = internal_plus;
2122 }
2123 else if( (resolved_var->attr & leading_e) )
2124 {
2125 sign_byte_location = resolved_location;
2126 ch = *sign_byte_location;
2127 turn_sign_bit_off(sign_byte_location);
2128 }
2129 else // if( !(resolved_var->attr & leading_e) )
2130 {
2131 sign_byte_location = resolved_location + resolved_length - 1;
2132 ch = *sign_byte_location;
2133 turn_sign_bit_off(sign_byte_location);
2134 }
2135
2136 // We know where the decimal point is because of rdigits. Because
2137 // we know that it a clean string of ASCII digits, we can use the
2138 // dirty converter:
2139 retval = __gg__dirty_to_binary_internal(PTRCAST(const char,
2140 resolved_location),
2141 resolved_length,
2142 rdigits );
2143 *rdigits = resolved_var->rdigits;
2144
2145 // Restore the sign byte
2146 *sign_byte_location = ch;
2147
2148 if( ch == internal_minus || is_sign_bit_on(ch) )
2149 {
2150 retval = -retval;
2151 }
2152 }
2153 break;
2154
2155 case FldNumericEdited :
2156 retval = edited_to_binary( PTRCAST(char, resolved_location),
2157 resolved_length,
2158 rdigits);
2159 break;
2160
2161 case FldNumericBinary :
2162 if( resolved_var->attr & signable_e)
2163 {
2164 retval = big_endian_to_binary_signed(
2165 PTRCAST(const unsigned char, resolved_location),
2166 resolved_length);
2167 }
2168 else
2169 {
2170 retval = big_endian_to_binary_unsigned(
2171 PTRCAST(const unsigned char, resolved_location),
2172 resolved_length);
2173 }
2174 *rdigits = resolved_var->rdigits;
2175 break;
2176
2177 case FldLiteralN:
2178 {
2179 if( resolved_var->attr & signable_e)
2180 {
2181 retval = little_endian_to_binary_signed(resolved_var->data,
2182 resolved_var->capacity);
2183 }
2184 else
2185 {
2186 retval = little_endian_to_binary_unsigned(resolved_var->data,
2187 resolved_var->capacity);
2188 }
2189 *rdigits = resolved_var->rdigits;
2190 break;
2191 }
2192
2193 case FldNumericBin5:
2194 case FldIndex:
2195 case FldPointer:
2196 if( resolved_var->attr & signable_e)
2197 {
2198 retval = little_endian_to_binary_signed(
2199 PTRCAST(const unsigned char, resolved_location),
2200 resolved_length);
2201 }
2202 else
2203 {
2204 retval = little_endian_to_binary_unsigned(
2205 PTRCAST(const unsigned char, resolved_location),
2206 resolved_length);
2207 }
2208 *rdigits = resolved_var->rdigits;
2209 break;
2210
2211 case FldPacked:
2212 {
2213 static const unsigned char dp2bin[160] =
2214 {
2215 // This may not be the weirdest table I've ever created, but it is
2216 // certainly a contender. Given the packed decimal byte 0x23, it
2217 // returns the equivalent decimal value of 23.
2218 00, 01, 02, 03, 04, 05, 06, 07, 8, 9, 0, 0, 0, 0, 0, 0, // 0x00
2219 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 0, 0, 0, 0, 0, // 0x10
2220 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 0, 0, 0, 0, 0, 0, // 0x20
2221 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 0, 0, 0, 0, 0, // 0x30
2222 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 0, 0, 0, 0, 0, 0, // 0x40
2223 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 0, 0, 0, 0, 0, 0, // 0x50
2224 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 0, 0, 0, 0, 0, 0, // 0x60
2225 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 0, 0, 0, 0, 0, 0, // 0x70
2226 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 0, 0, 0, 0, 0, 0, // 0x80
2227 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 0, 0, 0, 0, 0, // 0x90
2228 };
2229
2230 if( resolved_var->attr & packed_no_sign_e )
2231 {
2232 // This is packed decimal without a sign nybble
2233 retval = 0;
2234 for(size_t i=0; i<resolved_var->capacity; i++)
2235 {
2236 retval *= 100;
2237 retval += dp2bin[resolved_location[i]];
2238 }
2239 }
2240 else
2241 {
2242 // This is packed decimal with a final sign nybble
2243 retval = 0;
2244 size_t imputed_length = (resolved_var->digits + 2)/2;
2245 for(size_t i=0; i<imputed_length-1; i++)
2246 {
2247 retval *= 100;
2248 retval += dp2bin[resolved_location[i]];
2249 }
2250 retval *= 10;
2251 retval += resolved_location[imputed_length-1]>>4;
2252 if( (resolved_location[imputed_length-1]&0x0F) == 0x0D
2253 || (resolved_location[imputed_length-1]&0x0F) == 0x0B )
2254 {
2255 retval = -retval;
2256 }
2257 }
2258 *rdigits = resolved_var->rdigits;
2259 break;
2260 }
2261 }
2262
2263 if( resolved_var->attr & scaled_e )
2264 {
2265 // Here's where we handle a P-scaled number.
2266
2267 if( resolved_var->rdigits >= 0)
2268 {
2269 // We might be dealing with a source with a PICTURE string of
2270 // PPPPPP999, which means retval is a three-digit number
2271 // and resolved_var->rdigits is +6. That means we need to divide retval
2272 // by 10**9, and we need to make rdigits 9
2273 *rdigits = resolved_var->digits + resolved_var->rdigits;
2274 }
2275 else
2276 {
2277 // We have a source with a PIC string like 999PPPPPP, which is
2278 // a capacity of 3 and a resolved_var->rdigits of -6. We need to multiply
2279 // retval by +6, and make rdigits zero:
2280 retval *= __gg__power_of_ten( -resolved_var->rdigits );
2281 *rdigits = 0;
2282 }
2283 }
2284
2285 return retval;
2286 }
2287
2288 #pragma GCC diagnostic ignored "-Wformat-overflow"
2289
2290 static time_t
2291 cobol_time()
2292 {
2293 struct cbl_timespec tp;
2294 __gg__clock_gettime(&tp);
2295 return tp.tv_sec;
2296 }
2297
2298 extern "C"
2299 char *
2300 __gg__get_date_yymmdd()
2301 {
2302 char ach[32];
2303
2304 time_t t = cobol_time();
2305 const struct tm *local = localtime(&t);
2306
2307 sprintf(ach,
2308 "%2.2d%2.2d%2.2d",
2309 local->tm_year % 100,
2310 local->tm_mon+1 % 100,
2311 local->tm_mday % 100 );
2312
2313 ascii_to_internal_str(ach, strlen(ach));
2314 return strdup(ach);
2315 }
2316
2317 extern "C"
2318 char *
2319 __gg__get_date_yyyymmdd()
2320 {
2321 char ach[32];
2322
2323 time_t t = cobol_time();
2324 const struct tm *local = localtime(&t);
2325
2326 sprintf(ach,
2327 "%4.4d%2.2d%2.2d",
2328 local->tm_year + 1900,
2329 local->tm_mon+1,
2330 local->tm_mday);
2331
2332 ascii_to_internal_str(ach, strlen(ach));
2333 return strdup(ach);
2334 }
2335
2336 extern "C"
2337 char *
2338 __gg__get_date_yyddd()
2339 {
2340 char ach[32];
2341
2342 time_t t = cobol_time();
2343 const struct tm *local = localtime(&t);
2344
2345 sprintf(ach,
2346 "%2.2d%3.3d",
2347 local->tm_year % 100,
2348 local->tm_yday+1);
2349
2350 ascii_to_internal_str(ach, strlen(ach));
2351 return strdup(ach);
2352 }
2353
2354 extern "C"
2355 char *
2356 __gg__get_yyyyddd()
2357 {
2358 char ach[32];
2359
2360 time_t t = cobol_time();
2361 const struct tm *local = localtime(&t);
2362
2363 sprintf(ach,
2364 "%4.4d%3.3d",
2365 local->tm_year + 1900,
2366 local->tm_yday+1);
2367
2368 ascii_to_internal_str(ach, strlen(ach));
2369 return strdup(ach);
2370 }
2371
2372 extern "C"
2373 char *
2374 __gg__get_date_dow()
2375 {
2376 char ach[32];
2377
2378 time_t t = cobol_time();
2379 const struct tm *local = localtime(&t);
2380
2381 sprintf(ach,
2382 "%1.1d",
2383 local->tm_wday == 0 ? 7 : local->tm_wday);
2384
2385 ascii_to_internal_str(ach, strlen(ach));
2386 return strdup(ach);
2387 }
2388
2389 static int
2390 int_from_digits(const char * &p, int ndigits)
2391 {
2392 int retval = 0;
2393 while( p && ndigits )
2394 {
2395 char ch = *p++;
2396 if( isdigit(ch) )
2397 {
2398 retval *= 10;
2399 retval += (ch & 0xF);
2400 ndigits -= 1;
2401 }
2402 }
2403 return retval;
2404 }
2405
2406 // For testing purposes, this undef causes the use of gettimeofday().
2407 // #undef HAVE_CLOCK_GETTIME
2408
2409 static uint64_t
2410 get_time_nanoseconds_local()
2411 {
2412 // This code was unabashedly stolen from gcc/timevar.cc.
2413 // It returns the Unix epoch with nine decimal places.
2414
2415 /* Note: I am perplexed. I have been examining the gcc Makefiles and
2416 configure.ac files, and I am unable to locate where HAVE_GETTIMEOFDAY
2417 is established. There have been issues compiling on MacOS, where
2418 apparently clock_gettime() is not available. But I don't see exactly
2419 how gettimeofday() gets used, instead. But without the ability to
2420 compile on a MacOS system, I am fumbling along as best I can.
2421
2422 I decided to simply replace clock_gettime() with getttimeofday() when
2423 clock_gettime() isn't available, even though gcc/timevar.cc handles
2424 the situation differently.
2425
2426 -- Bob Dubner, 2025-06-11*/
2427
2428 uint64_t retval = 0;
2429
2430 #ifdef HAVE_CLOCK_GETTIME
2431 struct timespec ts;
2432 clock_gettime (CLOCK_REALTIME, &ts);
2433 retval = ts.tv_sec * 1000000000 + ts.tv_nsec;
2434 return retval;
2435 //#endif
2436 //#ifdef HAVE_GETTIMEOFDAY
2437 #else
2438 struct timeval tv;
2439 gettimeofday (&tv, NULL);
2440 retval = tv.tv_sec * 1000000000 + tv.tv_usec * 1000;
2441 return retval;
2442 #endif
2443 return retval;
2444 }
2445
2446 extern "C"
2447 void
2448 __gg__clock_gettime(struct cbl_timespec *tp)
2449 {
2450 const char *p = getenv("GCOBOL_CURRENT_DATE");
2451
2452 if( p )
2453 {
2454 time_t t;
2455 time (&t);
2456 struct tm tm;
2457
2458 memset(&tm, 0, sizeof(tm));
2459 localtime_r(&t, &tm); // This sets tm_isdst for the local time
2460
2461 tm.tm_year = int_from_digits(p, 4) - 1900;
2462 tm.tm_mon = int_from_digits(p, 2) - 1;
2463 tm.tm_mday = int_from_digits(p, 2);
2464 tm.tm_hour = int_from_digits(p, 2);
2465 tm.tm_min = int_from_digits(p, 2);
2466 tm.tm_sec = int_from_digits(p, 2);
2467
2468 tm.tm_isdst = 0;
2469 tp->tv_sec = mktime(&tm);
2470 tp->tv_nsec = 0;
2471 if( tm.tm_isdst )
2472 {
2473 tp->tv_sec -= 3600;
2474 }
2475 }
2476 else
2477 {
2478 uint64_t ns = get_time_nanoseconds_local();
2479 tp->tv_sec = ns/1000000000;
2480 tp->tv_nsec = ns%1000000000;
2481 }
2482 }
2483
2484 extern "C"
2485 char *
2486 __gg__get_date_hhmmssff()
2487 {
2488 char ach[32];
2489
2490 struct cbl_timespec tv;
2491 __gg__clock_gettime(&tv);
2492
2493 struct tm tm;
2494 localtime_r(&tv.tv_sec, &tm);
2495
2496 // // This routine returns local time:
2497 // int day_frac = (tv.tv_sec - timezone) % 86400;
2498
2499 // int hour = (day_frac / 3600);
2500 // int minute = (day_frac%3600) / 60;
2501 // int second = (day_frac % 60);
2502 int hundredths = tv.tv_nsec/10000000;
2503
2504 sprintf(ach,
2505 "%2.2d%2.2d%2.2d%2.2d",
2506 tm.tm_hour,
2507 tm.tm_min,
2508 tm.tm_sec,
2509 hundredths);
2510
2511 ascii_to_internal_str(ach, strlen(ach));
2512 return strdup(ach);
2513 }
2514
2515 extern "C"
2516 int
2517 __gg__setop_compare(
2518 const char *candidate,
2519 int capacity,
2520 char *domain)
2521 {
2522 // This routine is called to compare the characters of 'candidate'
2523 // against the list of character pairs in 'domain'
2524
2525 int retval = 0;
2526 int l;
2527 int h;
2528 char *d;
2529
2530 for(int i=0; i<capacity; i++)
2531 {
2532 int ch = (*candidate++ & 0xFF);
2533 d = domain;
2534 while(*d)
2535 {
2536 retval = 0;
2537 // We are decoding hexadecimal numbers, either in pairs,
2538 // or singletons: "20/30 " or "20 ". The final one is
2539 // terminated with '\0'
2540
2541 // See the comments in genapi.cc::get_class_condition_string
2542 // to see how this string was encoded.
2543
2544 l = (int)strtoll(d, reinterpret_cast<char **>(&d), 16);
2545 if( l < 0 )
2546 {
2547 l = -l;
2548 }
2549 h = l;
2550 if( *d == '/' )
2551 {
2552 d += 1;
2553 h = (int)strtoll(d, reinterpret_cast<char **>(&d), 16);
2554 if( h < 0 )
2555 {
2556 h = -h;
2557 }
2558 }
2559 else if( *d == ' ' )
2560 {
2561 d += 1;
2562 }
2563 if( ch >= l && ch <= h )
2564 {
2565 // This character is acceptable
2566 retval = 1;
2567 break;
2568 }
2569 }
2570
2571 // We checked the entire list of pairs for the candidate character
2572 if( retval == 0 )
2573 {
2574 // This candidate character failed, so we don't need to check
2575 // the rest of the candidates
2576 break;
2577 }
2578 }
2579
2580 return retval;
2581 }
2582
2583 extern "C"
2584 __int128
2585 __gg__dirty_to_binary_source(const char *dirty,
2586 int length,
2587 int *rdigits)
2588 {
2589 // This routine is used for converting uncontrolled strings to a
2590 // a 128-bit signed binary number.
2591
2592 // The string can start with a plus or minus
2593 // It can contain a single embedded dot
2594 // The rest of the characters have to be [0-9]
2595 // Any other character, including a second dot, ends processing.
2596
2597 // So, a "1ABC" will yield 1; "ABC" will yield 0.
2598
2599 // It takes pointers to "s_hyphen" and "s_rdigits" so that it can
2600 // report what it saw.
2601
2602 // It returns the binary result. So, 1031.2 returns 10312 and s_rdigits=1
2603
2604 // The binary number, if signed, is returned as a negative number.
2605
2606 __int128 retval = 0;
2607
2608 int hyphen = 0;
2609 *rdigits = 0;
2610
2611 // Create a delta_r for counting digits to the right of
2612 // any decimal point. If and when we encounter a decimal separator,
2613 // we'll set this to one, otherwise it'll stay zero.
2614 int delta_r = 0;
2615
2616 // We now loop over the remaining input characters:
2617 while( length-- >0 )
2618 {
2619 char ch = *dirty++;
2620
2621 if( ch == ascii_minus )
2622 {
2623 hyphen = 1;
2624 continue;
2625 }
2626 if( ch == ascii_plus )
2627 {
2628 continue;
2629 }
2630 if( ch == __gg__decimal_point && delta_r == 0 )
2631 {
2632 // This is the first decimal point we've seen, so we
2633 // can start counting rdigits:
2634 delta_r = 1;
2635 continue;
2636 }
2637 if( ch < ascii_0 || ch > ascii_9 )
2638 {
2639 // When we hit something that isn't a digit, then we are done
2640 break;
2641 }
2642 retval *= 10;
2643 retval += ch - ascii_0;
2644 *rdigits += delta_r;
2645 }
2646 if( !retval )
2647 {
2648 // Because the result is zero, there can't be a minus sign
2649 hyphen = 0;
2650 }
2651 if( hyphen )
2652 {
2653 // We saw a minus sign, so negate the result
2654 retval = -retval;
2655 }
2656 return retval;
2657 }
2658
2659 extern "C"
2660 __int128
2661 __gg__dirty_to_binary_internal( const char *dirty,
2662 int length,
2663 int *rdigits)
2664 {
2665 // This routine is used for converting uncontrolled strings to a
2666 // a 128-bit signed binary number.
2667
2668 // The string can start with a plus or minus
2669 // It can contain a single embedded dot
2670 // The rest of the characters have to be [0-9]
2671 // Any other character, including a second dot, ends processing.
2672
2673 // So, a "1ABC" will yield 1; "ABC" will yield 0.
2674
2675 // It also can handle 12345E-2 notation.
2676
2677 // It returns the binary result. So, 1031.2 returns 10312 and rdigits=1
2678
2679 // The binary number, if signed, is returned as a negative number.
2680
2681 // We are limiting the number of digits in the number to MAX_FIXED_POINT_DIGITS
2682
2683 __int128 retval = 0;
2684
2685 int digit_count = 0;
2686 int hyphen = 0;
2687 *rdigits = 0;
2688
2689 // Create a delta_r for counting digits to the right of
2690 // any decimal point. If and when we encounter a decimal separator,
2691 // we'll set this to one, otherwise it'll stay zero.
2692 int delta_r = 0;
2693
2694 // We now loop over the remaining input characters:
2695 unsigned char ch = '\0';
2696
2697 if(length-- > 0)
2698 {
2699 ch = *dirty++;
2700 if( ch == internal_minus )
2701 {
2702 hyphen = 1;
2703 }
2704 else if( ch == internal_plus )
2705 {
2706 // A plus sign is okay
2707 }
2708 else if( ch == ascii_to_internal(__gg__decimal_point) )
2709 {
2710 delta_r = 1;
2711 }
2712 else if( ch >= internal_0 && ch <= internal_9 )
2713 {
2714 retval = ch - internal_0 ;
2715 if( retval )
2716 {
2717 digit_count += 1;
2718 }
2719 }
2720 else
2721 {
2722 // Because didn't start with minus, plus, a decimal_place or a digit,
2723 // this isn't a number
2724 length = 0;
2725 ch = '\0';
2726 }
2727 }
2728
2729 while( length-- > 0 )
2730 {
2731 ch = *dirty++;
2732 if( ch == ascii_to_internal(__gg__decimal_point) && delta_r == 0 )
2733 {
2734 // This is the first decimal point we've seen, so we
2735 // can start counting rdigits:
2736 delta_r = 1;
2737 continue;
2738 }
2739 if( ch < internal_0 || ch > internal_9 )
2740 {
2741 // When we hit something that isn't a digit, then we are done
2742 break;
2743 }
2744 if( digit_count < MAX_FIXED_POINT_DIGITS )
2745 {
2746 retval *= 10;
2747 retval += ch - internal_0 ;
2748 *rdigits += delta_r;
2749 if( retval )
2750 {
2751 digit_count += 1;
2752 }
2753 }
2754 }
2755
2756 // Let's check for an exponent:
2757 if( ch == internal_E || ch == internal_e )
2758 {
2759 int exponent = 0;
2760 int exponent_sign = 1;
2761 if( length > 0 )
2762 {
2763 ch = *dirty;
2764 if( ch == internal_plus)
2765 {
2766 length -= 1;
2767 dirty += 1;
2768 }
2769 else if (ch == internal_minus)
2770 {
2771 exponent_sign = -1;
2772 length -= 1;
2773 dirty += 1;
2774 }
2775 }
2776 while(length-- > 0)
2777 {
2778 ch = *dirty++;
2779 if( ch < internal_0 || ch > internal_9 )
2780 {
2781 // When we hit something that isn't a digit, then we are done
2782 break;
2783 }
2784 exponent *= 10;
2785 exponent += ch - internal_0 ;
2786 }
2787 exponent *= exponent_sign;
2788 // We need to adjust the retval and the rdigits based on the exponent.
2789 if( exponent < 0)
2790 {
2791 *rdigits += -exponent;
2792 }
2793 else if(exponent > 0)
2794 {
2795 if( exponent <= *rdigits )
2796 {
2797 *rdigits -= exponent;
2798 }
2799 else
2800 {
2801 // Exponent is > rdigits
2802 retval *= __gg__power_of_ten(exponent - *rdigits);
2803 *rdigits = 0;
2804 }
2805 }
2806 }
2807
2808 if( !retval )
2809 {
2810 // Because the result is zero, there can't be a minus sign
2811 hyphen = 0;
2812 }
2813 if( hyphen )
2814 {
2815 // We saw a minus sign, so negate the result
2816 retval = -retval;
2817 }
2818 return retval;
2819 }
2820
2821 extern "C"
2822 GCOB_FP128
2823 __gg__dirty_to_float( const char *dirty,
2824 int length)
2825 {
2826 // This routine is used for converting uncontrolled strings to a
2827 // a _Float128
2828
2829 // The string can start with a plus or minus
2830 // It can contain a single embedded dot
2831 // The rest of the characters have to be [0-9]
2832 // Any other character, including a second dot, ends processing.
2833
2834 // So, a "1ABC" will yield 1; "ABC" will yield 0.
2835
2836 // It also can handle 12345E-2 notation.
2837
2838 GCOB_FP128 retval = 0;
2839
2840 int rdigits = 0;
2841 int hyphen = 0;
2842
2843 // Create a delta_r for counting digits to the right of
2844 // any decimal point. If and when we encounter a decimal separator,
2845 // we'll set this to one, otherwise it'll stay zero.
2846 int delta_r = 0;
2847
2848 // We now loop over the remaining input characters:
2849 char ch = '\0';
2850
2851 if(length-- > 0)
2852 {
2853 ch = *dirty++;
2854 if( ch == internal_minus )
2855 {
2856 hyphen = 1;
2857 }
2858 else if( ch == internal_plus )
2859 {
2860 // A plus sign is okay
2861 }
2862 else if( ch == ascii_to_internal(__gg__decimal_point) )
2863 {
2864 delta_r = 1;
2865 }
2866 else if( ch >= internal_0 && ch <= internal_9 )
2867 {
2868 retval = ch - internal_0 ;
2869 }
2870 else
2871 {
2872 // Because didn't start with minus, plus, a decimal_place or a digit,
2873 // this isn't a number. Set length to zero to prevent additional
2874 // processing
2875 length = 0;
2876 ch = '\0';
2877 }
2878 }
2879
2880 while( length-- > 0 )
2881 {
2882 ch = *dirty++;
2883 if( ch == ascii_to_internal(__gg__decimal_point) && delta_r == 0 )
2884 {
2885 // This is the first decimal point we've seen, so we
2886 // can start counting rdigits:
2887 delta_r = 1;
2888 continue;
2889 }
2890 if( ch < internal_0 || ch > internal_9 )
2891 {
2892 // When we hit something that isn't a digit, then we are done
2893 break;
2894 }
2895 retval *= 10;
2896 retval += ch - internal_0 ;
2897 rdigits += delta_r;
2898 }
2899
2900 // Let's check for an exponent:
2901 int exponent = 0;
2902 if( ch == internal_E || ch == internal_e )
2903 {
2904 int exponent_sign = 1;
2905 if( length > 0 )
2906 {
2907 ch = *dirty;
2908 if( ch == internal_plus)
2909 {
2910 length -= 1;
2911 dirty += 1;
2912 }
2913 else if (ch == internal_minus)
2914 {
2915 exponent_sign = -1;
2916 length -= 1;
2917 dirty += 1;
2918 }
2919 }
2920 while(length-- > 0)
2921 {
2922 ch = *dirty++;
2923 if( ch < internal_0 || ch > internal_9 )
2924 {
2925 // When we hit something that isn't a digit, then we are done
2926 break;
2927 }
2928 exponent *= 10;
2929 exponent += ch - internal_0 ;
2930 }
2931 exponent *= exponent_sign;
2932 }
2933
2934 // We need to adjust the retval based on rdigits and exponent.
2935 // Notice that 123.45E2 properly comes out to be 12345
2936 if( exponent - rdigits >= 0 )
2937 {
2938 retval *= __gg__power_of_ten(exponent - rdigits);
2939 }
2940 else
2941 {
2942 retval /= __gg__power_of_ten(rdigits - exponent);
2943 }
2944
2945 if( !retval )
2946 {
2947 // Because the result is zero, there can't be a minus sign
2948 hyphen = 0;
2949 }
2950 if( hyphen )
2951 {
2952 // We saw a minus sign, so negate the result
2953 retval = -retval;
2954 }
2955 return retval;
2956 }
2957
2958 extern "C"
2959 __int128
2960 __gg__get_integer_binary_value(cblc_field_t *var)
2961 {
2962 // This routine is called when a rounded integer is needed
2963
2964 __int128 retval;
2965
2966 int rdigits;
2967
2968 retval = __gg__binary_value_from_field(&rdigits, var);
2969
2970 while( rdigits-- > 1)
2971 {
2972 retval /= 10;
2973 }
2974
2975 if( rdigits-- == 1)
2976 {
2977 if( retval < 0 )
2978 {
2979 retval -= 5;
2980 }
2981 else
2982 {
2983 retval += 5;
2984 }
2985 retval /= 10;
2986 }
2987
2988 return retval;
2989 }
2990
2991 static
2992 void psz_to_internal(char *psz)
2993 {
2994 char *p = psz;
2995 while( *p )
2996 {
2997 *p = ascii_to_internal(*p);
2998 p += 1;
2999 }
3000 }
3001
3002 static int
3003 get_scaled_rdigits(const cblc_field_t *field)
3004 {
3005 int retval;
3006 if( !(field->attr & scaled_e) )
3007 {
3008 // The value is not P-scaled, so we just use the unchanged rdigits value
3009 retval = field->rdigits;
3010 }
3011 else
3012 {
3013 if( field->rdigits < 0 )
3014 {
3015 // The PIC string was something like 999PPPP, which means an rdigits value
3016 // of -4. We return zero; somebody else will have the job of multiplying
3017 // the three significant digits by 10^4 to get the magnitude correct.
3018 retval = 0;
3019 }
3020 else
3021 {
3022 // The PIC string was something like PPPP999, which means an rdigits value
3023 // of +4. We return an rdigits value of 4 + 3 = 7, which will mean that
3024 // the three significant digits will be scaled to 0.0000999
3025 retval = field->digits + field->rdigits;
3026 }
3027 }
3028 return retval;
3029 }
3030
3031 static char *
3032 format_for_display_internal(char **dest,
3033 size_t *dest_size,
3034 cblc_field_t *var,
3035 unsigned char *actual_location,
3036 int actual_length,
3037 int address_of)
3038 {
3039 // dest and dest_size represent a malloced buffer of dest_size.
3040
3041 // This routine will put the formatted result into dest if it fits, and
3042 // realloc dest if it doesn't. The new_size goes into the dest_size
3043 // reference. Used properly, the caller's buffer just keeps getting bigger
3044 // as necessary, cutting down on the number of reallocations needed.
3045
3046 int source_rdigits = var->rdigits;
3047
3048 if( var->attr & scaled_e )
3049 {
3050 source_rdigits = 0;
3051 }
3052
3053 // Special case, when var->address_of is on
3054
3055 if( address_of )
3056 {
3057 // Assume that DISPLAY OF ADDRESS OF should be what's expected:
3058
3059 __gg__realloc_if_necessary(dest, dest_size, 2*sizeof(void *) + 1);
3060
3061 sprintf( *dest,
3062 "0x%*.*lx",
3063 (int)(2*sizeof(void *)),
3064 (int)(2*sizeof(void *)),
3065 (unsigned long)actual_location);
3066 ascii_to_internal_str(*dest, strlen(*dest));
3067
3068 goto done;
3069 }
3070
3071 switch( var->type )
3072 {
3073 case FldLiteralA:
3074 case FldGroup:
3075 case FldAlphanumeric:
3076 case FldNumericEdited:
3077 case FldAlphaEdited:
3078 __gg__realloc_if_necessary(dest, dest_size, actual_length+1);
3079 if( actual_location )
3080 {
3081 memcpy(*dest, actual_location, actual_length);
3082 }
3083 else
3084 {
3085 fprintf(stderr, "attempting to display a NULL pointer in %s\n", var->name);
3086 abort();
3087 //memset(*dest, internal_query, actual_length);
3088 //memcpy(*dest, actual_location, actual_length);
3089 }
3090 (*dest)[actual_length] = NULLCH;
3091 break;
3092
3093 case FldNumericDisplay:
3094 {
3095 // We are going to make use of fact that a NumericDisplay's data is
3096 // almost already in the format we need. We have to add a decimal point,
3097 // if necessary, in the right place, and we need to tack on leading or
3098 // trailing zeroes for PPP999 and 999PPP scaled-e variables.
3099
3100 if( var_is_refmod(var) )
3101 {
3102 __gg__realloc_if_necessary(dest, dest_size, actual_length+1);
3103 memcpy((*dest), actual_location, actual_length);
3104 (*dest)[actual_length] = NULLCH;
3105 break;
3106 }
3107
3108 const unsigned char *running_location = actual_location;
3109
3110 // We need the counts of digits to the left and right of the decimal point
3111 int rdigits = get_scaled_rdigits(var);
3112 int ldigits = var->digits - rdigits;
3113
3114 // Calculate the minimum allocated size we need, keeping in mind that
3115 // ldigits can be negative when working with a PPP999 number
3116 int nsize = std::max(ldigits,0) + rdigits+1;
3117 if( ldigits < 0 )
3118 {
3119 // We are dealing with a scaled_e number
3120 rdigits += ldigits;
3121 }
3122
3123 if( rdigits )
3124 {
3125 // We need room for the inside decimal point
3126 nsize += 1;
3127 }
3128 if( var->attr & signable_e )
3129 {
3130 // We need room for a leading or trailing sign in the output
3131 nsize += 1;
3132 }
3133
3134 // nsize is now the actual number of bytes we need in the destination
3135 __gg__realloc_if_necessary(dest, dest_size, nsize);
3136
3137 if( actual_location )
3138 {
3139 int index = 0; // This is the running index into our output destination
3140 if( var->attr & signable_e )
3141 {
3142 if( var->attr & separate_e )
3143 {
3144 // We are dealing with a sign character maintained separately in
3145 // the data.
3146 if( var->attr & leading_e )
3147 {
3148 // The first character is the sign character
3149 (*dest)[index++] = *running_location++;
3150 }
3151 }
3152 else
3153 {
3154 // The sign character is not separate. It's in either the first
3155 // or last byte of the data:
3156 size_t sign_location = var->attr & leading_e ? 0 : actual_length-1 ;
3157 if( is_sign_bit_on( actual_location[sign_location]) )
3158 {
3159 (*dest)[index++] = internal_minus;
3160 }
3161 else
3162 {
3163 (*dest)[index++] = internal_plus;
3164 }
3165 }
3166 }
3167
3168 {//xxx
3169 // copy over the characters to the left of the decimal point:
3170 for(int i=0; i<ldigits; i++ )
3171 {
3172 char ch = *running_location++;
3173
3174 // The default HIGH-VALUE of 0xFF runs afoul of the
3175 // NumericDisplay sign bit 0f 0x40 when running in
3176 // ASCII mode. The following test handles that problem
3177 // when HIGH-VALUE is still 0xFF. That HIGH-VALUE can
3178 // be changed by the SPECIAL-NAMES ALPHABET clause. But
3179
3180 // I have decided that the onus of that problem is on
3181 // the user.
3182 if( (*dest)[index-1] != (char)DEGENERATE_HIGH_VALUE )
3183 {
3184 turn_sign_bit_off( PTRCAST(unsigned char, &ch));
3185 }
3186 (*dest)[index++] = ch;
3187 }
3188 if( rdigits )
3189 {
3190 // Lay down a decimal point
3191 (*dest)[index++] = ascii_to_internal(__gg__decimal_point);
3192
3193 if( ldigits < 0 )
3194 {
3195 // This is a scaled_e value, and we need that many zeroes:
3196 for( int i=0; i<-ldigits; i++ )
3197 {
3198 (*dest)[index++] = internal_zero;
3199 }
3200 }
3201
3202 // And the digits to the right
3203 for(int i=0; i<rdigits; i++ )
3204 {
3205 char ch = *running_location++;
3206 if( (*dest)[index-1] != (char)DEGENERATE_HIGH_VALUE )
3207 {
3208 turn_sign_bit_off(PTRCAST(unsigned char, &ch));
3209 }
3210 (*dest)[index++] = ch;
3211 }
3212 }
3213 }
3214 // At this point, for a 999PPP number, we need to tack on the zeroes
3215 if( var->rdigits < 0 )
3216 {
3217 for(int i=0; i < -(var->rdigits); i++)
3218 {
3219 (*dest)[index++] = internal_zero;
3220 }
3221 }
3222
3223 if( var->attr & signable_e
3224 && var->attr & separate_e
3225 && !(var->attr & leading_e) )
3226 {
3227 (*dest)[index++] = actual_location[actual_length-1];
3228 }
3229
3230 (*dest)[index++] = NULLCH;
3231 }
3232 else
3233 {
3234 fprintf(stderr, "attempting to display a NULL pointer in %s\n", var->name);
3235 abort();
3236 // memset(*dest, internal_query, nsize-1);
3237 // (*dest)[nsize] = NULLCH;
3238 }
3239 }
3240 break;
3241
3242 case FldNumericBinary:
3243 case FldPacked:
3244 case FldNumericBin5:
3245 {
3246 int dummy;
3247 int digits;
3248 __int128 value = get_binary_value_local(&dummy,
3249 var,
3250 actual_location,
3251 actual_length);
3252 // Perhaps weirdly, for a p-scaled value with negative rdigits,
3253 // value has been scaled by 10**(-rdigits), because for most purposes,
3254 // get_binary_value_local should be the actual value. But for display,
3255 // we need to bring it back down by that factor, because down below we
3256 // will be adding zeroes to the right. This is a tug-of-war between
3257 // USAGE DISPLAY and other USAGES:
3258
3259 if( (var->attr & scaled_e) && var->rdigits < 0 )
3260 {
3261 value = __gg__scale_by_power_of_ten_2(value, var->rdigits);
3262 }
3263
3264 if( var->digits )
3265 {
3266 digits = var->digits;
3267 }
3268 else
3269 {
3270 // USAGE BINARY comes through without a digits value. Force it based on
3271 // the capacity:
3272 switch( var->capacity )
3273 {
3274 case 1:
3275 digits = 3;
3276 break;
3277 case 2:
3278 digits = 5;
3279 break;
3280 case 4:
3281 digits = 10;
3282 break;
3283 case 8:
3284 digits = 19;
3285 break;
3286 case 16:
3287 digits = 38;
3288 break;
3289 default:
3290 warnx("%s(): %s has capacity %ld\n",
3291 __func__,
3292 var->name,
3293 var->capacity);
3294 abort();
3295 break;
3296 }
3297 }
3298
3299 char ach[128];
3300 __gg__binary_to_string_internal(ach, digits, value);
3301
3302 // And copy the code from up above:
3303 int nsize = digits+1;
3304 int index = 0;
3305 if( source_rdigits )
3306 {
3307 // We need room for the inside decimal point
3308 nsize += 1;
3309 }
3310 if( var->attr & signable_e )
3311 {
3312 // We need room for the leading sign
3313 nsize += 1;
3314 }
3315 __gg__realloc_if_necessary(dest, dest_size, nsize);
3316
3317 if( var->attr & signable_e )
3318 {
3319 if( value < 0 )
3320 {
3321 (*dest)[index++] = internal_minus;
3322 }
3323 else
3324 {
3325 (*dest)[index++] = internal_plus;
3326 }
3327 }
3328 // copy over the characters to the left of the decimal point:
3329 memcpy((*dest)+index, ach, digits - source_rdigits);
3330 index += digits - source_rdigits;
3331 if( source_rdigits )
3332 {
3333 (*dest)[index++] = ascii_to_internal(__gg__decimal_point);
3334 memcpy((*dest)+index, ach+(digits-source_rdigits), source_rdigits);
3335 index += source_rdigits;
3336 }
3337 (*dest)[index++] = NULLCH ;
3338 }
3339 break;
3340
3341 case FldIndex:
3342 {
3343 // The display of a FldIndex doesn't need to provide clues about its
3344 // length, so don't bother with leading zeroes.
3345 int dummy;
3346 __int128 value = get_binary_value_local(&dummy,
3347 var,
3348 actual_location,
3349 actual_length);
3350 char ach[64];
3351 sprintf(ach, "%lu", (unsigned long)value);
3352 __gg__realloc_if_necessary(dest, dest_size, strlen(ach)+1);
3353 strcpy(*dest, ach);
3354 }
3355 break;
3356
3357 case FldClass:
3358 {
3359 if( var->level != LEVEL88 )
3360 {
3361 size_t retsize = MINIMUM_ALLOCATION_SIZE;
3362 memset(*dest, 0, retsize);
3363 strcpy(*dest, "<CLASS>");
3364 }
3365 else
3366 {
3367 // This is a LEVEL 88 variable
3368 size_t retsize = MINIMUM_ALLOCATION_SIZE;
3369 memset(*dest, 0, retsize);
3370 strcpy(*dest, "<LEVEL88>");
3371 }
3372
3373 break;
3374 }
3375
3376 case FldPointer:
3377 {
3378 int digits;
3379 __int128 value = get_binary_value_local( &digits,
3380 var,
3381 actual_location,
3382 actual_length);
3383 __gg__realloc_if_necessary(dest, dest_size, 2*sizeof(void *) + 3);
3384
3385 sprintf( *dest,
3386 "0x%*.*lx",
3387 (int)(2*sizeof(void *)),
3388 (int)(2*sizeof(void *)),
3389 (unsigned long)value);
3390 ascii_to_internal_str(*dest, strlen(*dest));
3391 break;
3392 }
3393
3394 case FldFloat:
3395 {
3396 switch(var->capacity)
3397 {
3398 case 4:
3399 {
3400 // We will convert based on the fact that for float32, any seven-digit
3401 // number converts to float32 and then back again unchanged.
3402
3403 // We will also format numbers so that we produce 0.01 and 1E-3 on the low
3404 // side, and 9999999 and then 1E+7 on the high side
3405 // 10,000,000 = 1E7
3406 char ach[64];
3407 _Float32 floatval = *PTRCAST(_Float32, actual_location);
3408 strfromf32(ach, sizeof(ach), "%.9E", floatval);
3409 char *p = strchr(ach, 'E');
3410 if( !p )
3411 {
3412 // Probably INF -INF NAN or -NAN, so ach has our result
3413 }
3414 else
3415 {
3416 p += 1;
3417 int exp = atoi(p);
3418 if( exp >= 6 || exp <= -5 )
3419 {
3420 // We are going to stick with the E notation, so ach has our result
3421 }
3422 else
3423 {
3424 // We are going to produce our number in such a way that we specify
3425 // seven signicant digits, no matter where the decimal point lands.
3426 // Note that exp is in the range of 6 to -2
3427
3428 int precision = 9 - exp;
3429 sprintf(ach, "%.*f", precision, (double)floatval );
3430 }
3431 __gg__remove_trailing_zeroes(ach);
3432 __gg__realloc_if_necessary(dest, dest_size, strlen(ach)+1);
3433 }
3434 psz_to_internal(ach);
3435 strcpy(*dest, ach);
3436 break;
3437 }
3438
3439 case 8:
3440 {
3441 // We will convert based on the fact that for float32, any 15-digit
3442 // number converts to float64 and then back again unchanged.
3443
3444 // We will also format numbers so that we produce 0.01 and 1E-3 on the low
3445 // side, and 9999999 and then 1E+15 on the high side
3446 char ach[64];
3447 _Float64 floatval = *PTRCAST(_Float64, actual_location);
3448 strfromf64(ach, sizeof(ach), "%.17E", floatval);
3449 char *p = strchr(ach, 'E');
3450 if( !p )
3451 {
3452 // Probably INF -INF NAN or -NAN, so ach has our result
3453 }
3454 else
3455 {
3456 p += 1;
3457 int exp = atoi(p);
3458 if( exp >= 6 || exp <= -5 )
3459 {
3460 // We are going to stick with the E notation, so ach has our result
3461 }
3462 else
3463 {
3464 // We are going to produce our number in such a way that we specify
3465 // seven signicant digits, no matter where the decimal point lands.
3466 // Note that exp is in the range of 6 to -2
3467
3468 int precision = 17 - exp;
3469
3470 sprintf(ach, "%.*f", precision, (double)floatval );
3471 }
3472 __gg__remove_trailing_zeroes(ach);
3473 __gg__realloc_if_necessary(dest, dest_size, strlen(ach)+1);
3474 }
3475 psz_to_internal(ach);
3476 strcpy(*dest, ach);
3477 break;
3478 }
3479
3480 case 16:
3481 {
3482 // We will convert based on the fact that for float32, any 15-digit
3483 // number converts to float64 and then back again unchanged.
3484
3485 // We will also format numbers so that we produce 0.01 and 1E-3 on the low
3486 // side, and 9999999 and then 1E+15 on the high side
3487 char ach[128];
3488 // We can't use *(_Float64 *)actual_location;
3489 // That uses the SSE registers, which won't work if the source isn't
3490 // on a 16-bit boundary.
3491 GCOB_FP128 floatval;
3492 memcpy(&floatval, actual_location, 16);
3493 strfromfp128(ach, sizeof(ach), "%.36" FP128_FMT "E", floatval);
3494 char *p = strchr(ach, 'E');
3495 if( !p )
3496 {
3497 // Probably INF -INF NAN or -NAN, so ach has our result
3498 }
3499 else
3500 {
3501 p += 1;
3502 int exp = atoi(p);
3503 if( exp >= 6 || exp <= -5 )
3504 {
3505 // We are going to stick with the E notation, so ach has our result
3506 }
3507 else
3508 {
3509 // We are going to produce our number in such a way that we specify
3510 // seven signicant digits, no matter where the decimal point lands.
3511 // Note that exp is in the range of 6 to -2
3512
3513 int precision = 36 - exp;
3514 char achFormat[24];
3515 sprintf(achFormat, "%%.%d" FP128_FMT "f", precision);
3516 strfromfp128(ach, sizeof(ach), achFormat, floatval);
3517 }
3518 __gg__remove_trailing_zeroes(ach);
3519 __gg__realloc_if_necessary(dest, dest_size, strlen(ach)+1);
3520 }
3521
3522 psz_to_internal(ach);
3523 strcpy(*dest, ach);
3524 break;
3525 }
3526 }
3527 break;
3528 }
3529
3530 default:
3531 fprintf(stderr,
3532 "Unknown conversion %d in format_for_display_internal\n",
3533 var->type );
3534 abort();
3535 break;
3536 }
3537
3538 if( var->attr & scaled_e && var->type != FldNumericDisplay )
3539 {
3540 static size_t buffer_size = MINIMUM_ALLOCATION_SIZE;
3541 static char *buffer = static_cast<char *>(malloc(buffer_size));
3542 massert(buffer);
3543 if( var->rdigits > 0)
3544 {
3545 // We have something like 123 or +123. We need to insert a decimal
3546 // point and a rdigits zeroes to make it +.000000123
3547
3548 size_t new_length = strlen(*dest) + var->rdigits + 1 + 1;
3549 __gg__realloc_if_necessary(&buffer, &buffer_size, new_length);
3550
3551
3552 memset(buffer, internal_0, new_length);
3553 char *p = buffer;
3554 char *s = *dest;
3555 if( ((*dest)[0]&0xFF) < internal_0
3556 || ((*dest)[0]&0xFF) > internal_9 )
3557 {
3558 *p++ = (*dest)[0];
3559 s += 1;
3560 }
3561 *p++ = ascii_to_internal(__gg__decimal_point);
3562 p += var->rdigits; // Skip over the zeroes
3563 strcpy(p, s);
3564
3565 __gg__realloc_if_necessary(dest, dest_size, new_length);
3566 strcpy(*dest, buffer);
3567 }
3568 else // var->rdigits < 0
3569 {
3570 // We have something like 123 or +123. All we need to do is
3571 // add zeroes to the end:
3572 size_t new_length = strlen(*dest) + -var->rdigits + 1;
3573 __gg__realloc_if_necessary(&buffer, &buffer_size, new_length);
3574
3575 memset(buffer, internal_0, new_length);
3576 buffer[new_length-1] = NULLCH;
3577 memcpy(buffer, *dest, strlen(*dest));
3578
3579 __gg__realloc_if_necessary(dest, dest_size, new_length);
3580 strcpy(*dest, buffer);
3581 }
3582 }
3583
3584 if( var->type == FldNumericBin5 && (var->attr & intermediate_e) )
3585 {
3586 // Because this is a intermediate Bin5, let's strip off leading zeroes.
3587 //
3588 // Because we don't know what we are dealing with, we created a 38-digit
3589 // number with a variable number of rdigits. So, we usually have a boatload
3590 // of leading zeroes. I find that display offensive, so let's fix it:
3591 unsigned char *p1 = (unsigned char *)(*dest);
3592 if( *p1 == internal_plus || *p1 == internal_minus )
3593 {
3594 p1 += 1;
3595 }
3596 unsigned char *p2 = p1;
3597 while( p2[0] == internal_zero && p2[1] != '\0' )
3598 {
3599 p2 += 1;
3600 }
3601 strcpy(PTRCAST(char, p1), PTRCAST(char, p2));
3602 }
3603
3604 done:
3605 return *dest;
3606 }
3607
3608 static char *
3609 format_for_display_local( char **dest,
3610 size_t *dest_size,
3611 cblc_field_t *var,
3612 size_t var_offset,
3613 size_t var_size,
3614 int var_flags)
3615 {
3616 if(var)
3617 {
3618 // At this point, format the entire length. It's up to our caller to
3619 // trim it further, because this routine is used by both receivers and
3620 // senders
3621 format_for_display_internal(dest,
3622 dest_size,
3623 var,
3624 var->data + var_offset,
3625 var_size,
3626 var_flags & REFER_T_ADDRESS_OF);
3627 }
3628 else
3629 {
3630 **dest = '\0';
3631 }
3632 return *dest;
3633 }
3634
3635 static int
3636 compare_88( const char *list,
3637 const char *list_e,
3638 bool fig_const,
3639 cblc_field_t * /*conditional*/,
3640 unsigned char *conditional_location,
3641 int conditional_length)
3642 {
3643 int list_len = (int)(list_e-list);
3644 int test_len;
3645 char *test;
3646 if( fig_const )
3647 {
3648 // We are working with a figurative constant
3649
3650 test = static_cast<char *>(malloc(conditional_length));
3651 massert(test);
3652 test_len = conditional_length;
3653 // This is where we handle the zero-length strings that
3654 // nonetheless can magically be expanded into figurative
3655 // constants:
3656
3657 int ch = internal_space;
3658 // Check for the strings starting with 0xFF whose second character
3659 // indicates a figurative constant:
3660 if( list[0] == ascii_Z )
3661 {
3662 ch = internal_zero;
3663 }
3664 else if( list[0] == ascii_H )
3665 {
3666 if( __gg__high_value_character == DEGENERATE_HIGH_VALUE )
3667 {
3668 ch = __gg__high_value_character;
3669 }
3670 else
3671 {
3672 ch = ascii_to_internal(__gg__high_value_character);
3673 }
3674 }
3675 else if( list[0] == ascii_Q )
3676 {
3677 ch = ascii_to_internal(__gg__quote_character);
3678 }
3679 else if( list[0] == ascii_L )
3680 {
3681 ch = ascii_to_internal(__gg__low_value_character);
3682 }
3683 memset( test, ch, conditional_length );
3684 }
3685 else if( list_len < conditional_length )
3686 {
3687 // 'list' is too short; we have to right-fill with spaces:
3688 test = static_cast<char *>(malloc(conditional_length));
3689 massert(test);
3690 test_len = conditional_length;
3691 memset(test, internal_space, conditional_length);
3692 memcpy(test, list, list_len);
3693 }
3694 else
3695 {
3696 test = static_cast<char *>(malloc(list_len));
3697 massert(test);
3698 test_len = list_len;
3699 memcpy(test, list, list_len);
3700 }
3701
3702 int cmpval;
3703
3704 if( test[0] == NULLCH && conditional_location[0] == 0)
3705 {
3706 cmpval = 0;
3707 }
3708 else
3709 {
3710 cmpval = cstrncmp (test,
3711 PTRCAST(char, conditional_location),
3712 conditional_length);
3713 if( cmpval == 0 && (int)strlen(test) != conditional_length )
3714 {
3715 // When strncmp returns 0, the actual smaller string is the
3716 // the shorter of the two:
3717 cmpval = test_len - conditional_length;
3718 }
3719 }
3720
3721 free(test);
3722
3723 if( cmpval < 0 )
3724 {
3725 cmpval = -1;
3726 }
3727 else if(cmpval > 0)
3728 {
3729 cmpval = +1;
3730 }
3731 return cmpval;
3732 }
3733
3734 static GCOB_FP128
3735 get_float128( const cblc_field_t *field,
3736 unsigned char *location )
3737 {
3738 GCOB_FP128 retval=0;
3739 if(field->type == FldFloat )
3740 {
3741 switch( field->capacity )
3742 {
3743 case 4:
3744 retval = *PTRCAST(_Float32 , location);
3745 break;
3746 case 8:
3747 retval = *PTRCAST(_Float64 , location);
3748 break;
3749 case 16:
3750 // retval = *(_Float128 *)location; doesn't work, because the SSE
3751 // registers need the source on a 16-byte boundary, and we can't
3752 // guarantee that.
3753 memcpy(&retval, location, 16);
3754 break;
3755 }
3756 }
3757 else if( field->type == FldLiteralN )
3758 {
3759 if( __gg__decimal_point == '.' )
3760 {
3761 retval = strtofp128(field->initial, NULL);
3762 }
3763 else
3764 {
3765 // We need to replace any commas with periods
3766 static size_t size = 128;
3767 static char *buffer = static_cast<char *>(malloc(size));
3768 while( strlen(field->initial)+1 > size )
3769 {
3770 size *= 2;
3771 buffer = static_cast<char *>(malloc(size));
3772 }
3773 massert(buffer);
3774 strcpy(buffer, field->initial);
3775 char *p = strchr(buffer, ',');
3776 if(p)
3777 {
3778 *p = '.';
3779 }
3780 retval = strtofp128(buffer, NULL);
3781 }
3782 }
3783 else
3784 {
3785 fprintf(stderr, "What's all this then?\n");
3786 abort();
3787 }
3788 return retval;
3789 }
3790
3791 static
3792 int
3793 compare_field_class(cblc_field_t *conditional,
3794 unsigned char *conditional_location,
3795 int conditional_length,
3796 cblc_field_t *list)
3797 {
3798 int retval = 1; // Zero means equal
3799 __int128 value;
3800 int rdigits;
3801
3802 // list->initial points to a superstring: a double-null terminated
3803 // string containing pairs of strings. We are looking for equality.
3804
3805 switch( conditional->type )
3806 {
3807 case FldNumericDisplay:
3808 case FldNumericEdited:
3809 case FldNumericBinary:
3810 case FldPacked:
3811 case FldNumericBin5:
3812 case FldIndex:
3813 {
3814 value = get_binary_value_local (&rdigits,
3815 conditional,
3816 conditional_location,
3817 conditional_length);
3818 const char *walker = list->initial;
3819 while(*walker)
3820 {
3821 char left_flag;
3822 size_t left_len;
3823 char * left;
3824
3825 char right_flag;
3826 size_t right_len;
3827 char * right;
3828
3829 char *pend;
3830 left_len = strtoull(walker, &pend, 10);
3831 left_flag = *pend;
3832 left = pend+1;
3833
3834 right = left + left_len;
3835 right_len = strtoull(right, &pend, 10);
3836 right_flag = *pend;
3837 right = pend+1;
3838
3839 walker = right + right_len;
3840
3841 int left_rdigits;
3842 int right_rdigits;
3843
3844 __int128 left_value;
3845 if( left_flag == 'F' && left[0] == 'Z' )
3846 {
3847 left_value = 0;
3848 left_rdigits = 0;
3849 }
3850 else
3851 {
3852 left_value = __gg__dirty_to_binary_internal(
3853 left,
3854 left_len,
3855 &left_rdigits);
3856 }
3857
3858 __int128 right_value;
3859 if( right_flag == 'F' && right[0] == 'Z' )
3860 {
3861 right_value = 0;
3862 right_rdigits = 0;
3863 }
3864 else
3865 {
3866 right_value = __gg__dirty_to_binary_internal(
3867 right,
3868 right_len,
3869 &right_rdigits);
3870 }
3871
3872 // Normalize all three numbers to the same rdigits
3873 int max = std::max(rdigits, left_rdigits);
3874 max = std::max(max, right_rdigits);
3875
3876 if( max > rdigits )
3877 {
3878 value *= __gg__power_of_ten(max - rdigits);
3879 }
3880 if( max > left_rdigits )
3881 {
3882 left_value *= __gg__power_of_ten(max - left_rdigits);
3883 }
3884 if( max > right_rdigits )
3885 {
3886 right_value *= __gg__power_of_ten(max - right_rdigits);
3887 }
3888 if( left_value <= value && value <= right_value )
3889 {
3890 retval = 0;
3891 break;
3892 }
3893 }
3894 break;
3895 }
3896
3897 case FldGroup:
3898 case FldAlphanumeric:
3899 case FldLiteralA:
3900 {
3901 char *walker = list->initial;
3902 while(*walker)
3903 {
3904 bool fig1;
3905 bool fig2;
3906 char *first;
3907 char *last;
3908 char *first_e;
3909 char *last_e;
3910 size_t first_len;
3911 size_t last_len;
3912
3913 char *pend;
3914
3915 first = walker;
3916 first_len = strtoull(first, &pend, 10);
3917 fig1 = *pend == 'F';
3918 first = pend+1;
3919 first_e = first + first_len;
3920
3921 last = first_e;
3922
3923 last_len = strtoull(last, &pend, 10);
3924 fig2 = *pend == 'F';
3925 last = pend+1;
3926 last_e = last + last_len;
3927
3928 walker = last_e;
3929
3930 int compare_result;
3931
3932 compare_result = compare_88(first,
3933 first_e,
3934 fig1,
3935 conditional,
3936 conditional_location,
3937 conditional_length);
3938 if( compare_result > 0 )
3939 {
3940 // First is > conditional, so this is no good
3941 continue;
3942 }
3943 compare_result = compare_88(last,
3944 last_e,
3945 fig2,
3946 conditional,
3947 conditional_location,
3948 conditional_length);
3949 if( compare_result < 0 )
3950 {
3951 // Last is < conditional, so this is no good
3952 continue;
3953 }
3954
3955 // conditional is inclusively between first and last
3956 retval = 0;
3957 break;
3958 }
3959 break;
3960 }
3961
3962 case FldFloat:
3963 {
3964 GCOB_FP128 fp128 = get_float128(conditional, conditional_location) ;
3965 const char *walker = list->initial;
3966 while(*walker)
3967 {
3968 char left_flag;
3969 size_t left_len;
3970 char * left;
3971
3972 char right_flag;
3973 size_t right_len;
3974 char * right;
3975
3976 char *pend;
3977 left_len = strtoull(walker, &pend, 10);
3978 left_flag = *pend;
3979 left = pend+1;
3980
3981 right = left + left_len;
3982 right_len = strtoull(right, &pend, 10);
3983 right_flag = *pend;
3984 right = pend+1;
3985
3986 walker = right + right_len;
3987
3988 GCOB_FP128 left_value;
3989 if( left_flag == 'F' && left[0] == 'Z' )
3990 {
3991 left_value = 0;
3992 }
3993 else
3994 {
3995 left_value = __gg__dirty_to_float(left,
3996 left_len);
3997 }
3998
3999 GCOB_FP128 right_value;
4000 if( right_flag == 'F' && right[0] == 'Z' )
4001 {
4002 right_value = 0;
4003 }
4004 else
4005 {
4006 right_value = __gg__dirty_to_float( right,
4007 right_len);
4008 }
4009
4010 if( left_value <= fp128 && fp128 <= right_value )
4011 {
4012 retval = 0;
4013 break;
4014 }
4015 }
4016 break;
4017 }
4018
4019 default:
4020 printf( "%s(): doesn't know what to do with %s\n",
4021 __func__,
4022 conditional->name);
4023 abort();
4024 }
4025
4026 return retval;
4027 }
4028
4029 static
4030 bool
4031 local_is_numeric(int type, bool address_of)
4032 {
4033 bool retval;
4034 if( address_of )
4035 {
4036 retval = true;
4037 }
4038 else
4039 {
4040 switch(type)
4041 {
4042 case FldNumericDisplay:
4043 case FldNumericBinary:
4044 case FldPacked:
4045 case FldNumericBin5:
4046 case FldIndex:
4047 case FldPointer:
4048 case FldLiteralN:
4049 case FldFloat:
4050 retval = true;
4051 break;
4052 default:
4053 retval = false;
4054 break;
4055 }
4056 }
4057 return retval;
4058 }
4059
4060 static
4061 bool
4062 local_is_alpha(int type, bool address_of)
4063 {
4064 bool retval;
4065 if( address_of )
4066 {
4067 retval = false;
4068 }
4069 else
4070 {
4071 switch(type)
4072 {
4073 case FldGroup:
4074 case FldAlphanumeric:
4075 case FldAlphaEdited:
4076 case FldNumericEdited:
4077 case FldLiteralA:
4078 retval = true;
4079 break;
4080 default:
4081 retval = false;
4082 break;
4083 }
4084 }
4085 return retval;
4086 }
4087
4088 static
4089 int
4090 compare_strings(const char *left_string,
4091 size_t left_length,
4092 bool left_all,
4093 const char *right_string,
4094 size_t right_length,
4095 bool right_all)
4096 {
4097 int retval = 0;
4098 size_t i = 0;
4099
4100 if( right_all && right_length > left_length )
4101 {
4102 // In the rubber-bandy ALL situation, and the ALL is longer than the
4103 // fixed side, we just compare the characters of the fixed side:
4104 right_length = left_length;
4105 }
4106
4107 if( left_all && left_length > right_length )
4108 {
4109 left_length = right_length;
4110 }
4111
4112 while( !retval && i<left_length && i<right_length )
4113 {
4114 retval = collated((unsigned char)left_string[i])
4115 - collated((unsigned char)right_string[i]);
4116 i += 1;
4117 }
4118
4119 // We need to space-extend the shorter value. That's because
4120 // "Bob" is equal to "Bob "
4121 if( !right_all )
4122 {
4123 while( !retval && i<left_length )
4124 {
4125 retval = collated((unsigned char)left_string[i])
4126 - collated(internal_space);
4127 i += 1;
4128 }
4129 }
4130 else
4131 {
4132 // In an ALL situation where the ALL is shorter than the fixed side, we
4133 // wrap around the ALL characters
4134 while( !retval && i<left_length )
4135 {
4136 retval = collated((unsigned char)left_string[i])
4137 - collated((unsigned char)right_string[i%right_length]);
4138 i += 1;
4139 }
4140 }
4141
4142 if( !left_all )
4143 {
4144 while( !retval && i<right_length )
4145 {
4146 retval = collated(internal_space)
4147 - collated((unsigned char)right_string[i]);
4148 i += 1;
4149 }
4150 }
4151 else
4152 {
4153 if( left_length > right_length )
4154 {
4155 left_length = right_length;
4156 }
4157 while( !retval && i<right_length )
4158 {
4159 retval = collated((unsigned char)left_string[i%left_length])
4160 - collated((unsigned char)right_string[i]);
4161 i += 1;
4162 }
4163 }
4164 return retval;
4165 }
4166
4167 extern "C"
4168 int
4169 __gg__compare_2(cblc_field_t *left_side,
4170 unsigned char *left_location,
4171 size_t left_length,
4172 int left_attr,
4173 int left_flags,
4174 cblc_field_t *right_side,
4175 unsigned char *right_location,
4176 size_t right_length,
4177 int right_attr,
4178 int right_flags,
4179 int second_time_through)
4180 {
4181 // First order of business: If right_side is a FldClass, pass that off
4182 // to the speciality squad:
4183
4184 if( right_side->type == FldClass )
4185 {
4186 return compare_field_class( left_side,
4187 left_location,
4188 left_length,
4189 right_side);
4190 }
4191
4192 // Serene in our conviction that the left_side isn't a FldClass, we
4193 // move on.
4194
4195 // Extract the individual flags from the flag words:
4196 bool left_all = !!(left_flags & REFER_T_MOVE_ALL );
4197 bool left_address_of = !!(left_flags & REFER_T_ADDRESS_OF);
4198 bool right_all = !!(right_flags & REFER_T_MOVE_ALL );
4199 bool right_address_of = !!(right_flags & REFER_T_ADDRESS_OF);
4200 //bool left_refmod = !!(left_flags & REFER_T_REFMOD );
4201 bool right_refmod = !!(right_flags & REFER_T_REFMOD );
4202
4203 // Figure out if we have any figurative constants
4204 cbl_figconst_t left_figconst = (cbl_figconst_t)(left_attr & FIGCONST_MASK);
4205 cbl_figconst_t right_figconst = (cbl_figconst_t)(right_attr & FIGCONST_MASK);
4206
4207 unsigned int fig_left = 0;
4208 unsigned int fig_right = 0;
4209
4210 switch(left_figconst)
4211 {
4212 case normal_value_e :
4213 fig_left = 0;
4214 break;
4215 case low_value_e :
4216 fig_left = ascii_to_internal(__gg__low_value_character);
4217 break;
4218 case zero_value_e :
4219 fig_left = internal_zero;
4220 break;
4221 case space_value_e :
4222 fig_left = internal_space;
4223 break;
4224 case quote_value_e :
4225 fig_left = ascii_to_internal(__gg__quote_character);
4226 break;
4227 case high_value_e :
4228 if( __gg__high_value_character == DEGENERATE_HIGH_VALUE )
4229 {
4230 fig_left = __gg__high_value_character;
4231 }
4232 else
4233 {
4234 fig_left = ascii_to_internal(__gg__high_value_character);
4235 }
4236 break;
4237 case null_value_e:
4238 break;
4239 }
4240 switch(right_figconst)
4241 {
4242 case normal_value_e :
4243 fig_right = 0;
4244 break;
4245 case low_value_e :
4246 fig_right = ascii_to_internal(__gg__low_value_character);
4247 break;
4248 case zero_value_e :
4249 fig_right = internal_zero;
4250 break;
4251 case space_value_e :
4252 fig_right = internal_space;
4253 break;
4254 case quote_value_e :
4255 fig_right = ascii_to_internal(__gg__quote_character);
4256 break;
4257 case high_value_e :
4258 if( __gg__high_value_character == DEGENERATE_HIGH_VALUE )
4259 {
4260 fig_right = __gg__high_value_character;
4261 }
4262 else
4263 {
4264 fig_right = ascii_to_internal(__gg__high_value_character);
4265 }
4266 break;
4267 case null_value_e:
4268 break;
4269 }
4270
4271 // We have four high-level conditions to consider:
4272 int retval = 0;
4273 bool compare = false;
4274
4275 if( left_figconst && right_figconst )
4276 {
4277 // We are comparing two figurative constants
4278 retval = collated(fig_left) - collated(fig_right);
4279 compare = true;
4280 goto fixup_retval;
4281 }
4282 if( left_figconst && !right_figconst )
4283 {
4284 // Go directly to fixup_retval. Because 'compare' is false, we'll
4285 // end up trying again with the variables swapped:
4286 goto fixup_retval;
4287 }
4288 if( !left_figconst && right_figconst )
4289 {
4290 // We are comparing the left side to a figurative constant:
4291 switch( right_figconst )
4292 {
4293 default:
4294 fprintf(stderr,
4295 "%s() %s:%d -- Unknown figurative constant %d\n",
4296 __func__, __FILE__, __LINE__,
4297 (int)right_figconst);
4298 abort();
4299 break;
4300
4301 case null_value_e:
4302 break;
4303
4304 case low_value_e:
4305 case high_value_e:
4306 case quote_value_e:
4307 case space_value_e:
4308 retval = 0;
4309 for(size_t i=0; i<left_length; i++)
4310 {
4311 retval = collated((unsigned int)left_location[i])
4312 - collated(fig_right);
4313 if( retval )
4314 {
4315 break;
4316 }
4317 }
4318
4319 compare = true;
4320 goto fixup_retval;
4321 break;
4322
4323 case zero_value_e:
4324 {
4325 switch( left_side->type )
4326 {
4327 case FldNumericBinary:
4328 case FldPacked:
4329 case FldNumericBin5:
4330 case FldNumericDisplay:
4331 case FldLiteralN:
4332 case FldIndex:
4333 case FldPointer:
4334 // ZEROES is a chameleon. When compared to a numeric, it is
4335 // the number zero:
4336 {
4337 int rdigits;
4338 __int128 value;
4339
4340 if( left_side)
4341
4342 value = get_binary_value_local( &rdigits,
4343 left_side,
4344 left_location,
4345 left_length);
4346 retval = 0;
4347 retval = value < 0 ? -1 : retval;
4348 retval = value > 0 ? 1 : retval;
4349 compare = true;
4350 break;
4351 }
4352
4353 case FldFloat:
4354 {
4355 GCOB_FP128 value = __gg__float128_from_location(left_side,
4356 left_location);
4357 retval = 0;
4358 retval = value < 0 ? -1 : retval;
4359 retval = value > 0 ? 1 : retval;
4360 compare = true;
4361 break;
4362 }
4363
4364 default:
4365 // We are comparing a alphanumeric string to ZEROES
4366 retval = 0;
4367 for(size_t i=0; i<left_length; i++)
4368 {
4369 retval = collated((unsigned int)left_location[i])
4370 - collated(fig_right);
4371 if( retval )
4372 {
4373 break;
4374 }
4375 }
4376 compare = true;
4377 break;
4378 }
4379 goto fixup_retval;
4380 }
4381 }
4382 }
4383 else
4384 {
4385 // Neither left_side nor right_side is a figurative constant.
4386
4387 // Our strategy here is to compare two alphanumerics, two numerics,
4388 // or an alphanumeric to a numeric. We'll handle a numeric to an
4389 // alphanumeric on a second-time-through.
4390
4391 if( local_is_alpha(left_side->type, left_address_of)
4392 && local_is_alpha(right_side->type, right_address_of) )
4393 {
4394 retval = compare_strings( reinterpret_cast<char *>(left_location),
4395 left_length,
4396 left_all,
4397 reinterpret_cast<char *>(right_location),
4398 right_length,
4399 right_all );
4400
4401 compare = true;
4402 goto fixup_retval;
4403 }
4404
4405 if( local_is_numeric(left_side->type, left_address_of)
4406 && local_is_numeric(right_side->type, right_address_of) )
4407 {
4408 if( left_side->type == FldFloat && right_side->type == FldFloat )
4409 {
4410 // One or the other of the numerics is a FldFloat
4411 GCOB_FP128 left_value = __gg__float128_from_location(left_side, left_location);
4412 GCOB_FP128 right_value = __gg__float128_from_location(right_side, right_location);
4413 retval = 0;
4414 retval = left_value < right_value ? -1 : retval;
4415 retval = left_value > right_value ? 1 : retval;
4416 compare = true;
4417 goto fixup_retval;
4418 }
4419
4420 if( left_side->type == FldFloat )
4421 {
4422 // The left side is a FldFloat; the other is another type of numeric:
4423 int rdecimals;
4424 GCOB_FP128 left_value;
4425 GCOB_FP128 right_value;
4426
4427 if( right_side->type == FldLiteralN)
4428 {
4429 // In order to do the comparision, we need the value from the
4430 // literal to be the same flavor as the left side:
4431 // We need to replace any commas with periods
4432 static size_t size = 128;
4433 static char *buffer = static_cast<char *>(malloc(size));
4434 while( strlen(right_side->initial)+1 > size )
4435 {
4436 size *= 2;
4437 buffer = static_cast<char *>(malloc(size));
4438 }
4439 massert(buffer);
4440 strcpy(buffer, right_side->initial);
4441 if( __gg__decimal_point == ',' )
4442 {
4443 // We need to replace any commas with periods
4444 char *p = strchr(buffer, ',');
4445 if(p)
4446 {
4447 *p = '.';
4448 }
4449 }
4450
4451 // buffer[] now contains the string we want to convert
4452
4453 switch(left_side->capacity)
4454 {
4455 case 4:
4456 {
4457 _Float32 left_value4 = *PTRCAST(_Float32, left_location);
4458 _Float32 right_value4 = strtof(buffer, NULL);
4459 retval = 0;
4460 retval = left_value4 < right_value4 ? -1 : retval;
4461 retval = left_value4 > right_value4 ? 1 : retval;
4462 break;
4463 }
4464 case 8:
4465 {
4466 _Float64 left_value8 = *PTRCAST(_Float64, left_location);
4467 _Float64 right_value8 = strtod(buffer, NULL);
4468 retval = 0;
4469 retval = left_value8 < right_value8 ? -1 : retval;
4470 retval = left_value8 > right_value8 ? 1 : retval;
4471 break;
4472 }
4473 case 16:
4474 {
4475 //_Float128 left_value = *(_Float128 *)left_location;
4476 GCOB_FP128 left_value16;
4477 memcpy(&left_value16, left_location, 16);
4478 GCOB_FP128 right_value16 = strtofp128(buffer, NULL);
4479 retval = 0;
4480 retval = left_value16 < right_value16 ? -1 : retval;
4481 retval = left_value16 > right_value16 ? 1 : retval;
4482 break;
4483 }
4484 }
4485 }
4486 else
4487 {
4488 left_value = __gg__float128_from_location(left_side, left_location);
4489
4490 right_value = get_binary_value_local( &rdecimals,
4491 right_side,
4492 right_location,
4493 right_length);
4494 right_value /= __gg__power_of_ten(rdecimals);
4495 retval = 0;
4496 retval = left_value < right_value ? -1 : retval;
4497 retval = left_value > right_value ? 1 : retval;
4498 }
4499
4500 compare = true;
4501 goto fixup_retval;
4502 }
4503
4504 if( left_side->type != FldFloat && right_side->type != FldFloat)
4505 {
4506 // We are comparing a numeric to a numeric, neither are floats
4507 int ldecimals;
4508 int rdecimals;
4509 __int128 left_value;
4510 __int128 right_value;
4511
4512 if( left_address_of )
4513 {
4514 left_value = (__int128)left_location;
4515 ldecimals = 0;
4516 }
4517 else
4518 {
4519 left_value = get_binary_value_local( &ldecimals,
4520 left_side,
4521 left_location,
4522 left_length);
4523 }
4524 if( right_address_of )
4525 {
4526 right_value = (__int128)right_location;
4527 rdecimals = 0;
4528 }
4529 else
4530 {
4531 right_value = get_binary_value_local( &rdecimals,
4532 right_side,
4533 right_location,
4534 right_length);
4535 }
4536
4537 // We need to align the decimal points:
4538 if(rdecimals > ldecimals)
4539 {
4540 left_value *= __gg__power_of_ten(rdecimals-ldecimals);
4541 }
4542 else if( ldecimals > rdecimals )
4543 {
4544 right_value *= __gg__power_of_ten(ldecimals-rdecimals);
4545 }
4546
4547 retval = 0;
4548 retval = left_value < right_value ? -1 : retval;
4549 retval = left_value > right_value ? 1 : retval;
4550 compare = true;
4551 goto fixup_retval;
4552 }
4553 }
4554
4555 if( local_is_alpha(left_side->type, left_address_of)
4556 && local_is_numeric(right_side->type, right_address_of) )
4557 {
4558 // We are comparing an alphanumeric to a numeric.
4559
4560 // The right side is numeric. Sometimes people write code where they
4561 // take the refmod of a numeric displays. If somebody did that here,
4562 // just do a complete straight-up character by character comparison:
4563
4564 if( right_refmod )
4565 {
4566 retval = compare_strings( reinterpret_cast<char *>(left_location),
4567 left_length,
4568 left_all,
4569 reinterpret_cast<char *>(right_location),
4570 right_length,
4571 right_all);
4572 compare = true;
4573 goto fixup_retval;
4574 }
4575
4576
4577 // The trick here is to convert the numeric to its display form,
4578 // and compare that to the alphanumeric. For example, when comparing
4579 // a VAL5 PIC X(3) VALUE 5 to literals,
4580 //
4581 // VAL5 EQUAL 5 is TRUE
4582 // VAL5 EQUAL 005 is TRUE
4583 // VAL5 EQUAL "5" is FALSE
4584 // VAL5 EQUAL "005" is TRUE
4585 if( left_side->type == FldLiteralA )
4586 {
4587 left_location = reinterpret_cast<unsigned char *>(left_side->data);
4588 left_length = left_side->capacity;
4589 }
4590
4591 static size_t right_string_size = MINIMUM_ALLOCATION_SIZE;
4592 static char *right_string
4593 = static_cast<char *>(malloc(right_string_size));
4594
4595 right_string = format_for_display_internal(
4596 &right_string,
4597 &right_string_size,
4598 right_side,
4599 right_location,
4600 right_length,
4601 0);
4602
4603 // There is a tricky aspect to comparing an alphanumeric to
4604 // a string. In short, we have to strip off any leading plus sign
4605
4606 // And, according to the NIST tests, the same is true for minus signs.
4607 // Apparently, when comparing a number to an alphanumeric, it is
4608 // considered a "pseudo-move", and the rule for moving a negative
4609 // number to an alphanumeric is that negative signs get stripped off
4610
4611 if( *left_location == internal_plus || *left_location == internal_minus )
4612 {
4613 left_location += 1;
4614 left_length -= 1;
4615 }
4616
4617 const char *right_fixed;
4618 if( *right_string == internal_plus || *right_string == internal_minus )
4619 {
4620 right_fixed = right_string + 1;
4621 }
4622 else
4623 {
4624 right_fixed = right_string;
4625 }
4626
4627 retval = compare_strings( reinterpret_cast<char *>(left_location),
4628 left_length,
4629 left_all,
4630 right_fixed,
4631 strlen(right_fixed),
4632 right_all);
4633 compare = true;
4634 goto fixup_retval;
4635 }
4636 }
4637
4638 fixup_retval:
4639
4640 if( !compare && !second_time_through)
4641 {
4642 // This is the first time through, and we couldn't do the comparison.
4643 // Maybe we have to reverse the inputs:
4644 retval = __gg__compare_2( right_side,
4645 right_location,
4646 right_length,
4647 right_attr,
4648 right_flags,
4649 left_side,
4650 left_location,
4651 left_length,
4652 left_attr,
4653 left_flags,
4654 1);
4655 // And reverse the sense of the return value:
4656 compare = true;
4657 retval = -retval;
4658 }
4659
4660 if( !compare && second_time_through )
4661 {
4662 // Nope. We still couldn't do the comparison
4663 fprintf(stderr, "###### %10s in %s:%d\n", __func__, __FILE__, __LINE__ );
4664 fprintf(stderr, "###### We don't know how to compare types %d and %d\n",
4665 left_side->type,
4666 right_side->type);
4667 __gg__abort("__gg__compare_2() couldn't do the comparison");
4668 }
4669
4670 // Normalize negative and positive to just -1 and +1
4671 if( retval < 0 )
4672 {
4673 retval = -1;
4674 }
4675 else if( retval > 0)
4676 {
4677 retval = 1;
4678 }
4679 return retval;
4680 }
4681
4682 extern "C"
4683 int
4684 __gg__compare(struct cblc_field_t *left,
4685 size_t left_offset,
4686 size_t left_length,
4687 size_t left_flags,
4688 struct cblc_field_t *right,
4689 size_t right_offset,
4690 size_t right_length,
4691 size_t right_flags,
4692 int second_time_through )
4693 {
4694 int retval;
4695 left_length = left_length ? left_length : left->capacity;
4696 right_length = right_length ? right_length : right->capacity;
4697 retval = __gg__compare_2( left,
4698 left->data + left_offset,
4699 left_length,
4700 left->attr,
4701 left_flags,
4702 right,
4703 right->data + right_offset,
4704 right_length,
4705 right->attr,
4706 right_flags,
4707 second_time_through);
4708 return retval;
4709 }
4710
4711 extern "C"
4712 void
4713 __gg__double_to_target(cblc_field_t *tgt, double tgt_value, cbl_round_t rounded)
4714 {
4715 int tgt_rdigits = 0;
4716
4717 if( tgt->attr & intermediate_e )
4718 {
4719 // We are calculating an intermediate result. We want to keep as
4720 // much of the fractional part as we can. We are using a double,
4721 // which can hold almost 16 digits. So, keep multiplying non-zero
4722 // value by 10 until it's that big. Limit the number of
4723 // multiplies, in case we were given a ridiculously tiny number to
4724 // begin with:
4725 const double digits = 1E15;
4726
4727 if( tgt_value )
4728 {
4729 while( tgt_value > -digits && tgt_value < digits && tgt_rdigits < 15 )
4730 {
4731 tgt_value *= 10.0;
4732 tgt_rdigits += 1;
4733 }
4734 }
4735 // Alter the run-time target's rdigits
4736 tgt->rdigits = tgt_rdigits;
4737 }
4738 else
4739 {
4740 // We want a specific number of rdigits. We will multiply by
4741 // 10^(tgt->rdigits + 1), to allow for the possibility of rounding:
4742 tgt_rdigits = tgt->rdigits+1;
4743 for(int i=0; i<tgt_rdigits; i++)
4744 {
4745 tgt_value *= 10.0;
4746 }
4747 }
4748
4749 __gg__int128_to_field(tgt,
4750 tgt_value,
4751 tgt_rdigits,
4752 rounded,
4753 NULL);
4754 }
4755
4756 struct for_sort_table
4757 {
4758 size_t nkeys;
4759 cblc_field_t **keys;
4760 size_t *ascending;
4761 unsigned char *contents;
4762 size_t *offsets;
4763 size_t base;
4764 };
4765
4766 static for_sort_table sorter;
4767
4768 static int
4769 compare_two_records(unsigned char *range1, unsigned char *range2)
4770 {
4771 int retval = 0;
4772
4773 for(size_t i=0; i<sorter.nkeys; i++)
4774 {
4775 // Pick up the basic information about the current key:
4776 cblc_field_t field1;
4777 cblc_field_t field2;
4778
4779 memcpy(&field1, sorter.keys[i], sizeof(cblc_field_t));
4780 memcpy(&field2, sorter.keys[i], sizeof(cblc_field_t));
4781
4782 // Establish the locations inside the contents buffer
4783 field1.data = range1
4784 + field1.offset
4785 - sorter.base;
4786 field2.data = range2
4787 + field2.offset
4788 - sorter.base;
4789
4790 // We handle descending by swapping the data sources:
4791 if( !sorter.ascending[i] )
4792 {
4793 std::swap(field1.data, field2.data);
4794 }
4795
4796 retval = __gg__compare( &field1,
4797 0,
4798 field1.capacity,
4799 0,
4800 &field2,
4801 0,
4802 field2.capacity,
4803 0,
4804 0 );
4805 if( retval != 0 )
4806 {
4807 break;
4808 }
4809 }
4810
4811 return retval;
4812 }
4813
4814 static int
4815 compare_for_sort_table(const size_t e1, const size_t e2)
4816 {
4817 int retval = 0;
4818 // Pick up the offsets to the two records:
4819 size_t offset1 = e1;
4820 size_t offset2 = e2;
4821
4822 offset1 += sizeof(size_t);
4823
4824 offset2 += sizeof(size_t);
4825
4826 retval = compare_two_records(sorter.contents + offset1,
4827 sorter.contents + offset2);
4828
4829 if(retval == 0)
4830 {
4831 // Create a stable sort by using the original offset as a way of breaking
4832 // ties:
4833 retval = e1 - e2;
4834 }
4835
4836 return retval < 0;
4837 }
4838
4839 static void
4840 sort_contents(unsigned char *contents,
4841 std::vector<size_t> &offsets,
4842 size_t key_base,
4843 size_t nkeys,
4844 cblc_field_t **keys,
4845 size_t *ascending,
4846 int /*duplicates*/)
4847 {
4848 sorter.contents = contents;
4849 sorter.offsets = offsets.data();
4850 sorter.base = key_base,
4851 sorter.nkeys = nkeys;
4852 sorter.keys = keys;
4853 sorter.ascending = ascending;
4854
4855 std::sort(offsets.begin(), offsets.end(), compare_for_sort_table);
4856 }
4857
4858 extern "C"
4859 void
4860 __gg__sort_table( const cblc_field_t *table,
4861 size_t table_o,
4862 size_t depending_on,
4863 size_t nkeys,
4864 cblc_field_t **keys,
4865 size_t *ascending,
4866 int duplicates )
4867 {
4868 size_t buffer_size = 128;
4869 unsigned char *contents = static_cast<unsigned char *>(malloc(buffer_size));
4870 size_t offset = 0;
4871 std::vector<size_t>offsets;
4872 size_t record_size = table->capacity;
4873 unsigned char *next_record = table->data + table_o;
4874
4875 // Convert the table to our normalized form
4876 for(size_t i=0; i<depending_on; i++)
4877 {
4878 while( offset + sizeof(size_t) + record_size > buffer_size )
4879 {
4880 buffer_size *= 2;
4881 contents = static_cast<unsigned char *>(realloc(contents, buffer_size));
4882 }
4883 offsets.push_back(offset);
4884 memcpy(contents+offset, &record_size, sizeof(size_t));
4885 offset += sizeof(size_t);
4886 memcpy(contents+offset, next_record, record_size);
4887 offset += record_size;
4888 next_record += record_size;
4889 }
4890
4891 // Sort it
4892 sort_contents(contents,
4893 offsets,
4894 table->offset,
4895 nkeys,
4896 keys,
4897 ascending,
4898 duplicates);
4899
4900 // Put the sorted contents back
4901 next_record = table->data + table_o;
4902 for(size_t i=0; i<depending_on; i++)
4903 {
4904 offset = offsets[i];
4905 offset += sizeof(size_t);
4906 memcpy(next_record, contents+offset, record_size);
4907 next_record += record_size;
4908 }
4909
4910 free(contents);
4911 }
4912
4913 static char *
4914 as_initial(char *initial)
4915 {
4916 if( (size_t)initial & ~0xF )
4917 {
4918 return initial;
4919 }
4920 else
4921 {
4922 static char empty_string[] = "";
4923 return empty_string;
4924 }
4925 }
4926
4927 static const int DEFAULT_BYTE_MASK = 0x00000000FF;
4928 static const int NSUBSCRIPT_MASK = 0x0000000F00;
4929 static const int NSUBSCRIPT_SHIFT = 8;
4930 static const int DEFAULTBYTE_BIT = 0x0000001000;
4931 static const int EXPLICIT_BIT = 0x0000002000;
4932 static const int REDEFINED_BIT = 0x0000004000;
4933 static const int JUST_ONCE_BIT = 0x0000008000;
4934
4935 static
4936 void
4937 init_var_both(cblc_field_t *var,
4938 unsigned char *qual_data,
4939 int flag_bits)
4940 {
4941 //fprintf(stderr, "CALLED WITH %s 0x%x\n", var->name, flag_bits);
4942
4943 if( flag_bits & JUST_ONCE_BIT && var->attr & initialized_e )
4944 {
4945 return;
4946 }
4947
4948 bool is_redefined = !!(flag_bits & REDEFINED_BIT);
4949 bool explicitly = !!(flag_bits & EXPLICIT_BIT);
4950 bool defaultbyte_in_play = !!(flag_bits & DEFAULTBYTE_BIT);
4951 char defaultbyte = flag_bits & DEFAULT_BYTE_MASK;
4952 unsigned int nsubscripts = (flag_bits & NSUBSCRIPT_MASK) >> NSUBSCRIPT_SHIFT;
4953
4954 if( var->data == NULL
4955 && var->attr & (intermediate_e)
4956 && var->type != FldLiteralA
4957 && var->type != FldLiteralN )
4958 {
4959 //fprintf(stderr, "ABORTING on %2.2d %s %d\n", var->level, var->name, var->type);
4960 //abort();
4961 var->data = static_cast<unsigned char *>(malloc(var->capacity));
4962 }
4963
4964 // Set the "initialized" bit, which is tested in parser_symbol_add to make
4965 // sure this code gets executed only once.
4966 //fprintf(stderr, "__gg__initialize_variable %s setting initialize_e\n", var->name);
4967 var->attr |= initialized_e;
4968
4969 // We need to make sure that the program_states vector has at least one
4970 // entry in it. This happens when we are the very first PROGRAM-ID called
4971 // in this module.
4972
4973 // When there is no DATA DIVISION, program_states will be empty the first time
4974 // we arrive here.
4975 if( program_states.empty() )
4976 {
4977 initialize_program_state();
4978 }
4979
4980 char *local_initial = as_initial(var->initial);
4981
4982 if( var->level == LEVEL88 )
4983 {
4984 // We need to convert the options to the internal native codeset
4985
4986 size_t buffer_size = 4;
4987 char *buffer = static_cast<char *>(malloc(buffer_size));
4988
4989 size_t index = 0;
4990
4991 const cblc_field_t *parent = var->parent;
4992 switch(parent->type)
4993 {
4994 case FldGroup:
4995 case FldAlphanumeric:
4996 {
4997 char *walker = local_initial;
4998 while(*walker)
4999 {
5000 static size_t first_size = MINIMUM_ALLOCATION_SIZE;
5001 static char *first = static_cast<char *>(malloc(first_size));
5002 static size_t last_size = MINIMUM_ALLOCATION_SIZE;
5003 static char *last = static_cast<char *>(malloc(last_size));
5004 if( (*walker & 0xFF) == 0xFF )
5005 {
5006 strcpy(first, walker);
5007 }
5008 else
5009 {
5010 raw_to_internal(&first, &first_size, walker, strlen(walker));
5011 }
5012 walker += strlen(first) + 1;
5013
5014 if( (*walker & 0xFF) == 0xFF )
5015 {
5016 strcpy(last, walker);
5017 }
5018 else
5019 {
5020 raw_to_internal(&last, &last_size, walker, strlen(walker));
5021 }
5022 walker += strlen(last) + 1;
5023 while(index + strlen(first) + strlen(last) + 3 > buffer_size)
5024 {
5025 buffer_size *= 2;
5026 buffer = static_cast<char *>(realloc(buffer, buffer_size));
5027 }
5028 strcpy(buffer+index, first);
5029 index += strlen(first) + 1;
5030 strcpy(buffer+index, last);
5031 index += strlen(last) + 1;
5032 }
5033 buffer[index++] = 0;
5034 break;
5035 }
5036 }
5037 if( index > 0 )
5038 {
5039 buffer = static_cast<char *>(realloc(buffer, index));
5040 local_initial = buffer;
5041 }
5042 }
5043
5044 // Next order of business: When the variable was allocated in
5045 // parser_symbol_add(), only LEVEL 01 variables had memory allocated. All
5046 // child variables were given NULL data pointers. It is at this point that
5047 // we apply offsets:
5048
5049 cblc_field_t *parent = var->parent;
5050 if( !var->data )
5051 {
5052
5053 // We don't have any data. If our immediate parent does have data, then
5054 // we can calculate our data+offset from his data+offset:
5055
5056 if( parent && parent->data )
5057 {
5058 var->data = parent->data - parent->offset + var->offset;
5059 }
5060 }
5061
5062 if( !var->data )
5063 {
5064 // This can happen with BASED variables before they are allocated
5065 return;
5066 }
5067
5068 if( !(var->attr & based_e) && (var->attr & external_e) )
5069 {
5070 // These types can't be initialized
5071 return;
5072 }
5073
5074 // There are times, for example, when we are table with OCCURS, that we
5075 // look like a variable with no initial, and we might be tempted to set our
5076 // memory to the default. But if a parent has been initialized, we must not
5077 // touch our memory:
5078 bool a_parent_initialized = false;
5079 if( !explicitly )
5080 {
5081 while(parent)
5082 {
5083 if( strlen(as_initial(parent->initial)) )
5084 {
5085 a_parent_initialized = true;
5086 }
5087 if( parent->level == LEVEL01
5088 || parent->level == LEVEL77)
5089 {
5090 break;
5091 }
5092 parent = parent->parent; // I can't help it. This just tickles me.
5093 }
5094 }
5095
5096 if( is_redefined || a_parent_initialized || var->level == LEVEL66 || var->level == LEVEL88)
5097 {
5098 // Don't initialize variables that have the REDEFINES clause. Many things
5099 // in COBOL programs don't work if you do, in particular the initialization
5100 // of tables.
5101
5102 // Likewise, don't initialize variables with an OCCURS clause. To do so
5103 // means that we will likely clobber the values in the flat data item we
5104 // effectively redefine.
5105 return;
5106 }
5107
5108 // This is a little brutish, but it is nonetheless simple, effective, and
5109 // not at all costly. The numeric-edited variable type can have a
5110 // BLANK WHEN ZERO clause, which causes the storage to be set to spaces
5111 // when receiving a value of zero. But according to the ISO/IEC 1989:2014
5112 // specification, section 13.18.63.3 sentence 8, initialization is not
5113 // affected by any BLANK WHEN ZERO clause.
5114
5115 // So, I am going to rather ham-handedly turn that bit off here, and
5116 // restore it when initialization is done.
5117
5118 // Save this for later
5119 int save_the_attribute = var->attr;
5120
5121 // Turn off the bit in question
5122 var->attr &= ~blank_zero_e;
5123
5124 size_t capacity = var->capacity ;
5125
5126 size_t number_of_dimensions = 0;
5127 size_t limits[MAXIMUM_TABLE_DIMENSIONS];
5128 size_t capacities[MAXIMUM_TABLE_DIMENSIONS];
5129 size_t dimension[MAXIMUM_TABLE_DIMENSIONS+1];
5130
5131 bool there_can_be_more = nsubscripts == 0;
5132 if( nsubscripts == 0 )
5133 {
5134 cblc_field_t *family_tree = var;
5135 while(family_tree && number_of_dimensions < MAXIMUM_TABLE_DIMENSIONS)
5136 {
5137 if( family_tree->occurs_upper )
5138 {
5139 limits[number_of_dimensions] = family_tree->occurs_upper;
5140 capacities[number_of_dimensions] = family_tree->capacity;
5141 dimension[number_of_dimensions] = 0;
5142 number_of_dimensions += 1;
5143 }
5144
5145 family_tree = family_tree->parent;
5146 }
5147
5148 switch( var->type )
5149 {
5150 case FldIndex:
5151 case FldGroup:
5152 case FldClass:
5153 there_can_be_more = false;
5154 break;
5155 default:
5156 break;
5157 }
5158 }
5159
5160 // We need to save the location in case we start changing the location
5161 // to handle initializing table elements:
5162 unsigned char *save_the_location = var->data;
5163 bool there_is_more = false;
5164 unsigned char *outer_location;
5165 if( nsubscripts )
5166 {
5167 outer_location = qual_data;
5168 }
5169 else
5170 {
5171 outer_location = var->data;
5172 }
5173 do
5174 {
5175 var->data = outer_location;
5176 switch( var->type )
5177 {
5178 case FldGroup:
5179 case FldAlphanumeric:
5180 case FldAlphaEdited:
5181 case FldNumericEdited:
5182 case FldLiteralA:
5183 {
5184 // Any initialization values were converted to single-byte-coding in the
5185 // right codeset during parser_symbol_add()
5186 if( var->initial )
5187 {
5188 memcpy(outer_location, var->initial, var->capacity);
5189 }
5190 else
5191 {
5192 if( !defaultbyte_in_play )
5193 {
5194 memset( outer_location,
5195 internal_space,
5196 capacity );
5197 }
5198 else
5199 {
5200 memset( outer_location,
5201 defaultbyte,
5202 capacity );
5203 }
5204 }
5205 break;
5206 }
5207
5208 case FldNumericDisplay:
5209 {
5210 // Any initialization values were converted to single-byte-coding in the
5211 // right codeset during parser_symbol_add()
5212 if( var->initial )
5213 {
5214 memcpy(outer_location, var->initial, var->capacity);
5215 }
5216 else
5217 {
5218 if( !defaultbyte_in_play )
5219 {
5220 memset( outer_location,
5221 internal_zero,
5222 capacity );
5223 if( (var->attr & signable_e) && (var->attr & separate_e) )
5224 {
5225 if( var->attr & leading_e )
5226 {
5227 outer_location[0] = internal_plus;
5228 }
5229 else
5230 {
5231 outer_location[var->capacity-1] = internal_plus;
5232 }
5233 }
5234 }
5235 else
5236 {
5237 memset( outer_location,
5238 defaultbyte,
5239 capacity );
5240 }
5241 }
5242 break;
5243 }
5244
5245 case FldNumericBinary:
5246 case FldPacked:
5247 case FldNumericBin5:
5248 case FldIndex:
5249 case FldFloat:
5250 {
5251 // During parser_symbol_add(), the original text initial value was turned
5252 // into the appropriate binary value.
5253 if( var->initial )
5254 {
5255 memcpy(outer_location, var->initial, var->capacity);
5256 }
5257 else
5258 {
5259 if( !defaultbyte_in_play )
5260 {
5261 memset( outer_location,
5262 0,
5263 capacity );
5264 }
5265 else
5266 {
5267 memset( outer_location,
5268 defaultbyte,
5269 capacity );
5270 }
5271 }
5272 break;
5273 }
5274
5275 case FldLiteralN:
5276 break;
5277
5278 case FldClass:
5279 // Do nothing for class
5280 break;
5281
5282 case FldPointer:
5283 memset(var->data, 0, var->capacity);
5284 break;
5285
5286 default:
5287 fprintf(stderr, "###### %10s in %s:%d\n", __func__, __FILE__, __LINE__ );
5288 fprintf(stderr, "###### You got yourself a new CVT_type %d for variable %s (%s)\n",
5289 var->type,
5290 var->name,
5291 local_initial);
5292 __gg__abort("Unknown variable type");
5293 }
5294
5295 char *location = reinterpret_cast<char *>(save_the_location);
5296
5297 there_is_more = false;
5298 size_t i=0;
5299 // Roll up through the dimensions like an odometer.
5300 for(i=0; i<number_of_dimensions; i++)
5301 {
5302 if( ++dimension[i] < limits[i] )
5303 {
5304 break;
5305 }
5306 dimension[i] = 0;
5307 }
5308 if( i < number_of_dimensions )
5309 {
5310 there_is_more = there_can_be_more;
5311 }
5312 if( there_is_more )
5313 {
5314 // Augment location by the size of each dimension:
5315 for(i=0; i<number_of_dimensions; i++)
5316 {
5317 location += dimension[i] * capacities[i];
5318 }
5319 }
5320
5321 outer_location = reinterpret_cast<unsigned char *>(location);
5322 } while(there_is_more);
5323
5324 var->data = save_the_location;
5325
5326 // See the comment up above about suppressing and restoring
5327 // BLANK WHEN ZERO during initialization.
5328 var->attr |= (save_the_attribute&blank_zero_e);
5329 }
5330
5331 extern "C"
5332 void
5333 __gg__initialize_variable(cblc_field_t *var,
5334 size_t offset,
5335 int flag_bits)
5336 {
5337 init_var_both( var,
5338 var->data + offset,
5339 flag_bits);
5340 }
5341
5342 extern "C"
5343 void
5344 __gg__initialize_variable_clean(cblc_field_t *var, int flag_bits)
5345 {
5346 // if( var->type == FldLiteralA )
5347 // {
5348 // fprintf(stderr, "BAZINGA!\n");
5349 // }
5350
5351 init_var_both( var,
5352 var->data,
5353 flag_bits);
5354 }
5355
5356 static void
5357 alpha_to_alpha_move_from_location(cblc_field_t *field,
5358 size_t dest_offset,
5359 size_t dest_length,
5360 const char * source_location,
5361 size_t source_length,
5362 bool move_all)
5363 {
5364 // This is a helper function, called when it is known that both source
5365 // and dest are alphanumeric
5366 dest_length = dest_length ? dest_length : field->capacity;
5367
5368 char *to = reinterpret_cast<char *>(field->data + dest_offset);
5369 const char *from = source_location;
5370 size_t count = std::min(dest_length, source_length);
5371
5372 if( source_length >= dest_length )
5373 {
5374 // We have more source characters than places to put them
5375 if( field->attr & rjust_e )
5376 {
5377 // Destination is right-justified, so we
5378 // discard the leading source characters:
5379 memmove(to,
5380 from + (source_length - count),
5381 count);
5382 }
5383 else
5384 {
5385 // Destination is right-justified, so we
5386 // discard the trailing source characters:
5387 memmove(to,
5388 from,
5389 count);
5390 }
5391 }
5392 else
5393 {
5394 // We have too few source characters to fill the destination.
5395 if( field->attr & rjust_e )
5396 {
5397 // The destination is right-justified
5398 if( move_all )
5399 {
5400 // This does "BOBBO"
5401 size_t isource = 0;
5402 for(size_t i=0; i<dest_length; i++)
5403 {
5404 to[i] = from[isource++];
5405 if( isource >= source_length )
5406 {
5407 isource = 0;
5408 }
5409 }
5410 }
5411 else
5412 {
5413 // The destination is right-justified, and the source is an
5414 // ordinary string too short to fill it. So, we space-fill
5415 // the leading characters.
5416 // We do the move first, in case this is an overlapping move
5417 // involving characters that will be space-filled
5418 memmove(to + (dest_length-count),
5419 from,
5420 count);
5421 memset(to, internal_space, dest_length-count);
5422 }
5423 }
5424 else
5425 {
5426 // The source is smaller than the destination
5427 // The destination is left-justified
5428 if( move_all )
5429 {
5430 // and the source is move_all. We will repeat the input until
5431 // it fills the output, starting from the left side.
5432 size_t isource = 0;
5433 for(size_t i=0; i<dest_length; i++)
5434 {
5435 to[i] = from[isource++];
5436 if( isource >= source_length )
5437 {
5438 isource = 0;
5439 }
5440 }
5441 }
5442 else
5443 {
5444 // The destination is right-justified, and the source is an
5445 // ordinary string too short to fill it. So, we space-fill
5446 // the trailing characters.
5447 // We do the move first, in case this is an overlapping move
5448 // involving characters that will be space-filled
5449 memmove(to,
5450 from,
5451 count);
5452 memset( to + count,
5453 internal_space,
5454 dest_length-count);
5455 }
5456 }
5457 }
5458 }
5459
5460 static void
5461 alpha_to_alpha_move(cblc_field_t *dest,
5462 size_t dest_offset,
5463 size_t dest_size,
5464 const cblc_field_t *source,
5465 size_t source_offset,
5466 size_t source_size,
5467 bool source_move_all)
5468 {
5469 alpha_to_alpha_move_from_location( dest,
5470 dest_offset,
5471 dest_size,
5472 reinterpret_cast<char *>(source->data + source_offset),
5473 source_size,
5474 source_move_all);
5475 }
5476
5477 extern "C"
5478 void
5479 __gg__psz_to_alpha_move( cblc_field_t *field,
5480 size_t offset,
5481 size_t length,
5482 const char *source,
5483 size_t source_length )
5484 {
5485 alpha_to_alpha_move_from_location( field,
5486 offset,
5487 length,
5488 source,
5489 source_length,
5490 false);
5491 }
5492
5493 extern "C"
5494 int
5495 __gg__move( cblc_field_t *fdest,
5496 size_t dest_offset,
5497 size_t dest_size,
5498 cblc_field_t *fsource,
5499 size_t source_offset,
5500 size_t source_size,
5501 int source_flags,
5502 cbl_round_t rounded )
5503 {
5504 int size_error = 0; // This is the return value
5505
5506 __int128 value;
5507 int rdigits;
5508
5509 cbl_figconst_t source_figconst =
5510 (cbl_figconst_t)(fsource->attr & FIGCONST_MASK);
5511 cbl_field_type_t dest_type = (cbl_field_type_t)fdest->type;
5512 cbl_field_type_t source_type = (cbl_field_type_t)fsource->type;
5513
5514 if( var_is_refmod(fdest) )
5515 {
5516 // one or both are refmods,
5517 dest_type = FldAlphanumeric;
5518 if( source_figconst == normal_value_e )
5519 {
5520 source_type = FldAlphanumeric;
5521 }
5522 }
5523
5524 if( ( source_figconst == low_value_e
5525 || source_figconst == space_value_e
5526 || source_figconst == quote_value_e
5527 || source_figconst == high_value_e )
5528 &&
5529 ( fdest->type == FldNumericBinary
5530 || fdest->type == FldPacked
5531 || fdest->type == FldNumericBin5
5532 || fdest->type == FldNumericDisplay
5533 || fdest->type == FldFloat )
5534 )
5535 {
5536 // Regardless of what you see below, as time went on it became clear that
5537 // high-value and low-value required special processing in order to cope
5538 // with code. Or, at least, to cope with legacy tests.
5539
5540 // The ISO 2014 specification has this to say about the moving of figurative
5541 // constants to numerics:
5542
5543 // 14.9.24.3, paragraph 7)
5544
5545 /* NOTE: MOVE of the figurative constant QUOTE or QUOTES to a numeric data
5546 * item is an obsolete feature and is to be removed from the next edition
5547 * of standard COBOL. MOVE of figurative constants that are not numeric,
5548 * other than QUOTE or QUOTES, to a numeric item is an archaic feature of
5549 * standard COBOL and its use should be avoided
5550 */
5551
5552 int special_char = 0; // quiets cppcheck
5553 if( source_figconst == low_value_e )
5554 {
5555 special_char = ascii_to_internal(__gg__low_value_character);
5556 }
5557 else if( source_figconst == high_value_e )
5558 {
5559 special_char = ascii_to_internal(__gg__high_value_character);
5560 }
5561 else if( source_figconst == quote_value_e )
5562 {
5563 special_char = ascii_to_internal(__gg__quote_character);
5564 }
5565 else if( source_figconst == space_value_e )
5566 {
5567 special_char = ascii_to_internal(ascii_space);
5568 }
5569 memset( fdest->data + dest_offset,
5570 special_char,
5571 dest_size);
5572 }
5573 else
5574 {
5575 size_t min_length;
5576 bool moved = true;
5577 switch( dest_type )
5578 {
5579 case FldGroup:
5580 switch( source_type )
5581 {
5582 // For all other types, we just do a straight byte-for-byte move
5583 case FldAlphanumeric:
5584 case FldNumericEdited:
5585 case FldAlphaEdited:
5586 case FldNumericDisplay:
5587 case FldNumericBinary:
5588 case FldPacked:
5589 case FldNumericBin5:
5590 case FldGroup:
5591 // This is a little bold, but non-alphabetics will never
5592 // have the rjust_e or MOVE_ALL bits on, so it's safe
5593 // enough.
5594 alpha_to_alpha_move(fdest,
5595 dest_offset,
5596 dest_size,
5597 fsource,
5598 source_offset,
5599 source_size,
5600 !!(source_flags & REFER_T_MOVE_ALL));
5601 break;
5602
5603 default:
5604 moved = false;
5605 break;
5606 }
5607
5608 break;
5609
5610 case FldAlphanumeric:
5611 {
5612 switch( source_type )
5613 {
5614 case FldGroup:
5615 alpha_to_alpha_move(fdest,
5616 dest_offset,
5617 dest_size,
5618 fsource,
5619 source_offset,
5620 source_size,
5621 !!(source_flags & REFER_T_MOVE_ALL));
5622 break;
5623
5624 case FldAlphanumeric:
5625 case FldNumericEdited:
5626 case FldAlphaEdited:
5627 // This is an ordinary alpha-to-alpha move:
5628 alpha_to_alpha_move(fdest,
5629 dest_offset,
5630 dest_size,
5631 fsource,
5632 source_offset,
5633 source_size,
5634 !!(source_flags & REFER_T_MOVE_ALL));
5635 break;
5636
5637 case FldNumericDisplay:
5638 // We are moving a FldNumericDisplay to an alphanumeric:
5639 if( fsource->rdigits > 0 )
5640 {
5641 fprintf(stderr, "%s() %s:%d -- It isn't legal to move a"
5642 " non-integer NumericDisplay to an"
5643 " alphanumeric\n",
5644 __func__, __FILE__, __LINE__);
5645 fprintf( stderr,
5646 "%s to %s\n",
5647 fsource->name,
5648 fdest->name);
5649 abort();
5650 }
5651 else
5652 {
5653 // We are moving a integer NumericDisplay to an
5654 // alphanumeric. We ignore any sign bit, and just
5655 // move the characters:
5656
5657 size_t source_digits
5658 = fsource->digits
5659 + ( fsource->rdigits < 0
5660 ? -fsource->rdigits : 0) ;
5661
5662 // Pick up the absolute value of the source
5663 value = __gg__binary_value_from_qualified_field(&rdigits,
5664 fsource,
5665 source_offset,
5666 source_size);
5667
5668 char ach[128];
5669
5670 // Convert it to the full complement of digits available
5671 // from the source...but no more
5672 __gg__binary_to_string_internal(ach, source_digits, value);
5673
5674 if( !(fdest->attr & rjust_e) )
5675 {
5676 min_length = std::min( source_digits,
5677 dest_size);
5678 memmove(fdest->data + dest_offset, ach, min_length);
5679 if( min_length < dest_size )
5680 {
5681 // min_length is smaller than dest_length, so we
5682 // have to space-fill the excess bytes in the
5683 // destination:
5684 memset( fdest->data + dest_offset + min_length,
5685 internal_space,
5686 dest_size - min_length );
5687 }
5688 }
5689 else
5690 {
5691 // Destination is right-justified, so things are
5692 // slightly more complex
5693 if( source_digits >= dest_size )
5694 {
5695 // We need to truncate the source data on the
5696 // left:
5697 memmove(
5698 fdest->data + dest_offset,
5699 ach + (source_digits - dest_size),
5700 dest_size );
5701 }
5702 else
5703 {
5704 // We need to move the shorty source string to
5705 // the right side of the destination, and space-fill
5706 // the prefix:
5707 memmove(fdest->data + dest_offset + (dest_size - source_digits),
5708 ach,
5709 source_digits );
5710 memset( fdest->data + dest_offset,
5711 internal_space,
5712 dest_size - source_digits);
5713 }
5714 }
5715 }
5716 break;
5717
5718 case FldNumericBinary:
5719 case FldPacked:
5720 case FldNumericBin5:
5721 case FldLiteralN:
5722 // We are moving a binary number to an alphanumeric:
5723 if( fsource->rdigits > 0 )
5724 {
5725 fprintf(stderr, "%s() %s:%d -- It isn't legal to move a"
5726 " non-integer binary number to an"
5727 " alphanumeric\n",
5728 __func__, __FILE__, __LINE__);
5729 fprintf(stderr, "%s to %s\n", fsource->name, fdest->name);
5730 abort();
5731 }
5732 else
5733 {
5734 char ach[128];
5735
5736 // Turn the integer source into a value:
5737 value = __gg__binary_value_from_qualified_field(&rdigits,
5738 fsource,
5739 source_offset,
5740 source_size);
5741
5742 source_size = fsource->digits;
5743
5744 // Turn the integer value into a string:
5745 __gg__binary_to_string_internal(ach,
5746 source_size,
5747 value);
5748
5749 char *pach = ach;
5750
5751 // When source is a temporary variable, it was set to
5752 // a large number of digits, which will give the wrong
5753 // result. So, we will make like the US Marine Corp,
5754 // and improvise, adapt, and overcome.
5755
5756 // Specifically, we'll move pach to point to the first
5757 // character that isn't zero.
5758
5759 if( fsource->attr & intermediate_e )
5760 {
5761 while(source_size > 1) // This ensures we leave one '0'
5762 {
5763 if( *(pach+1) == '\0' )
5764 {
5765 break;
5766 }
5767 if( ((*pach)&0xFF) != internal_zero )
5768 {
5769 break;
5770 }
5771 pach += 1;
5772 source_size -= 1;
5773 }
5774 }
5775
5776 if( !(fdest->attr & rjust_e) )
5777 {
5778 min_length = std::min( source_size,
5779 dest_size);
5780 memmove(fdest->data+dest_offset, pach, min_length);
5781 if( min_length < dest_size )
5782 {
5783 // min_length is smaller than dest_length, so we have to
5784 // space-fill the excess bytes in the destination:
5785 memset( fdest->data+dest_offset + min_length,
5786 internal_space,
5787 dest_size - min_length );
5788 }
5789 }
5790 else
5791 {
5792 // Destination is right-justified, so things are slightly more complex
5793 if( source_size >= dest_size )
5794 {
5795 // We need to truncate the source data on the left:
5796 memmove(fdest->data+dest_offset,
5797 pach + (source_size - dest_size),
5798 dest_size );
5799 }
5800 else
5801 {
5802 // We need to move the shorty source string to the
5803 // right side of the destination, and space-fill the prefix:
5804 memmove(fdest->data+dest_offset + (dest_size - source_size),
5805 pach,
5806 source_size );
5807 memset(fdest->data+dest_offset, internal_space, (dest_size - source_size));
5808 }
5809 }
5810 }
5811 break;
5812
5813 case FldIndex:
5814 {
5815 char ach[128];
5816
5817 // Turn the integer source into a value:
5818 value = __gg__binary_value_from_qualified_field(&rdigits,
5819 fsource,
5820 source_offset,
5821 source_size);
5822 sprintf(ach, "%lu", (unsigned long)value);
5823
5824 char *pach = ach;
5825
5826 if( !(fdest->attr & rjust_e) )
5827 {
5828 min_length = std::min( source_size,
5829 dest_size);
5830 memmove(fdest->data+dest_offset, pach, min_length);
5831 if( min_length < dest_size )
5832 {
5833 // min_length is smaller than dest_length, so we have to
5834 // space-fill the excess bytes in the destination:
5835 memset( fdest->data+dest_offset + min_length,
5836 internal_space,
5837 dest_size - min_length );
5838 }
5839 }
5840 else
5841 {
5842 // Destination is right-justified, so things are slightly more complex
5843 if( source_size >= dest_size )
5844 {
5845 // We need to truncate the source data on the left:
5846 memmove(fdest->data+dest_offset,
5847 pach + (source_size - dest_size),
5848 dest_size );
5849 }
5850 else
5851 {
5852 // We need to move the shorty source string to the
5853 // right side of the destination, and space-fill the prefix:
5854 memmove(fdest->data+dest_offset + (dest_size - source_size),
5855 pach,
5856 source_size );
5857 memset(fdest->data+dest_offset, internal_space, (dest_size - source_size));
5858 }
5859 }
5860 }
5861 break;
5862
5863 default:
5864 moved = false;
5865 break;
5866 }
5867 break;
5868 }
5869
5870 case FldNumericBinary:
5871 {
5872 switch( source_type )
5873 {
5874 case FldGroup:
5875 min_length = std::min(source_size, dest_size);
5876 memmove(fdest->data+dest_offset, fsource->data+source_offset, min_length);
5877 if( min_length < dest_size )
5878 {
5879 // min_length is smaller than dest_length, so we have to
5880 // space-fill the excess bytes in the destination:
5881 memset( fdest->data+dest_offset + min_length,
5882 internal_space,
5883 dest_size - min_length );
5884 }
5885 fdest->attr &= ~FIGCONST_MASK;
5886 break;
5887
5888 case FldAlphanumeric:
5889 case FldNumericDisplay:
5890 case FldNumericEdited:
5891 case FldNumericBinary:
5892 case FldPacked:
5893 case FldNumericBin5:
5894 case FldIndex:
5895 case FldLiteralN:
5896 {
5897 // We are moving a number to a number:
5898 value = __gg__binary_value_from_qualified_field(&rdigits,
5899 fsource,
5900 source_offset,
5901 source_size);
5902
5903 if( truncation_mode == trunc_std_e )
5904 {
5905 // We need to adjust the value to have the rdigits of the
5906 // the destination:
5907
5908 int scaler = rdigits - fdest->rdigits;
5909 if( scaler > 0 )
5910 {
5911 value /= __gg__power_of_ten(scaler);
5912 rdigits -= scaler;
5913 }
5914 else if( scaler < 0 )
5915 {
5916 value *= __gg__power_of_ten(-scaler);
5917 rdigits -= scaler;
5918 }
5919 if( value < 0 )
5920 {
5921 value = -value;
5922 value %= __gg__power_of_ten(fdest->digits);
5923 value = -value;
5924 }
5925 else
5926 {
5927 value %= __gg__power_of_ten(fdest->digits);
5928 }
5929 }
5930
5931 __gg__int128_to_qualified_field(
5932 fdest,
5933 dest_offset,
5934 dest_size,
5935 value,
5936 rdigits,
5937 rounded,
5938 &size_error );
5939 break;
5940 }
5941
5942 case FldFloat:
5943 {
5944 rdigits = get_scaled_rdigits(fdest);
5945 bool negative = false;
5946 __int128 value128 = 0;
5947 switch(fsource->capacity)
5948 {
5949 case 4:
5950 {
5951 _Float32 val = *PTRCAST(_Float32, fsource->data+source_offset);
5952 if(val < 0)
5953 {
5954 negative = true;
5955 val = -val;
5956 }
5957 val *= static_cast<_Float32>(__gg__power_of_ten(rdigits));
5958 value128 = (__int128)val;
5959 break;
5960 }
5961 case 8:
5962 {
5963 _Float64 val = *PTRCAST(_Float64, fsource->data+source_offset);
5964 if(val < 0)
5965 {
5966 negative = true;
5967 val = -val;
5968 }
5969 val *= (_Float32)__gg__power_of_ten(rdigits);
5970 value128 = (__int128)val;
5971 break;
5972 }
5973 case 16:
5974 {
5975 //_Float128 val = *(_Float128 *)(fsource->data+source_offset);
5976 GCOB_FP128 val;
5977 memcpy(&val, fsource->data+source_offset, 16);
5978 if(val < 0)
5979 {
5980 negative = true;
5981 val = -val;
5982 }
5983 val *= (_Float32)__gg__power_of_ten(rdigits);
5984 value128 = (__int128)val;
5985 break;
5986 }
5987 }
5988 if( negative )
5989 {
5990 value128 = -value128;
5991 }
5992 __gg__int128_to_qualified_field(
5993 fdest,
5994 dest_offset,
5995 dest_size,
5996 value128,
5997 rdigits,
5998 rounded,
5999 &size_error );
6000 break;
6001 }
6002
6003 default:
6004 {
6005 moved = false;
6006 break;
6007 }
6008 }
6009 break;
6010 }
6011
6012 case FldNumericDisplay:
6013 case FldNumericEdited:
6014 case FldNumericBin5:
6015 case FldPacked:
6016 case FldIndex:
6017 // Bin5 and Index are treated with no truncation, as if they were
6018 // trunc_bin_e. The other types aren't subject to truncation.
6019 switch( source_type )
6020 {
6021 case FldGroup:
6022 min_length = std::min(source_size, dest_size);
6023 memmove(fdest->data+dest_offset, fsource->data+source_offset, min_length);
6024 if( min_length < dest_size )
6025 {
6026 // min_length is smaller than dest_length, so we have to
6027 // space-fill the excess bytes in the destination:
6028 memset( fdest->data+dest_offset + min_length,
6029 internal_space,
6030 dest_size - min_length );
6031 }
6032 break;
6033
6034 case FldAlphanumeric:
6035 case FldNumericDisplay:
6036 case FldNumericEdited:
6037 case FldNumericBinary:
6038 case FldPacked:
6039 case FldNumericBin5:
6040 case FldIndex:
6041 case FldLiteralN:
6042 {
6043 // We are moving a number to a number:
6044 value = __gg__binary_value_from_qualified_field(&rdigits,
6045 fsource,
6046 source_offset,
6047 source_size);
6048 __gg__int128_to_qualified_field(
6049 fdest,
6050 dest_offset,
6051 dest_size,
6052 value,
6053 rdigits,
6054 rounded,
6055 &size_error );
6056 break;
6057 }
6058
6059 case FldFloat:
6060 {
6061 // We are converted a floating-point value fixed-point
6062
6063 rdigits = get_scaled_rdigits(fdest);
6064 GCOB_FP128 fp128=0;
6065 switch(fsource->capacity)
6066 {
6067 case 4:
6068 {
6069 fp128 = *reinterpret_cast<_Float32 *>(fsource->data+source_offset);
6070 break;
6071 }
6072 case 8:
6073 {
6074 fp128 = *reinterpret_cast<_Float64 *>(fsource->data+source_offset);
6075 break;
6076 }
6077 case 16:
6078 {
6079 // value = *(_Float128 *)(fsource->data+source_offset);
6080 memcpy(&fp128, fsource->data+source_offset, 16);
6081 break;
6082 }
6083 }
6084 __gg__float128_to_qualified_field(
6085 fdest,
6086 dest_offset,
6087 fp128,
6088 rounded,
6089 &size_error);
6090 break;
6091 }
6092
6093 default:
6094 moved = false;
6095 break;
6096 }
6097 break;
6098
6099 case FldAlphaEdited:
6100 {
6101 switch( source_type )
6102 {
6103 case FldGroup:
6104 min_length = std::min(source_size, dest_size);
6105 memmove(fdest->data+dest_offset, fsource->data+source_offset, min_length);
6106 if( min_length < dest_size )
6107 {
6108 // min_length is smaller than dest_length, so we have to
6109 // space-fill the excess bytes in the destination:
6110 memset( fdest->data+dest_offset + min_length,
6111 internal_space,
6112 dest_size - min_length );
6113 }
6114 break;
6115
6116 case FldNumericDisplay:
6117 {
6118 int source_digits = fsource->digits + (fsource->rdigits<0 ? -fsource->rdigits : 0) ;
6119
6120 // Pick up the absolute value of the source
6121 value = __gg__binary_value_from_qualified_field(&rdigits,
6122 fsource,
6123 source_offset,
6124 source_size);
6125 char ach[64];
6126
6127 // Convert it to the full complement of digits available
6128 // from the source...but no more
6129 __gg__binary_to_string(ach, source_digits, value);
6130
6131 // Binary to string returns ASCII characters:
6132 for(int i=0; i<source_digits; i++)
6133 {
6134 ach[i] = ascii_to_internal(ach[i]);
6135 }
6136
6137 // And move them into place:
6138 __gg__string_to_alpha_edited( reinterpret_cast<char *>(fdest->data+dest_offset),
6139 ach,
6140 source_digits,
6141 fdest->picture);
6142 break;
6143 }
6144
6145 default:
6146 {
6147 static size_t display_string_size = MINIMUM_ALLOCATION_SIZE;
6148 static char *display_string = static_cast<char *>(malloc(display_string_size));
6149
6150 size_t display_string_length = dest_size;
6151 __gg__realloc_if_necessary( &display_string,
6152 &display_string_size,
6153 display_string_length);
6154
6155 if( source_figconst == low_value_e )
6156 {
6157 memset(display_string, ascii_to_internal(__gg__low_value_character), dest_size);
6158 }
6159 else if( source_figconst == zero_value_e )
6160 {
6161 memset(display_string, internal_zero, dest_size);
6162 }
6163 else if( source_figconst == space_value_e )
6164 {
6165 memset(display_string, internal_space, dest_size);
6166 }
6167 else if( source_figconst == quote_value_e )
6168 {
6169 memset(display_string, ascii_to_internal(__gg__quote_character), dest_size);
6170 }
6171 else if( source_figconst == high_value_e )
6172 {
6173 memset(display_string, ascii_to_internal(__gg__high_value_character), dest_size);
6174 }
6175 else
6176 {
6177 display_string = format_for_display_internal(
6178 &display_string,
6179 &display_string_size,
6180 fsource,
6181 reinterpret_cast<unsigned char *>(fsource->data+source_offset),
6182 source_size,
6183 source_flags && REFER_T_ADDRESS_OF);
6184 display_string_length = strlen(display_string);
6185 }
6186 __gg__string_to_alpha_edited( reinterpret_cast<char *>(fdest->data+dest_offset),
6187 display_string,
6188 display_string_length,
6189 fdest->picture);
6190 break;
6191 }
6192 }
6193 break;
6194 }
6195
6196 case FldFloat:
6197 {
6198 switch( source_type )
6199 {
6200 case FldAlphanumeric:
6201 {
6202 char ach[256];
6203 size_t len = std::min(source_size, sizeof(ach)-1);
6204 memcpy(ach, fsource->data+source_offset, len);
6205 ach[len] = '\0';
6206 __gg__internal_to_console_in_place(ach, len);
6207 switch( fdest->capacity )
6208 {
6209 case 4:
6210 {
6211 *PTRCAST(float, fdest->data+dest_offset) = strtod(ach, NULL);
6212 break;
6213 }
6214 case 8:
6215 {
6216 *PTRCAST(double, fdest->data+dest_offset) = strtod(ach, NULL);
6217 break;
6218 }
6219 case 16:
6220 {
6221 //*(_Float128 *)(fdest->data+dest_offset) = strtofp128(ach, NULL);
6222 GCOB_FP128 t = strtofp128(ach, NULL);
6223 memcpy(fdest->data+dest_offset, &t, 16);
6224 break;
6225 }
6226 }
6227 break;
6228 }
6229 default:
6230 moved = false;
6231 break;
6232 }
6233 break;
6234 }
6235
6236 default:
6237 moved = false;
6238 break;
6239 }
6240 if( !moved )
6241 {
6242 fprintf(stderr, "%s() %s:%d -- We were unable to do a move from "
6243 "type %d to %d\n",
6244 __func__, __FILE__, __LINE__,
6245 fsource->type, fdest->type);
6246 abort();
6247 }
6248 }
6249 return size_error;
6250 }
6251
6252 extern "C"
6253 int
6254 __gg__move_literala(cblc_field_t *field,
6255 size_t field_offset,
6256 size_t field_size,
6257 cbl_round_t rounded_,
6258 const char *str,
6259 size_t strlen )
6260 {
6261 cbl_round_t rounded = static_cast<cbl_round_t>(rounded_ & ~REFER_ALL_BIT);
6262 bool move_all = !!(rounded_ & REFER_ALL_BIT);
6263
6264 int size_error = 0; // This is the return value
6265
6266 bool moved = true;
6267
6268 __int128 value;
6269 int rdigits;
6270
6271 cbl_field_type_t dest_type = (cbl_field_type_t)field->type;
6272 if( var_is_refmod(field) )
6273 {
6274 dest_type = FldAlphanumeric;
6275 }
6276
6277 switch( dest_type )
6278 {
6279 case FldGroup:
6280 case FldAlphanumeric:
6281 {
6282 alpha_to_alpha_move_from_location(field, field_offset, field_size, str, strlen, move_all);
6283 break;
6284 }
6285
6286 case FldNumericBinary:
6287 {
6288 value = __gg__dirty_to_binary_internal( str,
6289 strlen,
6290 &rdigits );
6291 if( truncation_mode == trunc_std_e )
6292 {
6293 // We need to adjust the value to have the rdigits of the
6294 // the destination:
6295
6296 int scaler = rdigits - field->rdigits;
6297 if( scaler > 0 )
6298 {
6299 value /= __gg__power_of_ten(scaler);
6300 rdigits -= scaler;
6301 }
6302 else if( scaler < 0 )
6303 {
6304 value *= __gg__power_of_ten(-scaler);
6305 rdigits -= scaler;
6306 }
6307
6308 if( value < 0 )
6309 {
6310 value = -value;
6311 value %= __gg__power_of_ten(field->digits);
6312 value = -value;
6313 }
6314 else
6315 {
6316 value %= __gg__power_of_ten(field->digits);
6317 }
6318 }
6319 __gg__int128_to_qualified_field(
6320 field,
6321 field_offset,
6322 field_size,
6323 value,
6324 rdigits,
6325 rounded,
6326 &size_error );
6327 break;
6328 }
6329
6330 case FldNumericDisplay:
6331 case FldNumericEdited:
6332 case FldNumericBin5:
6333 case FldPacked:
6334 case FldIndex:
6335 // Bin5 and Index are treated with no truncation, as if they were
6336 // trunc_bin_e. The other types aren't subject to truncation.
6337 // We are moving a number to a number:
6338 value = __gg__dirty_to_binary_internal( str,
6339 strlen,
6340 &rdigits );
6341 __gg__int128_to_qualified_field(
6342 field,
6343 field_offset,
6344 field_size,
6345 value,
6346 rdigits,
6347 rounded,
6348 &size_error );
6349 break;
6350
6351 case FldAlphaEdited:
6352 {
6353 static size_t display_string_size = MINIMUM_ALLOCATION_SIZE;
6354 static char *display_string = static_cast<char *>(malloc(display_string_size));
6355
6356 __gg__realloc_if_necessary( &display_string,
6357 &display_string_size,
6358 field_size);
6359
6360 memset(display_string, internal_space, display_string_size);
6361 size_t len = std::min(display_string_size, strlen);
6362 memcpy(display_string, str, len);
6363 __gg__string_to_alpha_edited( reinterpret_cast<char *>(field->data+field_offset),
6364 display_string,
6365 field_size,
6366 field->picture);
6367 break;
6368 }
6369
6370 case FldFloat:
6371 {
6372 char ach[256];
6373 size_t len = std::min(strlen, sizeof(ach)-1);
6374 memcpy(ach, str, len);
6375 ach[len] = '\0';
6376 switch( field->capacity )
6377 {
6378 case 4:
6379 {
6380 *PTRCAST(float, field->data+field_offset) = strtod(ach, NULL);
6381 break;
6382 }
6383 case 8:
6384 {
6385 *PTRCAST(double, field->data+field_offset) = strtod(ach, NULL);
6386 break;
6387 }
6388 case 16:
6389 {
6390 GCOB_FP128 t = strtofp128(ach, NULL);
6391 memcpy(field->data+field_offset, &t, 16);
6392 break;
6393 }
6394 }
6395 break;
6396 }
6397
6398 default:
6399 moved = false;
6400 break;
6401 }
6402
6403 if( !moved )
6404 {
6405 fprintf(stderr, "%s() %s:%d -- We were unable to do a move to "
6406 "type %d\n",
6407 __func__, __FILE__, __LINE__,
6408 field->type);
6409 abort();
6410 }
6411
6412 return size_error;
6413 }
6414
6415 extern "C"
6416 void
6417 __gg__file_sort_ff_input( cblc_file_t *workfile,
6418 cblc_file_t *input)
6419 {
6420 // The name means "file-file input"
6421
6422 // We are going to read records from input and write them to workfile. These
6423 // files are already open.
6424
6425 sv_suppress_eof_ec = true;
6426 for(;;)
6427 {
6428 // Read the data from the input file into its record_area
6429 __gg__file_read(input,
6430 -1);
6431 if( input->io_status >= FhNotOkay )
6432 {
6433 break;
6434 }
6435 // We have the data we need. Transmit it to workfile.
6436 int before_advancing = 0;
6437 if( workfile->org == file_line_sequential_e )
6438 {
6439 // we need a newline at the end of each line
6440 before_advancing = 1;
6441 }
6442 else if( workfile->org == file_sequential_e )
6443 {
6444 // We don't want any vertical movement
6445 before_advancing = -1;
6446 }
6447
6448 size_t bytes_to_write = std::min( workfile->record_area_max,
6449 input->record_area_max );
6450
6451 __gg__file_write( workfile,
6452 input->default_record->data,
6453 bytes_to_write,
6454 0,
6455 before_advancing,
6456 0); // non-random
6457 }
6458 sv_suppress_eof_ec = false;
6459 }
6460
6461 extern "C"
6462 void
6463 __gg__file_sort_ff_output( cblc_file_t *output,
6464 cblc_file_t *workfile)
6465 {
6466 // The name means "file-file output"
6467
6468 // We read records from workfile and write them to the output file
6469
6470 // Make sure workfile is positioned at the beginning
6471 __gg__file_reopen(workfile, 'r');
6472
6473 sv_suppress_eof_ec = true;
6474 for(;;)
6475 {
6476 __gg__file_read( workfile,
6477 -1);
6478 if( workfile->io_status >= FhNotOkay )
6479 {
6480 break;
6481 }
6482 int advancing = -1; // Default to no vertical movement
6483 if( output->org == file_line_sequential_e )
6484 {
6485 advancing = 1;
6486 }
6487
6488 __gg__file_write( output,
6489 workfile->default_record->data,
6490 workfile->record_area_max,
6491 0,
6492 advancing,
6493 0); // 1 would be is_random
6494 }
6495 sv_suppress_eof_ec = false;
6496 }
6497
6498 extern "C"
6499 void
6500 __gg__sort_workfile(cblc_file_t *workfile,
6501 size_t nkeys,
6502 cblc_field_t **keys,
6503 size_t *ascending,
6504 int duplicates)
6505 {
6506 // We are going to read the records of workfile into memory. We keep offsets
6507 // into the memory buffer, and then we'll sort those offsets according to the
6508 // things they point to.
6509
6510 // The workfile is open and positioned at zero when we arrive here.
6511
6512 // Read the file into memory
6513 size_t buffer_size = 128;
6514 unsigned char *contents = static_cast<unsigned char *>(malloc(buffer_size));
6515 size_t offset = 0;
6516 std::vector<size_t>offsets;
6517 size_t bytes_read;
6518 size_t bytes_to_write;
6519
6520 sv_suppress_eof_ec = true;
6521 for(;;)
6522 {
6523 __gg__file_read(workfile,
6524 -1);
6525 if( workfile->record_length )
6526 {
6527 int rdigits;
6528 bytes_read = (size_t) __gg__binary_value_from_field(
6529 &rdigits,
6530 workfile->record_length);
6531 }
6532 else
6533 {
6534 bytes_read = workfile->record_area_max;
6535 }
6536 if( workfile->io_status >= FhNotOkay )
6537 {
6538 break;
6539 }
6540
6541 while( offset + sizeof(size_t) + bytes_read > buffer_size )
6542 {
6543 buffer_size *= 2;
6544 contents = static_cast<unsigned char *>(realloc(contents, buffer_size));
6545 }
6546 offsets.push_back(offset);
6547
6548 // Copy over the record size:
6549 memcpy(contents+offset, &bytes_read, sizeof(size_t));
6550 offset += sizeof(size_t);
6551
6552 // And the contents of the record
6553 memcpy(contents+offset, workfile->default_record->data, bytes_read);
6554 offset += bytes_read;
6555 }
6556 sv_suppress_eof_ec = false;
6557
6558 sort_contents(contents,
6559 offsets,
6560 0,
6561 nkeys,
6562 keys,
6563 ascending,
6564 duplicates);
6565
6566 // We now put the sorted data back out onto the disk:
6567 fclose(workfile->file_pointer);
6568 __gg__file_reopen(workfile, 'w');
6569
6570 for(size_t i=0; i<offsets.size(); i++)
6571 {
6572 offset = offsets[i];
6573 memcpy(&bytes_to_write, contents+offset, sizeof(size_t));
6574 offset += sizeof(size_t);
6575 int advancing = -1;
6576 if( workfile->org == file_line_sequential_e )
6577 {
6578 advancing = 1;
6579 }
6580 if( workfile->record_area_min != workfile->record_area_max
6581 && workfile->record_length )
6582 {
6583 __gg__int128_to_field(workfile->record_length,
6584 bytes_to_write,
6585 0,
6586 truncation_e,
6587 NULL);
6588 }
6589 __gg__file_write( workfile,
6590 contents+offset,
6591 bytes_to_write,
6592 0,
6593 advancing,
6594 0); // 1 would be is_random
6595 }
6596 free(contents);
6597 }
6598
6599 extern "C"
6600 void
6601 __gg__merge_files( cblc_file_t *workfile,
6602 size_t nkeys,
6603 cblc_field_t **keys,
6604 size_t *ascending,
6605 size_t ninputs,
6606 cblc_file_t **inputs)
6607 {
6608 // Merge takes in N files that are already sorted. It looks at the N records
6609 // at the top of the N files, and figures out who the winner is, and puts each
6610 // winner into workfile. If it notices that any of the files are not in the
6611 // order specified by the keys it raises the EC-SORT-MERGE-SEQUENCE exception.
6612
6613 // Is everybody ready?
6614
6615 // Then we will begin.
6616
6617 sorter.nkeys = nkeys;
6618 sorter.keys = keys;
6619 sorter.ascending = ascending;
6620
6621 // We need to prime the pump by reading one record from everybody
6622 size_t the_biggest = 0;
6623 for(size_t i=0; i<ninputs; i++)
6624 {
6625 the_biggest = std::max(the_biggest, inputs[i]->record_area_max);
6626
6627 __gg__file_read(inputs[i],
6628 -1);
6629 if( inputs[i]->io_status >= FhNotOkay )
6630 {
6631 inputs[i] = NULL;
6632 }
6633 }
6634
6635 // For each input, either there is a good record in its record area, or else
6636 // inputs[i] for that file is NULL
6637
6638 if( !the_biggest )
6639 {
6640 return;
6641 }
6642
6643 unsigned char *prior_winner = static_cast<unsigned char *>(malloc(the_biggest));
6644 massert(prior_winner);
6645 *prior_winner = '\0';
6646
6647 for(;;)
6648 {
6649 int winner = -1;
6650 for(int i=0; i<(int)ninputs; i++ )
6651 {
6652 if( !inputs[i] )
6653 {
6654 // This input has been exhausted
6655 continue;
6656 }
6657 if( winner == -1 )
6658 {
6659 // Establish the first file as the current winner
6660 winner = i;
6661 continue;
6662 }
6663 // We now compare inputs[i] to the current winner
6664 int ncompare = compare_two_records( inputs[i]->default_record->data,
6665 inputs[winner]->default_record->data);
6666 if( ncompare < 0 )
6667 {
6668 // We have a new winner
6669 winner = i;
6670 }
6671 }
6672 // We have scanned all the inputs, looking for the smallest of them.
6673 if( winner == -1 )
6674 {
6675 // We have exhausted all of the inputs, which means we are done.
6676 break;
6677 }
6678 if( *prior_winner )
6679 {
6680 // We need to compare the current winner to the prior winner
6681 int ncompare = compare_two_records( prior_winner,
6682 inputs[winner]->default_record->data);
6683 if( ncompare > 0 )
6684 {
6685 // The prior winner is bigger than the current winner, which means that
6686 // the input files were not in order. This is a run-time error.
6687
6688 exception_raise(ec_sort_merge_sequence_e);
6689 abort();
6690 }
6691 }
6692 // Establish winner as the prior_winner
6693 memcpy( prior_winner,
6694 inputs[winner]->default_record->data,
6695 inputs[winner]->record_area_max);
6696 // And send it to the workfile
6697
6698 int before_advancing = -1; // No vertical movement...
6699 if( workfile->org == file_line_sequential_e )
6700 {
6701 // we need a newline at the end of each line sequential line
6702 before_advancing = 1;
6703 }
6704
6705 __gg__file_write( workfile,
6706 inputs[winner]->default_record->data,
6707 inputs[winner]->record_area_max,
6708 0,
6709 before_advancing,
6710 0); // 1 means is_random
6711
6712
6713 // And now we need to replace the winner:
6714
6715 __gg__file_read(inputs[winner],
6716 -1);
6717 if( inputs[winner]->io_status >= FhNotOkay )
6718 {
6719 inputs[winner] = NULL;
6720 }
6721 }
6722
6723 free(prior_winner);
6724 }
6725
6726 static const char *
6727 funky_find( const char *piece,
6728 const char *piece_end,
6729 const char *whole,
6730 const char *whole_end )
6731 {
6732 const char *retval = NULL;
6733
6734 size_t length_of_piece = piece_end - piece;
6735 if(length_of_piece == 0)
6736 {
6737 __gg__abort("funky_find() length_of_piece shouldn't be zero");
6738 }
6739
6740 whole_end -= length_of_piece;
6741
6742 while( whole <= whole_end )
6743 {
6744 if( memcmp( piece, whole, length_of_piece) == 0 )
6745 {
6746 retval = whole;
6747 break;
6748 }
6749 whole += 1;
6750 }
6751 return retval;
6752 }
6753
6754 static const char *
6755 funky_find_backward(const char *piece,
6756 const char *piece_end,
6757 const char *whole,
6758 const char *whole_end )
6759 {
6760 const char *retval = NULL;
6761
6762 size_t length_of_piece = piece_end - piece;
6763 if(length_of_piece == 0)
6764 {
6765 __gg__abort("funky_find_backward() length_of_piece shouldn't be zero");
6766 }
6767
6768 whole_end -= length_of_piece;
6769
6770 while( whole <= whole_end )
6771 {
6772 if( memcmp( piece, whole_end, length_of_piece) == 0 )
6773 {
6774 retval = whole_end;
6775 break;
6776 }
6777 whole_end -= 1;
6778 }
6779 return retval;
6780 }
6781
6782 typedef struct normalized_operand
6783 {
6784 // These are the characters of the string. When the field is NumericDisplay
6785 // any leading or trailing +/- characters are removed, and any embedded
6786 // NUMERIC_DISPLAY_SIGN_BIT bits are removed.
6787 std::string the_characters;
6788 size_t offset; // Usually zero. One when there is a leading sign.
6789 size_t length; // Usually the same as the original. But it is one less
6790 // // than the original when there is a trailing sign.
6791 } normalized_operand;
6792
6793 typedef struct comparand
6794 {
6795 size_t id_2_index;
6796 cbl_inspect_bound_t operation;
6797 normalized_operand identifier_3; // The thing to be found
6798 normalized_operand identifier_5; // The replacement, for FORMAT 2
6799 const char *alpha; // The start location within normalized_id_1
6800 const char *omega; // The end+1 location within normalized_id_1
6801 size_t leading_count;
6802 bool leading;
6803 bool first;
6804 } comparand;
6805
6806 typedef struct id_2_result
6807 {
6808 cblc_field_t *id2;
6809 size_t id2_o;
6810 size_t id2_s;
6811 size_t result;
6812 } id_2_result;
6813
6814 static normalized_operand
6815 normalize_id( const cblc_field_t *refer,
6816 size_t refer_o,
6817 size_t refer_s
6818 )
6819 {
6820 normalized_operand retval;
6821
6822 if( refer )
6823 {
6824 const unsigned char *data = refer->data + refer_o;
6825 cbl_figconst_t figconst
6826 = (cbl_figconst_t)(refer->attr & FIGCONST_MASK);
6827
6828 retval.offset = 0;
6829 retval.length = refer_s;
6830
6831 if( refer->type == FldNumericDisplay )
6832 {
6833 // The value is NumericDisplay.
6834 if( refer->attr & separate_e )
6835 {
6836 // Because the sign is a separate plus or minus, the length
6837 // gets reduced by one:
6838 retval.length = refer_s - 1;
6839 if( refer->attr & leading_e )
6840 {
6841 // Because the sign character is LEADING, we increase the
6842 // offset by one
6843 retval.offset = 1;
6844 }
6845 }
6846 for( size_t i=retval.offset; i<retval.length; i++ )
6847 {
6848 // Because we are dealing with a NumericDisplay that might have
6849 // the NUMERIC_DISPLAY_SIGN_BIT turned on, we need to mask it off
6850 unsigned char ch = data[i];
6851 turn_sign_bit_off(&ch);
6852 retval.the_characters += ch;
6853 }
6854 }
6855 else
6856 {
6857 // We are set up to create the_characters;
6858 if( figconst == normal_value_e )
6859 {
6860 for( size_t i=retval.offset; i<retval.length; i++ )
6861 {
6862 retval.the_characters += data[i];
6863 }
6864 }
6865 else
6866 {
6867 char ch=0;
6868 switch( figconst )
6869 {
6870 case low_value_e :
6871 ch = ascii_to_internal(__gg__low_value_character);
6872 break;
6873 case zero_value_e :
6874 ch = internal_zero;
6875 break;
6876 case space_value_e :
6877 ch = internal_space;
6878 break;
6879 case quote_value_e :
6880 ch = ascii_to_internal(__gg__quote_character);
6881 break;
6882 case high_value_e :
6883 if( __gg__high_value_character == DEGENERATE_HIGH_VALUE )
6884 {
6885 ch = __gg__high_value_character;
6886 }
6887 else
6888 {
6889 ch = ascii_to_internal(__gg__high_value_character);
6890 }
6891 break;
6892 case normal_value_e:
6893 // We can't get here
6894 break;
6895 case null_value_e:
6896 break;
6897 }
6898 for( size_t i=retval.offset; i<retval.length; i++ )
6899 {
6900 retval.the_characters += ch;
6901 }
6902 }
6903 }
6904 }
6905 else
6906 {
6907 // THere is no field, so leave the_characters empty.
6908 retval.offset = 0;
6909 retval.length = 0;
6910 }
6911 return retval;
6912 }
6913
6914 static void
6915 match_lengths( normalized_operand &id_target,
6916 const normalized_operand &id_source)
6917 {
6918 char ch = id_target.the_characters[0];
6919 id_target.the_characters.clear();
6920 for(size_t i=0; i<id_source.length; i++)
6921 {
6922 id_target.the_characters += ch;
6923 }
6924 id_target.length = id_source.length;
6925 }
6926
6927 static void
6928 the_alpha_and_omega(const normalized_operand &id_before,
6929 const normalized_operand &id_after,
6930 const char * &alpha,
6931 const char * &omega)
6932 {
6933 /* The 2023 ISO description of the AFTER and BEFORE phrases of the INSPECT
6934 statement is, in a word, garbled.
6935
6936 IBM's COBOL for Linux 1.2 is a little better, but still a bit confusing
6937 because the description for AFTER neglects to specifically state that
6938 the scan starts one character to the right of the *first* occurrence of
6939 the AFTER value.
6940
6941 Micro Focus 9.2.5 has the advantage of being ungarbled, succinct, and
6942 unambiguous.
6943
6944 The BEFORE phrase modifies the character position to use as the rightmost
6945 position in source for the corresponding comparison operation. Comparisons
6946 in source occur only to the left of the first occurrence of delimiter. If
6947 delimiter is not present in source, then the comparison proceeds as if
6948 there were no BEFORE phrase.
6949
6950 The AFTER phrase modifies the character position to use as the leftmost
6951 position in source for the corresponding comparison operation. Comparisons
6952 in source occur only to the right of the first occurrence of delimiter.
6953 This character position is the one immediately to the right of the
6954 rightmost character of the delimiter found. If delimiter is not found in
6955 source, the INSPECT statement has no effect (no tallying or replacement
6956 occurs).
6957
6958 "xyzxyzAFTERxyzxyzxyzxyzBEFORExyzxyzAFTERxyzxyz"
6959 ^ ^
6960 | |
6961 | |-- omega
6962 ----------------alpha
6963 */
6964
6965 if( id_before.length )
6966 {
6967 // This is the BEFORE delimiter. We look for the first occurrence of that
6968 // delimiter starting at the left of id_1
6969
6970 const char *start = id_before.the_characters.c_str();
6971 const char *end = start + id_before.length;
6972 const char *found = funky_find(start, end, alpha, omega);
6973 if( found )
6974 {
6975 // We found id_before within alpha/omega, so reduce omega
6976 // to the found location.
6977 omega = found;
6978 // If not found, we just leave omega alone.
6979 }
6980 }
6981
6982 if( id_after.length )
6983 {
6984 // This is the AFTER delimiter. We look for the first occurrence of that
6985 // delimiter in id_1
6986
6987 const char *start = id_after.the_characters.c_str();
6988 const char *end = start + id_after.length;
6989 const char *found = funky_find(start, end, alpha, omega);
6990 if( found )
6991 {
6992 // We found id_after in the alpha/omega segment. We update alpha
6993 // be the character after the id_after substring.
6994 alpha = found + (end-start);
6995 }
6996 else
6997 {
6998 // We didn't find the id_after string, so we set the alpha to be
6999 // omega. That means that no tally or replace operation will take
7000 // because no characters will qualify.
7001 alpha = omega;
7002 }
7003 }
7004 }
7005
7006 static void
7007 the_alpha_and_omega_backward( const normalized_operand &id_before,
7008 const normalized_operand &id_after,
7009 const char * &alpha,
7010 const char * &omega)
7011 {
7012 /* Not unlike the_alpha_and_omega(), but for handling BACKWARD.
7013
7014 "xyzxyzBEFORExyzxyzAFTERxyzxyzxyzxyzBEFORExyzxyzAFTERxyzxyz"
7015 ^ ^
7016 | |
7017 | -- omega
7018 |--------alpha
7019 */
7020
7021 const char *id_1 = alpha;
7022 const char *id_1_end = omega;
7023
7024 if( id_before.length )
7025 {
7026 // This is the BEFORE delimiter. We look for the first occurrence of it
7027 // from the right end of id_1
7028
7029 const char *start = id_before.the_characters.c_str();
7030 const char *end = start + id_before.length;
7031 const char *found = funky_find_backward(start, end, id_1, id_1_end);
7032 if( found )
7033 {
7034 // We found id_before within id_1, so change alpha to the character just
7035 // to the right of BEFORE. Otherwise, we will leave alpha alone, so that
7036 // it stays at the beginning of id_1
7037 alpha = found + id_before.length;
7038 }
7039 }
7040
7041 if( id_after.length )
7042 {
7043 // This is the AFTER delimiter. We look for the first occurrence in id_1
7044
7045 const char *start = id_after.the_characters.c_str();
7046 const char *end = start + id_after.length;
7047 const char *found = funky_find_backward(start, end, alpha, omega);
7048 if( found )
7049 {
7050 // We found id_after in id_1. We update omega to be
7051 // at that location.
7052 omega = found;
7053 }
7054 else
7055 {
7056 // If the AFTER isn't found, we need to adjust things so that nothing
7057 // happens.
7058 omega = id_1;
7059 }
7060 }
7061 }
7062
7063 static
7064 void
7065 inspect_backward_format_1(const size_t integers[])
7066 {
7067 size_t int_index = 0;
7068 size_t cblc_index = 0;
7069
7070 // Reference the language specification for the meanings of identifier_X
7071
7072 // Pick up the number of identifier_2 loops in this INSPECT statement
7073 size_t n_identifier_2 = integers[int_index++];
7074
7075 std::vector<id_2_result> id_2_results(n_identifier_2);
7076
7077 // Pick up identifier_1, which is the string being inspected
7078 const cblc_field_t *id1 = __gg__treeplet_1f[cblc_index];
7079 size_t id1_o = __gg__treeplet_1o[cblc_index];
7080 size_t id1_s = __gg__treeplet_1s[cblc_index];
7081 cblc_index += 1;
7082 // normalize it, according to the language specification.
7083 normalized_operand normalized_id_1 = normalize_id(id1, id1_o, id1_s);
7084
7085 std::vector<comparand> comparands;
7086
7087 for(size_t i=0; i<n_identifier_2; i++)
7088 {
7089 // For each identifier_2, we pick up its value:
7090
7091 id_2_results[i].id2 = __gg__treeplet_1f [cblc_index];
7092 id_2_results[i].id2_o = __gg__treeplet_1o[cblc_index];
7093 id_2_results[i].id2_s = __gg__treeplet_1s[cblc_index];
7094
7095 cblc_index += 1;
7096 id_2_results[i].result = 0;
7097
7098 // For each identifier 2, there is a count of operations:
7099 size_t nbounds = integers[int_index++];
7100
7101 for(size_t j=0; j<nbounds; j++ )
7102 {
7103 // each operation has a bound code:
7104 cbl_inspect_bound_t operation
7105 = (cbl_inspect_bound_t)integers[int_index++];
7106 switch( operation )
7107 {
7108 case bound_characters_e:
7109 {
7110 // We are counting characters. There is no identifier-3,
7111 // but we we hard-code the length to one to represent a
7112 // single character.
7113 comparand next_comparand = {};
7114 next_comparand.id_2_index = i;
7115 next_comparand.operation = operation;
7116 next_comparand.identifier_3.length = 1;
7117
7118 const cblc_field_t *id4_before = __gg__treeplet_1f [cblc_index];
7119 size_t id4_before_o = __gg__treeplet_1o[cblc_index];
7120 size_t id4_before_s = __gg__treeplet_1s[cblc_index];
7121 cblc_index += 1;
7122
7123 const cblc_field_t *id4_after = __gg__treeplet_1f [cblc_index];
7124 size_t id4_after_o = __gg__treeplet_1o[cblc_index];
7125 size_t id4_after_s = __gg__treeplet_1s[cblc_index];
7126 cblc_index += 1;
7127
7128 normalized_operand normalized_id_4_before
7129 = normalize_id(id4_before, id4_before_o, id4_before_s);
7130
7131 normalized_operand normalized_id_4_after
7132 = normalize_id(id4_after, id4_after_o, id4_after_s);
7133
7134 next_comparand.alpha
7135 = normalized_id_1.the_characters.c_str();
7136
7137 next_comparand.omega
7138 = next_comparand.alpha + normalized_id_1.length;
7139
7140 the_alpha_and_omega_backward( normalized_id_4_before,
7141 normalized_id_4_after,
7142 next_comparand.alpha,
7143 next_comparand.omega);
7144 comparands.push_back(next_comparand);
7145 break;
7146 }
7147 default:
7148 {
7149 // We have some number of identifer-3 values,
7150 // each with possible PHRASE1 modifiers.
7151 size_t pair_count = integers[int_index++];
7152
7153 // We need to build up pair_count comparand structures:
7154
7155 for(size_t k=0; k<pair_count; k++)
7156 {
7157 comparand next_comparand = {};
7158 next_comparand.id_2_index = i;
7159 next_comparand.operation = operation;
7160
7161 const cblc_field_t *id3 = __gg__treeplet_1f[cblc_index];
7162 size_t id3_o = __gg__treeplet_1o[cblc_index];
7163 size_t id3_s = __gg__treeplet_1s[cblc_index];
7164 cblc_index += 1;
7165
7166 const cblc_field_t *id4_before = __gg__treeplet_1f[cblc_index];
7167 size_t id4_before_o = __gg__treeplet_1o[cblc_index];
7168 size_t id4_before_s = __gg__treeplet_1s[cblc_index];
7169 cblc_index += 1;
7170
7171 const cblc_field_t *id4_after = __gg__treeplet_1f[cblc_index];
7172 size_t id4_after_o = __gg__treeplet_1o[cblc_index];
7173 size_t id4_after_s = __gg__treeplet_1s[cblc_index];
7174 cblc_index += 1;
7175
7176 next_comparand.identifier_3
7177 = normalize_id(id3, id3_o, id3_s);
7178
7179 next_comparand.alpha
7180 = normalized_id_1.the_characters.c_str();
7181 next_comparand.omega
7182 = next_comparand.alpha + normalized_id_1.length;
7183
7184 normalized_operand normalized_id_4_before
7185 = normalize_id(id4_before, id4_before_o, id4_before_s);
7186
7187 normalized_operand normalized_id_4_after
7188 = normalize_id(id4_after, id4_after_o, id4_after_s);
7189
7190 the_alpha_and_omega_backward( normalized_id_4_before,
7191 normalized_id_4_after,
7192 next_comparand.alpha,
7193 next_comparand.omega);
7194 next_comparand.leading = true;
7195 next_comparand.leading_count = 0;
7196 comparands.push_back(next_comparand);
7197 }
7198 }
7199 }
7200 }
7201 }
7202
7203 // We are now ready to walk through identifier-1, character by
7204 // character, checking each of the comparands for a match:
7205
7206 // We are now set up to accomplish the data flow described
7207 // in the language specification. We loop through the
7208 // the character positions in normalized_id_1:
7209 const char *leftmost = normalized_id_1.the_characters.c_str();
7210 const char *rightmost = leftmost + normalized_id_1.length;
7211 const char *the_end_of_the_world = rightmost;
7212
7213 while( leftmost < rightmost )
7214 {
7215 rightmost -= 1;
7216 // We look at the rightmost position. If that position is within the
7217 // alpha-to-omega qualified range, we check all possible matches:
7218
7219 for(size_t k=0; k<comparands.size(); k++)
7220 {
7221 if( rightmost < comparands[k].alpha )
7222 {
7223 // This can't be a match, because rightmost is
7224 // to the left of the comparand's alpha.
7225 continue;
7226 }
7227 if( rightmost + comparands[k].identifier_3.length > comparands[k].omega )
7228 {
7229 // This can't be a match, because the rightmost
7230 // character of the comparand falls to the right
7231 // of the comparand's omega
7232 continue;
7233 }
7234 if( rightmost + comparands[k].identifier_3.length > the_end_of_the_world )
7235 {
7236 // This can't be a match, because the rightmost character of the
7237 // comparand falls past the new edge of id_1 established by a prior
7238 // match.
7239 continue;
7240 }
7241 // A match is theoretically possible, because all
7242 // the characters of the comparand fall between
7243 // alpha and omega:
7244 bool possible_match = true;
7245
7246 if( comparands[k].operation != bound_characters_e )
7247 {
7248 for(size_t m=0; m<comparands[k].identifier_3.length; m++)
7249 {
7250 if( comparands[k].identifier_3.the_characters[m] != rightmost[m] )
7251 {
7252 possible_match = false;
7253 break;
7254 }
7255 }
7256 }
7257 if( possible_match )
7258 {
7259 // The characters of the comparand match the
7260 // characters at rightmost.
7261 bool match = false;
7262 switch( comparands[k].operation )
7263 {
7264 case bound_first_e:
7265 // This can't happen in a FORMAT_1
7266 warnx("The compiler goofed: "
7267 "INSPECT FORMAT 1 "
7268 "shouldn't have "
7269 "bound_first_e");
7270 abort();
7271 break;
7272
7273 case bound_characters_e:
7274 match = 1;
7275 break;
7276
7277 case bound_all_e:
7278 {
7279 // We have a match.
7280 match = true;
7281 break;
7282 }
7283
7284 case bound_leading_e:
7285 {
7286 // We have a match at rightmost. But we need to figure out if this
7287 // particular match is valid for LEADING.
7288
7289 if( comparands[k].leading )
7290 {
7291 if( rightmost + comparands[k].identifier_3.length
7292 == comparands[k].omega)
7293 {
7294 // This means that the match here is just the latest of a
7295 // string of LEADING matches that started at .omega
7296 comparands[k].leading_count += 1;
7297 match = true;
7298 }
7299 }
7300 break;
7301 }
7302
7303 case bound_trailing_e:
7304 {
7305 // We have a match at rightmost.
7306 //
7307 // We want to know if this is a trailing match. For that to be,
7308 // all of the possible matches from here leftward to the alpha have
7309 // to be true as well:
7310
7311 if( (rightmost - comparands[k].alpha )
7312 % comparands[k].identifier_3.length == 0 )
7313 {
7314 // The remaining number of characters is correct for a match.
7315 // Keep checking.
7316
7317 // Assume a match until we learn otherwise:
7318 match = true;
7319 const char *local_left = rightmost;
7320 local_left -= comparands[k].identifier_3.length;
7321 while( local_left >= comparands[k].alpha )
7322 {
7323 for(size_t m=0; m<comparands[k].identifier_3.length; m++)
7324 {
7325 if( comparands[k].identifier_3.the_characters[m]
7326 != local_left[m] )
7327 {
7328 // We have a mismatched character, so no trailing match is
7329 // possible
7330 match = false;
7331 break;
7332 }
7333 }
7334 local_left -= comparands[k].identifier_3.length;
7335 }
7336 }
7337 break;
7338 }
7339 }
7340
7341 if( match )
7342 {
7343 // We have a match at rightmost:
7344 // Bump the result counter
7345 id_2_results[comparands[k].id_2_index].result += 1;
7346
7347 // Because we are scanning from right to left, we have to drag
7348 // the goalpost along with us to ensure that following
7349 // comparisions don't spill over into the characters we just matched.
7350 the_end_of_the_world = rightmost;
7351
7352 break;
7353 }
7354 }
7355 else
7356 {
7357 // We are within alpha/omega, but there was no
7358 // match, which permanently disqualifies the
7359 // possibility of LEADING
7360 comparands[k].leading = false;
7361 }
7362 }
7363 }
7364
7365 // Add our results to the identifier_2 values:
7366
7367 for(size_t i = 0; i<id_2_results.size(); i++)
7368 {
7369 int rdigits;
7370 __int128 id_2_value
7371 = __gg__binary_value_from_qualified_field(&rdigits,
7372 id_2_results[i].id2,
7373 id_2_results[i].id2_o,
7374 id_2_results[i].id2_s);
7375 while(rdigits--)
7376 {
7377 id_2_value /= 10.0;
7378 }
7379
7380 // Accumulate what we've found into it
7381 id_2_value += id_2_results[i].result;
7382
7383 // And put it back:
7384 __gg__int128_to_qualified_field(id_2_results[i].id2,
7385 id_2_results[i].id2_o,
7386 id_2_results[i].id2_s,
7387 id_2_value,
7388 0,
7389 truncation_e,
7390 NULL);
7391 }
7392 }
7393
7394 extern "C"
7395 void
7396 __gg__inspect_format_1(int backward, size_t integers[])
7397 {
7398 if( backward )
7399 {
7400 return inspect_backward_format_1(integers);
7401 }
7402
7403 size_t int_index = 0;
7404 size_t cblc_index = 0;
7405
7406 // Reference the language specification for the meanings of identifier_X
7407
7408 // Pick up the number of identifier_2 loops in this INSPECT statement
7409 size_t n_identifier_2 = integers[int_index++];
7410
7411 std::vector<id_2_result> id_2_results(n_identifier_2);
7412
7413 // Pick up identifier_1, which is the string being inspected
7414 const cblc_field_t *id1 = __gg__treeplet_1f[cblc_index];
7415 size_t id1_o = __gg__treeplet_1o[cblc_index];
7416 size_t id1_s = __gg__treeplet_1s[cblc_index];
7417 cblc_index += 1;
7418 // normalize it, according to the language specification.
7419 normalized_operand normalized_id_1
7420 = normalize_id(id1, id1_o, id1_s);
7421
7422 std::vector<comparand> comparands;
7423
7424 for(size_t i=0; i<n_identifier_2; i++)
7425 {
7426 // For each identifier_2, we pick up its value:
7427
7428 id_2_results[i].id2 = __gg__treeplet_1f [cblc_index];
7429 id_2_results[i].id2_o = __gg__treeplet_1o[cblc_index];
7430 id_2_results[i].id2_s = __gg__treeplet_1s[cblc_index];
7431
7432 cblc_index += 1;
7433 id_2_results[i].result = 0;
7434
7435 // For each identifier 2, there is a count of operations:
7436 size_t nbounds = integers[int_index++];
7437
7438 for(size_t j=0; j<nbounds; j++ )
7439 {
7440 // each operation has a bound code:
7441 cbl_inspect_bound_t operation
7442 = (cbl_inspect_bound_t)integers[int_index++];
7443 switch( operation )
7444 {
7445 case bound_characters_e:
7446 {
7447 // We are counting characters. There is no identifier-3,
7448 // but we we hard-code the length to one to represent a
7449 // single character.
7450 comparand next_comparand = {};
7451 next_comparand.id_2_index = i;
7452 next_comparand.operation = operation;
7453 next_comparand.identifier_3.length = 1;
7454
7455 const cblc_field_t *id4_before = __gg__treeplet_1f [cblc_index];
7456 size_t id4_before_o = __gg__treeplet_1o[cblc_index];
7457 size_t id4_before_s = __gg__treeplet_1s[cblc_index];
7458 cblc_index += 1;
7459
7460 const cblc_field_t *id4_after = __gg__treeplet_1f [cblc_index];
7461 size_t id4_after_o = __gg__treeplet_1o[cblc_index];
7462 size_t id4_after_s = __gg__treeplet_1s[cblc_index];
7463 cblc_index += 1;
7464
7465 normalized_operand normalized_id_4_before
7466 = normalize_id(id4_before, id4_before_o, id4_before_s);
7467
7468 normalized_operand normalized_id_4_after
7469 = normalize_id(id4_after, id4_after_o, id4_after_s);
7470
7471 next_comparand.alpha
7472 = normalized_id_1.the_characters.c_str();
7473
7474 next_comparand.omega
7475 = next_comparand.alpha + normalized_id_1.length;
7476
7477 the_alpha_and_omega(normalized_id_4_before,
7478 normalized_id_4_after,
7479 next_comparand.alpha,
7480 next_comparand.omega);
7481 comparands.push_back(next_comparand);
7482 break;
7483 }
7484 default:
7485 {
7486 // We have some number of identifer-3 values,
7487 // each with possible PHRASE1 modifiers.
7488 size_t pair_count = integers[int_index++];
7489
7490 // We need to build up pair_count comparand structures:
7491
7492 for(size_t k=0; k<pair_count; k++)
7493 {
7494 comparand next_comparand = {};
7495 next_comparand.id_2_index = i;
7496 next_comparand.operation = operation;
7497
7498 const cblc_field_t *id3 = __gg__treeplet_1f[cblc_index];
7499 size_t id3_o = __gg__treeplet_1o[cblc_index];
7500 size_t id3_s = __gg__treeplet_1s[cblc_index];
7501 cblc_index += 1;
7502
7503 const cblc_field_t *id4_before = __gg__treeplet_1f[cblc_index];
7504 size_t id4_before_o = __gg__treeplet_1o[cblc_index];
7505 size_t id4_before_s = __gg__treeplet_1s[cblc_index];
7506 cblc_index += 1;
7507
7508 const cblc_field_t *id4_after = __gg__treeplet_1f[cblc_index];
7509 size_t id4_after_o = __gg__treeplet_1o[cblc_index];
7510 size_t id4_after_s = __gg__treeplet_1s[cblc_index];
7511 cblc_index += 1;
7512
7513 next_comparand.identifier_3
7514 = normalize_id(id3, id3_o, id3_s);
7515
7516 next_comparand.alpha
7517 = normalized_id_1.the_characters.c_str();
7518 next_comparand.omega
7519 = next_comparand.alpha + normalized_id_1.length;
7520
7521 normalized_operand normalized_id_4_before
7522 = normalize_id(id4_before, id4_before_o, id4_before_s);
7523
7524 normalized_operand normalized_id_4_after
7525 = normalize_id(id4_after, id4_after_o, id4_after_s);
7526
7527 the_alpha_and_omega(normalized_id_4_before,
7528 normalized_id_4_after,
7529 next_comparand.alpha,
7530 next_comparand.omega);
7531 next_comparand.leading = true;
7532 next_comparand.leading_count = 0;
7533 comparands.push_back(next_comparand);
7534 }
7535 }
7536 }
7537 }
7538 }
7539
7540 // We are now ready to walk through identifier-1, character by
7541 // character, checking each of the comparands for a match:
7542
7543 // We are now set up to accomplish the data flow described
7544 // in the language specification. We loop through the
7545 // the character positions in normalized_id_1:
7546 const char *leftmost
7547 = normalized_id_1.the_characters.c_str();
7548 const char *rightmost
7549 = leftmost + normalized_id_1.length;
7550
7551 while( leftmost < rightmost )
7552 {
7553 // For each leftmost position, we check each of the
7554 // pairs:
7555
7556 for(size_t k=0; k<comparands.size(); k++)
7557 {
7558 if( leftmost < comparands[k].alpha )
7559 {
7560 // This can't be a match, because leftmost is
7561 // to the left of the comparand's alpha.
7562 continue;
7563 }
7564 if( leftmost + comparands[k].identifier_3.length > comparands[k].omega )
7565 {
7566 // This can't be a match, because the rightmost
7567 // character of the comparand falls to the right
7568 // of the comparand's omega
7569 continue;
7570 }
7571 // A match is theoretically possible, because all
7572 // the characters of the comparand fall between
7573 // alpha and omega:
7574 bool possible_match = true;
7575
7576 if( comparands[k].operation != bound_characters_e )
7577 {
7578 for(size_t m=0; m<comparands[k].identifier_3.length; m++)
7579 {
7580 if( comparands[k].identifier_3.the_characters[m] != leftmost[m] )
7581 {
7582 possible_match = false;
7583 break;
7584 }
7585 }
7586 }
7587 if( possible_match )
7588 {
7589 // The characters of the comparand match the
7590 // characters at leftmost.
7591 bool match = false;
7592 switch( comparands[k].operation )
7593 {
7594 case bound_first_e:
7595 // This can't happen in a FORMAT_1
7596 warnx("The compiler goofed: "
7597 "INSPECT FORMAT 1 "
7598 "shouldn't have "
7599 "bound_first_e");
7600 abort();
7601 break;
7602
7603 case bound_characters_e:
7604 match = 1;
7605 break;
7606
7607 case bound_all_e:
7608 {
7609 // We have a match.
7610 match = true;
7611 break;
7612 }
7613
7614 case bound_leading_e:
7615 {
7616 // We have a match at leftmost. But we need to figure out if this
7617 // particular match is valid for LEADING.
7618
7619 // Hang onto your hat. This is delightfully clever.
7620 //
7621 // This position is LEADING if:
7622 // 1) .leading is still true
7623 // 2) leftmost / (length_of_comparand ) = current_count
7624 //
7625 // I get chills every time I look at that.
7626 if( comparands[k].leading )
7627 {
7628 // So far, so good.
7629 size_t count = (leftmost - comparands[k].alpha)
7630 / comparands[k].identifier_3.length;
7631 if( count == comparands[k].leading_count )
7632 {
7633 // This means that the match here is just the latest of a
7634 // string of LEADING matches that started at .alpha
7635 comparands[k].leading_count += 1;
7636 match = true;
7637 }
7638 }
7639 break;
7640 }
7641
7642 case bound_trailing_e:
7643 {
7644 // We have a match at leftmost.
7645 //
7646 // We want to know if this is a trailing match. For that to be,
7647 // all of the possible matches from here to the omega have to be
7648 // true as well:
7649
7650 if( (comparands[k].omega-leftmost)
7651 % comparands[k].identifier_3.length == 0 )
7652 {
7653 // The remaining number of characters is correct for a match.
7654 // Keep checking.
7655
7656 // Assume a match until we learn otherwise:
7657 match = true;
7658 const char *local_left = leftmost;
7659 local_left += comparands[k].identifier_3.length;
7660 while( local_left < comparands[k].omega )
7661 {
7662 for(size_t m=0; m<comparands[k].identifier_3.length; m++)
7663 {
7664 if( comparands[k].identifier_3.the_characters[m]
7665 != local_left[m] )
7666 {
7667 // We have a mismatched character, so no trailing match is
7668 // possible
7669 match = false;
7670 break;
7671 }
7672 }
7673 local_left += comparands[k].identifier_3.length;
7674 }
7675 }
7676 break;
7677 }
7678 }
7679
7680 if( match )
7681 {
7682 // We have a match at leftmost:
7683
7684 // Bump the result counter
7685 id_2_results[comparands[k].id_2_index].result += 1;
7686
7687 // Adjust the leftmost pointer to point to
7688 // the rightmost character of the matched
7689 // string, keeping in mind that it will be
7690 // bumped again after we break out of the
7691 // k<pair_count loop:
7692 leftmost += comparands[k].identifier_3.length - 1;
7693 break;
7694 }
7695 }
7696 else
7697 {
7698 // We are within alpha/omega, but there was no
7699 // match, which permanently disqualifies the
7700 // possibility of LEADING
7701 comparands[k].leading = false;
7702 }
7703 }
7704 leftmost += 1;
7705 }
7706
7707 // Add our results to the identifier_2 values:
7708
7709
7710 for(size_t i = 0; i<id_2_results.size(); i++)
7711 {
7712 int rdigits;
7713 __int128 id_2_value
7714 = __gg__binary_value_from_qualified_field(&rdigits,
7715 id_2_results[i].id2,
7716 id_2_results[i].id2_o,
7717 id_2_results[i].id2_s);
7718 while(rdigits--)
7719 {
7720 id_2_value /= 10.0;
7721 }
7722
7723 // Accumulate what we've found into it
7724 id_2_value += id_2_results[i].result;
7725
7726 // And put it back:
7727 __gg__int128_to_qualified_field(id_2_results[i].id2,
7728 id_2_results[i].id2_o,
7729 id_2_results[i].id2_s,
7730 id_2_value,
7731 0,
7732 truncation_e,
7733 NULL);
7734 }
7735 }
7736
7737 static
7738 void
7739 inspect_backward_format_2(const size_t integers[])
7740 {
7741 size_t int_index = 0;
7742 size_t cblc_index = 0;
7743
7744 // Reference the language specification for the meanings of identifier_X
7745
7746 // Pick up identifier_1, which is the string being inspected
7747 cblc_field_t *id1 = __gg__treeplet_1f[cblc_index];
7748 size_t id1_o = __gg__treeplet_1o[cblc_index];
7749 size_t id1_s = __gg__treeplet_1s[cblc_index];
7750 cblc_index += 1;
7751
7752 // normalize it, according to the language specification.
7753 normalized_operand normalized_id_1
7754 = normalize_id(id1, id1_o, id1_s);
7755
7756 std::vector<comparand> comparands;
7757
7758 // Pick up the count of operations:
7759 size_t nbounds = integers[int_index++];
7760
7761 for(size_t j=0; j<nbounds; j++ )
7762 {
7763 // each operation has a bound code:
7764 cbl_inspect_bound_t operation = (cbl_inspect_bound_t)integers[int_index++];
7765 switch( operation )
7766 {
7767 case bound_characters_e:
7768 {
7769 comparand next_comparand = {};
7770 next_comparand.operation = operation;
7771
7772 const cblc_field_t *id5 = __gg__treeplet_1f[cblc_index];
7773 size_t id5_o = __gg__treeplet_1o[cblc_index];
7774 size_t id5_s = __gg__treeplet_1s[cblc_index];
7775 cblc_index += 1;
7776
7777 const cblc_field_t *id4_before = __gg__treeplet_1f[cblc_index];
7778 size_t id4_before_o = __gg__treeplet_1o[cblc_index];
7779 size_t id4_before_s = __gg__treeplet_1s[cblc_index];
7780 cblc_index += 1;
7781
7782 const cblc_field_t *id4_after = __gg__treeplet_1f [cblc_index];
7783 size_t id4_after_o = __gg__treeplet_1o[cblc_index];
7784 size_t id4_after_s = __gg__treeplet_1s[cblc_index];
7785 cblc_index += 1;
7786
7787 next_comparand.identifier_5
7788 = normalize_id(id5, id5_o, id5_s);
7789 normalized_operand normalized_id_4_before
7790 = normalize_id(id4_before, id4_before_o, id4_before_s);
7791 normalized_operand normalized_id_4_after
7792 = normalize_id(id4_after, id4_after_o, id4_after_s);
7793
7794 // Because this is a CHARACTER operation, the lengths of
7795 // identifier-3 and identifier-5 should be one. Let's avoid the
7796 // chaos that will otherwise ensue should the lengths *not* be
7797 // one.
7798 next_comparand.identifier_3.length = 1;
7799 next_comparand.identifier_5.length = 1;
7800
7801 next_comparand.alpha = normalized_id_1.the_characters.c_str();
7802 next_comparand.omega
7803 = next_comparand.alpha + normalized_id_1.length;
7804
7805 the_alpha_and_omega_backward( normalized_id_4_before,
7806 normalized_id_4_after,
7807 next_comparand.alpha,
7808 next_comparand.omega);
7809 comparands.push_back(next_comparand);
7810 break;
7811 }
7812 default:
7813 {
7814 // We have some number of identifer-3/identifier-5 pairs,
7815 // each with possible PHRASE1 modifiers.
7816 size_t pair_count = integers[int_index++];
7817
7818 for(size_t k=0; k<pair_count; k++)
7819 {
7820 comparand next_comparand = {};
7821 next_comparand.operation = operation;
7822
7823 const cblc_field_t *id3 = __gg__treeplet_1f[cblc_index];
7824 size_t id3_o = __gg__treeplet_1o[cblc_index];
7825 size_t id3_s = __gg__treeplet_1s[cblc_index];
7826 cblc_index += 1;
7827
7828 const cblc_field_t *id5 = __gg__treeplet_1f[cblc_index];
7829 size_t id5_o = __gg__treeplet_1o[cblc_index];
7830 size_t id5_s = __gg__treeplet_1s[cblc_index];
7831 cblc_index += 1;
7832
7833 const cblc_field_t *id4_before = __gg__treeplet_1f[cblc_index];
7834 size_t id4_before_o = __gg__treeplet_1o[cblc_index];
7835 size_t id4_before_s = __gg__treeplet_1s[cblc_index];
7836 cblc_index += 1;
7837
7838 const cblc_field_t *id4_after = __gg__treeplet_1f[cblc_index];
7839 size_t id4_after_o = __gg__treeplet_1o[cblc_index];
7840 size_t id4_after_s = __gg__treeplet_1s[cblc_index];
7841 cblc_index += 1;
7842
7843 next_comparand.identifier_3 = normalize_id(id3, id3_o, id3_s);
7844 next_comparand.identifier_5 = normalize_id(id5, id5_o, id5_s);
7845
7846 // Identifiers 3 and 5 have to be the same length. But
7847 // but either, or both, can be figurative constants. If
7848 // they are figurative constants, they start off with a
7849 // length of one. We will expand figurative constants to
7850 // match the length of the other one:
7851
7852 if( id3->attr & FIGCONST_MASK )
7853 {
7854 match_lengths( next_comparand.identifier_3,
7855 next_comparand.identifier_5);
7856 }
7857 else if( id5->attr & FIGCONST_MASK )
7858 {
7859 match_lengths( next_comparand.identifier_5,
7860 next_comparand.identifier_3);
7861 }
7862
7863 next_comparand.alpha
7864 = normalized_id_1.the_characters.c_str();
7865 next_comparand.omega
7866 = next_comparand.alpha + normalized_id_1.length;
7867
7868 normalized_operand normalized_id_4_before
7869 = normalize_id(id4_before, id4_before_o, id4_before_s);
7870 normalized_operand normalized_id_4_after
7871 = normalize_id(id4_after, id4_after_o, id4_after_s);
7872
7873 the_alpha_and_omega_backward( normalized_id_4_before,
7874 normalized_id_4_after,
7875 next_comparand.alpha,
7876 next_comparand.omega);
7877 next_comparand.leading = true;
7878 next_comparand.leading_count = 0;
7879 next_comparand.first = true;
7880 comparands.push_back(next_comparand);
7881 }
7882 }
7883 }
7884 }
7885
7886 const char *leftmost = normalized_id_1.the_characters.c_str();
7887 const char *rightmost = leftmost + normalized_id_1.length;
7888 const char *the_end_of_the_world = rightmost;
7889
7890 while( leftmost < rightmost )
7891 {
7892 rightmost -= 1;
7893 // We look at the rightmost position. If that position is within the
7894 // alpha-to-omega qualified range, we check all possible matches:
7895
7896 for(size_t k=0; k<comparands.size(); k++)
7897 {
7898 if( rightmost < comparands[k].alpha )
7899 {
7900 // This can't be a match, because rightmost is
7901 // to the left of the comparand's alpha.
7902 continue;
7903 }
7904 if( rightmost + comparands[k].identifier_3.length > comparands[k].omega )
7905 {
7906 // This can't be a match, because the rightmost
7907 // character of the comparand falls to the right
7908 // of the comparand's omega
7909 continue;
7910 }
7911 if( rightmost + comparands[k].identifier_3.length > the_end_of_the_world )
7912 {
7913 // This can't be a match, because the rightmost character of the
7914 // comparand falls past the new edge of id_1 established by a prior
7915 // match.
7916 continue;
7917 }
7918 // A match is theoretically possible, because all
7919 // the characters of the comparand fall between
7920 // alpha and omega:
7921 bool possible_match = true;
7922
7923 if( comparands[k].operation != bound_characters_e )
7924 {
7925 for(size_t m=0; m<comparands[k].identifier_3.length; m++)
7926 {
7927 if( comparands[k].identifier_3.the_characters[m] != rightmost[m] )
7928 {
7929 possible_match = false;
7930 break;
7931 }
7932 }
7933 }
7934 if( possible_match )
7935 {
7936 // The characters of the comparand match the
7937 // characters at rightmost.
7938 bool match = false;
7939 switch( comparands[k].operation )
7940 {
7941 case bound_first_e:
7942 // This can't happen in a FORMAT_2
7943 warnx("The compiler goofed: "
7944 "INSPECT FORMAT 2 "
7945 "shouldn't have "
7946 "bound_first_e");
7947 abort();
7948 break;
7949
7950 case bound_characters_e:
7951 match = 1;
7952 break;
7953
7954 case bound_all_e:
7955 {
7956 // We have a match.
7957 match = true;
7958 break;
7959 }
7960
7961 case bound_leading_e:
7962 {
7963 // We have a match at rightmost. But we need to figure out if this
7964 // particular match is valid for LEADING.
7965
7966 if( comparands[k].leading )
7967 {
7968 if( rightmost
7969 + comparands[k].identifier_3.length
7970 + comparands[k].leading_count
7971 == comparands[k].omega)
7972 {
7973 // This means that the match here is just the latest of a
7974 // string of LEADING matches that started at .omega
7975 comparands[k].leading_count += 1;
7976 match = true;
7977 }
7978 }
7979 break;
7980 }
7981
7982 case bound_trailing_e:
7983 {
7984 // We have a match at rightmost.
7985 //
7986 // We want to know if this is a trailing match. For that to be,
7987 // all of the possible matches from here leftward to the alpha have
7988 // to be true as well:
7989
7990 if( (rightmost - comparands[k].alpha )
7991 % comparands[k].identifier_3.length == 0 )
7992 {
7993 // The remaining number of characters is correct for a match.
7994 // Keep checking.
7995
7996 // Assume a match until we learn otherwise:
7997 match = true;
7998 const char *local_left = rightmost;
7999 local_left -= comparands[k].identifier_3.length;
8000 while( local_left >= comparands[k].alpha )
8001 {
8002 for(size_t m=0; m<comparands[k].identifier_3.length; m++)
8003 {
8004 if( comparands[k].identifier_3.the_characters[m]
8005 != local_left[m] )
8006 {
8007 // We have a mismatched character, so no trailing match is
8008 // possible
8009 match = false;
8010 break;
8011 }
8012 }
8013 local_left -= comparands[k].identifier_3.length;
8014 }
8015 }
8016 break;
8017 }
8018 }
8019
8020 if( match )
8021 {
8022 // We have a match at rightmost. We need to
8023 // to replace the characters in normalized_id_1
8024 // with the characters from normalized_id_5
8025 //fprintf(stderr, "Rule: %ld %p %s\n", k+1, rightmost, rightmost);
8026
8027 size_t index = rightmost - normalized_id_1.the_characters.c_str();
8028 for( size_t l = 0;
8029 l < comparands[k].identifier_5.length;
8030 l++ )
8031 {
8032 char ch = comparands[k].identifier_5.
8033 the_characters[l];
8034 normalized_id_1.the_characters[index++] = ch;
8035 }
8036
8037 the_end_of_the_world = rightmost;
8038
8039 break;
8040 }
8041 }
8042 else
8043 {
8044 comparands[k].leading = false;
8045 }
8046 }
8047 }
8048
8049 // Here is where we take the characters from normalized_id_1 and put them
8050 // back into identifier_1. There is some special processing to make sure
8051 // an embedded sign in a NumericDisplay survives the processing.
8052 unsigned char *id1_data = id1->data + id1_o;
8053 int index_dest = normalized_id_1.offset;
8054 if( id1->type == FldNumericDisplay )
8055 {
8056 for(size_t i=0; i<normalized_id_1.length; i++)
8057 {
8058 id1_data[index_dest] = normalized_id_1.the_characters[i];
8059 if( is_sign_bit_on (normalized_id_1.the_characters[i]) )
8060 {
8061 turn_sign_bit_on(&id1_data[index_dest]);
8062 }
8063 else
8064 {
8065 turn_sign_bit_off(&id1_data[index_dest]);
8066 }
8067 index_dest += 1;
8068 }
8069 }
8070 else
8071 {
8072 for(size_t i=0; i<normalized_id_1.length; i++)
8073 {
8074 id1_data[index_dest++] = normalized_id_1.the_characters[i];
8075 }
8076 }
8077 return;
8078 }
8079
8080 extern "C"
8081 void
8082 __gg__inspect_format_2(int backward, size_t integers[])
8083 {
8084 if( backward )
8085 {
8086 return inspect_backward_format_2(integers);
8087 }
8088 size_t int_index = 0;
8089 size_t cblc_index = 0;
8090
8091 // Reference the language specification for the meanings of identifier_X
8092
8093 // Pick up identifier_1, which is the string being inspected
8094 cblc_field_t *id1 = __gg__treeplet_1f[cblc_index];
8095 size_t id1_o = __gg__treeplet_1o[cblc_index];
8096 size_t id1_s = __gg__treeplet_1s[cblc_index];
8097 cblc_index += 1;
8098
8099 // normalize it, according to the language specification.
8100 normalized_operand normalized_id_1
8101 = normalize_id(id1, id1_o, id1_s);
8102
8103 std::vector<comparand> comparands;
8104
8105 // Pick up the count of operations:
8106 size_t nbounds = integers[int_index++];
8107
8108 for(size_t j=0; j<nbounds; j++ )
8109 {
8110 // each operation has a bound code:
8111 cbl_inspect_bound_t operation
8112 = (cbl_inspect_bound_t)integers[int_index++];
8113 switch( operation )
8114 {
8115 case bound_characters_e:
8116 {
8117 comparand next_comparand = {} ;
8118 next_comparand.operation = operation;
8119
8120 const cblc_field_t *id5 = __gg__treeplet_1f[cblc_index];
8121 size_t id5_o = __gg__treeplet_1o[cblc_index];
8122 size_t id5_s = __gg__treeplet_1s[cblc_index];
8123 cblc_index += 1;
8124
8125 const cblc_field_t *id4_before = __gg__treeplet_1f[cblc_index];
8126 size_t id4_before_o = __gg__treeplet_1o[cblc_index];
8127 size_t id4_before_s = __gg__treeplet_1s[cblc_index];
8128 cblc_index += 1;
8129
8130 const cblc_field_t *id4_after = __gg__treeplet_1f [cblc_index];
8131 size_t id4_after_o = __gg__treeplet_1o[cblc_index];
8132 size_t id4_after_s = __gg__treeplet_1s[cblc_index];
8133 cblc_index += 1;
8134
8135 next_comparand.identifier_5
8136 = normalize_id(id5, id5_o, id5_s);
8137 normalized_operand normalized_id_4_before
8138 = normalize_id(id4_before, id4_before_o, id4_before_s);
8139 normalized_operand normalized_id_4_after
8140 = normalize_id(id4_after, id4_after_o, id4_after_s);
8141
8142 // Because this is a CHARACTER operation, the lengths of
8143 // identifier-3 and identifier-5 should be one. Let's avoid the
8144 // chaos that will otherwise ensue should the lengths *not* be
8145 // one.
8146 next_comparand.identifier_3.length = 1;
8147 next_comparand.identifier_5.length = 1;
8148
8149 next_comparand.alpha = normalized_id_1.the_characters.c_str();
8150 next_comparand.omega
8151 = next_comparand.alpha + normalized_id_1.length;
8152
8153 the_alpha_and_omega(normalized_id_4_before,
8154 normalized_id_4_after,
8155 next_comparand.alpha,
8156 next_comparand.omega);
8157 comparands.push_back(next_comparand);
8158 break;
8159 }
8160 default:
8161 {
8162 // We have some number of identifer-3/identifier-5 pairs,
8163 // each with possible PHRASE1 modifiers.
8164 size_t pair_count = integers[int_index++];
8165
8166 for(size_t k=0; k<pair_count; k++)
8167 {
8168 comparand next_comparand = {};
8169 next_comparand.operation = operation;
8170
8171 const cblc_field_t *id3 = __gg__treeplet_1f[cblc_index];
8172 size_t id3_o = __gg__treeplet_1o[cblc_index];
8173 size_t id3_s = __gg__treeplet_1s[cblc_index];
8174 cblc_index += 1;
8175
8176 const cblc_field_t *id5 = __gg__treeplet_1f[cblc_index];
8177 size_t id5_o = __gg__treeplet_1o[cblc_index];
8178 size_t id5_s = __gg__treeplet_1s[cblc_index];
8179 cblc_index += 1;
8180
8181 const cblc_field_t *id4_before = __gg__treeplet_1f[cblc_index];
8182 size_t id4_before_o = __gg__treeplet_1o[cblc_index];
8183 size_t id4_before_s = __gg__treeplet_1s[cblc_index];
8184 cblc_index += 1;
8185
8186 const cblc_field_t *id4_after = __gg__treeplet_1f[cblc_index];
8187 size_t id4_after_o = __gg__treeplet_1o[cblc_index];
8188 size_t id4_after_s = __gg__treeplet_1s[cblc_index];
8189 cblc_index += 1;
8190
8191 next_comparand.identifier_3 = normalize_id(id3, id3_o, id3_s);
8192 next_comparand.identifier_5 = normalize_id(id5, id5_o, id5_s);
8193
8194 // Identifiers 3 and 5 have to be the same length. But
8195 // but either, or both, can be figurative constants. If
8196 // they are figurative constants, they start off with a
8197 // length of one. We will expand figurative constants to
8198 // match the length of the other one:
8199
8200 if( id3->attr & FIGCONST_MASK )
8201 {
8202 match_lengths( next_comparand.identifier_3,
8203 next_comparand.identifier_5);
8204 }
8205 else if( id5->attr & FIGCONST_MASK )
8206 {
8207 match_lengths( next_comparand.identifier_5,
8208 next_comparand.identifier_3);
8209 }
8210
8211 next_comparand.alpha
8212 = normalized_id_1.the_characters.c_str();
8213 next_comparand.omega
8214 = next_comparand.alpha + normalized_id_1.length;
8215
8216 normalized_operand normalized_id_4_before
8217 = normalize_id(id4_before, id4_before_o, id4_before_s);
8218 normalized_operand normalized_id_4_after
8219 = normalize_id(id4_after, id4_after_o, id4_after_s);
8220
8221 the_alpha_and_omega(normalized_id_4_before,
8222 normalized_id_4_after,
8223 next_comparand.alpha,
8224 next_comparand.omega);
8225 next_comparand.leading = true;
8226 next_comparand.leading_count = 0;
8227 next_comparand.first = true;
8228 comparands.push_back(next_comparand);
8229 }
8230 }
8231 }
8232 }
8233
8234 // We are now set up to accomplish the data flow described
8235 // in the language specification. We loop through the
8236 // the character positions in normalized_id_1:
8237 const char *leftmost
8238 = normalized_id_1.the_characters.c_str();
8239 const char *rightmost
8240 = leftmost + normalized_id_1.length;
8241
8242 while( leftmost < rightmost )
8243 {
8244 // For each leftmost position, we check each of the
8245 // comparands
8246
8247 for(size_t k=0; k<comparands.size(); k++)
8248 {
8249 if( leftmost < comparands[k].alpha )
8250 {
8251 // This can't be a match, because leftmost is
8252 // to the left of the comparand's alpha.
8253 continue;
8254 }
8255 if( leftmost + comparands[k].identifier_3.length
8256 > comparands[k].omega )
8257 {
8258 // This can't be a match, because the rightmost
8259 // character of the comparand falls to the right
8260 // of the comparand's omega
8261 continue;
8262 }
8263 // A match is theoretically possible, because all
8264 // the characters of the comparand fall between
8265 // alpha and omega:
8266 bool possible_match = true;
8267 if( comparands[k].operation != bound_characters_e)
8268 {
8269 for(size_t m=0; m<comparands[k].identifier_3.length; m++)
8270 {
8271 if( comparands[k].identifier_3.the_characters[m]
8272 != leftmost[m] )
8273 {
8274 possible_match = false;
8275 break;
8276 }
8277 }
8278 }
8279 if( possible_match )
8280 {
8281 // The characters of the comparand match the
8282 // characters at leftmost. See if further processing is
8283 // indicated:
8284
8285 bool match = false;
8286 switch( comparands[k].operation )
8287 {
8288 case bound_characters_e:
8289 match = true;
8290 break;
8291
8292 case bound_first_e:
8293 if( comparands[k].first )
8294 {
8295 match = true;
8296 comparands[k].first = false;
8297 }
8298 break;
8299
8300 case bound_all_e:
8301 {
8302 // We have a match.
8303 match = true;
8304 break;
8305 }
8306
8307 case bound_leading_e:
8308 {
8309 // We have a match at leftmost. But we need to figure out if this
8310 // particular match is valid for LEADING.
8311
8312 // Hang onto your hat. This is delightfully clever.
8313 //
8314 // This position is LEADING if:
8315 // 1) .leading is still true
8316 // 2) leftmost / (length_of_comparand ) = current_count
8317 //
8318 // I get chills every time I look at that.
8319 if( comparands[k].leading )
8320 {
8321 // So far, so good.
8322 size_t count = (leftmost - comparands[k].alpha)
8323 / comparands[k].identifier_3.length;
8324 if( count == comparands[k].leading_count )
8325 {
8326 // This means that the match here is just the latest of a
8327 // string of LEADING matches that started at .alpha
8328 comparands[k].leading_count += 1;
8329 match = true;
8330 }
8331 }
8332 break;
8333 }
8334
8335 case bound_trailing_e:
8336 {
8337 // We have a match at leftmost.
8338 //
8339 // We want to know if this is a trailing match. For that to be,
8340 // all of the possible matches from here to the omega have to be
8341 // true as well:
8342
8343 if( (comparands[k].omega-leftmost)
8344 % comparands[k].identifier_3.length == 0 )
8345 {
8346 // The remaining number of characters is correct for a match.
8347 // Keep checking.
8348
8349 // Assume a match until we learn otherwise:
8350 match = true;
8351 const char *local_left = leftmost;
8352 local_left += comparands[k].identifier_3.length;
8353 while( local_left < comparands[k].omega )
8354 {
8355 for(size_t m=0; m<comparands[k].identifier_3.length; m++)
8356 {
8357 if( comparands[k].identifier_3.the_characters[m]
8358 != local_left[m] )
8359 {
8360 // We have a mismatched character, so no trailing match is
8361 // possible
8362 match = false;
8363 break;
8364 }
8365 }
8366 local_left += comparands[k].identifier_3.length;
8367 }
8368 }
8369 break;
8370 }
8371 }
8372 if( match )
8373 {
8374 // We have a match at leftmost. We need to
8375 // to replace the characters in normalized_id_1
8376 // with the characters from normalized_id_5
8377
8378 size_t index = leftmost
8379 - normalized_id_1.the_characters.c_str();
8380 for( size_t l = 0;
8381 l < comparands[k].identifier_5.length;
8382 l++ )
8383 {
8384 char ch = comparands[k].identifier_5.
8385 the_characters[l];
8386 normalized_id_1.the_characters[index++] = ch;
8387 }
8388 // Adjust the leftmost pointer to point to
8389 // the rightmost character of the matched
8390 // string, keeping in mind that it will be
8391 // bumped again after we break out of the
8392 // k<pair_count loop:
8393 leftmost += comparands[k].identifier_3.length - 1;
8394 break;
8395 }
8396 }
8397 else
8398 {
8399 comparands[k].leading = false;
8400 }
8401 }
8402 leftmost += 1;
8403 }
8404
8405 // Here is where we take the characters from normalized_id_1 and put them
8406 // back into identifier_1. There is some special processing to make sure
8407 // an embedded sign in a NumericDisplay survives the processing.
8408 unsigned char *id1_data = id1->data + id1_o;
8409 int index_dest = normalized_id_1.offset;
8410 if( id1->type == FldNumericDisplay )
8411 {
8412 for(size_t i=0; i<normalized_id_1.length; i++)
8413 {
8414 id1_data[index_dest] = normalized_id_1.the_characters[i];
8415 if( is_sign_bit_on (normalized_id_1.the_characters[i]) )
8416 {
8417 turn_sign_bit_on(&id1_data[index_dest]);
8418 }
8419 else
8420 {
8421 turn_sign_bit_off(&id1_data[index_dest]);
8422 }
8423 index_dest += 1;
8424 }
8425 }
8426 else
8427 {
8428 for(size_t i=0; i<normalized_id_1.length; i++)
8429 {
8430 id1_data[index_dest++] = normalized_id_1.the_characters[i];
8431 }
8432 }
8433 return;
8434 }
8435
8436 extern "C"
8437 void
8438 __gg__inspect_format_4( int backward,
8439 cblc_field_t *input,
8440 size_t input_offset,
8441 size_t input_size,
8442 cblc_field_t *original,
8443 size_t original_offset,
8444 size_t original_size,
8445 cblc_field_t *replacement,
8446 size_t replacement_offset,
8447 size_t replacement_size,
8448 cblc_field_t *after,
8449 size_t after_offset,
8450 size_t after_size,
8451 cblc_field_t *before,
8452 size_t before_offset,
8453 size_t before_size
8454 )
8455 {
8456 static size_t psz_input_size = MINIMUM_ALLOCATION_SIZE;
8457 static size_t psz_original_size = MINIMUM_ALLOCATION_SIZE;
8458 static size_t psz_replacement_size = MINIMUM_ALLOCATION_SIZE;
8459 static size_t psz_after_size = MINIMUM_ALLOCATION_SIZE;
8460 static size_t psz_before_size = MINIMUM_ALLOCATION_SIZE;
8461 static size_t psz_figstring_size = MINIMUM_ALLOCATION_SIZE;
8462
8463 static char *psz_input = static_cast<char *>(malloc(psz_input_size ));
8464 static char *psz_original = static_cast<char *>(malloc(psz_original_size ));
8465 static char *psz_replacement = static_cast<char *>(malloc(psz_replacement_size));
8466 static char *psz_after = static_cast<char *>(malloc(psz_after_size ));
8467 static char *psz_before = static_cast<char *>(malloc(psz_before_size ));
8468 static char *psz_figstring = static_cast<char *>(malloc(psz_figstring_size ));
8469
8470 bool all = replacement_size == (size_t)(-1LL);
8471 if( all )
8472 {
8473 replacement_size = psz_original_size;
8474 }
8475
8476 psz_input = format_for_display_local(&psz_input , &psz_input_size , input , input_offset , input_size , 0);
8477 psz_original = format_for_display_local(&psz_original , &psz_original_size , original , original_offset , original_size , 0);
8478 psz_replacement = format_for_display_local(&psz_replacement, &psz_replacement_size, replacement, replacement_offset, replacement_size, 0);
8479 psz_after = format_for_display_local(&psz_after , &psz_after_size , after , after_offset , after_size , 0);
8480 psz_before = format_for_display_local(&psz_before , &psz_before_size , before , before_offset , before_size , 0);
8481
8482 if( all )
8483 {
8484 memset(psz_replacement, *(replacement->data+replacement_offset), replacement_size);
8485 }
8486
8487 cbl_figconst_t figconst =
8488 (cbl_figconst_t)(replacement->attr & FIGCONST_MASK);
8489 if( figconst )
8490 {
8491 size_t figchars = strlen(psz_input)+1;
8492 __gg__realloc_if_necessary(&psz_figstring, &psz_figstring_size, figchars);
8493 char figchar = '\0';
8494 switch( figconst )
8495 {
8496 case normal_value_e:
8497 abort();
8498 break;
8499 case low_value_e :
8500 figchar = __gg__low_value_character;
8501 break;
8502 case zero_value_e :
8503 figchar = internal_0;
8504 break;
8505 case space_value_e :
8506 figchar = internal_space;
8507 break;
8508 case quote_value_e :
8509 figchar = ascii_to_internal(__gg__quote_character);
8510 break;
8511 case high_value_e :
8512 figchar = __gg__high_value_character;
8513 break;
8514 case null_value_e:
8515 break;
8516 }
8517 memset(psz_figstring, figchar, figchars-1);
8518 psz_figstring[figchars] = '\0';
8519 psz_replacement = psz_figstring;
8520 }
8521
8522 // Use a simple map to make this O(N), rather than an O(N-squared),
8523 // computational complexity
8524 static const unsigned char map_init[256] =
8525 {
8526 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
8527 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
8528 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
8529 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
8530 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
8531 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
8532 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
8533 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
8534 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
8535 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
8536 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
8537 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
8538 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
8539 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
8540 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
8541 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
8542 };
8543 unsigned char map[256];
8544 unsigned char replaced[256];
8545
8546 memcpy(map, map_init, 256);
8547 memset(replaced, 0, 256);
8548
8549 for(size_t i=0; i<strlen(psz_original); i++)
8550 {
8551 if( !replaced[(unsigned char )psz_original[i]] )
8552 {
8553 // The rule is, if the same character appears more than once in the
8554 // original (which is identifier-6), then the first occurrence of the
8555 // character is used for replacement
8556 map[ (unsigned char )psz_original[i] ] = (unsigned char )psz_replacement[i];
8557 replaced[(unsigned char )psz_original[i]] = 1;
8558 }
8559 }
8560
8561 char *pstart = NULL;
8562 const char *pend = NULL;
8563 if( backward )
8564 {
8565 if( strlen(psz_before) )
8566 {
8567 size_t nfound = std::string(psz_input).rfind(psz_before);
8568 if( nfound == std::string::npos )
8569 {
8570 // The BEFORE string isn't in the input, so we will scan from
8571 // the leftmost character
8572 pstart = psz_input;
8573 }
8574 else
8575 {
8576 pstart = psz_input + nfound;
8577 if( !pstart )
8578 {
8579 pstart = psz_input;
8580 }
8581 pstart += strlen(psz_before);
8582 }
8583 }
8584 else
8585 {
8586 pstart = psz_input;
8587 }
8588
8589 if( strlen(psz_after) )
8590 {
8591 size_t nfound = std::string(psz_input).rfind(psz_after);
8592 if( nfound == std::string::npos )
8593 {
8594 nfound = strlen(psz_input);
8595 }
8596 pend = psz_input + nfound;
8597 }
8598 if( !pend )
8599 {
8600 pend = psz_input+strlen(psz_input);
8601 }
8602 }
8603 else
8604 {
8605 if( strlen(psz_after) )
8606 {
8607 pstart = strstr(psz_input, psz_after);
8608 }
8609 if( !pstart )
8610 {
8611 pstart = psz_input;
8612 }
8613 pstart += strlen(psz_after);
8614
8615 if( strlen(psz_before) )
8616 {
8617 pend = strstr(psz_input, psz_before);
8618 }
8619 if( !pend )
8620 {
8621 pend = psz_input + strlen(psz_input);
8622 }
8623 }
8624
8625
8626 while(pstart && pstart < pend)
8627 {
8628 *pstart = map[(unsigned char)*pstart];
8629 pstart += 1;
8630 }
8631
8632 memcpy(input->data+input_offset, psz_input, input_size);
8633 }
8634
8635 static void
8636 move_string(cblc_field_t *field,
8637 size_t offset,
8638 size_t length,
8639 const char *from,
8640 size_t strlen_from = (size_t)(-1) )
8641 {
8642 bool moved = true;
8643
8644 if( strlen_from == (size_t)(-1) )
8645 {
8646 strlen_from = strlen(from);
8647 }
8648
8649 switch(field->type)
8650 {
8651 case FldGroup:
8652 case FldAlphanumeric:
8653 case FldAlphaEdited:
8654 {
8655 char *to = reinterpret_cast<char *>(field->data + offset);
8656 size_t dest_length = length ? length : field->capacity;
8657 size_t source_length = strlen_from;
8658 size_t count = std::min(dest_length, source_length);
8659
8660 if( source_length >= dest_length )
8661 {
8662 // We have more source characters than places to put them
8663 if( field->attr & rjust_e )
8664 {
8665 // Destination is right-justified, so we
8666 // discard the leading source characters:
8667 memmove(to,
8668 from + (source_length - count),
8669 count);
8670 }
8671 else
8672 {
8673 // Destination is right-justified, so we
8674 // discard the trailing source characters:
8675 memmove(to,
8676 from,
8677 count);
8678 }
8679 }
8680 else
8681 {
8682 // We have too few source characters to fill the destination.
8683 if( field->attr & rjust_e )
8684 {
8685 // The destination is right-justified, and the source is an
8686 // ordinary string too short to fill it. So, we space-fill
8687 // the leading characters.
8688 memmove(to + (dest_length-count),
8689 from,
8690 count);
8691 memset(to, internal_space, dest_length-count);
8692 }
8693 else
8694 {
8695 // The destination is left-justified
8696 // We do the move first, in case this is an overlapping move
8697 // involving characters that will be space-filled
8698 memmove(to,
8699 from,
8700 count);
8701 memset( to + count,
8702 internal_space,
8703 dest_length-count);
8704 }
8705 }
8706 break;
8707 }
8708
8709 case FldNumericBinary:
8710 case FldPacked:
8711 case FldNumericDisplay:
8712 case FldNumericEdited:
8713 case FldNumericBin5:
8714 case FldIndex:
8715 {
8716 // We are starting with a string, and setting it to a numerical
8717 // target.
8718 int rdigits;
8719 __int128 value = __gg__dirty_to_binary_internal( from,
8720 strlen_from,
8721 &rdigits);
8722 __gg__int128_to_qualified_field(field,
8723 offset,
8724 length,
8725 value,
8726 rdigits,
8727 truncation_e,
8728 NULL);
8729 break;
8730 }
8731
8732 default:
8733 moved = false;
8734 break;
8735 }
8736 if( !moved )
8737 {
8738 fprintf(stderr, "%s() %s:%d -- We were unable move a string to "
8739 "field type %d\n",
8740 __func__, __FILE__, __LINE__,
8741 field->type);
8742 abort();
8743 }
8744 }
8745
8746 static char *
8747 brute_force_trim(char *str)
8748 {
8749 char *retval = str;
8750 while( *retval == internal_space )
8751 {
8752 retval += 1;
8753 }
8754 char *p = retval + strlen(retval)-1;
8755 while( p > retval && *p == internal_space )
8756 {
8757 *p-- = NULLCH;
8758 }
8759 return retval;
8760 }
8761
8762 extern "C"
8763 int
8764 __gg__string(const size_t integers[])
8765 {
8766 // The first integer is the count of identifier-2 values. Call it N
8767 // The following N integers are the counts of each of the identifier-1 values,
8768 // one for each identifier-1. Call them M.
8769
8770 // The first refer is the target
8771 // The second refer is the pointer
8772 // The third refer is identifier-2 for N1
8773 // That's followed by M1 identifier-1 values
8774 // That's followed by identifier2 for N2
8775 // And so on
8776
8777 cblc_field_t **ref = __gg__treeplet_1f;
8778 const size_t *ref_o = __gg__treeplet_1o;
8779 const size_t *ref_s = __gg__treeplet_1s;
8780
8781 static const int INDEX_OF_POINTER = 1;
8782
8783 size_t index_cblc = 0 ;
8784
8785 char figlow[2] = {ascii_to_internal(__gg__low_value_character), 0x00};
8786 char fighigh[2] = {ascii_to_internal(__gg__high_value_character), 0x00};
8787 char figzero[2] = {(char)internal_zero, 0x00};
8788 char figquote[2] = {ascii_to_internal(__gg__quote_character), 0x00};
8789 char figspace[2] = {(char)internal_space, 0x00};
8790
8791 if( __gg__high_value_character == DEGENERATE_HIGH_VALUE )
8792 {
8793 fighigh[0] = __gg__high_value_character;
8794 }
8795 else
8796 {
8797 fighigh[0] = ascii_to_internal(__gg__high_value_character);
8798 }
8799
8800
8801 // Pick up the target
8802 const cblc_field_t *tgt = ref[index_cblc];
8803 size_t tgt_o = ref_o[index_cblc];
8804 size_t tgt_s = ref_s[index_cblc];
8805 index_cblc += 1;
8806 char *dest = reinterpret_cast<char *>(tgt->data + tgt_o);
8807 ssize_t dest_length = tgt_s;
8808
8809 // Skip over the index of POINTER:
8810 index_cblc += 1;
8811
8812 // Pick up the pointer, if any
8813 ssize_t pointer = 0;
8814 if( ref[INDEX_OF_POINTER] )
8815 {
8816 int rdigits;
8817 pointer = (size_t)__gg__binary_value_from_qualified_field(
8818 &rdigits,
8819 ref [INDEX_OF_POINTER],
8820 ref_o[INDEX_OF_POINTER],
8821 ref_s[INDEX_OF_POINTER]
8822 );
8823 pointer -= 1;
8824 }
8825
8826 int overflow = 0;
8827
8828 // Make sure that the destination pointer is within the destination
8829 if( pointer >= 0 || pointer < dest_length )
8830 {
8831 // We are go for looping through identifier-2 values:
8832
8833 size_t index_int = 0;
8834
8835 // Pick up the number of identifier-2 values
8836 size_t N = integers[index_int++];
8837
8838 for( size_t i=0; i<N; i++ )
8839 {
8840 size_t M = integers[index_int++];
8841
8842 // Pick up the identifier_2 DELIMITED BY value
8843 const cblc_field_t *id2 = ref[index_cblc];
8844 size_t id2_o = ref_o[index_cblc];
8845 size_t id2_s = ref_s[index_cblc];
8846 index_cblc += 1;
8847
8848 char *piece;
8849 const char *piece_end;
8850 cbl_figconst_t figconst = (cbl_figconst_t) ( id2
8851 ? (id2->attr & FIGCONST_MASK)
8852 : 0 );
8853 switch(figconst)
8854 {
8855 case low_value_e:
8856 piece = figlow;
8857 piece_end = piece + 1;
8858 break;
8859 case zero_value_e:
8860 piece = figzero;
8861 piece_end = piece + 1;
8862 break;
8863 case space_value_e:
8864 piece = figspace;
8865 piece_end = piece + 1;
8866 break;
8867 case quote_value_e:
8868 piece = figquote;
8869 piece_end = piece + 1;
8870 break;
8871 case high_value_e:
8872 piece = fighigh;
8873 piece_end = piece + 1;
8874 break;
8875 default:
8876 piece = id2 ? reinterpret_cast<char *>(id2->data + id2_o) : NULL;
8877 piece_end = id2 ? piece + id2_s : NULL;
8878 break;
8879 }
8880
8881 for(size_t j=0; j<M; j++)
8882 {
8883 // Pick up the next identifier-1 source string:
8884 const cblc_field_t *id1 = ref[index_cblc];
8885 size_t id1_o = ref_o[index_cblc];
8886 size_t id1_s = ref_s[index_cblc];
8887 index_cblc += 1;
8888
8889 const char *whole = id1 ? reinterpret_cast<char *>(id1->data + id1_o): NULL ;
8890 const char *whole_end = id1 ? whole + id1_s : NULL;
8891
8892 // As usual, we need to cope with figurative constants:
8893 figconst = (cbl_figconst_t) ( id1 ? (id1->attr & FIGCONST_MASK) : 0 );
8894 switch( figconst )
8895 {
8896 case low_value_e:
8897 whole = figlow;
8898 whole_end = whole + 1;
8899 break;
8900 case zero_value_e:
8901 whole = figzero;
8902 whole_end = whole + 1;
8903 break;
8904 case space_value_e:
8905 whole = figspace;
8906 whole_end = whole + 1;
8907 break;
8908 case quote_value_e:
8909 whole = figquote;
8910 whole_end = whole + 1;
8911 break;
8912 case high_value_e:
8913 whole = fighigh;
8914 whole_end = whole + 1;
8915 break;
8916 default:
8917 break;
8918 }
8919
8920 if(piece)
8921 {
8922 const char *found = funky_find( piece, piece_end,
8923 whole, whole_end);
8924 if(found)
8925 {
8926 whole_end = found;
8927 }
8928 }
8929 while(whole < whole_end)
8930 {
8931 if(pointer >= dest_length)
8932 {
8933 overflow = 1;
8934 break;
8935 }
8936 dest[pointer++] = *whole++;
8937 }
8938 if( overflow )
8939 {
8940 break;
8941 }
8942 }
8943 }
8944
8945 // Update the pointer, if there is one
8946 if( ref[INDEX_OF_POINTER] )
8947 {
8948 __gg__int128_to_qualified_field(ref [INDEX_OF_POINTER],
8949 ref_o[INDEX_OF_POINTER],
8950 ref_s[INDEX_OF_POINTER],
8951 (__int128)(pointer+1),
8952 0,
8953 truncation_e,
8954 NULL );
8955 }
8956 }
8957 else
8958 {
8959 // The initial pointer is not inside the destination
8960 overflow = 1;
8961 }
8962
8963 return overflow;
8964 }
8965
8966 static
8967 void
8968 display_both(cblc_field_t *field,
8969 unsigned char *qual_data,
8970 size_t qual_size,
8971 int flags,
8972 int file_descriptor,
8973 int advance )
8974 {
8975 static size_t display_string_size = MINIMUM_ALLOCATION_SIZE;
8976 static char *display_string = static_cast<char *>(malloc(display_string_size));
8977
8978 format_for_display_internal(&display_string,
8979 &display_string_size,
8980 field,
8981 qual_data,
8982 qual_size,
8983 !!(flags & REFER_T_ADDRESS_OF) );
8984
8985 // Let's honor the locale of the system, as best we can:
8986 static size_t converted_size = MINIMUM_ALLOCATION_SIZE;
8987 static char *converted = static_cast<char *>(malloc(converted_size));
8988
8989 internal_to_console(&converted, &converted_size, display_string, strlen(display_string));
8990
8991 ssize_t ss = write( file_descriptor,
8992 converted,
8993 strlen(converted));
8994 if(ss == -1)
8995 {
8996 fprintf(stderr, "__gg__display() %s %p\n", field->name, qual_data);
8997 fprintf(stderr, "__gg__display() %ld\n", static_cast<long>(converted_size));
8998 fprintf(stderr, "__gg__display() ");
8999 for(size_t i=0; i<converted_size; i++)
9000 {
9001 fprintf(stderr, "%c(%2.2x) ", converted[i]<32 ? '?' : converted[i], converted[i]);
9002 }
9003 __gg__abort("display_both() some kind of write() error");
9004 fprintf(stderr, "\n");
9005 }
9006
9007 if( advance )
9008 {
9009 write( file_descriptor,
9010 "\n",
9011 1);
9012 }
9013 }
9014
9015 extern "C"
9016 void
9017 __gg__display( cblc_field_t *field,
9018 size_t offset,
9019 size_t size,
9020 int file_descriptor,
9021 int advance )
9022 {
9023 display_both( field,
9024 field->data + offset,
9025 size,
9026 0,
9027 file_descriptor,
9028 advance);
9029 }
9030
9031 extern "C"
9032 void
9033 __gg__display_clean(cblc_field_t *field,
9034 int file_descriptor,
9035 int advance )
9036 {
9037 display_both( field,
9038 field->data,
9039 field->capacity,
9040 0,
9041 file_descriptor,
9042 advance);
9043 }
9044
9045 #pragma GCC diagnostic push
9046 #pragma GCC diagnostic ignored "-Wunused-result"
9047
9048 extern "C"
9049 void
9050 __gg__display_string( int file_descriptor,
9051 const char *str,
9052 size_t length,
9053 int advance )
9054 {
9055 // Let's honor the locale of the system, as best we can:
9056 static size_t converted_size = MINIMUM_ALLOCATION_SIZE;
9057 static char *converted = static_cast<char *>(malloc(converted_size));
9058
9059 size_t max_possible = 2 * length;
9060 if( max_possible > converted_size )
9061 {
9062 converted_size = max_possible;
9063 converted = static_cast<char *>(realloc(converted, converted_size));
9064 }
9065
9066 __gg__ascii_to_console(&converted, &converted_size, str, length);
9067
9068 write( file_descriptor,
9069 converted,
9070 strlen(converted));
9071 if( advance )
9072 {
9073 write( file_descriptor,
9074 "\n",
9075 1);
9076 }
9077 }
9078
9079 static
9080 char *
9081 mangler_core(const char *s, const char *eos)
9082 {
9083 // The caller needs to be aware that the return value is a static character
9084 // array. Program accordingly.
9085
9086 // This is the run-time version of the code in cobol1.cc routine that mangles
9087 // cobol names into workable form. The logic here has to match the logic
9088 // there so that calls work.
9089
9090 static char cobol_name[1024];
9091
9092 while( s < eos && *s == ascii_space )
9093 {
9094 s += 1;
9095 }
9096 while( s < eos && *(eos-1) == ascii_space )
9097 {
9098 eos -= 1;
9099 }
9100
9101 char *d = cobol_name;
9102 if( s[0] >= ascii_0 && s[0] <= ascii_9 )
9103 {
9104 *d++ = '_';
9105 }
9106
9107 while(s < eos)
9108 {
9109 int ch = *s++;
9110 if( ch == ascii_hyphen )
9111 {
9112 *d++ = ascii_dollar_sign;
9113 }
9114 else
9115 {
9116 *d++ = tolower((unsigned char)ch);
9117 }
9118 }
9119 *d++ = NULLCH;
9120
9121 return cobol_name;
9122 }
9123
9124 static
9125 char *
9126 not_mangled_core(const char *s, const char *eos)
9127 {
9128 const char *s1 = s;
9129 const char *s2 = eos;
9130 bool has_dash = false;
9131
9132 while( s < eos && *s == internal_space )
9133 {
9134 s += 1;
9135 }
9136 while( s < eos && *(eos-1) == internal_space )
9137 {
9138 eos -= 1;
9139 }
9140
9141 if( s[0] >= ascii_0 && s[0] <= ascii_9 )
9142 {
9143 has_dash = true;
9144 }
9145 else
9146 {
9147 while(s < eos)
9148 {
9149 int ch = *s++;
9150 if( ch == ascii_hyphen )
9151 {
9152 has_dash = true;
9153 }
9154 }
9155 }
9156
9157 if( has_dash )
9158 {
9159 return mangler_core(s1, s2);
9160 }
9161
9162 return (char *)s1;
9163 }
9164
9165 extern "C"
9166 void
9167 __gg__accept( enum special_name_t special_e,
9168 cblc_field_t *field,
9169 size_t offset,
9170 size_t length)
9171 {
9172 int file_descriptor = 0; // Default to stdin
9173
9174 size_t max_chars = length ? length : field->capacity;
9175
9176 if( special_e == CONSOLE_e )
9177 {
9178 // Welcome to the land of possibly screwball assumptions. If reading
9179 // from CONSOLE/stdin it's possible that the target variable is
9180 // a NumericBinary of length 4, which can hold a 10-digit number. So,
9181 // we need room to accept the characters, which will later on be converted
9182 // to a binary value.
9183
9184 // But SYSIN and SYSIPT seem to require that characters be read until the
9185 // size of the target variable is satisfied, which implies further that
9186 // the target must be alphanumeric.
9187
9188 // What reality will ultimately offer is unknown to me. But I'm doing
9189 // the best I can with what I've got, and, right now, this is what
9190 // I've got.
9191 if( max_chars < 64 )
9192 {
9193 // Set a floor for the length of the buffer. This will let us cope
9194 // with, say, a four-byte binary value that can hold ten digits
9195 max_chars = 64;
9196 }
9197 }
9198
9199 char *buffer = static_cast<char *>(malloc(max_chars+1));
9200 massert(buffer);
9201 memset(buffer, ascii_space, max_chars);
9202 buffer[max_chars] = NULLCH;
9203 size_t i = 0;
9204
9205 for(;;)
9206 {
9207 char ch;
9208 ssize_t bytes_read = read(file_descriptor, &ch, 1);
9209 if( bytes_read <= 0 )
9210 {
9211 // Error or end-of-file, so give up
9212 break;
9213 }
9214
9215 if( ch == '\n' )
9216 {
9217 // End-of-line
9218 if( special_e == CONSOLE_e )
9219 {
9220 // When reading from the console, a newline means that the
9221 // typist pressed ENTER/RETURN, and the input is done. This is
9222 // also the case even when stdin was redirected from a file or
9223 // another process
9224 break;
9225 }
9226 else
9227 {
9228 // But if SYSIN_e or SYSIPT_e was specified, we are emulating
9229 // the universe of punched cards, so we just keep reading in
9230 // characters until we have read in max_chars. We found it
9231 // necessary to implement ACCEPT in this fashion to get the
9232 // NIST test suite to work.
9233
9234 // Note that in both cases, we keep reading until we hit
9235 // an actual newline or end-of-file
9236
9237 if( i >= max_chars )
9238 {
9239 break;
9240 }
9241 continue;
9242 }
9243 }
9244 if(i < max_chars)
9245 {
9246 buffer[i++] = ch;
9247 }
9248 }
9249
9250 switch(field->type)
9251 {
9252 case FldGroup :
9253 case FldAlphanumeric :
9254 case FldAlphaEdited :
9255 console_to_internal(buffer, i);
9256 move_string(field,
9257 offset,
9258 length,
9259 buffer,
9260 strlen(buffer));
9261 break;
9262
9263 case FldNumericDisplay:
9264 {
9265 // In the NIST tests, feeding ten digits 0123456789 into a
9266 // PIC 9(9) results in a nine-digit 012345678 rather than our
9267 // default 123456789
9268
9269 int digit_count = 0;
9270 char *p = buffer;
9271 while(*p && digit_count < field->digits)
9272 {
9273 if( *p == __gg__decimal_point )
9274 {
9275 p += 1;
9276 continue;
9277 }
9278
9279 switch(*p)
9280 {
9281 case ascii_0:
9282 case ascii_1:
9283 case ascii_2:
9284 case ascii_3:
9285 case ascii_4:
9286 case ascii_5:
9287 case ascii_6:
9288 case ascii_7:
9289 case ascii_8:
9290 case ascii_9:
9291 p += 1;
9292 digit_count += 1;
9293 continue;
9294 break;
9295 case ascii_minus:
9296 case ascii_plus:
9297 p += 1;
9298 continue;
9299 break;
9300 default:
9301 goto we_are_done;
9302 break;
9303 }
9304 }
9305 we_are_done:
9306 *p = NULLCH;
9307
9308 int rdigits;
9309 __int128 value = __gg__dirty_to_binary_source( buffer,
9310 (int)i,
9311 &rdigits);
9312
9313 __gg__int128_to_qualified_field(field,
9314 offset,
9315 length,
9316 value,
9317 rdigits,
9318 truncation_e,
9319 NULL);
9320 break;
9321 }
9322
9323 default:
9324 {
9325 int rdigits;
9326
9327 __int128 value = __gg__dirty_to_binary_source( buffer,
9328 (int)i,
9329 &rdigits);
9330
9331 __gg__int128_to_qualified_field(field,
9332 offset,
9333 length,
9334 value,
9335 rdigits,
9336 truncation_e,
9337 NULL);
9338 break;
9339 }
9340 }
9341 #if LOGGING_FOR_TESTING
9342 if( isatty(file_descriptor) )
9343 {
9344 auto p = strchr(buffer, '\0');
9345 *p = '\n';
9346 write(1, buffer, (p - buffer) + 1);
9347 }
9348 #endif
9349 free(buffer);
9350 }
9351
9352 extern "C"
9353 __int128
9354 __gg__binary_value_from_field( int *rdigits,
9355 cblc_field_t *var)
9356 {
9357 return get_binary_value_local( rdigits,
9358 var,
9359 var->data,
9360 var->capacity);
9361 }
9362
9363 extern "C"
9364 __int128
9365 __gg__binary_value_from_qualified_field(int *rdigits,
9366 const cblc_field_t *var,
9367 size_t offset,
9368 size_t size)
9369 {
9370 return get_binary_value_local( rdigits,
9371 var,
9372 var->data + offset,
9373 size);
9374 }
9375
9376 extern "C"
9377 GCOB_FP128
9378 __gg__float128_from_field( cblc_field_t *field )
9379 {
9380 GCOB_FP128 retval=0;
9381 if( field->type == FldFloat || field->type == FldLiteralN )
9382 {
9383 retval = get_float128(field, field->data);
9384 }
9385 else
9386 {
9387 int rdigits;
9388 retval = (GCOB_FP128)__gg__binary_value_from_field(&rdigits, field);
9389 if( rdigits )
9390 {
9391 retval /= (GCOB_FP128)__gg__power_of_ten(rdigits);
9392 }
9393 }
9394 return retval;
9395 }
9396
9397 extern "C"
9398 GCOB_FP128
9399 __gg__float128_from_qualified_field(const cblc_field_t *field, size_t offset, size_t size)
9400 {
9401 GCOB_FP128 retval=0;
9402 if( field->type == FldFloat || field->type == FldLiteralN )
9403 {
9404 retval = get_float128(field, field->data+offset);
9405 }
9406 else
9407 {
9408 int rdigits;
9409 retval = (GCOB_FP128)__gg__binary_value_from_qualified_field(&rdigits, field, offset, size);
9410 if( rdigits )
9411 {
9412 retval /= (GCOB_FP128)__gg__power_of_ten(rdigits);
9413 }
9414 }
9415 return retval;
9416 }
9417
9418 extern "C"
9419 __int128
9420 __gg__integer_from_qualified_field( cblc_field_t *var,
9421 size_t var_offset,
9422 size_t var_size)
9423 {
9424 // This is useful when a temporary value with some number of rdigits
9425 // is passed when the value is known to be an integer
9426
9427 int rdigits;
9428 __int128 retval = get_binary_value_local( &rdigits,
9429 var,
9430 var->data + var_offset,
9431 var_size);
9432 if( rdigits )
9433 {
9434 retval /= __gg__power_of_ten(rdigits);
9435 }
9436 return retval;
9437 }
9438
9439 extern "C"
9440 void
9441 __gg__int128_to_field(cblc_field_t *tgt,
9442 __int128 value,
9443 int source_rdigits,
9444 enum cbl_round_t rounded,
9445 int *compute_error)
9446 {
9447 int128_to_field(tgt,
9448 tgt->data,
9449 tgt->capacity,
9450 value,
9451 source_rdigits,
9452 rounded,
9453 compute_error);
9454 }
9455
9456 extern "C"
9457 void
9458 __gg__int128_to_qualified_field(cblc_field_t *tgt,
9459 size_t offset,
9460 size_t length,
9461 __int128 value,
9462 int source_rdigits,
9463 enum cbl_round_t rounded,
9464 int *compute_error)
9465 {
9466 int128_to_field(tgt,
9467 tgt->data + offset,
9468 length ? length : tgt->capacity,
9469 value,
9470 source_rdigits,
9471 rounded,
9472 compute_error);
9473 }
9474
9475 static __int128
9476 float128_to_int128( int *rdigits,
9477 const cblc_field_t *field,
9478 GCOB_FP128 value,
9479 cbl_round_t rounded,
9480 int *compute_error)
9481 {
9482 __int128 retval = 0;
9483 if( value == INFINITY )
9484 {
9485 *compute_error = compute_error_overflow;
9486 }
9487 else if( value == NAN )
9488 {
9489 *compute_error = compute_error_underflow;
9490 }
9491 else
9492 {
9493 // Our mission is to take a 128-bit floating point value and convert it
9494 // to a 128-bit number. If we can't, we flag it appropriately.
9495
9496 if( field->attr & intermediate_e )
9497 {
9498 // Our target doesn't have a fixed number of rdigits. We will look at the
9499 // value, and from that calculate the maximum number of rdigits we can
9500 // get away with.
9501
9502 // Calculate the number of digits to the left of the decimal point:
9503 int digits = (int)(FP128_FUNC(floor)(FP128_FUNC(log)(FP128_FUNC(fabs)(value)))+1);
9504
9505 // Make sure it is not a negative number
9506 digits = std::max(0, digits);
9507
9508 // From that we can calculate the number of rdigits
9509 *rdigits = MAX_FIXED_POINT_DIGITS - digits;
9510 }
9511 else
9512 {
9513 // Our target has a fixed number of rdigits:
9514 *rdigits = field->rdigits;
9515 }
9516
9517 // We now multiply our value by 10**rdigits, in order to make the
9518 // floating-point value have the same magnitude as our target __int128
9519
9520 value *= FP128_FUNC(pow)(GCOB_FP128_LITERAL (10.0), (GCOB_FP128)(*rdigits));
9521
9522 // We are ready to cast value to an __int128. But this value could be
9523 // too large to fit, which is an error condition we want to flag:
9524
9525 if( FP128_FUNC(fabs)(value) >= GCOB_FP128_LITERAL (1.0E38) )
9526 {
9527 *compute_error = compute_error_overflow;
9528 }
9529 else
9530 {
9531 retval = f128_to_i128_rounded(rounded, value, compute_error);
9532 }
9533 }
9534
9535 return retval;
9536 }
9537
9538 static void
9539 float128_to_location( cblc_field_t *tgt,
9540 unsigned char *data,
9541 size_t size,
9542 GCOB_FP128 value,
9543 enum cbl_round_t rounded,
9544 int *compute_error)
9545 {
9546 switch(tgt->type)
9547 {
9548 case FldFloat:
9549 {
9550 switch(tgt->capacity)
9551 {
9552 case 4:
9553 if( FP128_FUNC(fabs)(value) == (GCOB_FP128)INFINITY
9554 || FP128_FUNC(fabs)(value) > GCOB_FP128_LITERAL (3.4028235E38) )
9555 {
9556 if( compute_error )
9557 {
9558 *compute_error |= compute_error_overflow;
9559 }
9560 if( value < 0 )
9561 {
9562 *PTRCAST(float, data) = -INFINITY;
9563 }
9564 else
9565 {
9566 *PTRCAST(float, data) = INFINITY;
9567 }
9568 }
9569 else
9570 {
9571 *PTRCAST(float, data) = static_cast<float>(value);
9572 }
9573 break;
9574
9575 case 8:
9576 if( FP128_FUNC(fabs)(value) == (GCOB_FP128)INFINITY
9577 || FP128_FUNC(fabs)(value) > GCOB_FP128_LITERAL (1.7976931348623157E308) )
9578 {
9579 if( compute_error )
9580 {
9581 *compute_error |= compute_error_overflow;
9582 }
9583 if( value < 0 )
9584 {
9585 *PTRCAST(double, data) = -INFINITY;
9586 }
9587 else
9588 {
9589 *PTRCAST(double, data) = INFINITY;
9590 }
9591 }
9592 else
9593 {
9594 *PTRCAST(double, data) = static_cast<double>(value);
9595 }
9596 break;
9597
9598 case 16:
9599 if( FP128_FUNC(fabs)(value) == (GCOB_FP128)INFINITY )
9600 {
9601 if( compute_error )
9602 {
9603 *compute_error |= compute_error_overflow;
9604 }
9605 }
9606
9607 //*(_Float128 *)(data) = value;
9608 memcpy(data, &value, 16);
9609 break;
9610 }
9611 break;
9612 }
9613
9614 default:
9615 {
9616 if( compute_error )
9617 {
9618 int digits;
9619 if( tgt->attr & intermediate_e )
9620 {
9621 digits = MAX_FIXED_POINT_DIGITS;
9622 }
9623 else
9624 {
9625 digits = tgt->digits;
9626 }
9627
9628 GCOB_FP128 maximum;
9629
9630 if( digits )
9631 {
9632 maximum = __gg__power_of_ten(digits);
9633 }
9634
9635 // When digits is zero, this is a binary value without a PICTURE string.
9636 // we don't truncate in that case
9637 if( digits && FP128_FUNC(fabs)(value) >= maximum )
9638 {
9639 *compute_error |= compute_error_truncate;
9640 }
9641 }
9642
9643 int rdigits=0; // Initialized to quiet a compiler warning.
9644 __int128 val128 = float128_to_int128( &rdigits,
9645 tgt,
9646 value,
9647 rounded,
9648 compute_error);
9649 int128_to_field(tgt,
9650 data,
9651 size,
9652 val128,
9653 rdigits,
9654 rounded,
9655 compute_error);
9656 break;
9657 }
9658 }
9659 }
9660
9661
9662 extern "C"
9663 void
9664 __gg__float128_to_field(cblc_field_t *tgt,
9665 GCOB_FP128 value,
9666 enum cbl_round_t rounded,
9667 int *compute_error)
9668 {
9669 float128_to_location( tgt,
9670 tgt->data,
9671 tgt->capacity,
9672 value,
9673 rounded,
9674 compute_error);
9675 }
9676
9677 extern "C"
9678 void
9679 __gg__float128_to_qualified_field(cblc_field_t *tgt,
9680 size_t tgt_offset,
9681 GCOB_FP128 value,
9682 enum cbl_round_t rounded,
9683 int *compute_error)
9684 {
9685 float128_to_location( tgt,
9686 tgt->data + tgt_offset,
9687 tgt->capacity,
9688 value,
9689 rounded,
9690 compute_error);
9691 }
9692
9693 extern "C"
9694 bool
9695 __gg__bitop(cblc_field_t *a,
9696 bitop_t op,
9697 size_t bitmask)
9698 {
9699 bool retval = false;
9700 int rdigits;
9701 __int128 value = __gg__binary_value_from_field(&rdigits, a);
9702 switch(op)
9703 {
9704 case bit_set_op: // set bits on
9705 value |= bitmask;
9706 __gg__int128_to_field(a,
9707 value,
9708 0,
9709 truncation_e,
9710 NULL);
9711 break;
9712
9713 case bit_clear_op: // set bits off
9714 value &= ~bitmask;
9715 __gg__int128_to_field(a,
9716 value,
9717 0,
9718 truncation_e,
9719 NULL);
9720 break;
9721
9722 case bit_on_op: // true if any bitmask bit is on
9723 retval = bitmask & value;
9724 break;
9725
9726 case bit_off_op: // true if any bitmask bit is off
9727 retval = bitmask & ~value;
9728 break;
9729
9730 default:
9731 __gg__abort("__gg__bitop() unknown operation code");
9732 break;
9733 }
9734
9735 return retval;
9736 }
9737
9738 extern "C"
9739 void
9740 __gg__bitwise_op( cblc_field_t *tgt,
9741 cblc_field_t *a,
9742 bitop_t op,
9743 size_t bitmask)
9744 {
9745 int rdigits;
9746 __int128 value = __gg__binary_value_from_field(&rdigits, a);
9747 switch(op)
9748 {
9749 case bit_and_op:
9750 value &= bitmask;
9751 __gg__int128_to_field(tgt,
9752 value,
9753 0,
9754 truncation_e,
9755 NULL);
9756 break;
9757
9758 case bit_or_op:
9759 value |= bitmask;
9760 __gg__int128_to_field(tgt,
9761 value,
9762 0,
9763 truncation_e,
9764 NULL);
9765 break;
9766
9767 case bit_xor_op:
9768 value ^= bitmask;
9769 __gg__int128_to_field(tgt,
9770 value,
9771 0,
9772 truncation_e,
9773 NULL);
9774 break;
9775
9776 default:
9777 __gg__abort("__gg__bitwise_op() unknown operation code");
9778 break;
9779 }
9780 }
9781
9782 extern "C"
9783 void
9784 __gg__set_initial_switch_value( )
9785 {
9786 // We need to establish the initial value of the UPSI-1 switch register
9787 // We are using IBM's conventions:
9788 // https://www.ibm.com/docs/en/zvse/6.2?topic=SSB27H_6.2.0/fa2sf_communicate_appl_progs_via_job_control.html
9789 // UPSI 10000110 means that bits 0, 5, and 6 are on, which means that SW-0, SW-5, and SW-6 are on.
9790
9791 __int128 value = 0;
9792 __int128 bit = 1;
9793 char ach[129];
9794 memset(ach, 0, sizeof(ach));
9795 const char *p = getenv("UPSI");
9796 if( p )
9797 {
9798 snprintf(ach, sizeof(ach), "%s", p);
9799 p = ach;
9800 while(*p)
9801 {
9802 if( *p++ == ascii_1 )
9803 {
9804 value |= bit;
9805 }
9806 bit <<= 1 ;
9807 }
9808 }
9809 __gg__data_upsi_0[0] = (value>>0) & 0xFF;
9810 __gg__data_upsi_0[1] = (value>>8) & 0xFF;
9811 }
9812
9813 static int
9814 is_numeric_edited_numeric(cblc_field_t *, size_t, size_t )
9815 {
9816 fprintf(stderr, "We don't know how to see if numeric-edited is numeric\n");
9817 abort();
9818 }
9819
9820 static int
9821 is_numeric_display_numeric(cblc_field_t *field, size_t offset, size_t size)
9822 {
9823 int retval = 1;
9824 bool signable = !!(field->attr & signable_e);
9825 bool leading = !!(field->attr & leading_e);
9826 bool separate = !!(field->attr & separate_e);
9827
9828 char *digits = reinterpret_cast<char *>(field->data + offset);
9829 char *digits_e = digits + size;
9830
9831 if( leading && separate && signable )
9832 {
9833 // First character must be +/-
9834 if( digits < digits_e
9835 || ( *digits != internal_plus
9836 && *digits != internal_minus) )
9837 {
9838 retval = 0;
9839 }
9840 digits += 1;
9841 }
9842
9843 if( !leading && separate && signable )
9844 {
9845 // Last character must be +/-
9846 digits_e -= 1;
9847 if( digits < digits_e
9848 || ( *digits_e != internal_plus
9849 && *digits_e != internal_minus) )
9850 {
9851 retval = 0;
9852 }
9853 }
9854
9855 if( leading && !separate && signable )
9856 {
9857 // The first character is allowed to have a sign bit.
9858 if( digits < digits_e )
9859 {
9860 unsigned char first_char = (unsigned char)*digits;
9861 turn_sign_bit_off(&first_char);
9862 if(first_char<internal_0 || first_char>internal_9)
9863 {
9864 retval = 0;
9865 }
9866 }
9867 digits += 1;
9868 }
9869
9870 if( !leading && !separate && signable )
9871 {
9872 // The final character is allowed to have a sign bit.
9873 if( digits < digits_e )
9874 {
9875 digits_e -= 1;
9876 unsigned char final_char = (unsigned char)*digits_e;
9877 turn_sign_bit_off(&final_char);
9878 if(final_char<internal_0 || final_char>internal_9)
9879 {
9880 retval = 0;
9881 }
9882 }
9883 }
9884
9885 // all remaining characters are supposed to be zero through nine
9886 while( digits < digits_e )
9887 {
9888 if( (unsigned char)(*digits)<internal_0
9889 || (unsigned char)(*digits)>internal_9 )
9890 {
9891 retval = 0;
9892 break;
9893 }
9894 digits += 1;
9895 }
9896 return retval;
9897 }
9898
9899 static int
9900 is_packed_numeric(const cblc_field_t *field, size_t offset, size_t size)
9901 {
9902 int retval = 1;
9903 bool is_comp6 = !!(field->attr&packed_no_sign_e);
9904 int digits = field->digits;
9905 bool signable = !!(field->attr & signable_e);
9906 const unsigned char *bytes = field->data + offset;
9907
9908 int nybble = 0;
9909 int nybble_e = nybble + digits;
9910 unsigned char should_be_zero = 0;
9911 if( is_comp6 )
9912 {
9913 // This is packed decimal with no sign nybble at the end
9914 if( digits & 1 )
9915 {
9916 // There are an odd number of digits, so the string starts on the
9917 // the right side of the first byte
9918 nybble += 1;
9919 nybble_e += 1;
9920 should_be_zero = *bytes & 0xF0;
9921 }
9922 }
9923 else
9924 {
9925 // This is packed decimal, and ends with a sign nybble
9926 if( size )
9927 {
9928 unsigned char nyb = bytes[size-1] & 0x0F;
9929 if( !signable && nyb != 0x0F)
9930 {
9931 retval = 0;
9932 }
9933 if( signable && nyb != 0x0C && nyb != 0x0D )
9934 {
9935 retval = 0;
9936 }
9937 }
9938 if( !(digits & 1) )
9939 {
9940 // There are an even number of digits before the sign nybble. So the
9941 // string starts on the right side of the first byte
9942 nybble += 1;
9943 nybble_e += 1;
9944 should_be_zero = *bytes & 0xF0;
9945 }
9946 }
9947 if( should_be_zero != 0 )
9948 {
9949 retval = 0;
9950 }
9951 // At this point, all nybbles between nybble and nybble_e should be between
9952 // 0x00 and 0x09.
9953 while(nybble < nybble_e)
9954 {
9955 unsigned char nyb = bytes[nybble/2];
9956 if( !(nybble & 1))
9957 {
9958 nyb >>= 4;
9959 }
9960 else
9961 {
9962 nyb &= 0xF;
9963 }
9964 if( nyb > 0x09 )
9965 {
9966 retval = 0;
9967 break;
9968 }
9969 nybble += 1;
9970 }
9971 return retval;
9972 }
9973
9974 static int
9975 is_alpha_a_number(const cblc_field_t *field,
9976 size_t offset,
9977 size_t size)
9978 {
9979 int retval = 1;
9980 const unsigned char *bytes = (field->data + offset);
9981 for( size_t i=0; i<size; i++ )
9982 {
9983 unsigned char ch = bytes[i];
9984 if( (ch < internal_0)
9985 || (ch > internal_9) )
9986 {
9987 retval = 0;
9988 break;
9989 }
9990 }
9991 return retval;
9992 }
9993
9994 extern "C"
9995 int
9996 __gg__classify( classify_t type,
9997 cblc_field_t *field,
9998 size_t offset,
9999 size_t size)
10000 {
10001 // The default answer is TRUE
10002 int retval = 1;
10003
10004 const unsigned char *alpha = reinterpret_cast<unsigned char *>(field->data+offset);
10005
10006 size_t str_length = size;
10007
10008 const unsigned char *omega = alpha + str_length;
10009
10010 if(alpha >= omega)
10011 {
10012 // If there is nothing there, then it can't be TRUE. Can it?
10013 retval = 0;
10014 }
10015
10016 unsigned char ch;
10017 switch(type)
10018 {
10019 case ClassNumericType:
10020 {
10021 switch( field->type )
10022 {
10023 case FldNumericEdited:
10024 retval = is_numeric_edited_numeric(field, offset, size);
10025 break;
10026 case FldNumericDisplay:
10027 retval = is_numeric_display_numeric(field, offset, size);
10028 break;
10029 case FldPacked:
10030 retval = is_packed_numeric(field, offset, size);
10031 break;
10032 case FldGroup:
10033 case FldAlphanumeric:
10034 case FldAlphaEdited:
10035 retval = is_alpha_a_number(field, offset, size);
10036 break;
10037
10038 case FldNumericBinary:
10039 case FldNumericBin5:
10040 // These need to checked for fitting into field->digits
10041 break;
10042
10043 default:
10044 fprintf(stderr,
10045 "We need code for %s numeric type %d\n",
10046 field->name,
10047 field->type);
10048 abort();
10049 break;
10050 }
10051
10052 break;
10053 }
10054
10055 case ClassAlphabeticType:
10056 while(alpha < omega)
10057 {
10058 ch = (*alpha++)&0xFF;
10059 if( ch == internal_space )
10060 {
10061 continue;
10062 }
10063 // If necessary, this could be sped up with the creation of
10064 // appropriate mapping tables.
10065
10066 // The oddball construction of this if() statement is a consequence of
10067 // EBCDIC. Because of peculiarities going all the back to the encoding
10068 // of characters on IBM cards, where it wasn't a good idea to have too
10069 // many consecutive punches in a column because it would weaken the card
10070 // to the point where its structural integrity might be threatened, the
10071 // coding for the letter of the alphabet are not contiguous.
10072 if(!( ( ch >= internal_A && ch <= internal_I)
10073 || (ch >= internal_J && ch <= internal_R)
10074 || (ch >= internal_S && ch <= internal_Z)
10075 || (ch >= internal_a && ch <= internal_i)
10076 || (ch >= internal_j && ch <= internal_r)
10077 || (ch >= internal_s && ch <= internal_z) ) )
10078 {
10079 // The character is not alphabetic
10080 retval = 0;
10081 break;
10082 }
10083 }
10084 break;
10085
10086 case ClassLowerType:
10087 while(alpha < omega)
10088 {
10089 ch = *alpha++;
10090 if( ch == internal_space )
10091 {
10092 continue;
10093 }
10094 if(!( ( ch >= internal_a && ch <= internal_i)
10095 || (ch >= internal_j && ch <= internal_r)
10096 || (ch >= internal_s && ch <= internal_z) ) )
10097 {
10098 retval = 0;
10099 break;
10100 }
10101 }
10102 break;
10103 case ClassUpperType:
10104 while(alpha < omega)
10105 {
10106 ch = *alpha++;
10107 if( ch == internal_space )
10108 {
10109 continue;
10110 }
10111 if(!( ( ch >= internal_A && ch <= internal_I)
10112 || (ch >= internal_J && ch <= internal_R)
10113 || (ch >= internal_S && ch <= internal_Z) ) )
10114 {
10115 retval = 0;
10116 break;
10117 }
10118 }
10119 break;
10120
10121 case ClassInvalidType:
10122 case ClassDbcsType:
10123 case ClassKanjiType:
10124 default:
10125 warnx("%s(): Don't know how to handle %s",
10126 __func__,
10127 classify_str(type));
10128 abort();
10129 break;
10130 }
10131
10132 return retval;
10133 }
10134
10135 static
10136 int
10137 accept_envar( cblc_field_t *tgt,
10138 size_t tgt_offset,
10139 size_t tgt_length,
10140 const char *psz_name)
10141 {
10142 int retval = 1; // 1 means we couldn't find it
10143 if( psz_name )
10144 {
10145 tgt_length = tgt_length ? tgt_length : tgt->capacity;
10146
10147 // Pick up the environment variable name, which is in the internal codeset
10148 char *env = strdup(psz_name);
10149 massert(env);
10150
10151 // Get rid of leading and trailing internal_space characters:
10152 char *trimmed_env = brute_force_trim(env);
10153
10154 // Convert the name to the console codeset:
10155 __gg__internal_to_console_in_place(trimmed_env, strlen(trimmed_env));
10156
10157 // Pick up the environment variable, and convert it to the internal codeset
10158 const char *p = getenv(trimmed_env);
10159 if(p)
10160 {
10161 char *pp = strdup(p);
10162 massert(pp);
10163 console_to_internal(pp, strlen(pp));
10164 retval = 0; // Okay
10165 move_string(tgt, tgt_offset, tgt_length, pp);
10166 free(pp);
10167 }
10168 free(env);
10169 }
10170
10171 if( retval == 1 )
10172 {
10173 // Could't find it
10174 exception_raise(ec_argument_imp_environment_e);
10175 }
10176
10177 return retval;
10178 }
10179
10180 extern "C"
10181 int
10182 __gg__accept_envar( cblc_field_t *tgt,
10183 size_t tgt_offset,
10184 size_t tgt_length,
10185 const cblc_field_t *name,
10186 size_t name_offset,
10187 size_t name_length)
10188 {
10189 // We need the name to be nul-terminated:
10190 char *p = static_cast<char *>(malloc(name_length + 1));
10191 massert(p);
10192 memcpy(p, name->data+name_offset, name_length);
10193 p[name_length] = '\0';
10194 int retval = accept_envar(tgt,
10195 tgt_offset,
10196 tgt_length,
10197 p);
10198 free(p);
10199 return retval;
10200 }
10201
10202 extern "C"
10203 bool
10204 __gg__set_envar(cblc_field_t *name,
10205 size_t name_offset,
10206 size_t name_length,
10207 cblc_field_t *value,
10208 size_t value_offset,
10209 size_t value_length)
10210 {
10211 bool retval = false; // true means the variable existed:
10212
10213 name_length = name_length ? name_length : name->capacity;
10214 value_length = value_length ? value_length : value->capacity;
10215
10216 static char *env = NULL;
10217 static size_t env_length = 0;
10218 static char *val = NULL;
10219 static size_t val_length = 0;
10220 if( env_length < name_length+1 )
10221 {
10222 env_length = name_length+1;
10223 env = static_cast<char *>(realloc(env, env_length));
10224 }
10225 if( val_length < value_length+1 )
10226 {
10227 val_length = value_length+1;
10228 val = static_cast<char *>(realloc(val, val_length));
10229 }
10230
10231 massert(val);
10232 massert(env);
10233
10234 // The name and the value arrive in the internal codeset:
10235 memcpy(env, name->data+name_offset , name_length);
10236 env[name_length] = '\0';
10237 memcpy(val, value->data+value_offset, value_length);
10238 val[value_length] = '\0';
10239
10240 // Get rid of leading and trailing internal_space characters
10241 char *trimmed_env = brute_force_trim(env);
10242 char *trimmed_val = brute_force_trim(val);
10243
10244 // Conver them to the console codeset
10245 __gg__internal_to_console_in_place(trimmed_env, strlen(trimmed_env));
10246 __gg__internal_to_console_in_place(trimmed_val, strlen(trimmed_val));
10247
10248 if( getenv(trimmed_env) )
10249 {
10250 // It already existed:
10251 retval = true;
10252 }
10253
10254 // And now, anticlimactically, set the variable:
10255 setenv(trimmed_env, trimmed_val, 1);
10256
10257 return retval;
10258 }
10259
10260 static int stashed_argc = 0;
10261 static char **stashed_argv = NULL;
10262
10263 extern "C"
10264 void
10265 __gg__stash_argc_argv(int argc, char **argv)
10266 {
10267 stashed_argc = argc;
10268 stashed_argv = argv;
10269
10270 // This routine is called once by main(), so it is a convenient place to make
10271 // the stack much bigger, because when people create COBOL programs with
10272 // ridiculous numbers of variables, the stack gets ridiculously large.
10273
10274 struct rlimit stack_size = {33554432, 33554432};
10275 if( setrlimit(RLIMIT_STACK, &stack_size) )
10276 {
10277 fprintf(stderr, "warning: attempt to set stack size to 32M failed\n");
10278 }
10279 }
10280
10281 static void
10282 command_line_plan_b()
10283 {
10284 // It's vaguely possible that somebody can try to access these command-line
10285 // functions without a main() function having been invoked. This code, for
10286 // example, could have been created as a stand-alone .so, or it could be
10287 // from a COBOL .o that was linked to main() from another language. So, we
10288 // are going to believe that /proc/cmdline is available, and proceed from
10289 // there:
10290 if( !stashed_argc )
10291 {
10292 static char input[4096];
10293 sprintf(input, "/proc/%ld/cmdline", (long)getpid());
10294 FILE *f = fopen(input, "r");
10295 if( f )
10296 {
10297 size_t bytes_read = fread(input, 1, sizeof(input), f);
10298 fclose(f);
10299 if( bytes_read )
10300 {
10301 char *p = input;
10302 const char *p_end = p + bytes_read;
10303 char prior_char = '\0';
10304 while( p < p_end )
10305 {
10306 if( prior_char == '\0' )
10307 {
10308 stashed_argc += 1;
10309 stashed_argv = static_cast<char **>(realloc(stashed_argv,
10310 stashed_argc * sizeof(char *)));
10311 stashed_argv[stashed_argc-1] = p;
10312 }
10313 prior_char = *p++;
10314 }
10315 }
10316 }
10317 }
10318 }
10319
10320 extern "C"
10321 void
10322 __gg__get_argc(cblc_field_t *dest, size_t offset, size_t length)
10323 {
10324 command_line_plan_b();
10325 char ach[128];
10326 sprintf(ach, "%d", stashed_argc);
10327 ascii_to_internal_str(ach, strlen(ach));
10328 move_string(dest, offset, length, ach);
10329 }
10330
10331 extern "C"
10332 int
10333 __gg__get_argv( cblc_field_t *dest,
10334 size_t dest_offset,
10335 size_t dest_length,
10336 cblc_field_t *index,
10337 size_t index_offset,
10338 size_t index_size)
10339 {
10340 int retcode;
10341 command_line_plan_b();
10342 int rdigits;
10343 __int128 N = get_binary_value_local(&rdigits,
10344 index,
10345 index->data + index_offset,
10346 index_size);
10347
10348 // N is 1-based, per normal COBOL. We have to decrement it here:
10349 N -= 1;
10350
10351 dest_length = dest_length ? dest_length : dest->capacity;
10352
10353 // If he gives us fractional digits, just truncate
10354 N /= __gg__power_of_ten(rdigits);
10355
10356 if( N >= stashed_argc || N < 0 )
10357 {
10358 exception_raise(ec_argument_imp_command_e);
10359 retcode = 1; // Error
10360 }
10361 else
10362 {
10363 char *retval = strdup(stashed_argv[N]);
10364 console_to_internal(retval, strlen(retval));
10365 move_string(dest, dest_offset, dest_length, retval);
10366 free(retval);
10367 retcode = 0; // Okay
10368 }
10369 return retcode;
10370 }
10371
10372 extern "C"
10373 int
10374 __gg__get_command_line( cblc_field_t *field,
10375 size_t offset,
10376 size_t flength)
10377 {
10378 int retcode;
10379 command_line_plan_b();
10380 size_t length = 1;
10381 char *retval = static_cast<char *>(malloc(length));
10382 massert(retval);
10383 *retval = NULLCH;
10384
10385 for( int i=1; i<stashed_argc; i++ )
10386 {
10387 while( strlen(retval) + strlen(stashed_argv[i]) + 2 > length )
10388 {
10389 length *= 2;
10390 retval = static_cast<char *>(realloc(retval, length));
10391 massert(retval);
10392 }
10393 if( *retval )
10394 {
10395 strcat(retval, " ");
10396 }
10397 strcat(retval, stashed_argv[i]);
10398 }
10399
10400 if( *retval )
10401 {
10402 flength = flength ? flength : field->capacity;
10403 console_to_internal(retval, strlen(retval));
10404 move_string(field, offset, flength, retval);
10405 retcode = 0; // Okay
10406 }
10407 else
10408 {
10409 exception_raise(ec_argument_imp_command_e);
10410 retcode = 1;// Error
10411 }
10412
10413 free(retval);
10414 return retcode;
10415 }
10416
10417 extern "C"
10418 void
10419 __gg__set_pointer(cblc_field_t *target,
10420 size_t target_o,
10421 int target_flags,
10422 const cblc_field_t *source,
10423 size_t source_o,
10424 int source_flags)
10425 {
10426 void *source_address;
10427 if( source_flags & REFER_T_ADDRESS_OF )
10428 {
10429 // This is SET <something> TO ADDRESS OF SOURCE
10430 source_address = source->data + source_o;
10431 }
10432 else
10433 {
10434 // This is SET <something> TO POINTER
10435 if( source )
10436 {
10437 source_address = *reinterpret_cast<void **>(source->data + source_o);
10438 }
10439 else
10440 {
10441 // This is SET xxx TO NULL
10442 source_address = NULL;
10443 }
10444 }
10445
10446 if( target_flags & REFER_T_ADDRESS_OF )
10447 {
10448 // This is SET ADDRESS OF target TO ....
10449 // We know it has to be an unqualified LINKAGE level 01 or level 77
10450 target->data = reinterpret_cast<unsigned char *>(source_address);
10451 // The caller will propogate data + offset to their children.
10452 }
10453 else
10454 {
10455 // This is SET <pointer> TO ....
10456 if( source->type == FldLiteralN )
10457 {
10458 // This is [almost certainly] INITIALIZE <pointer> when -fdefaultbyte
10459 // was specified.
10460 memset( target->data+target_o,
10461 *reinterpret_cast<unsigned char *>(source_address),
10462 target->capacity);
10463 }
10464 else
10465 {
10466 *reinterpret_cast<void **>(target->data+target_o) = source_address;
10467 }
10468 }
10469 }
10470
10471 extern "C"
10472 void
10473 __gg__alphabet_use( cbl_encoding_t encoding,
10474 size_t alphabet_index)
10475 {
10476 // We simply replace the values in the current program_state. If the
10477 // state needs to be saved -- for example, if we are doing a SORT with an
10478 // ALPHABET override -- that's up to the caller
10479
10480 // When there is no DATA DIVISION, program_states can be empty when
10481 // we arrive here.
10482 if( program_states.empty() )
10483 {
10484 initialize_program_state();
10485 }
10486
10487 switch( encoding )
10488 {
10489 case ASCII_e:
10490 case iso646_e:
10491 __gg__low_value_character = DEGENERATE_LOW_VALUE;
10492 __gg__high_value_character = DEGENERATE_HIGH_VALUE;
10493
10494 program_states.back().rt_low_value_character = DEGENERATE_LOW_VALUE;
10495 program_states.back().rt_high_value_character = DEGENERATE_HIGH_VALUE;
10496
10497 if( !internal_is_ebcdic )
10498 {
10499 program_states.back().rt_collation = __gg__one_to_one_values;
10500 }
10501 else
10502 {
10503 program_states.back().rt_collation = __gg__ebcdic_to_cp1252_collation;
10504 }
10505
10506 break;
10507
10508 case EBCDIC_e:
10509 __gg__low_value_character = DEGENERATE_LOW_VALUE;
10510 __gg__high_value_character = DEGENERATE_HIGH_VALUE;
10511
10512 program_states.back().rt_low_value_character = DEGENERATE_LOW_VALUE;
10513 program_states.back().rt_high_value_character = DEGENERATE_HIGH_VALUE;
10514 if( internal_is_ebcdic )
10515 {
10516 program_states.back().rt_collation = __gg__one_to_one_values;
10517 }
10518 else
10519 {
10520 program_states.back().rt_collation = __gg__cp1252_to_ebcdic_collation;
10521 }
10522 break;
10523
10524 case custom_encoding_e:
10525 {
10526 std::unordered_map<size_t, alphabet_state>::const_iterator it =
10527 __gg__alphabet_states.find(alphabet_index);
10528
10529 if( it == __gg__alphabet_states.end() )
10530 {
10531 __gg__abort("__gg__alphabet_use() fell off the end of __gg__alphabet_states");
10532 }
10533 __gg__low_value_character = it->second.low_char;
10534 __gg__high_value_character = it->second.high_char;
10535 program_states.back().rt_low_value_character = it->second.low_char;
10536 program_states.back().rt_high_value_character = it->second.high_char;
10537
10538 program_states.back().rt_collation = it->second.collation;
10539 break;
10540 }
10541 }
10542 return;
10543 }
10544
10545 extern "C"
10546 void
10547 __gg__ascii_to_internal_field(cblc_field_t *var)
10548 {
10549 ascii_to_internal_str(reinterpret_cast<char *>(var->data), var->capacity);
10550 }
10551
10552 extern "C"
10553 void
10554 __gg__ascii_to_internal(char *location, size_t length)
10555 {
10556 ascii_to_internal_str(location, length);
10557 }
10558
10559 extern "C"
10560 void
10561 __gg__console_to_internal(char *location, size_t length)
10562 {
10563 console_to_internal(location, length);
10564 }
10565
10566 extern "C"
10567 void
10568 __gg__parser_set_conditional(cblc_field_t *var, int figconst_)
10569 {
10570 cbl_figconst_t figconst = (cbl_figconst_t)figconst_;
10571
10572 unsigned char special = internal_space;
10573 switch(figconst)
10574 {
10575 case space_value_e:
10576 special = *__gg__data_space;
10577 break;
10578 case low_value_e:
10579 special = *__gg__data_low_values;
10580 break;
10581 case high_value_e:
10582 special = *__gg__data_high_values;
10583 break;
10584 case zero_value_e:
10585 special = *__gg__data_zeros;
10586 break;
10587 case quote_value_e:
10588 special = *__gg__data_quotes;
10589 break;
10590 default:
10591 break;
10592 }
10593 memset( var->data, special, var->capacity);
10594 }
10595
10596 extern "C"
10597 void
10598 __gg__internal_to_console_in_place(char *loc, size_t length)
10599 {
10600 static size_t dest_size = MINIMUM_ALLOCATION_SIZE;
10601 static char *dest = static_cast<char *>(malloc(dest_size));
10602
10603 internal_to_console(&dest, &dest_size, loc, length);
10604 memcpy(loc, dest, length);
10605 }
10606
10607 extern "C"
10608 int
10609 __gg__routine_to_call(const char *name,
10610 int program_id)
10611 {
10612 // The list of names is sorted, so at the very least this should be replaced
10613 // with a binary search:
10614
10615 std::unordered_map<int, char***>::const_iterator it =
10616 accessible_programs.find(program_id);
10617
10618 if(it == accessible_programs.end())
10619 {
10620 __gg__abort("__gg__routine_to_call() couldn't find program_id");
10621 }
10622
10623 char **names = *(it->second);
10624
10625 int retval = -1;
10626
10627 if( names )
10628 {
10629 int i=0;
10630 while(*names)
10631 {
10632 if( strstr(*names, name) )
10633 {
10634 // The first part of the names match
10635 if( (*names)[strlen(name)] == '.' )
10636 {
10637 // And the first character after the match is a '.'
10638 retval = i;
10639 break;
10640 }
10641 }
10642 i += 1;
10643 names += 1;
10644 }
10645 }
10646 return retval;
10647 }
10648
10649 extern "C"
10650 __int128
10651 __gg__fetch_call_by_value_value(const cblc_field_t *field,
10652 size_t field_o,
10653 size_t field_s)
10654
10655 {
10656 int rdigits;
10657 unsigned char *data = field->data + field_o;
10658 const size_t length = field_s;
10659
10660 __int128 retval = 0;
10661 switch(field->type)
10662 {
10663 case FldGroup:
10664 case FldAlphanumeric:
10665 case FldAlphaEdited:
10666 case FldLiteralA:
10667 retval = *reinterpret_cast<char *>(data);
10668 break;
10669
10670 case FldFloat:
10671 {
10672 switch(length)
10673 {
10674 case 4:
10675 *PTRCAST(float, &retval) = *PTRCAST(float, data);
10676 break;
10677
10678 case 8:
10679 *PTRCAST(double, &retval) = *PTRCAST(double, data);
10680 break;
10681
10682 case 16:
10683 // *(_Float128 *)(&retval) = double(*(_Float128 *)data);
10684 GCOB_FP128 t;
10685 memcpy(&t, data, 16);
10686 memcpy(&retval, &t, 16);
10687 break;
10688 }
10689 break;
10690 }
10691
10692 case FldNumericBinary:
10693 case FldPacked:
10694 case FldNumericBin5:
10695 case FldNumericDisplay:
10696 case FldNumericEdited:
10697 case FldLiteralN:
10698 case FldIndex:
10699 case FldPointer:
10700 retval = __gg__binary_value_from_qualified_field( &rdigits,
10701 field,
10702 field_o,
10703 field_s);
10704 if( rdigits )
10705 {
10706 retval /= __gg__power_of_ten(rdigits);
10707 }
10708 default:
10709 break;
10710 }
10711 return retval;
10712 }
10713
10714 extern "C"
10715 void
10716 __gg__assign_value_from_stack(cblc_field_t *dest, __int128 parameter)
10717 {
10718 switch(dest->type)
10719 {
10720 case FldGroup:
10721 case FldAlphanumeric:
10722 case FldAlphaEdited:
10723 case FldNumericEdited:
10724 if( dest->capacity >= 1)
10725 {
10726 warnx("%s is not valid for BY VALUE", dest->name);
10727 abort();
10728 }
10729 break;
10730
10731 case FldFloat:
10732 {
10733 switch(dest->capacity)
10734 {
10735 case 4:
10736 *PTRCAST(float, dest->data) = *PTRCAST(float, (&parameter));
10737 break;
10738
10739 case 8:
10740 *PTRCAST(double, dest->data) = *PTRCAST(double, (&parameter));
10741 break;
10742
10743 case 16:
10744 // *(_Float128 *)(dest->data) = *(_Float128 *)&parameter;
10745 GCOB_FP128 t;
10746 memcpy(&t, &parameter, 16);
10747 memcpy(dest->data, &t, 16);
10748 break;
10749 }
10750 break;
10751 }
10752
10753 case FldNumericBinary:
10754 case FldPacked:
10755 case FldNumericBin5:
10756 case FldNumericDisplay:
10757 case FldLiteralN:
10758 case FldIndex:
10759 case FldPointer:
10760 __gg__int128_to_field(dest,
10761 parameter,
10762 0,
10763 truncation_e,
10764 NULL);
10765 break;
10766
10767 default:
10768 break;
10769 }
10770 }
10771
10772 extern "C"
10773 int
10774 __gg__literaln_alpha_compare(const char *left_side,
10775 const cblc_field_t *right,
10776 size_t offset,
10777 size_t length,
10778 int flags)
10779 {
10780 int retval;
10781 if( length == 0 )
10782 {
10783 length = right->capacity;
10784 }
10785 retval = compare_strings( left_side,
10786 strlen(left_side),
10787 false,
10788 reinterpret_cast<char *>((right->data + offset)),
10789 length,
10790 !!(flags & REFER_T_MOVE_ALL) );
10791 return retval;
10792 }
10793
10794 static char *
10795 string_in( char *str,
10796 const char *str_e,
10797 const char *frag,
10798 const char *frag_e)
10799 {
10800 // This simple routine could be improved. Instead of using memcmp, we could
10801 // use established, albeit complex, techniques of string searching:
10802
10803 // Looking for "abcde" in "abcdabcde", for example. One could notice that
10804 // starting at the first 'a' results in a mismatch at the second 'a'. There
10805 // is thus no need to start the second search at the first 'b' in the searched
10806 // string; one could jump ahead to the second 'a' and continue from there.
10807
10808 // Feel free. It won't matter in the real world; a program whose innermost
10809 // loop is an UNSTRING is difficult to imagine. But feel free.
10810
10811 char *retval = NULL;
10812 size_t nchars = frag_e - frag;
10813 char *p = str;
10814 while( p + nchars <= str_e )
10815 {
10816 if( memcmp(p, frag, nchars) == 0 )
10817 {
10818 retval = p;
10819 break;
10820 }
10821 p += 1;
10822 }
10823 return retval;
10824 }
10825
10826 extern "C"
10827 int
10828 __gg__unstring( const cblc_field_t *id1, // The string being unstring
10829 size_t id1_o,
10830 size_t id1_s,
10831 size_t ndelimiteds, // The number of DELIMITED entries
10832 const char *all_flags, // The number of ALL flags, one per ndelimiteds
10833 size_t nreceivers, // The number of DELIMITER receivers
10834 cblc_field_t *id7, // The index of characters, both for starting updated at end
10835 size_t id7_o,
10836 size_t id7_s,
10837 cblc_field_t *id8, // Count of the number of times identifier-4 was updated
10838 size_t id8_o,
10839 size_t id8_s)
10840 {
10841 // The names of the parameters are based on the ISO 1989:2014 specification.
10842
10843 // There are complexities because of figurative constants, including the
10844 // LOW-VALUE figurative constant, which precludes the use of string
10845 // operations that would be confused by embedded NUL characters. Dammit.
10846
10847 // For each delimiter, there is an identifier-4 receiver that must be
10848 // resolved. Each might have an identifier-5 delimiter, and each might have
10849 // an identifier-6 count.
10850
10851 // The delimiting strings; one per ndelimiteds
10852 cblc_field_t **id2 = __gg__treeplet_1f;
10853 const size_t *id2_o = __gg__treeplet_1o;
10854 const size_t *id2_s = __gg__treeplet_1s;
10855 // The delimited string; one per nreceiver
10856 cblc_field_t **id4 = __gg__treeplet_2f;
10857 const size_t *id4_o = __gg__treeplet_2o;
10858 const size_t *id4_s = __gg__treeplet_2s;
10859 // The delimiting string; one per receiver
10860 cblc_field_t **id5 = __gg__treeplet_3f;
10861 const size_t *id5_o = __gg__treeplet_3o;
10862 const size_t *id5_s = __gg__treeplet_3s;
10863 // The count of characters examined; one per receiver
10864 cblc_field_t **id6 = __gg__treeplet_4f;
10865 const size_t *id6_o = __gg__treeplet_4o;
10866 const size_t *id6_s = __gg__treeplet_4s;
10867
10868 // Initialize the state variables
10869 int overflow = 0;
10870 int tally = 0;
10871 int pointer = 1;
10872 size_t nreceiver;
10873 char *left = NULL;
10874 char *right = NULL;
10875 int previous_delimiter;
10876
10877 if( id8 )
10878 {
10879 int rdigits;
10880 tally = (int)__gg__binary_value_from_qualified_field(&rdigits,
10881 id8,
10882 id8_o,
10883 id8_s);
10884 }
10885
10886 if( id7 )
10887 {
10888 int rdigits;
10889 pointer = (int)__gg__binary_value_from_qualified_field(&rdigits,
10890 id7,
10891 id7_o,
10892 id7_s);
10893 }
10894
10895 // As per the spec, if the string is zero-length; we are done.
10896 if( id1_s == 0 )
10897 {
10898 goto done;
10899 }
10900
10901 // As per the spec, we have an overflow condition if pointer is out of
10902 // range:
10903 if( pointer < 1 || pointer > (int)id1_s )
10904 {
10905 overflow = 1;
10906 goto done;
10907 }
10908
10909 left = reinterpret_cast<char *>(id1->data+id1_o) + pointer-1;
10910 right = reinterpret_cast<char *>(id1->data+id1_o) + id1_s;
10911
10912 if( ndelimiteds == 0 )
10913 {
10914 // There are no DELIMITED BY identifier-2 values, so we just peel off
10915 // characters from identifier-1 and put them into each identifier-4:
10916 for( size_t i=0; i<nreceivers; i++ )
10917 {
10918 if( left >= right )
10919 {
10920 break;
10921 }
10922 size_t id_4_size = id4_s[i];
10923 if( id4[i]->attr & separate_e )
10924 {
10925 // The receiver is NumericDisplay with a separate signe
10926 id_4_size = id4_s[i] - 1;
10927 }
10928
10929 // Make sure id_4_size doesn't move past the end of the universe
10930 if( left + id_4_size > right )
10931 {
10932 id_4_size = right - left;
10933 }
10934
10935 // Move the data into place:
10936 move_string(id4[i], id4_o[i], id4_s[i], left, id_4_size);
10937
10938 // Update the state variables:
10939 left += id_4_size;
10940 pointer += id_4_size;
10941 tally += 1;
10942 }
10943 goto done;
10944 }
10945
10946 // Arriving here means there is some number of ndelimiteds
10947
10948 nreceiver = 0;
10949 previous_delimiter = -1;
10950 while( left < right )
10951 {
10952 // Starting at 'left', see if we can find any of the delimiters
10953 char *leftmost_delimiter = NULL;
10954 int ifound = -1;
10955 cbl_figconst_t figconst;
10956 char achfigconst[1];
10957 for( size_t i=0; i<ndelimiteds; i++ )
10958 {
10959 char *pfound;
10960 figconst = (cbl_figconst_t)(id2[i]->attr & FIGCONST_MASK);
10961
10962 switch(figconst)
10963 {
10964 case low_value_e :
10965 achfigconst[0] = ascii_to_internal(__gg__low_value_character);
10966 pfound = string_in( left,
10967 right,
10968 achfigconst,
10969 achfigconst+1);
10970 break;
10971
10972 case zero_value_e :
10973 achfigconst[0] = internal_zero;
10974 pfound = string_in( left,
10975 right,
10976 achfigconst,
10977 achfigconst+1);
10978 break;
10979
10980 case space_value_e :
10981 achfigconst[0] = internal_space;
10982 pfound = string_in( left,
10983 right,
10984 achfigconst,
10985 achfigconst+1);
10986 break;
10987
10988 case quote_value_e :
10989 achfigconst[0] = ascii_to_internal(__gg__quote_character);
10990 pfound = string_in( left,
10991 right,
10992 achfigconst,
10993 achfigconst+1);
10994 break;
10995
10996 case high_value_e :
10997 achfigconst[0] = ascii_to_internal(__gg__high_value_character);
10998 pfound = string_in( left,
10999 right,
11000 achfigconst,
11001 achfigconst+1);
11002 break;
11003
11004 case normal_value_e :
11005 default:
11006 pfound = string_in( left,
11007 right,
11008 reinterpret_cast<char *>(id2[i]->data+id2_o[i]),
11009 reinterpret_cast<char *>((id2[i]->data+id2_o[i])
11010 + id2_s[i]));
11011 break;
11012 }
11013
11014 if( pfound )
11015 {
11016 // We found a delimiter
11017 if( !leftmost_delimiter || pfound < leftmost_delimiter )
11018 {
11019 ifound = i;
11020 leftmost_delimiter = pfound;
11021 }
11022 }
11023 }
11024
11025 if( ifound >= 0
11026 && leftmost_delimiter == left
11027 && ifound == previous_delimiter )
11028 {
11029 // We found another instance of an ALL delimiter.
11030 // So, we just skip it.
11031 left += id2_s[previous_delimiter];
11032 pointer += id2_s[previous_delimiter];
11033 continue;
11034 }
11035
11036 // We did not re-find an ALL DELIMITER
11037 previous_delimiter = -1;
11038
11039 // If we've used up all receivers, we bail at this point
11040 if( nreceiver >= nreceivers )
11041 {
11042 break;
11043 }
11044
11045 if( ifound >= 0 && all_flags[ifound] == ascii_1 )
11046 {
11047 // Arriving here means we found a new delimiter.
11048 // If the ALL flag was on, set up to notice repeats
11049 previous_delimiter = ifound;
11050 }
11051
11052 if( !leftmost_delimiter )
11053 {
11054 // We were unable to find a delimiter, so we eat up the remainder
11055 // of the sender:
11056 leftmost_delimiter = right;
11057 }
11058
11059 // Apply what we have learned to the next receiver:
11060
11061 size_t examined = leftmost_delimiter - left;
11062
11063 // Move the data into place:
11064 move_string(id4[nreceiver], id4_o[nreceiver], id4_s[nreceiver], left, examined);
11065
11066 // Update the left pointer
11067 left = leftmost_delimiter;
11068 if( ifound >= 0 )
11069 {
11070 // And skip over the delimiter
11071 left += id2_s[ifound];
11072 }
11073
11074 if( id5[nreceiver] )
11075 {
11076 if( ifound >= 0 )
11077 {
11078 if( figconst )
11079 {
11080 move_string(id5[nreceiver], id5_o[nreceiver], id5_s[nreceiver],
11081 achfigconst,
11082 1);
11083 }
11084 else
11085 {
11086 move_string(id5[nreceiver], id5_o[nreceiver], id5_s[nreceiver],
11087 reinterpret_cast<char *>(id2[ifound]->data+id2_o[ifound]),
11088 id2_s[ifound]);
11089 }
11090 }
11091 else
11092 {
11093 move_string(id5[nreceiver], id5_o[nreceiver], id5_s[nreceiver], "");
11094 }
11095 }
11096
11097 if( id6[nreceiver] )
11098 {
11099 __gg__int128_to_qualified_field(id6[nreceiver],
11100 id6_o[nreceiver],
11101 id6_s[nreceiver],
11102 (__int128)examined,
11103 0,
11104 truncation_e,
11105 NULL );
11106 }
11107
11108 // Update the state variables:
11109 pointer += examined + id2_s[ifound];
11110 tally += 1;
11111 nreceiver += 1;
11112 }
11113
11114 done:
11115
11116 if( id8 )
11117 {
11118 __gg__int128_to_qualified_field(id8,
11119 id8_o,
11120 id8_s,
11121 (__int128)tally,
11122 0,
11123 truncation_e,
11124 NULL );
11125 }
11126
11127 if( id7 )
11128 {
11129 __gg__int128_to_qualified_field(id7,
11130 id7_o,
11131 id7_s,
11132 (__int128)pointer,
11133 0,
11134 truncation_e,
11135 NULL );
11136 }
11137
11138 if( left < right )
11139 {
11140 overflow = 1;
11141 }
11142
11143 return overflow;
11144 }
11145
11146 static std::set<size_t> to_be_canceled;
11147
11148 extern "C"
11149 void __gg__to_be_canceled(size_t function_pointer)
11150 {
11151 if( function_pointer )
11152 {
11153 to_be_canceled.insert(function_pointer);
11154 }
11155 }
11156
11157 extern "C"
11158 int __gg__is_canceled(size_t function_pointer)
11159 {
11160 int retval = 0;
11161 std::set<size_t>::iterator it = to_be_canceled.find(function_pointer);
11162 if( it == to_be_canceled.end() )
11163 {
11164 retval = 0;
11165 }
11166 else
11167 {
11168 retval = 1;
11169 to_be_canceled.erase(it);
11170 }
11171 return retval;
11172 }
11173
11174 // Tue Feb 28 10:10:16 2023
11175 // Associate specific I/O status an with exception condition.
11176 // Cf. ISO Table 14 — Exception-names and exception conditions
11177
11178 static inline ec_type_t
11179 local_ec_type_of( file_status_t status )
11180 {
11181 int status10 = (int)status / 10;
11182 assert( 0 <= status10 ); // was enum, can't be negative.
11183 if( 10 < status10 )
11184 {
11185 __gg__abort("local_ec_type_of(): status10 out of range");
11186 }
11187
11188 static const std::vector<ec_type_t> ec_by_status {
11189 /* 0 */ ec_none_e, // ec_io_warning_e if low byte is nonzero
11190 /* 1 */ ec_io_at_end_e,
11191 /* 2 */ ec_io_invalid_key_e,
11192 /* 3 */ ec_io_permanent_error_e,
11193 /* 4 */ ec_io_logic_error_e,
11194 /* 5 */ ec_io_record_operation_e,
11195 /* 6 */ ec_io_file_sharing_e,
11196 /* 7 */ ec_io_record_content_e,
11197 /* 8 */ ec_none_e, // unused, not defined by ISO
11198 /* 9 */ ec_io_imp_e,
11199 };
11200 assert(ec_by_status.size() == 10);
11201
11202 return ec_by_status[status10];
11203 }
11204
11205 /*
11206 * Store and report the enabled exceptions.
11207 * 7.3.20.3 General rules:
11208 * 1) The default TURN directive is '>>TURN EC-ALL CHECKING OFF'.
11209 */
11210 struct exception_descr_t {
11211 bool location;
11212 //std::set<size_t> files;
11213 };
11214
11215 struct cbl_exception_t {
11216 // size_t program,
11217 size_t file;
11218 ec_type_t type;
11219 cbl_file_mode_t mode;
11220 };
11221
11222 /*
11223 * Compare the raised exception, cbl_exception_t, to the USE critera
11224 * of a declarative, cbl_declarative_t.
11225 */
11226 static bool
11227 match_declarative( bool enabled,
11228 const cbl_exception_t& raised,
11229 const cbl_declarative_t& dcl )
11230 {
11231 if( MATCH_DECLARATIVE && raised.type) {
11232 warnx("match_declarative: checking: ec %s vs. dcl %s (%s enabled and %s format_1)",
11233 local_ec_type_str(raised.type),
11234 local_ec_type_str(dcl.type),
11235 enabled? "is" : "not",
11236 dcl.is_format_1()? "is" : "not");
11237 }
11238 if( ! (enabled || dcl.is_format_1()) ) return false;
11239
11240 bool matches = ec_cmp(raised.type, (dcl.type));
11241
11242 if( matches && dcl.nfile > 0 ) {
11243 matches = dcl.match_file(raised.file);
11244 }
11245
11246 // Having matched, the EC must either be enabled, or
11247 // the Declarative must be USE Format 1.
11248 if( matches ) {
11249 // I/O declaratives match by file or mode, not EC.
11250 if( dcl.is_format_1() ) { // declarative is for particular files or mode
11251 if( dcl.nfile == 0 ) {
11252 matches = raised.mode == dcl.mode;
11253 }
11254 } else {
11255 matches = enabled;
11256 }
11257
11258 if( matches && MATCH_DECLARATIVE ) {
11259 warnx(" matches exception %s (file %u mode %s)",
11260 local_ec_type_str(raised.type),
11261 static_cast<unsigned int>(raised.file),
11262 cbl_file_mode_str(raised.mode));
11263 }
11264 }
11265 return matches;
11266 }
11267
11268 static
11269 void open_syslog(int option, int facility)
11270 {
11271 static bool first_time = true;
11272 if( first_time ) {
11273 #if HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME
11274 /* Declared in errno.h, when available. */
11275 static const char * const ident = program_invocation_short_name;
11276 #elif defined (HAVE_GETPROGNAME)
11277 /* Declared in stdlib.h. */
11278 static const char * const ident = getprogname();
11279 #else
11280 /* Avoid a NULL entry. */
11281 static const char * const ident = "unnamed_COBOL_program";
11282 #endif
11283 // TODO: Program to set option in library via command-line and/or environment.
11284 // Library listens to program, not to the environment.
11285 openlog(ident, option, facility);
11286 first_time = false;
11287 }
11288 }
11289
11290 /*
11291 * The default exception handler is called if:
11292 * 1. The EC is enabled and was not handled by a Declarative, or
11293 * 2. The EC is EC-I-O and was not handled by a Format-1 Declarative, or
11294 * 3. The EC is EC-I-O, associated with a file, and is not OPEN or CLOSE.
11295 */
11296 static void
11297 default_exception_handler( ec_type_t ec )
11298 {
11299 static const int priority = LOG_INFO, option = LOG_PERROR, facility = LOG_USER;
11300 open_syslog(option, facility);
11301
11302 ec_disposition_t disposition = ec_category_fatal_e;
11303
11304
11305 if( ec != ec_none_e ) {
11306 auto pec = std::find_if( __gg__exception_table, __gg__exception_table_end,
11307 [ec](const ec_descr_t& descr) {
11308 return descr.type == ec;
11309 } );
11310 if( pec != __gg__exception_table_end ) {
11311 disposition = pec->disposition;
11312 } else {
11313 warnx("logic error: unknown exception %x", ec );
11314 }
11315 /*
11316 * An enabled, unhandled fatal EC normally results in termination. But
11317 * EC-I-O is a special case:
11318 * OPEN and CLOSE never result in termination.
11319 * A SELECT statement with FILE STATUS indicates the user will handle the error.
11320 * Only I/O statements are considered.
11321 * Declaratives are handled first. We are in the default handler here,
11322 * which is reached only if no Declarative was matched.
11323 */
11324 auto file = ec_status.file_status();
11325 const char *filename = nullptr;
11326
11327 if( file.ifile ) {
11328 filename = file.filename;
11329 switch( last_exception_file_operation ) {
11330 case file_op_none: // not an I/O statement
11331 assert(false);
11332 abort();
11333 case file_op_open:
11334 case file_op_close: // No OPEN/CLOSE results in a fatal error.
11335 disposition = ec_category_none_e;
11336 break;
11337 default:
11338 if( file.user_status ) {
11339 // Not fatal if FILE STATUS is part of the file's SELECT statement.
11340 disposition = ec_category_none_e;
11341 }
11342 break;
11343 }
11344 } else {
11345 assert( ec_status.is_enabled() );
11346 assert( ec_status.is_enabled(ec) );
11347 }
11348
11349 switch( disposition ) {
11350 case ec_category_none_e:
11351 case uc_category_none_e:
11352 break;
11353 case ec_category_fatal_e:
11354 case uc_category_fatal_e:
11355 if( filename ) {
11356 syslog(priority, "fatal exception: %s:%d: %s %s: %s (%s)",
11357 program_name,
11358 ec_status.lineno,
11359 ec_status.statement,
11360 filename, // show affected file before EC name
11361 pec->name,
11362 pec->description);
11363 } else {
11364 syslog(priority, "fatal exception: %s:%d: %s: %s (%s)",
11365 program_name,
11366 ec_status.lineno,
11367 ec_status.statement,
11368 pec->name,
11369 pec->description);
11370 }
11371 abort();
11372 break;
11373 case ec_category_nonfatal_e:
11374 case uc_category_nonfatal_e:
11375 syslog(priority, "%s:%d: %s: %s (%s)",
11376 program_name,
11377 ec_status.lineno,
11378 ec_status.statement,
11379 pec->name,
11380 pec->description);
11381 break;
11382 case ec_category_implementor_e:
11383 case uc_category_implementor_e:
11384 break;
11385 }
11386
11387 ec_status.clear();
11388 }
11389 }
11390
11391 /*
11392 * To reach the default handler, an EC must have effect and not have been
11393 * handled by program logic. To have effect, it must have been enabled
11394 * explictly, or be of type EC-I-O. An EC may be handled by the statement or
11395 * by a Declarative.
11396 *
11397 * Any EC handled by statement's conditional clause (e.g. ON SIZE ERROR)
11398 * prevents an EC from being raised. Because it is not raised, it is handled
11399 * neither by a Declarative, nor by the the default handler.
11400 *
11401 * A nonfatal EC matched to a Declarative is considered handled. A fatal EC is
11402 * considered handled if the Declarative uses RESUME. For any EC that is
11403 * handled (with RESUME for fatal), program control passes to the next
11404 * statement. Else control passes here first.
11405 *
11406 * Any EC explicitly enabled (with >>TURN) must be explicitly handled. Only
11407 * explicitly enabled ECs appear in enabled_ECs. when EC-I-O is raised as a
11408 * byproduct of error status on a file operation, we say it is "implicitly
11409 * enabled". It need not be explicitly handled.
11410 *
11411 * Implicit EC-I-O not handled by the statement or a Declarative is considered
11412 * handled if the statement includes the FILE STATUS phrase. OPEN and CLOSE
11413 * never cause program termination with EC-I-O; for those two statements the
11414 * fatal status is ignored. These conditions are screened out by
11415 * __gg__check_fatal_exception(), so that the default handler is not called.
11416 *
11417 * An unhandled EC reaches the default handler for any of 3 reasons:
11418 * 1. It is EC-I-O (enabled does not matter).
11419 * 2. It is enabled.
11420 * 3. It is fatal and was matched to a Declarative that did not use RESUME.
11421 * The default handler, default_exception_handler(), logs the EC. For a fatal
11422 * EC, the process terminated with abort(3).
11423 *
11424 * Except for OPEN and CLOSE, I/O statements that raise an unhandled fatal EC
11425 * cause program termination, consistent with IBM documentation. See
11426 * Enterprise COBOL for z/OS: Enterprise COBOL for z/OS 6.4 Programming Guide,
11427 * page 244, "Handling errors in input and output operations".
11428 */
11429 extern "C"
11430 void
11431 __gg__check_fatal_exception()
11432 {
11433 if( MATCH_DECLARATIVE )
11434 warnx("%s: ec_status is %s", __func__, ec_status.unset()? "unset" : "set");
11435
11436 if( ec_status.copy_environment().unset() )
11437 {
11438 ec_status.update(); // __gg__match_exception was not called first
11439 // This is a good time to set the exception code back to zero
11440 __gg__exception_code = 0;
11441 }
11442
11443 if( ec_status.done() ) { // false for part-handled fatal
11444 if( MATCH_DECLARATIVE )
11445 warnx("%s: clearing ec_status", __func__);
11446 ec_status.clear();
11447 return; // already handled
11448 }
11449
11450 auto ec = ec_status.unhandled();
11451
11452 if( MATCH_DECLARATIVE )
11453 warnx("%s: %s was not handled %s enabled", __func__,
11454 local_ec_type_str(ec), ec_status.is_enabled(ec)? "is" : "is not");
11455
11456 // Look for ways I/O statement might have dealt with EC.
11457 auto file = ec_status.file_status();
11458 if( file.ifile && ec_cmp(ec, ec_io_e) ) {
11459 if( MATCH_DECLARATIVE )
11460 warnx("%s: %s with %sFILE STATUS", __func__,
11461 file.op_str(), file.user_status? "" : "no ");
11462 if( file.user_status ) {
11463 ec_status.clear();
11464 return; // has FILE STATUS, ok
11465 }
11466 switch( file.operation ) {
11467 case file_op_none:
11468 assert(false);
11469 abort();
11470 case file_op_open: // implicit, no Declarative, no FILE STATUS, but ok
11471 case file_op_close:
11472 ec_status.clear();
11473 return;
11474 case file_op_start:
11475 case file_op_read:
11476 case file_op_write:
11477 case file_op_rewrite:
11478 case file_op_delete:
11479 break;
11480 }
11481 } else {
11482 if( ! ec_status.is_enabled() ) {
11483 if( MATCH_DECLARATIVE )
11484 warnx("%s: %s is not enabled", __func__, local_ec_type_str(ec));
11485 ec_status.clear();
11486 return;
11487 }
11488 if( MATCH_DECLARATIVE )
11489 warnx("%s: %s is enabled", __func__, local_ec_type_str(ec));
11490 }
11491
11492 if( MATCH_DECLARATIVE )
11493 warnx("%s: calling default_exception_handler(%s)", __func__,
11494 local_ec_type_str(ec));
11495
11496 default_exception_handler(ec);
11497 }
11498
11499 /*
11500 * Preserve the state of the raised EC during Declarative execution.
11501 */
11502 extern "C"
11503 void
11504 __gg__exception_push()
11505 {
11506 ec_stack.push(ec_status);
11507 if( MATCH_DECLARATIVE )
11508 warnx("%s: %s: %u ECs, %u declaratives", __func__,
11509 __gg__exception_statement,
11510 static_cast<unsigned int>(enabled_ECs.size()),
11511 static_cast<unsigned int>(declaratives.size()));
11512 }
11513
11514 /*
11515 * Restore the state of the raised EC after Declarative execution.
11516 */
11517 extern "C"
11518 void
11519 __gg__exception_pop()
11520 {
11521 ec_status = ec_stack.top();
11522 ec_stack.pop();
11523 ec_status.reset_environment();
11524 if( MATCH_DECLARATIVE )
11525 warnx("%s: %s: %u ECs, %u declaratives", __func__,
11526 __gg__exception_statement,
11527 static_cast<unsigned int>(enabled_ECs.size()),
11528 static_cast<unsigned int>(declaratives.size()));
11529 __gg__check_fatal_exception();
11530 }
11531
11532 // Called for RESUME in a Declarative to indicate a fatal EC was handled.
11533 extern "C"
11534 void
11535 __gg__clear_exception()
11536 {
11537 ec_stack.top().clear();
11538 }
11539
11540 void
11541 cbl_enabled_exception_t::dump( int i ) const {
11542 warnx("cbl_enabled_exception_t: %2d {%s, %s, %u}",
11543 i,
11544 location? "location" : " none",
11545 local_ec_type_str(ec),
11546 static_cast<unsigned int>(file) );
11547 }
11548
11549 /*
11550 * Match the raised exception against a Declarative.
11551 *
11552 * A Declarative that handles I/O errors with USE Format 1 doesn't name a
11553 * specific EC. It's matched based on the file's status, irrespective of
11554 * whether or not EC-I-O is enabled. USE Format 1 Declaratives are honored
11555 * regardless of any >>TURN directive.
11556 *
11557 * An EC is enabled by the >>TURN directive. The only ECs that can be disabled
11558 * are those that were explicitly enabled. If EC-I-O is enabled, and mentioned
11559 * in a Declarative with USE Format 3, then it is matched just like any other.
11560 */
11561 extern "C"
11562 void
11563 __gg__match_exception( cblc_field_t *index )
11564 {
11565 size_t isection = 0;
11566
11567 if( MATCH_DECLARATIVE ) enabled_ECs.dump("match_exception begin");
11568
11569 auto ec = ec_status.update().unhandled();
11570
11571 if( ec != ec_none_e ) {
11572 /*
11573 * An EC was raised and was not handled by the statement.
11574 * We know the EC and, for I/O, the current file and its mode.
11575 * Scan declaratives for a match:
11576 * - EC is enabled or program has a Format 1 Declarative
11577 * - EC matches the Declarative's USE statement
11578 * Format 1 declaratives apply only to EC-I-O, whether or not enabled.
11579 * Format 1 may be restricted to a particular mode (for all files).
11580 * Format 1 and 3 may be restricted to a set of files.
11581 */
11582
11583 // This is a good time to set the actual exception code back to zero.
11584 __gg__exception_code = 0;
11585
11586 auto f = ec_status.file_status();
11587 cbl_exception_t raised = { /*0,*/ f.ifile, ec, f.mode };
11588 bool enabled = enabled_ECs.match(ec);
11589
11590 if( MATCH_DECLARATIVE ) enabled_ECs.dump("match_exception enabled");
11591
11592 auto p = std::find_if( declaratives.begin(), declaratives.end(),
11593 [enabled, raised]( const cbl_declarative_t& dcl ) {
11594 return match_declarative(enabled, raised, dcl);
11595 } );
11596
11597 if( p == declaratives.end() ) {
11598 if( MATCH_DECLARATIVE ) {
11599 warnx("__gg__match_exception:%d: raised exception "
11600 "%s not matched (%u enabled)", __LINE__,
11601 local_ec_type_str(ec),
11602 static_cast<unsigned int>(enabled_ECs.size()));
11603 }
11604 } else {
11605 isection = p->section;
11606 ec_status.handled_by(isection);
11607
11608 if( MATCH_DECLARATIVE ) {
11609 warnx("__gg__match_exception:%d: matched "
11610 "%s against mask %s for section #%u",
11611 __LINE__,
11612 local_ec_type_str(ec),
11613 local_ec_type_str(p->type),
11614 static_cast<unsigned int>(p->section));
11615 }
11616 }
11617 assert(ec != ec_none_e);
11618 } // end EC match logic
11619
11620 // If a declarative matches the raised exception, return its
11621 // symbol_table index.
11622 __gg__int128_to_field(index,
11623 (__int128)isection,
11624 0,
11625 truncation_e,
11626 NULL);
11627 }
11628
11629 static std::vector<void *>proc_signatures;
11630 static std::vector<void *>return_addresses;
11631 static std::vector<size_t>bookmarks;
11632
11633 extern "C"
11634 void
11635 __gg__pseudo_return_push( void *proc_signature,
11636 void *return_address)
11637 {
11638 proc_signatures.push_back(proc_signature);
11639 return_addresses.push_back(return_address);
11640 __gg__exit_address = proc_signature;
11641 }
11642
11643 extern "C"
11644 void *
11645 __gg__pseudo_return_pop()
11646 {
11647 void *retval = return_addresses.back();
11648
11649 return_addresses.pop_back();
11650 proc_signatures.pop_back();
11651
11652 if( proc_signatures.size() > bookmarks.back() )
11653 {
11654 __gg__exit_address = proc_signatures.back();
11655 }
11656 else
11657 {
11658 // We can't go below the floor established by the bookmark.
11659 __gg__exit_address = NULL;
11660 }
11661
11662 return retval;
11663 }
11664
11665 extern "C"
11666 void
11667 __gg__pseudo_return_bookmark()
11668 {
11669 bookmarks.push_back(proc_signatures.size());
11670 }
11671
11672 extern "C"
11673 void
11674 __gg__pseudo_return_flush()
11675 {
11676 if( bookmarks.size() == 0 )
11677 {
11678 __gg__abort("__gg__pseudo_return_flush(): bookmarks.size() is zero");
11679 }
11680 proc_signatures.resize(bookmarks.back());
11681 return_addresses.resize(bookmarks.back());
11682 bookmarks.pop_back();
11683
11684 if( proc_signatures.size() )
11685 {
11686 __gg__exit_address = proc_signatures.back();
11687 }
11688 }
11689
11690 extern "C"
11691 GCOB_FP128
11692 __gg__float128_from_location( const cblc_field_t *var,
11693 const unsigned char *location)
11694 {
11695 GCOB_FP128 retval = 0;
11696 switch( var->capacity )
11697 {
11698 case 4:
11699 {
11700 retval = *reinterpret_cast<_Float32 *>(
11701 const_cast<unsigned char *>(location));
11702 break;
11703 }
11704
11705 case 8:
11706 {
11707 retval = *reinterpret_cast<_Float64 *>(
11708 const_cast<unsigned char *>(location));
11709 break;
11710 }
11711
11712 case 16:
11713 {
11714 //retval = *(_Float128 *)location;
11715 memcpy(&retval, location, 16);
11716 break;
11717 }
11718 }
11719 return retval;
11720 }
11721
11722 extern "C"
11723 __int128
11724 __gg__integer_from_float128(const cblc_field_t *field)
11725 {
11726 GCOB_FP128 fvalue = __gg__float128_from_location(field, field->data);
11727 // we round() to take care of the possible 2.99999999999... problem.
11728 fvalue = FP128_FUNC(round)(fvalue);
11729 return (__int128)fvalue;
11730 }
11731
11732
11733 extern "C"
11734 void
11735 __gg__adjust_dest_size(cblc_field_t *dest, size_t ncount)
11736 {
11737 if( dest->attr & (intermediate_e) )
11738 {
11739 if( dest->allocated < ncount )
11740 {
11741 fprintf(stderr, "libgcobol.cc:__gg__adjust_dest_size(): Adjusting size upward is not possible.\n");
11742 abort();
11743 // dest->allocated = ncount;
11744 // dest->data = (unsigned char *)realloc(dest->data, ncount);
11745 }
11746 dest->capacity = ncount;
11747 }
11748 }
11749
11750 extern "C"
11751 void
11752 __gg__func_exception_location(cblc_field_t *dest)
11753 {
11754 char ach[512] = " ";
11755 if( last_exception_code )
11756 {
11757 ach[0] = '\0';
11758 if( last_exception_program_id )
11759 {
11760 strcat(ach, last_exception_program_id);
11761 strcat(ach, "; ");
11762 }
11763
11764 if( last_exception_paragraph )
11765 {
11766 strcat(ach, last_exception_paragraph );
11767 if( last_exception_section )
11768 {
11769 strcat(ach, " OF ");
11770 strcat(ach, last_exception_section);
11771 }
11772 }
11773 else
11774 {
11775 if( last_exception_section )
11776 {
11777 strcat(ach, last_exception_section);
11778 }
11779 }
11780 strcat(ach, "; ");
11781
11782 if( last_exception_source_file )
11783 {
11784 char achSource[128] = "";
11785 snprintf( achSource,
11786 sizeof(achSource),
11787 "%s:%d ",
11788 last_exception_source_file,
11789 last_exception_line_number);
11790 strcat(ach, achSource);
11791 }
11792 else
11793 {
11794 strcpy(ach, " ");
11795 }
11796 }
11797 __gg__adjust_dest_size(dest, strlen(ach));
11798 memcpy(dest->data, ach, strlen(ach));
11799 }
11800
11801 extern "C"
11802 void
11803 __gg__func_exception_statement(cblc_field_t *dest)
11804 {
11805 char ach[128] = " ";
11806 if(last_exception_statement)
11807 {
11808 snprintf(ach, sizeof(ach), "%s", last_exception_statement);
11809 ach[sizeof(ach)-1] = '\0';
11810 }
11811 __gg__adjust_dest_size(dest, strlen(ach));
11812 memcpy(dest->data, ach, strlen(ach));
11813 }
11814
11815 extern "C"
11816 void
11817 __gg__func_exception_status(cblc_field_t *dest)
11818 {
11819 char ach[128] = "<not in table?>";
11820 if(last_exception_code)
11821 {
11822 ec_descr_t *p = __gg__exception_table;
11823 while(p < __gg__exception_table_end )
11824 {
11825 if( p->type == (ec_type_t)last_exception_code )
11826 {
11827 snprintf(ach, sizeof(ach), "%s", p->name);
11828 break;
11829 }
11830 p += 1;
11831 }
11832 }
11833 else
11834 {
11835 strcpy(ach, " ");
11836 }
11837 __gg__adjust_dest_size(dest, strlen(ach));
11838 memcpy(dest->data, ach, strlen(ach));
11839 }
11840
11841 extern "C"
11842 void
11843 __gg__set_exception_file(const cblc_file_t *file)
11844 {
11845 ec_type_t ec = local_ec_type_of( file->io_status );
11846 if( ec )
11847 {
11848 // During SORT operations, which routinely read files until they end, we
11849 // need to suppress them.
11850 if( ec != ec_io_at_end_e || !sv_suppress_eof_ec )
11851 {
11852 last_exception_file_operation = file->prior_op;
11853 last_exception_file_status = file->io_status;
11854 last_exception_file_name = file->name;
11855 exception_raise(ec);
11856 }
11857 }
11858 }
11859
11860 extern "C"
11861 void
11862 __gg__func_exception_file(cblc_field_t *dest,
11863 const cblc_file_t *file)
11864 {
11865 char ach[128];
11866 if( !file )
11867 {
11868 // This is where we process FUNCTION EXCEPTION-FILE <no parameter>
11869 if( !(last_exception_code & ec_io_e) )
11870 {
11871 // There is no EC-I-O exception code, so we return two alphanumeric zeros.
11872 strcpy(ach, "00");
11873 }
11874 else
11875 {
11876 // The last exception code is an EC-I-O
11877 if( sv_from_raise_statement )
11878 {
11879 strcpy(ach, " ");
11880 }
11881 else
11882 {
11883 snprintf( ach,
11884 sizeof(ach), "%2.2d%s",
11885 last_exception_file_status,
11886 last_exception_file_name);
11887 }
11888 }
11889 }
11890 else
11891 {
11892 // This is where we process FUNCTION EXCEPTION-FILE file->name
11893 if( file->prior_op == file_op_none )
11894 {
11895 // this file hasn't been accessed
11896 strcpy(ach, " ");
11897 }
11898 else
11899 {
11900 snprintf(ach, sizeof(ach), "%2.2d%s", file->io_status, file->name);
11901 }
11902 }
11903
11904 __gg__adjust_dest_size(dest, strlen(ach));
11905 memcpy(dest->data, ach, strlen(ach));
11906 }
11907
11908 extern "C"
11909 void
11910 __gg__set_exception_code(ec_type_t ec, int from_raise_statement)
11911 {
11912 if( MATCH_DECLARATIVE )
11913 {
11914 warnx("%s: %s:%u: %s: %s",
11915 __func__,
11916 __gg__exception_source_file,
11917 __gg__exception_line_number,
11918 __gg__exception_statement,
11919 local_ec_type_str(ec));
11920 }
11921 sv_from_raise_statement = from_raise_statement;
11922
11923 __gg__exception_code = ec;
11924 if( ec == ec_none_e)
11925 {
11926 last_exception_code = 0 ;
11927 last_exception_program_id = NULL ;
11928 last_exception_section = NULL ;
11929 last_exception_paragraph = NULL ;
11930 last_exception_source_file = NULL ;
11931 last_exception_line_number = 0 ;
11932 last_exception_statement = NULL ;
11933 last_exception_file_operation = file_op_none ;
11934 last_exception_file_status = FsSuccess ;
11935 last_exception_file_name = NULL ;
11936 }
11937 else
11938 {
11939 last_exception_code = __gg__exception_code ;
11940 last_exception_program_id = __gg__exception_program_id ;
11941 last_exception_section = __gg__exception_section ;
11942 last_exception_paragraph = __gg__exception_paragraph ;
11943 last_exception_source_file = __gg__exception_source_file ;
11944 last_exception_line_number = __gg__exception_line_number ;
11945 last_exception_statement = __gg__exception_statement ;
11946
11947 // These are set in __gg__set_exception_file just before this routine is
11948 // called. In cases where the ec is not a file-i-o operation, we clear
11949 // them here:
11950 if( !(ec & ec_io_e) )
11951 {
11952 last_exception_file_operation = file_op_none ;
11953 last_exception_file_status = FsSuccess ;
11954 last_exception_file_name = NULL ;
11955 }
11956 }
11957 }
11958
11959 extern "C"
11960 void
11961 __gg__float32_from_int128(cblc_field_t *destination,
11962 size_t destination_offset,
11963 cblc_field_t *source,
11964 size_t source_offset,
11965 cbl_round_t rounded,
11966 int *size_error)
11967 {
11968 int rdigits;
11969 GCOB_FP128 value = get_binary_value_local( &rdigits,
11970 source,
11971 source->data + source_offset,
11972 source->capacity);
11973 value /= __gg__power_of_ten(rdigits);
11974
11975 if( FP128_FUNC(fabs)(value) > GCOB_FP128_LITERAL (3.4028235E38) )
11976 {
11977 if(size_error)
11978 {
11979 *size_error = 1;
11980 }
11981 }
11982 else
11983 {
11984 if(size_error)
11985 {
11986 *size_error = 0;
11987 }
11988 __gg__float128_to_qualified_field(destination,
11989 destination_offset,
11990 value,
11991 rounded,
11992 NULL);
11993 }
11994 }
11995
11996 extern "C"
11997 void
11998 __gg__float64_from_int128(cblc_field_t *destination,
11999 size_t destination_offset,
12000 cblc_field_t *source,
12001 size_t source_offset,
12002 cbl_round_t rounded,
12003 int *size_error)
12004 {
12005 if(size_error)
12006 {
12007 *size_error = 0;
12008 }
12009 int rdigits;
12010 GCOB_FP128 value = get_binary_value_local( &rdigits,
12011 source,
12012 source->data + source_offset,
12013 source->capacity);
12014 value /= __gg__power_of_ten(rdigits);
12015 __gg__float128_to_qualified_field(destination,
12016 destination_offset,
12017 value,
12018 rounded,
12019 NULL);
12020 }
12021
12022 extern "C"
12023 void
12024 __gg__float128_from_int128(cblc_field_t *destination,
12025 size_t destination_offset,
12026 cblc_field_t *source,
12027 size_t source_offset,
12028 cbl_round_t rounded,
12029 int *size_error)
12030 {
12031 if(size_error) *size_error = 0;
12032 int rdigits;
12033 GCOB_FP128 value = get_binary_value_local( &rdigits,
12034 source,
12035 source->data + source_offset,
12036 source->capacity);
12037 value /= __gg__power_of_ten(rdigits);
12038 __gg__float128_to_qualified_field(destination,
12039 destination_offset,
12040 value,
12041 rounded,
12042 NULL);
12043 }
12044
12045 extern "C"
12046 int
12047 __gg__is_float_infinite(const cblc_field_t *source, size_t offset)
12048 {
12049 int retval = 0;
12050 switch(source->capacity)
12051 {
12052 case 4:
12053 retval = fpclassify( *reinterpret_cast<_Float32*>(source->data+offset)) == FP_INFINITE;
12054 break;
12055 case 8:
12056 retval = fpclassify( *reinterpret_cast<_Float64*>(source->data+offset)) == FP_INFINITE;
12057 break;
12058 case 16:
12059 // retval = *(_Float128*)(source->data+offset) == INFINITY;
12060 GCOB_FP128 t;
12061 memcpy(&t, source->data+offset, 16);
12062 retval = t == INFINITY;
12063 break;
12064 }
12065 return retval;
12066 }
12067
12068 extern "C"
12069 int
12070 __gg__float32_from_128( const cblc_field_t *dest,
12071 size_t dest_offset,
12072 const cblc_field_t *source,
12073 size_t source_offset)
12074 {
12075 int retval = 0;
12076 //_Float128 value = *(_Float128*)(source->data+source_offset);
12077 GCOB_FP128 value;
12078 memcpy(&value, source->data+source_offset, 16);
12079 if( FP128_FUNC(fabs)(value) > GCOB_FP128_LITERAL (3.4028235E38) )
12080 {
12081 retval = 1;
12082 }
12083 else
12084 {
12085 *reinterpret_cast<_Float32 *>(dest->data+dest_offset) = (_Float32)value;
12086 }
12087 return retval;
12088 }
12089
12090 extern "C"
12091 int
12092 __gg__float32_from_64( const cblc_field_t *dest,
12093 size_t dest_offset,
12094 const cblc_field_t *source,
12095 size_t source_offset)
12096 {
12097 int retval = 0;
12098 _Float64 value = *reinterpret_cast<_Float64*>(source->data+source_offset);
12099 if( FP128_FUNC(fabs)(value) > GCOB_FP128_LITERAL (3.4028235E38) )
12100 {
12101 retval = 1;
12102 }
12103 else
12104 {
12105 *reinterpret_cast<_Float32 *>(dest->data+dest_offset) = (_Float32)value;
12106 }
12107 return retval;
12108 }
12109
12110 extern "C"
12111 int
12112 __gg__float64_from_128( const cblc_field_t *dest,
12113 size_t dest_offset,
12114 const cblc_field_t *source,
12115 size_t source_offset)
12116 {
12117 int retval = 0;
12118 // _Float128 value = *(_Float128*)(source->data+source_offset);
12119 GCOB_FP128 value;
12120 memcpy(&value, source->data+source_offset, 16);
12121 if( FP128_FUNC(fabs)(value) > GCOB_FP128_LITERAL(1.7976931348623157E308) )
12122 {
12123 retval = 1;
12124 }
12125 else
12126 {
12127 *reinterpret_cast<_Float64 *>(dest->data+dest_offset) = (_Float64)value;
12128 }
12129 return retval;
12130 }
12131
12132 extern "C"
12133 char *
12134 __gg__display_int128(__int128 value)
12135 {
12136 static char ach[64];
12137
12138 if( value == 0 )
12139 {
12140 strcpy(ach, "0");
12141 return ach;
12142 }
12143
12144 bool is_negative = false;
12145 if( value < 0 )
12146 {
12147 is_negative = true;
12148 value = -value;
12149 }
12150 char *p = ach+64;
12151 *--p = '\0';
12152
12153 while(value)
12154 {
12155 *--p = value%10 + '0';
12156 value /= 10;
12157 }
12158 if( is_negative )
12159 {
12160 *--p = '-';
12161 }
12162 return p;
12163 }
12164
12165 typedef struct LV_DATA
12166 {
12167 size_t unique_id;
12168 cblc_field_t *field;
12169 unsigned char *data;
12170 }LV_DATA;
12171
12172 static std::vector<LV_DATA> lv_variables;
12173
12174 extern "C"
12175 void
12176 __gg__push_local_variable(cblc_field_t *field)
12177 {
12178 LV_DATA lv_data;
12179 lv_data.unique_id = __gg__unique_prog_id;
12180 lv_data.field = field;
12181 lv_data.data = field->data;
12182 lv_variables.push_back(lv_data);
12183 }
12184
12185 extern "C"
12186 void
12187 __gg__pop_local_variables()
12188 {
12189 while( lv_variables.size()
12190 && lv_variables.back().unique_id == __gg__unique_prog_id)
12191 {
12192 lv_variables.back().field->data = lv_variables.back().data;
12193 lv_variables.pop_back();
12194 }
12195 }
12196
12197 extern "C"
12198 void
12199 __gg__copy_as_big_endian( unsigned char *dest,
12200 const unsigned char *source)
12201 {
12202 // copy eight bytes of source to dest, flipping the endianness
12203 for(size_t i=0; i<8; i++)
12204 {
12205 dest[i] = source[7-i];
12206 }
12207 }
12208
12209 extern "C"
12210 void
12211 __gg__codeset_figurative_constants()
12212 {
12213 // This routine gets called after the codeset has been changed
12214 *__gg__data_space = internal_space;
12215 *__gg__data_low_values = ascii_to_internal(__gg__low_value_character);
12216 *__gg__data_zeros = internal_0;
12217 *__gg__data_high_values = ascii_to_internal(__gg__high_value_character);
12218 *__gg__data_quotes = ascii_to_internal(__gg__quote_character);;
12219 }
12220
12221 extern "C"
12222 unsigned char *
12223 __gg__get_figconst_data(const cblc_field_t *field)
12224 {
12225 unsigned char *retval = NULL;
12226 cbl_figconst_t figconst = (cbl_figconst_t)(size_t)(field->initial);
12227 switch(figconst)
12228 {
12229 case low_value_e :
12230 retval = __gg__data_low_values;
12231 break;
12232 case zero_value_e :
12233 retval = __gg__data_zeros;
12234 break;
12235 case space_value_e :
12236 retval = __gg__data_space;
12237 break;
12238 case quote_value_e :
12239 retval = __gg__data_quotes;
12240 break;
12241 case high_value_e :
12242 retval = __gg__data_high_values;
12243 break;
12244 case normal_value_e :
12245 fprintf(stderr, "__gg__get_figconst_data(): Weird figconst\n");
12246 abort();
12247 break;
12248 case null_value_e:
12249 break;
12250 }
12251 return retval;
12252 }
12253
12254 extern "C"
12255 void
12256 __gg__set_program_list( int program_id,
12257 char ***prog_list,
12258 PFUNC **prog_pointers)
12259 {
12260 accessible_programs[program_id] = prog_list;
12261 accessible_pointers[program_id] = prog_pointers;
12262 }
12263
12264 static std::unordered_map<std::string, void *> already_found;
12265
12266 static
12267 void *
12268 find_in_dirs(const char *dirs, char *unmangled_name, char *mangled_name)
12269 {
12270
12271 std::unordered_map<std::string, void *>::const_iterator it =
12272 already_found.find(unmangled_name);
12273
12274 if( it != already_found.end() )
12275 {
12276 return it->second;
12277 }
12278 it = already_found.find(mangled_name);
12279 if( it != already_found.end() )
12280 {
12281 return it->second;
12282 }
12283
12284 void *retval = NULL;
12285 if( dirs )
12286 {
12287 char directory[1024];
12288 char file[1024];
12289 const char *p = dirs;
12290 while( !retval && *p )
12291 {
12292 size_t index = 0;
12293 while( index < sizeof(directory)-1 && *p && *p != ':' )
12294 {
12295 directory[index++] = *p++;
12296 }
12297 directory[index++] = '\0';
12298 if( *p == ':' )
12299 {
12300 p += 1;
12301 }
12302 // directory is the next one for us to check:
12303 DIR *dir = opendir(directory);
12304 if( dir )
12305 {
12306 while( !retval )
12307 {
12308 const dirent *entry = readdir(dir);
12309 if( !entry )
12310 {
12311 break;
12312 }
12313 size_t len = strlen(entry->d_name);
12314 if( len > 3
12315 && entry->d_name[len-3] == '.'
12316 && entry->d_name[len-2] == 's'
12317 && entry->d_name[len-1] == 'o'
12318 )
12319 {
12320 strcpy(file, directory);
12321 strcat(file, "/");
12322 strcat(file, entry->d_name);
12323 void *handle = dlopen(file, RTLD_LAZY|RTLD_NODELETE );
12324 if( handle )
12325 {
12326 retval = dlsym(handle, unmangled_name);
12327 if( retval )
12328 {
12329 already_found[unmangled_name] = retval;
12330 break;
12331 }
12332 retval = dlsym(handle, mangled_name);
12333 if( retval )
12334 {
12335 already_found[mangled_name] = retval;
12336 break;
12337 }
12338 dlclose(handle);
12339 }
12340 }
12341 }
12342 closedir(dir);
12343 }
12344 }
12345 }
12346 return retval;
12347 }
12348
12349 extern "C"
12350 void *
12351 __gg__function_handle_from_cobpath( char *unmangled_name, char *mangled_name)
12352 {
12353 void *retval = NULL;
12354
12355 // We search for a function. We check first for the unmangled name, and then
12356 // the mangled name. We do this first for the executable, then for .so
12357 // files in COBPATH, and then for files in LD_LIBRARY_PATH
12358
12359 static void *handle_executable = NULL;
12360 if( !handle_executable )
12361 {
12362 handle_executable = dlopen(NULL, RTLD_LAZY);
12363 }
12364 //if( !retval )
12365 {
12366 retval = dlsym(handle_executable, unmangled_name);
12367 }
12368 if( !retval )
12369 {
12370 retval = dlsym(handle_executable, mangled_name);
12371 }
12372 if( !retval )
12373 {
12374 const char *COBPATH = getenv("GCOBOL_LIBRARY_PATH");
12375 retval = find_in_dirs(COBPATH, unmangled_name, mangled_name);
12376 }
12377 if( !retval )
12378 {
12379 const char *LD_LIBRARY_PATH = getenv("LD_LIBRARY_PATH");
12380 retval = find_in_dirs(LD_LIBRARY_PATH, unmangled_name, mangled_name);
12381 }
12382
12383 return retval;
12384 }
12385
12386 extern "C"
12387 void
12388 __gg__just_mangle_name( const cblc_field_t *field,
12389 char **mangled_name
12390 )
12391 {
12392 static char ach_name[1024];
12393 static char ach_unmangled[1024];
12394 static char ach_mangled[1024];
12395
12396 assert(field);
12397 assert(field->data);
12398
12399 size_t length;
12400 length = field->capacity;
12401 memcpy(ach_name, field->data, length);
12402 ach_name[length] = '\0';
12403
12404 if( internal_is_ebcdic)
12405 {
12406 // The name is in EBCDIC
12407 __gg__ebcdic_to_ascii(ach_name, length);
12408 }
12409
12410 bool is_pointer = false;
12411
12412 if( field->type == FldPointer )
12413 {
12414 is_pointer = true;
12415 }
12416
12417 if( is_pointer )
12418 {
12419 strcpy(ach_name, "<pointer>");
12420 }
12421
12422 // At this point we have a null-terminated ascii function name.
12423
12424 // Convert it to both unmangled and mangled forms:
12425 strcpy(ach_unmangled, not_mangled_core(ach_name, ach_name+length));
12426 strcpy(ach_mangled, mangler_core( ach_name, ach_name+length));
12427
12428 if( mangled_name )
12429 {
12430 *mangled_name = ach_mangled;
12431 }
12432 }
12433
12434 extern "C"
12435 void *
12436 __gg__function_handle_from_literal(int program_id,
12437 const char *literal)
12438 {
12439 void *retval = NULL;
12440 static char ach_unmangled[1024];
12441 static char ach_mangled[1024];
12442
12443 size_t length;
12444
12445 length = strlen(literal);
12446
12447 // At this point we have a null-terminated ascii function name.
12448
12449 // Convert it to both unmangled and mangled forms:
12450 strcpy(ach_unmangled, not_mangled_core(literal, literal+length));
12451 strcpy(ach_mangled, mangler_core( literal, literal+length));
12452
12453 int function_index = __gg__routine_to_call(ach_mangled, program_id);
12454 if( function_index > -1 )
12455 {
12456 std::unordered_map<int, PFUNC**>::const_iterator it =
12457 accessible_pointers.find(program_id);
12458 if( it == accessible_pointers.end() )
12459 {
12460 __gg__abort("__gg__function_handle_from_literal():"
12461 " fell off the end of accessible_pointers");
12462 }
12463 PFUNC **pointers_p = it->second;
12464 PFUNC *pointers = *pointers_p;
12465 retval = reinterpret_cast<void *>(pointers[function_index]);
12466 }
12467 else
12468 {
12469 retval = __gg__function_handle_from_cobpath(ach_unmangled, ach_mangled);
12470 }
12471
12472 return retval;
12473 }
12474
12475 extern "C"
12476 void *
12477 __gg__function_handle_from_name(int program_id,
12478 const cblc_field_t *field,
12479 size_t offset,
12480 size_t length )
12481 {
12482 void *retval = NULL;
12483 static char ach_name[1024];
12484 static char ach_unmangled[1024];
12485 static char ach_mangled[1024];
12486
12487 if( length == 0 )
12488 {
12489 length = field->capacity;
12490 }
12491
12492 memcpy(ach_name, field->data + offset, length);
12493
12494 if( internal_is_ebcdic)
12495 {
12496 // The name is in EBCDIC
12497 __gg__ebcdic_to_ascii(ach_name, length);
12498 }
12499
12500 // At this point we have a null-terminated ascii function name.
12501
12502 // Convert it to both unmangled and mangled forms:
12503 strcpy(ach_unmangled, not_mangled_core(ach_name, ach_name+length));
12504 strcpy(ach_mangled, mangler_core( ach_name, ach_name+length));
12505
12506 int function_index = __gg__routine_to_call(ach_mangled, program_id);
12507 if( function_index > -1 )
12508 {
12509 std::unordered_map<int, PFUNC**>::const_iterator it =
12510 accessible_pointers.find(program_id);
12511 if(it == accessible_pointers.end())
12512 {
12513 __gg__abort("__gg__function_handle_from_name():"
12514 " fell off the end of accessible_pointers");
12515 }
12516 PFUNC **pointers_p = it->second;
12517 PFUNC *pointers = *pointers_p;
12518 retval = reinterpret_cast<void *>(pointers[function_index]);
12519 }
12520 else
12521 {
12522 retval = __gg__function_handle_from_cobpath(ach_unmangled, ach_mangled);
12523 }
12524
12525 return retval;
12526 }
12527
12528 extern "C"
12529 void
12530 __gg__variables_to_init(cblc_field_t *array[], const char *clear)
12531 {
12532 int i=0;
12533 for(;;)
12534 {
12535 cblc_field_t *field = array[i++];
12536 if( !field )
12537 {
12538 break;
12539 }
12540 int flag_bits = 0;
12541 flag_bits |= clear
12542 ? DEFAULTBYTE_BIT + (*clear & DEFAULT_BYTE_MASK)
12543 : 0;
12544 __gg__initialize_variable_clean(field, flag_bits);
12545 }
12546 }
12547
12548 extern "C"
12549 void
12550 __gg__mirror_range( size_t nrows,
12551 cblc_field_t *src, // The row
12552 size_t src_o,
12553 size_t nspans, // The number of spans
12554 const size_t *spans,
12555 size_t table,
12556 size_t ntbl,
12557 const size_t *tbls)
12558 {
12559 static std::unordered_map<size_t, size_t> rows_in_table;
12560 static std::unordered_map<size_t, size_t> widths_of_table;
12561 static std::unordered_map<size_t, std::vector<size_t>> spans_in_table;
12562
12563 // Let's do the memorization bookkeeping for the target table
12564 // We have to do this every time, because if we have memory, everything gets
12565 // higgledepiggledy when INITIALZE ALL FILLER is followed by
12566 // INITIALIZE ALL VALUE
12567 std::vector<size_t> spans_this_time(2*nspans);
12568 for(size_t i=0; i<2*nspans; i++)
12569 {
12570 spans_this_time[i] = spans[i];
12571 }
12572 rows_in_table[table] = nrows;
12573 spans_in_table[table] = spans_this_time;
12574
12575 // We need to know the width of one row of this table, which is different
12576 // depending on type of src:
12577
12578 const cblc_field_t *parent = src;
12579 while( parent )
12580 {
12581 if( parent->occurs_upper )
12582 {
12583 break;
12584 }
12585 }
12586 if( parent == nullptr )
12587 {
12588 __gg__abort("__gg__mirror_range() parent is NULL");
12589 }
12590 size_t width;
12591 if( parent->type == FldGroup )
12592 {
12593 width = parent->capacity;
12594 }
12595 else
12596 {
12597 width = parent->capacity * parent->occurs_upper;
12598 }
12599 widths_of_table[table] = width;
12600
12601 if( nspans == 0 && ntbl == 0 )
12602 {
12603 // There are no FILLERS to be skipped, so we can just do our cute line
12604 // duplicating trick. We understand that there isn't actually much in the
12605 // the way of computational savings -- every byte has to be written, after
12606 // all -- but it is satisfying.
12607 size_t stride = src->capacity;
12608 unsigned char *source = src->data + src_o;
12609 unsigned char *dest = source + stride;
12610 nrows -= 1; // This reflects that row[0] equals row[0]
12611
12612 size_t nrows_this_time = 1;
12613 while(nrows)
12614 {
12615 memcpy(dest, source, nrows_this_time * stride);
12616 dest += nrows_this_time * stride;
12617 nrows -= nrows_this_time;
12618 nrows_this_time *= 2;
12619 nrows_this_time = std::min(nrows_this_time, nrows);
12620 }
12621 }
12622 else
12623 {
12624 size_t stride = src->capacity;
12625 unsigned char *source = src->data + src_o;
12626 unsigned char *dest = source;
12627
12628 while( nrows-- )
12629 {
12630 // These spans are for non-table elements
12631 if( nspans == 0 )
12632 {
12633 // Special case: We have no spans, but in the case of, for example,
12634 // 01 four-by-four2.
12635 // 05 label5 pic x(12) value "four-by-four".
12636 // 05 four-outer2 occurs 4 times.
12637 // 10 four-inner2 occurs 4 times.
12638 // 15 label15 pic x(12) value "four-inner".
12639 // 15 FNAME PIC X(7) VALUE "James".
12640 // 15 FILLER PIC X(7) VALUE "Keen ".
12641 // 15 LNAME PIC X(7) VALUE "Lowden".
12642 // 10 label10 pic x(12) value "four-outer".
12643 //
12644 // the label10 field *should* be a span. The parser doesn't do that,
12645 // though, so we have to:
12646 size_t left = 0;
12647 size_t right = stride;
12648 for(size_t subtable=0; subtable<ntbl; subtable++)
12649 {
12650 size_t subtable_offset = tbls[2*subtable ];
12651 size_t subtable_index = tbls[2*subtable+1];
12652
12653 if( widths_of_table.find(subtable_index) == widths_of_table.end() )
12654 {
12655 __gg__abort("__gg__mirror_range() fell off widths_of_table");
12656 }
12657 size_t subtable_width = widths_of_table[subtable_index];
12658 size_t subtable_rows = rows_in_table [subtable_index];
12659
12660 right = subtable_offset;
12661
12662 memcpy(dest + left,
12663 source + left ,
12664 right - left);
12665 left = right + subtable_rows * subtable_width;
12666 // Set right to stride, in case this is the final 'subtable' iteration
12667 right = stride;
12668 }
12669
12670 if( left < right )
12671 {
12672 memcpy(dest + left,
12673 source + left ,
12674 right - left);
12675 }
12676 }
12677 for(size_t span=0; span<nspans; span++)
12678 {
12679 size_t offset = spans[2*span];
12680 size_t length = spans[2*span + 1] - offset;
12681 memcpy( dest+offset, source+offset, length);
12682 }
12683
12684 // Our table's row might have sub-tables:
12685 for(size_t subtable=0; subtable<ntbl; subtable++)
12686 {
12687 size_t subtable_offset = tbls[2*subtable ];
12688 size_t subtable_index = tbls[2*subtable+1];
12689
12690 if( widths_of_table.find(subtable_index) == widths_of_table.end() )
12691 {
12692 __gg__abort("__gg__mirror_range(): fell off widths of table");
12693 }
12694
12695 size_t subtable_stride = widths_of_table[subtable_index];
12696 size_t subtable_rows = rows_in_table [subtable_index];
12697 std::vector<size_t> subtable_spans
12698 = spans_in_table [subtable_index];
12699
12700 const unsigned char *subtable_source = source + subtable_offset;
12701
12702 if( subtable_spans.size() == 0 )
12703 {
12704 unsigned char *subtable_dest = dest + subtable_offset;
12705 size_t span_start = 0;
12706 size_t span_end = subtable_stride;
12707 size_t subtable_row = subtable_rows;
12708 while( subtable_row-- )
12709 {
12710 memcpy(subtable_dest + span_start,
12711 subtable_source + span_start,
12712 span_end - span_start);
12713 subtable_dest += subtable_stride;
12714 }
12715 }
12716
12717 for(size_t span=0; span<subtable_spans.size(); span += 2 )
12718 {
12719 unsigned char *subtable_dest = dest + subtable_offset;
12720 size_t span_start = subtable_spans[span ];
12721 size_t span_end = subtable_spans[span+1];
12722 size_t subtable_row = subtable_rows;
12723 while( subtable_row-- )
12724 {
12725 memcpy(subtable_dest + span_start,
12726 subtable_source + span_start,
12727 span_end - span_start);
12728 subtable_dest += subtable_stride;
12729 }
12730 }
12731 }
12732 dest += stride;
12733 }
12734 }
12735 }
12736
12737 extern "C"
12738 void
12739 __gg__sleep(cblc_field_t *field, size_t offset, size_t size)
12740 {
12741 int rdigits;
12742 __int128 value = get_binary_value_local( &rdigits,
12743 field,
12744 field->data + offset,
12745 size);
12746 double delay = (double)value / __gg__power_of_ten(rdigits);
12747 if( delay < 0 )
12748 {
12749 exception_raise(ec_continue_less_than_zero);
12750 delay = 0;
12751 }
12752
12753 // Convert the time to nanoseconds.
12754 delay = delay * 1000000000;
12755
12756 // Convert the result to seconds/nanoseconds for nanosleep()
12757 size_t tdelay = (size_t)delay;
12758 timespec duration;
12759
12760 duration.tv_sec = tdelay / 1000000000;
12761 duration.tv_nsec = tdelay % 1000000000;
12762
12763 nanosleep(&duration, NULL);
12764 }
12765
12766 extern "C"
12767 void
12768 __gg__deallocate( cblc_field_t *target,
12769 size_t offset,
12770 int addr_of)
12771 {
12772 if( addr_of || (target->attr & based_e))
12773 {
12774 // Free the target's data pointer
12775 if( target->data )
12776 {
12777 free(target->data);
12778 target->data = NULL;
12779 }
12780 }
12781 else if (target->type == FldPointer)
12782 {
12783 // Target is a pointer. Free the data location
12784 int rdigits;
12785 size_t addrv = get_binary_value_local(&rdigits,
12786 target,
12787 target->data + offset,
12788 sizeof(void *));
12789 void *ptr = reinterpret_cast<void *>(addrv);
12790 if( ptr )
12791 {
12792 free(ptr);
12793 // And set the data location to zero
12794 *static_cast<char **>(static_cast<void *>(target->data + offset))
12795 = NULL;
12796 }
12797 }
12798 }
12799
12800 static int
12801 get_the_byte(cblc_field_t *field)
12802 {
12803 int retval = -1;
12804 if( field )
12805 {
12806 cbl_figconst_t figconst = (cbl_figconst_t)(field->attr & FIGCONST_MASK);
12807 switch(figconst)
12808 {
12809 case null_value_e:
12810 retval = 0;
12811 break;
12812 case low_value_e:
12813 retval = ascii_to_internal(__gg__low_value_character);
12814 break;
12815 case zero_value_e:
12816 retval = internal_zero;
12817 break;
12818 case space_value_e:
12819 retval = internal_space;
12820 break;
12821 case quote_value_e:
12822 retval = ascii_to_internal(__gg__quote_character);
12823 break;
12824 case high_value_e:
12825 retval = ascii_to_internal(__gg__high_value_character) & 0xFF;
12826 break;
12827 case normal_value_e:
12828 retval = (int)__gg__get_integer_binary_value(field);
12829 break;
12830 }
12831 }
12832 return retval;
12833 }
12834
12835 extern "C"
12836 void
12837 __gg__allocate( cblc_field_t *first,
12838 size_t first_offset,
12839 int initialized,
12840 int default_byte,
12841 cblc_field_t *f_working_byte,
12842 cblc_field_t *f_local_byte,
12843 const cblc_field_t *returning,
12844 size_t returning_offset)
12845 {
12846 int working_byte = get_the_byte(f_working_byte);
12847 int local_byte = get_the_byte(f_local_byte);
12848 int fill_char;
12849
12850 unsigned char *retval = NULL;
12851 if( first->attr & based_e )
12852 {
12853 // first is the BASED variable we are allocating memory for
12854 if( first->capacity )
12855 {
12856 retval = static_cast<unsigned char *>(malloc(first->capacity));
12857
12858 fill_char = 0;
12859 if( initialized )
12860 {
12861 // This is ISO 2023 ALLOCATE rule 7 (ALL TO VALUE)
12862 if( default_byte >= 0 )
12863 {
12864 fill_char = default_byte;
12865 memset(retval, fill_char, first->capacity);
12866 }
12867 }
12868 else
12869 {
12870 // This is ISO 2023 ALLOCATE rule 9 (pointers NULL, otherwise OPT_INIT)
12871 if( default_byte >= 0 )
12872 {
12873 fill_char = default_byte;
12874 }
12875 if( first->attr & (linkage_e | local_e) )
12876 {
12877 if( local_byte >= 0 )
12878 {
12879 fill_char = local_byte;
12880 }
12881 }
12882 else
12883 {
12884 if( working_byte >= 0 )
12885 {
12886 fill_char = working_byte;
12887 }
12888 }
12889 memset(retval, fill_char, first->capacity);
12890 }
12891 }
12892 first->data = retval;
12893 }
12894 else
12895 {
12896 // This is an ALLOCATE CHARACTERS
12897 // first contains the number of bytes to allocate
12898 int rdigits;
12899 ssize_t tsize = (ssize_t)get_binary_value_local(&rdigits,
12900 first,
12901 first->data + first_offset,
12902 sizeof(void *));
12903 tsize = std::max(0L, tsize);
12904 size_t pof10 = __gg__power_of_ten(rdigits);
12905
12906 // If there are any non-zero digits to the right of the decimal point,
12907 // increment the units place:
12908 tsize += (pof10-1);
12909
12910 // Adjust the result to be an integer.
12911 tsize /= pof10;
12912 if( tsize )
12913 {
12914 retval = static_cast<unsigned char *>(malloc(tsize));
12915 if(!retval)
12916 {
12917 abort();
12918 }
12919
12920 fill_char = 0;
12921 if( initialized )
12922 {
12923 // This is ISO 2023 rule 6 (defaultbyte if specified, else zero)
12924 if( default_byte >= 0 )
12925 {
12926 fill_char = default_byte;
12927 }
12928 }
12929 else
12930 {
12931 // This is ISO 2023 rule 8 (OPT_INIT if specified, otherwise defaultbyte, otherwise zero)")
12932 if( default_byte >= 0 )
12933 {
12934 fill_char = default_byte;
12935 }
12936 if( first->attr & (linkage_e | local_e) )
12937 {
12938 if( local_byte >= 0 )
12939 {
12940 fill_char = local_byte;
12941 }
12942 }
12943 else
12944 {
12945 if( working_byte >= 0 )
12946 {
12947 fill_char = working_byte;
12948 }
12949 }
12950 }
12951
12952 memset(retval, fill_char, tsize);
12953 }
12954 }
12955
12956 if( returning )
12957 {
12958 // 'returning' has to be a FldPointer variable; assign the retval to it.
12959 *reinterpret_cast<unsigned char **>(returning->data + returning_offset) = retval;
12960 }
12961 }
12962
12963 static std::vector<std::string>module_name_stack;
12964
12965 extern "C"
12966 void
12967 __gg__module_name_push(const char *module_name)
12968 {
12969 module_name_stack.push_back(module_name);
12970 }
12971
12972 extern "C"
12973 void
12974 __gg__module_name_pop()
12975 {
12976 if( module_name_stack.size() == 0 )
12977 {
12978 __gg__abort("__gg__module_name_pop(): module_name_stack is empty");
12979 }
12980 module_name_stack.pop_back();
12981 }
12982
12983 extern "C"
12984 void
12985 __gg__module_name(cblc_field_t *dest, module_type_t type)
12986 {
12987 static size_t result_size = 64;
12988 static char *result = static_cast<char *>(malloc(result_size));
12989 massert(result);
12990
12991 strcpy(result, "");
12992
12993 size_t ssize = module_name_stack.size();
12994
12995 switch( type )
12996 {
12997 case module_activating_e:
12998 /* 5) If the ACTIVATING keyword is specified and the function is in a COBOL
12999 main program, then the returned value shall be a single space. The
13000 implementor shall document how a main program is identified. If the function
13001 is not specified in a main program, then the returned value is the name of
13002 the runtime element that activated the currently running runtime element.
13003 This may be by a CALL statement, an INVOKE statement, a function reference,
13004 or an inline invocation. */
13005
13006 /* 6) If the ACTIVATING keyword is specified and the activating statement
13007 is within a nested program, then it is implementor defined what value is
13008 returned. This may be the name of the nested program or the name of the
13009 outermost program containing the nested program. */
13010
13011 switch( module_name_stack.back()[0] )
13012 {
13013 case 'T':
13014 // We are in a top-level program, not nested:
13015 if( module_name_stack.size() == 1
13016 || (module_name_stack.size() == 2
13017 && module_name_stack.front()[0] == 'M' ) )
13018 {
13019 // This is a "main program", so we return a single space.
13020 strcpy(result, " ");
13021 }
13022 else
13023 {
13024 // This is a called program, so we return the name of the "runtime
13025 // element" that called us:
13026 strcpy(result, module_name_stack[ssize-2].substr(1).c_str());
13027 }
13028 break;
13029
13030 case 'N':
13031 // We are in a nested function.
13032 {
13033 // This is a called program, so we return the name of the program that
13034 // called us
13035 strcpy(result, module_name_stack[ssize-2].substr(1).c_str());
13036 }
13037 }
13038 break;
13039
13040 case module_current_e:
13041 // 7) If the CURRENT keyword is specified then the returned value is the
13042 // name of the runtime element of the outermost program of the compilation
13043 // unit’s code that is currently running.
13044
13045 // Look upward for our parent T.
13046 // Termination is weird because size_t is unsigned
13047 for(size_t i=ssize-1; i<ssize; i--)
13048 {
13049 if( module_name_stack[i][0] == 'T' )
13050 {
13051 strcpy(result, module_name_stack[i].substr(1).c_str());
13052 break;
13053 }
13054 }
13055 break;
13056
13057 case module_nested_e:
13058 // 8) If the NESTED keyword is specified, then the returned value is the
13059 // name, as specified in the PROGRAM-ID, of the currently running, most
13060 // recently nested program.
13061
13062 // This specification seems weird to me. What if the currently running
13063 // program isn't nested?
13064
13065 // So, we'll just return us
13066 strcpy(result, module_name_stack[ssize-1].substr(1).c_str());
13067 break;
13068
13069 case module_stack_e:
13070 for(size_t i=ssize-1; i<ssize; i--)
13071 {
13072 if( module_name_stack[i][0] == 'T'
13073 || module_name_stack[i][0] == 'N' )
13074 {
13075 if( strlen(result) + module_name_stack[i].substr(1).length() + 4 > result_size)
13076 {
13077 result_size *= 2;
13078 result = static_cast<char *>(realloc(result, result_size));
13079 }
13080 strcat(result, module_name_stack[i].substr(1).c_str());
13081 strcat(result, ";");
13082 }
13083 }
13084 strcat(result, " ");
13085
13086 break;
13087
13088 case module_toplevel_e:
13089 {
13090 size_t i = 0;
13091 if( module_name_stack[i] == "Mmain" )
13092 {
13093 i += 1;
13094 }
13095 strcpy(result, module_name_stack[i].substr(1).c_str());
13096 }
13097 break;
13098 }
13099
13100 __gg__adjust_dest_size(dest, strlen(result));
13101 memcpy(dest->data, result, strlen(result)+1);
13102 }
13103
13104 /*
13105 * Runtime functions defined for cbl_enabled_exceptions_t
13106 */
13107 cbl_enabled_exceptions_t&
13108 cbl_enabled_exceptions_t::decode( const std::vector<uint64_t>& encoded ) {
13109 auto p = encoded.begin();
13110 while( p != encoded.end() ) {
13111 auto location = static_cast<bool>(*p++);
13112 auto ec = static_cast<ec_type_t>(*p++);
13113 auto file = *p++;
13114 cbl_enabled_exception_t enabled(location, ec, file);
13115 insert(enabled);
13116 }
13117 return *this;
13118 }
13119 const cbl_enabled_exception_t *
13120 cbl_enabled_exceptions_t::match( ec_type_t type, size_t file ) const {
13121 auto output = enabled_exception_match( begin(), end(), type, file );
13122
13123 if( output != end() ) {
13124 if( MATCH_DECLARATIVE )
13125 warnx(" enabled_exception_match found %x in input\n", type);
13126 return &*output;
13127 }
13128 return nullptr;
13129 }
13130
13131 void
13132 cbl_enabled_exceptions_t::dump( const char tag[] ) const {
13133 if( empty() ) {
13134 warnx("%s: no enabled exceptions", tag );
13135 return;
13136 }
13137 int i = 1;
13138 for( auto& elem : *this ) {
13139 warnx("%s: %2d {%s, %04x %s, %u}", tag,
13140 i++,
13141 elem.location? "with location" : " no location",
13142 elem.ec,
13143 local_ec_type_str(elem.ec),
13144 static_cast<unsigned int>(elem.file) );
13145 }
13146 }
13147
13148
13149 static std::vector<cbl_declarative_t>&
13150 decode( std::vector<cbl_declarative_t>& dcls,
13151 const std::vector<uint64_t>& encoded ) {
13152 auto p = encoded.begin();
13153 while( p != encoded.end() ) {
13154 auto section = static_cast<size_t>(*p++);
13155 auto global = static_cast<bool>(*p++);
13156 auto type = static_cast<ec_type_t>(*p++);
13157 auto nfile = static_cast<uint32_t>(*p++);
13158 std::list<size_t> files;
13159 assert(nfile <= cbl_declarative_t::files_max);
13160 auto pend = p + nfile;
13161 std::copy(p, pend, std::back_inserter(files));
13162 p += cbl_declarative_t::files_max;
13163 auto mode = cbl_file_mode_t(*p++);
13164 cbl_declarative_t dcl( section, type, files, mode, global );
13165 dcls.push_back(dcl);
13166 }
13167 return dcls;
13168 }
13169
13170 static std::vector<cbl_declarative_t>&
13171 operator<<( std::vector<cbl_declarative_t>& dcls,
13172 const std::vector<uint64_t>& encoded ) {
13173 return decode( dcls, encoded );
13174 }
13175
13176 // The first element of each array is the number of elements that follow
13177 // The first element of each array is the number of elements that follow
13178 extern "C"
13179 void
13180 __gg__set_exception_environment( uint64_t *ecs, uint64_t *dcls )
13181 {
13182 static struct prior_t {
13183 uint64_t *ecs = nullptr, *dcls = nullptr;
13184 } prior;
13185
13186 if( MATCH_DECLARATIVE )
13187 if( prior.ecs != ecs || prior.dcls != dcls )
13188 warnx("set_exception_environment: %s: %p, %p",
13189 __gg__exception_statement, ecs, dcls);
13190
13191 if( ecs ) {
13192 if( prior.ecs != ecs ) {
13193 uint64_t *ecs_begin = ecs + 1, *ecs_end = ecs_begin + ecs[0];
13194 if( MATCH_DECLARATIVE ) {
13195 warnx("%u elements implies %u ECs",
13196 static_cast<unsigned int>(ecs[0]),
13197 static_cast<unsigned int>(ecs[0] / 3));
13198 }
13199 cbl_enabled_exceptions_t enabled;
13200 enabled_ECs = enabled.decode( std::vector<uint64_t>(ecs_begin, ecs_end) );
13201 if( MATCH_DECLARATIVE ) enabled_ECs.dump("set_exception_environment");
13202 }
13203 } else {
13204 enabled_ECs.clear();
13205 }
13206
13207 if( dcls ) {
13208 if( prior.dcls != dcls ) {
13209 uint64_t *dcls_begin = dcls + 1, *dcls_end = dcls_begin + dcls[0];
13210 if( MATCH_DECLARATIVE ) {
13211 warnx("%u elements implies %u declaratives",
13212 static_cast<unsigned int>(dcls[0]),
13213 static_cast<unsigned int>(dcls[0] / 21));
13214 }
13215 declaratives.clear();
13216 declaratives << std::vector<uint64_t>( dcls_begin, dcls_end );
13217 }
13218 } else {
13219 declaratives.clear();
13220 }
13221
13222 __gg__exception_code = ec_none_e;
13223
13224 prior.ecs = ecs;
13225 prior.dcls = dcls;
13226 }
13227
13228 static char *sv_envname = NULL;
13229
13230 extern "C"
13231 void
13232 __gg__set_env_name( const cblc_field_t *var,
13233 size_t offset,
13234 size_t length )
13235 {
13236 // implements DISPLAY UPON ENVIRONMENT-NAME
13237 free(sv_envname);
13238 sv_envname = static_cast<char *>(malloc(length+1));
13239 massert(sv_envname);
13240 memcpy(sv_envname, var->data+offset, length);
13241 sv_envname[length] = '\0';
13242 }
13243
13244
13245 extern "C"
13246 void
13247 __gg__get_env_name( cblc_field_t *dest,
13248 size_t dest_offset,
13249 size_t dest_length)
13250 {
13251 // Implements ACCEPT FROM ENVIRONMENT-NAME
13252 // It returns the value previously established by __gg__set_env_name.
13253 if( sv_envname )
13254 {
13255 sv_envname = strdup("");
13256 }
13257 move_string(dest, dest_offset, dest_length, sv_envname);
13258 }
13259
13260 extern "C"
13261 int
13262 __gg__get_env_value(cblc_field_t *dest,
13263 size_t dest_offset,
13264 size_t dest_length)
13265 {
13266 return accept_envar(dest,
13267 dest_offset,
13268 dest_length,
13269 sv_envname);
13270 }
13271
13272 extern "C"
13273 void
13274 __gg__set_env_value(const cblc_field_t *value,
13275 size_t offset,
13276 size_t length )
13277 {
13278 // implements DISPLAY UPON ENVIRONMENT-VALUE
13279 size_t name_length = strlen(sv_envname);
13280 size_t value_length = length;
13281
13282 static size_t env_length = 16;
13283 static char *env = static_cast<char *>(malloc(env_length+1));
13284 static size_t val_length = 16;
13285 static char *val = static_cast<char *>(malloc(val_length+1));
13286 if( env_length < name_length+1 )
13287 {
13288 env_length = name_length+1;
13289 env = static_cast<char *>(realloc(env, env_length));
13290 }
13291 if( val_length < value_length+1 )
13292 {
13293 val_length = value_length+1;
13294 val = static_cast<char *>(realloc(val, val_length));
13295 }
13296 massert(env);
13297 massert(val);
13298
13299 // The name and the value arrive in the internal codeset:
13300 memcpy(env, sv_envname, name_length);
13301 env[name_length] = '\0';
13302 memcpy(val, value->data+offset, value_length);
13303 val[value_length] = '\0';
13304
13305 // Get rid of leading and trailing internal_space characters
13306 char *trimmed_env = brute_force_trim(env);
13307 char *trimmed_val = brute_force_trim(val);
13308
13309 // Conver them to the console codeset
13310 __gg__internal_to_console_in_place(trimmed_env, strlen(trimmed_env));
13311 __gg__internal_to_console_in_place(trimmed_val, strlen(trimmed_val));
13312
13313 // And now, anticlimactically, set the variable:
13314 setenv(trimmed_env, trimmed_val, 1);
13315 }
13316
13317 extern "C"
13318 void
13319 __gg__fprintf_stderr(const char *format_string, ...)
13320 __attribute__ ((__format__ (__printf__, 1, 2)));
13321
13322 extern "C"
13323 void
13324 __gg__fprintf_stderr(const char *format_string, ...)
13325 {
13326 /* This routine allows the compiler to send stuff to stderr in a way
13327 that is straightforward to use.. */
13328 va_list ap;
13329 va_start(ap, format_string);
13330 vfprintf(stderr, format_string, ap);
13331 va_end(ap);
13332 }
13333
13334
13335 static int sv_argument_number = 0;
13336
13337 extern "C"
13338 void
13339 __gg__set_arg_num( const cblc_field_t *index,
13340 size_t index_offset,
13341 size_t index_size )
13342 {
13343 // Implements DISPLAY UPON ARGUMENT-NUMBER.
13344 int rdigits;
13345 __int128 N = get_binary_value_local(&rdigits,
13346 index,
13347 index->data + index_offset,
13348 index_size);
13349 // If he gives us fractional digits, just truncate
13350 N /= __gg__power_of_ten(rdigits);
13351
13352 // N is 1-based, per normal COBOL. We have to decrement it here:
13353 N -= 1;
13354 sv_argument_number = static_cast<int>(N);
13355 }
13356
13357 extern "C"
13358 int
13359 __gg__accept_arg_value( cblc_field_t *dest,
13360 size_t dest_offset,
13361 size_t dest_length)
13362 {
13363 // Implements ACCEPT FROM ARGUMENT-VALUE
13364 int retcode;
13365 command_line_plan_b();
13366 if( sv_argument_number >= stashed_argc || sv_argument_number < 0 )
13367 {
13368 exception_raise(ec_argument_imp_command_e);
13369 retcode = 1; // Error
13370 }
13371 else
13372 {
13373 char *retval = strdup(stashed_argv[sv_argument_number]);
13374 console_to_internal(retval, strlen(retval));
13375 move_string(dest, dest_offset, dest_length, retval);
13376 free(retval);
13377 retcode = 0; // Okay
13378
13379 // The Fujitsu spec says bump this value by one.
13380 sv_argument_number += 1;
13381 }
13382 return retcode;
13383 }
13384
13385 extern "C"
13386 int
13387 __gg__get_file_descriptor(const char *device)
13388 {
13389 int retval = open(device, O_WRONLY);
13390
13391 if( retval == -1 )
13392 {
13393 char *msg;
13394 int ec = asprintf(&msg,
13395 "Trying to open %s. Got error %s",
13396 device,
13397 strerror(errno));
13398 if( ec != -1 )
13399 {
13400 static const int priority = LOG_INFO,
13401 option = LOG_PERROR,
13402 facility = LOG_USER;
13403 open_syslog(option, facility);
13404 syslog(priority, "%s", msg);
13405 }
13406
13407 // Open a new handle to /dev/stdout, since our caller will be closing it
13408 retval = open("/dev/stdout", O_WRONLY);
13409 }
13410 return retval;
13411 }