Debian Codegraph @

gcc/cobol/cdf-copy.cc

raw
1 /*
2 * Copyright (c) 2021-2025 Symas Corporation
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 * * Neither the name of the Symas Corporation nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 // NOTE: Unlike charmaps-copy.cc and valprint-copy.cc, this file implements
32 // the Compiler Directives Facility for the COBOL "COPY" statement. So, this
33 // file is the actual source code, and not a copy of something in libgcobol
34 //
35 // We regret any confusion engendered.
36
37 #include "config.h"
38
39 #include "cobol-system.h"
40 #include "cbldiag.h"
41 #include "util.h"
42 #include "copybook.h"
43
44 #define COUNT_OF(X) (sizeof(X) / sizeof(X[0]))
45
46 /*
47 * There are 3 kinds of replacement types:
48 * 1. keywords, identifiers, figurative constants, and function names
49 * 2. string literals
50 * 3. pseudo-text
51 *
52 * Types #1 and #3 are delimited by separators:
53 * [[:space:],.;()]. String literals begin and end with ["] or [']
54 * (matched).
55 *
56 * Space in pseudo-text is "elastic"; one or more in the matching
57 * argument matches one or more in the input. Exception: when the
58 * argument is only a comma or semicolon, it matches exactly.
59 *
60 * The matching algorithm operates on the source file word by word.
61 * Comments are copied literally, as are any CDF statements.
62 *
63 * The candidate word is used as the beginning of all possible
64 * matches, in the order they appear in the COPY statement. If none
65 * match, the word is copied to the output and the next word is
66 * tried.
67 *
68 * On a match, the replacement is applied, the result copied to the
69 * output, and the next word is tried, starting again from the first
70 * match candidate.
71 *
72 * The parser composes the regular expressions. It "literalizes"
73 * any regex metacharacters that may appear in the COPY text and
74 * constructs the correct matching expression for "stretchable"
75 * space. This function only applies them.
76 */
77
78 const char * cobol_filename();
79 bool is_fixed_format();
80 bool is_reference_format();
81
82 struct line_t {
83 char *p, *pend;
84 line_t( size_t len, char *data ) : p(data), pend(data + len) {
85 gcc_assert(p && p <= pend);
86 }
87 line_t( char *data, char *eodata ) : p(data), pend(eodata) {
88 gcc_assert(p && p <= pend);
89 }
90 ssize_t size() const { return pend - p; }
91 };
92
93 static bool
94 is_separator_space( const char *p) {
95 switch( *p ) {
96 case ',':
97 case ';':
98 if( p[1] == 0x20 ) return true;
99 break;
100 }
101 return ISSPACE(*p);
102 }
103
104 static void
105 verify_bounds( size_t pos, size_t size, const char input[] ) {
106 gcc_assert(pos < size );
107 if( !( pos < size) ) {
108 cbl_internal_error( "REPLACING %zu characters exceeds system capacity"
109 "'%s'", pos, input);
110 }
111 }
112
113 /*
114 * Replace any separators in the copybook's REPLACING candidate with
115 * "stretchable" space. Escape any regex metacharacters in candidate.
116 *
117 * "For matching purposes, each occurrence of a separator comma, a
118 * separator semicolon, or a sequence of one or more separator spaces
119 * is considered to be a single space."
120 *
121 * If the indicator column is column 7 and is a 'D', we treat that as
122 * a SPACE for the purposes of matching a COPY REPLACING or REPLACE
123 * directive.
124 */
125 const char *
126 esc( size_t len, const char input[] ) {
127 static const char space[] = "([,;]?[[:space:]])+";
128 static const char spaceD[] = "(\n {6}D" "|" "[,;]?[[:space:]])+";
129 static char buffer[64 * 1024];
130 char *p = buffer;
131 const char *eoinput = input + len;
132
133 const char *spacex = is_reference_format()? spaceD : space;
134
135 for( const char *s=input; *s && s < eoinput; s++ ) {
136 *p = '\0';
137 verify_bounds( 4 + size_t(p - buffer), sizeof(buffer), buffer );
138 switch(*s) {
139 case '^': case '$':
140 case '(': case ')':
141 case '*': case '+': case '?':
142 case '[': case ']':
143 case '{': case '}':
144 case '|':
145 case '.':
146 *p++ = '\\';
147 *p++ = *s;
148 break;
149 case '\\':
150 *p++ = '[';
151 *p++ = *s;
152 *p++ = ']';
153 break;
154
155 case ';': case ',':
156 if( ! (s+1 < eoinput && s[1] == 0x20) ) {
157 *p++ = *s;
158 break;
159 }
160 __attribute__((fallthrough));
161 case 0x20: case '\n':
162 verify_bounds( (p + sizeof(spacex)) - buffer, sizeof(buffer), buffer );
163 p = stpcpy( p, spacex );
164 while( s+1 < eoinput && is_separator_space(s+1) ) {
165 s++;
166 }
167 break;
168 default:
169 *p++ = *s;
170 break;
171 }
172 }
173 *p = '\0';
174
175 #if 0
176 dbgmsg("%s:%d: regex '%s'", __func__, __LINE__, buffer);
177 #endif
178 return buffer; // caller must strdup static buffer
179 }
180
181 void
182 copybook_directory_add( const char gcob_copybook[] ) {
183 if( !gcob_copybook ) return;
184 char *directories = xstrdup(gcob_copybook), *p = directories;
185 char *eodirs = strchr(directories, '\0');
186 gcc_assert(eodirs);
187
188 do {
189 char *pend = std::find(p, eodirs, ':');
190 if( pend != eodirs ) {
191 *pend = '\0';
192 }
193 copybook.directory_add(p);
194 p = pend;
195 } while( ++p < eodirs );
196
197 }
198
199 class case_consistent {
200 int lower_upper; // -1 lower, 1 upper
201 public:
202 case_consistent() : lower_upper(0) {}
203 bool operator()( char ch ) {
204 if( !ISALPHA(ch) ) return true;
205 int lu = ISLOWER(ch)? -1 : 1;
206 if( !lower_upper ) {
207 lower_upper = lu;
208 return true;
209 }
210 return lu == lower_upper;
211 }
212 };
213
214 void
215 copybook_extension_add( const char ext[] ) {
216 char *alt = NULL;
217 bool one_case = std::all_of( ext, ext + strlen(ext), case_consistent() );
218 if( one_case ) {
219 alt = xstrdup(ext);
220 gcc_assert(alt);
221 auto convert = ISLOWER(ext[0])? toupper : tolower;
222 std::transform( alt, alt+strlen(alt), alt, convert );
223 }
224 copybook.extensions_add( ext, alt );
225 }
226
227
228 std::list<const char *> copybook_elem_t::suffixes {
229 "", ".cpy", ".CPY", ".cbl", ".CBL", ".cob", ".COB"
230 };
231
232 void
233 copybook_t::extensions_add( const char ext[], const char alt[] ) {
234 book.suffixes.push_back(ext);
235 if( alt ) book.suffixes.push_back(alt);
236 }
237
238 static inline ino_t
239 inode_of( int fd ) {
240 struct stat sb;
241 if( -1 == fstat(fd, &sb) ) {
242 cbl_err("could not stat fd %d", fd);
243 }
244 return sb.st_ino;
245 }
246
247 int
248 copybook_elem_t::open_file( const char directory[], bool literally ) {
249 char *dname = NULL, *copier = xstrdup(cobol_filename());
250
251 if ( directory ) {
252 dname = xstrdup(directory);
253 } else {
254 dname = ldirname(copier);
255 gcc_assert (dname != NULL); /* out of memory */
256 if( '\0' == dname[0] ) {
257 free (dname);
258 dname = NULL;
259 }
260 }
261
262 char *path = NULL;
263
264 if( dname || library.name ) {
265 if( dname && library.name ) {
266 path = xasprintf( "%s/%s/%s", dname, library.name, source.name );
267 } else {
268 const char *dir = dname? dname : library.name;
269 path = xasprintf( "%s/%s", dir, source.name );
270 }
271 } else {
272 path = xasprintf( "%s", source.name );
273 }
274
275 free(dname);
276 gcc_assert(path);
277
278 if( literally ) {
279 dbgmsg("copybook_elem_t::open_file: trying %s", path);
280
281 if( (this->fd = open(path, O_RDONLY)) == -1 ) {
282 dbgmsg("could not open %s: %s", path, xstrerror(errno));
283 return fd;
284 }
285 this->source.name = path;
286 if( ! cobol_filename(this->source.name, inode_of(fd)) ) {
287 error_msg(source.loc, "recursive copybook: '%s' includes itself", path);
288 (void)! close(fd);
289 fd = -1;
290 }
291 return fd;
292 }
293 gcc_assert( ! literally );
294
295 free(copier);
296
297 for( auto suffix : suffixes ) {
298 std::string pattern(path);
299 pattern += suffix;
300 dbgmsg("%s: trying %s", __func__, pattern.c_str());
301
302 auto filename = pattern.c_str();
303 if( (this->fd = open(filename, O_RDONLY)) != -1 ) {
304 dbgmsg("found copybook file %s", filename);
305 this->source.name = xstrdup(filename);
306 if( ! cobol_filename(this->source.name, inode_of(fd)) ) {
307 error_msg(source.loc, "recursive copybook: '%s' includes itself",
308 this->source.name);
309 (void)! close(fd);
310 fd = -1;
311 }
312 dbgmsg("%s: opened %s as fd %d", __func__, source.name, fd);
313 return fd;
314 }
315 }
316
317 return -1;
318 }