Debian Codegraph @

gcc/ada/adaint.c

raw
1 /****************************************************************************
2 * *
3 * GNAT COMPILER COMPONENTS *
4 * *
5 * A D A I N T *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 1992-2025, Free Software Foundation, Inc. *
10 * *
11 * GNAT is free software; you can redistribute it and/or modify it under *
12 * terms of the GNU General Public License as published by the Free Soft- *
13 * ware Foundation; either version 3, or (at your option) any later ver- *
14 * sion. GNAT is distributed in the hope that it will be useful, but WITH- *
15 * OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *
16 * or FITNESS FOR A PARTICULAR PURPOSE. *
17 * *
18 * As a special exception under Section 7 of GPL version 3, you are granted *
19 * additional permissions described in the GCC Runtime Library Exception, *
20 * version 3.1, as published by the Free Software Foundation. *
21 * *
22 * You should have received a copy of the GNU General Public License and *
23 * a copy of the GCC Runtime Library Exception along with this program; *
24 * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see *
25 * <http://www.gnu.org/licenses/>. *
26 * *
27 * GNAT was originally developed by the GNAT team at New York University. *
28 * Extensive contributions were provided by Ada Core Technologies Inc. *
29 * *
30 ****************************************************************************/
31
32 /* This file contains those routines named by Import pragmas in
33 packages in the GNAT hierarchy (especially GNAT.OS_Lib) and in
34 package Osint. Many of the subprograms in OS_Lib import standard
35 library calls directly. This file contains all other routines. */
36
37 /* Ensure access to errno is thread safe. */
38
39 #ifndef _REENTRANT
40 #define _REENTRANT
41 #endif
42
43 #ifndef _THREAD_SAFE
44 #define _THREAD_SAFE
45 #endif
46
47 /* Use 64 bit Large File API */
48 #if defined (__QNX__)
49 #define _LARGEFILE64_SOURCE 1
50 #elif !defined(_LARGEFILE_SOURCE)
51 #define _LARGEFILE_SOURCE
52 #endif
53 #define _FILE_OFFSET_BITS 64
54
55 #ifdef __vxworks
56
57 /* No need to redefine exit here. */
58 #undef exit
59
60 /* We want to use the POSIX variants of include files. */
61 #define POSIX
62 #include "vxWorks.h"
63 #include <sys/time.h>
64
65 #if defined (__mips_vxworks)
66 #include "cacheLib.h"
67 #endif /* __mips_vxworks */
68
69 /* If SMP, access vxCpuConfiguredGet */
70 #ifdef _WRS_CONFIG_SMP
71 #include <vxCpuLib.h>
72 #endif /* _WRS_CONFIG_SMP */
73
74 /* We need to know the VxWorks version because some file operations
75 (such as chmod) are only available on VxWorks 6. */
76 #include "version.h"
77
78 /* vwModNum.h and dosFsLib.h are needed for the VxWorks 6 rename workaround.
79 See below. */
80 #if (_WRS_VXWORKS_MAJOR == 6)
81 #include <vwModNum.h>
82 #include <dosFsLib.h>
83 #endif /* 6.x */
84 #endif /* VxWorks */
85
86 #if defined (__APPLE__)
87 #include <unistd.h>
88 #include <signal.h>
89 #include <sys/time.h>
90 #include <TargetConditionals.h>
91 #endif
92
93 #if defined (__hpux__)
94 #include <sys/param.h>
95 #include <sys/pstat.h>
96 #endif
97
98 #ifdef __PikeOS__
99 #define __BSD_VISIBLE 1
100 #endif
101
102 #ifdef __QNX__
103 #include <sys/syspage.h>
104 #include <sys/time.h>
105 #endif
106
107 #ifdef IN_RTS
108
109 #ifdef STANDALONE
110 #include <errno.h>
111 #include <sys/types.h>
112 #include <sys/stat.h>
113 #include <unistd.h>
114 #include <stdlib.h>
115 #include <string.h>
116
117 /* for CPU_SET/CPU_ZERO */
118 #define _GNU_SOURCE
119 #define __USE_GNU
120
121 #include "runtime.h"
122
123 #else
124 #include "tconfig.h"
125 #include "tsystem.h"
126 #endif
127
128 #include <sys/stat.h>
129 #include <fcntl.h>
130 #include <time.h>
131
132 #if defined (__vxworks) || defined (__ANDROID__)
133 /* S_IREAD and S_IWRITE are not defined in VxWorks or Android */
134 #ifndef S_IREAD
135 #define S_IREAD (S_IRUSR | S_IRGRP | S_IROTH)
136 #endif
137
138 #ifndef S_IWRITE
139 #define S_IWRITE (S_IWUSR)
140 #endif
141 #endif
142
143 /* We don't have libiberty, so use malloc. */
144 #define xmalloc(S) malloc (S)
145 #define xrealloc(V,S) realloc (V,S)
146 #else
147 #include "config.h"
148 #include "system.h"
149 #include "version.h"
150 #endif
151
152 /* limits.h is needed for LLONG_MIN. */
153 #ifdef __cplusplus
154 #include <climits>
155 #else
156 #include <limits.h>
157 #endif
158
159 #ifdef __cplusplus
160 extern "C" {
161 #endif
162
163 #if defined (__DJGPP__)
164
165 /* For isalpha-like tests in the compiler, we're expected to resort to
166 safe-ctype.h/ISALPHA. This isn't available for the runtime library
167 build, so we fallback on ctype.h/isalpha there. */
168
169 #ifdef IN_RTS
170 #include <ctype.h>
171 #define ISALPHA isalpha
172 #endif
173
174 #elif defined (__MINGW32__) || defined (__CYGWIN__)
175
176 #include "mingw32.h"
177
178 /* Current code page and CCS encoding to use, set in rtinit.c. */
179 UINT __gnat_current_codepage;
180 UINT __gnat_current_ccs_encoding;
181
182 #include <sys/utime.h>
183
184 /* For isalpha-like tests in the compiler, we're expected to resort to
185 safe-ctype.h/ISALPHA. This isn't available for the runtime library
186 build, so we fallback on ctype.h/isalpha there. */
187
188 #ifdef IN_RTS
189 #include <ctype.h>
190 #define ISALPHA isalpha
191 #endif
192
193 #elif defined (__Lynx__)
194
195 /* Lynx utime.h only defines the entities of interest to us if
196 defined (VMOS_DEV), so ... */
197 #define VMOS_DEV
198 #include <utime.h>
199 #undef VMOS_DEV
200
201 #else
202 #include <utime.h>
203 #endif
204
205 /* wait.h processing */
206 #if defined (__vxworks) && defined (__RTP__)
207 # include <wait.h>
208 #elif defined (__Lynx__)
209 /* ??? We really need wait.h and it includes resource.h on Lynx. GCC
210 has a resource.h header as well, included instead of the lynx
211 version in our setup, causing lots of errors. We don't really need
212 the lynx contents of this file, so just workaround the issue by
213 preventing the inclusion of the GCC header from doing anything. */
214 # define GCC_RESOURCE_H
215 # include <sys/wait.h>
216 #elif defined (__PikeOS__) || defined (__MINGW32__)
217 /* No wait() or waitpid() calls available. */
218 #else
219 /* Default case. */
220 #include <sys/wait.h>
221 #endif
222
223 #if defined (__DJGPP__)
224 #include <process.h>
225 #include <signal.h>
226 #include <dir.h>
227 #include <utime.h>
228 #undef DIR_SEPARATOR
229 #define DIR_SEPARATOR '\\'
230
231 #elif defined (_WIN32)
232
233 /* Cannot redefine abort here. */
234 #undef abort
235
236 #define WIN32_LEAN_AND_MEAN
237 #include <windows.h>
238 #include <accctrl.h>
239 #include <aclapi.h>
240 #include <tlhelp32.h>
241 #include <signal.h>
242 #undef DIR_SEPARATOR
243 #define DIR_SEPARATOR '\\'
244
245 #ifdef STANDALONE
246 #undef PATH_SEPARATOR
247 #define PATH_SEPARATOR ';'
248 #undef HOST_EXECUTABLE_SUFFIX
249 #define HOST_EXECUTABLE_SUFFIX ".exe"
250 #endif
251
252 #else
253 #include <signal.h>
254 #include <utime.h>
255 #endif
256
257 #include "adaint.h"
258
259 int __gnat_in_child_after_fork = 0;
260
261 #if defined (__APPLE__) && defined (st_mtime)
262 #define st_atim st_atimespec
263 #define st_mtim st_mtimespec
264 #endif
265
266 /* Define symbols O_BINARY and O_TEXT as harmless zeroes if they are not
267 defined in the current system. On DOS-like systems these flags control
268 whether the file is opened/created in text-translation mode (CR/LF in
269 external file mapped to LF in internal file), but in Unix-like systems,
270 no text translation is required, so these flags have no effect. */
271
272 #ifndef O_BINARY
273 #define O_BINARY 0
274 #endif
275
276 #ifndef O_TEXT
277 #define O_TEXT 0
278 #endif
279
280 #ifndef HOST_EXECUTABLE_SUFFIX
281 #define HOST_EXECUTABLE_SUFFIX ""
282 #endif
283
284 #ifndef HOST_OBJECT_SUFFIX
285 #define HOST_OBJECT_SUFFIX ".o"
286 #endif
287
288 #ifndef PATH_SEPARATOR
289 #define PATH_SEPARATOR ':'
290 #endif
291
292 #ifndef DIR_SEPARATOR
293 #define DIR_SEPARATOR '/'
294 #define IS_DIRECTORY_SEPARATOR(c) ((c) == DIR_SEPARATOR)
295 #else
296 #define IS_DIRECTORY_SEPARATOR(c) ((c) == '/' || (c) == DIR_SEPARATOR)
297 #endif
298
299 /* Check for cross-compilation. */
300 #if defined (CROSS_COMPILE) || defined (CROSS_DIRECTORY_STRUCTURE)
301 #define IS_CROSS 1
302 int __gnat_is_cross_compiler = 1;
303 #else
304 #undef IS_CROSS
305 int __gnat_is_cross_compiler = 0;
306 #endif
307
308 char __gnat_dir_separator = DIR_SEPARATOR;
309
310 char __gnat_path_separator = PATH_SEPARATOR;
311
312 /* The GNAT_LIBRARY_TEMPLATE contains a list of expressions that define
313 the base filenames that libraries specified with -lsomelib options
314 may have. This is used by GNATMAKE to check whether an executable
315 is up-to-date or not. The syntax is
316
317 library_template ::= { pattern ; } pattern NUL
318 pattern ::= [ prefix ] * [ postfix ]
319
320 These should only specify names of static libraries as it makes
321 no sense to determine at link time if dynamic-link libraries are
322 up to date or not. Any libraries that are not found are supposed
323 to be up-to-date:
324
325 * if they are needed but not present, the link
326 will fail,
327
328 * otherwise they are libraries in the system paths and so
329 they are considered part of the system and not checked
330 for that reason.
331
332 ??? This should be part of a GNAT host-specific compiler
333 file instead of being included in all user applications
334 as well. This is only a temporary work-around for 3.11b. */
335
336 #ifndef GNAT_LIBRARY_TEMPLATE
337 #define GNAT_LIBRARY_TEMPLATE "lib*.a"
338 #endif
339
340 const char *__gnat_library_template = GNAT_LIBRARY_TEMPLATE;
341
342 #if defined (__vxworks)
343 #define GNAT_MAX_PATH_LEN PATH_MAX
344
345 #else
346
347 #include <sys/param.h>
348
349 #ifdef MAXPATHLEN
350 #define GNAT_MAX_PATH_LEN MAXPATHLEN
351 #else
352 #define GNAT_MAX_PATH_LEN 256
353 #endif
354
355 #endif
356
357 /* Used for runtime check that Ada constant File_Attributes_Size is no
358 less than the actual size of struct file_attributes (see Osint
359 initialization). */
360 int __gnat_size_of_file_attributes = sizeof (struct file_attributes);
361
362 void __gnat_stat_to_attr (int fd, char* name, struct file_attributes* attr);
363
364 /* The __gnat_max_path_len variable is used to export the maximum
365 length of a path name to Ada code. max_path_len is also provided
366 for compatibility with older GNAT versions, please do not use
367 it. */
368
369 int __gnat_max_path_len = GNAT_MAX_PATH_LEN;
370 int max_path_len = GNAT_MAX_PATH_LEN;
371
372 /* Control whether we can use ACL on Windows. */
373
374 int __gnat_use_acl = 1;
375
376 /* The following macro HAVE_READDIR_R should be defined if the
377 system provides the routine readdir_r.
378 ... but we never define it anywhere??? */
379 #undef HAVE_READDIR_R
380
381 #define MAYBE_TO_PTR32(argv) argv
382
383 static const char ATTR_UNSET = 127;
384
385 /* Reset the file attributes as if no system call had been performed */
386
387 void
388 __gnat_reset_attributes (struct file_attributes* attr)
389 {
390 attr->exists = ATTR_UNSET;
391 attr->error = EINVAL;
392
393 attr->writable = ATTR_UNSET;
394 attr->readable = ATTR_UNSET;
395 attr->executable = ATTR_UNSET;
396
397 attr->regular = ATTR_UNSET;
398 attr->symbolic_link = ATTR_UNSET;
399 attr->directory = ATTR_UNSET;
400
401 attr->timestamp = (OS_Time)-2;
402 attr->file_length = -1;
403 }
404
405 int
406 __gnat_error_attributes (struct file_attributes *attr) {
407 return attr->error;
408 }
409
410 OS_Time
411 __gnat_current_time (void)
412 {
413 time_t res = time (NULL);
414 return (OS_Time) res;
415 }
416
417 /* Return the current local time as a string in the ISO 8601 format of
418 "YYYY-MM-DD HH:MM:SS.SS". The returned string is 22 + 1 (NULL) characters
419 long. */
420
421 void
422 __gnat_current_time_string (char *result)
423 {
424 const char *format = "%Y-%m-%d %H:%M:%S";
425 /* Format string necessary to describe the ISO 8601 format */
426
427 const time_t t_val = time (NULL);
428
429 strftime (result, 22, format, localtime (&t_val));
430 /* Convert the local time into a string following the ISO format, copying
431 at most 22 characters into the result string. */
432
433 result [19] = '.';
434 result [20] = '0';
435 result [21] = '0';
436 /* The sub-seconds are manually set to zero since type time_t lacks the
437 precision necessary for nanoseconds. */
438 }
439
440 void
441 __gnat_to_gm_time (OS_Time *p_time, int *p_year, int *p_month, int *p_day,
442 int *p_hours, int *p_mins, int *p_secs)
443 {
444 struct tm *res;
445 time_t time = (time_t) *p_time;
446
447 res = gmtime (&time);
448 if (res)
449 {
450 *p_year = res->tm_year;
451 *p_month = res->tm_mon;
452 *p_day = res->tm_mday;
453 *p_hours = res->tm_hour;
454 *p_mins = res->tm_min;
455 *p_secs = res->tm_sec;
456 }
457 else
458 *p_year = *p_month = *p_day = *p_hours = *p_mins = *p_secs = 0;
459 }
460
461 void
462 __gnat_to_os_time (OS_Time *p_time, int year, int month, int day,
463 int hours, int mins, int secs)
464 {
465 struct tm v;
466
467 v.tm_year = year;
468 v.tm_mon = month;
469 v.tm_mday = day;
470 v.tm_hour = hours;
471 v.tm_min = mins;
472 v.tm_sec = secs;
473 v.tm_isdst = -1;
474
475 /* returns -1 of failing, this is s-os_lib Invalid_Time */
476
477 *p_time = (OS_Time) mktime (&v);
478 }
479
480 /* Place the contents of the symbolic link named PATH in the buffer BUF,
481 which has size BUFSIZ. If PATH is a symbolic link, then return the number
482 of characters of its content in BUF. Otherwise, return -1.
483 For systems not supporting symbolic links, always return -1. */
484
485 int
486 __gnat_readlink (char *path ATTRIBUTE_UNUSED,
487 char *buf ATTRIBUTE_UNUSED,
488 size_t bufsiz ATTRIBUTE_UNUSED)
489 {
490 #if defined (_WIN32) \
491 || defined(__vxworks) || defined (__PikeOS__)
492 return -1;
493 #else
494 return readlink (path, buf, bufsiz);
495 #endif
496 }
497
498 /* Creates a symbolic link named NEWPATH which contains the string OLDPATH.
499 If NEWPATH exists it will NOT be overwritten.
500 For systems not supporting symbolic links, always return -1. */
501
502 int
503 __gnat_symlink (char *oldpath ATTRIBUTE_UNUSED,
504 char *newpath ATTRIBUTE_UNUSED)
505 {
506 #if defined (_WIN32) \
507 || defined(__vxworks) || defined (__PikeOS__)
508 return -1;
509 #else
510 return symlink (oldpath, newpath);
511 #endif
512 }
513
514 /* Try to lock a file, return 1 if success. */
515
516 #if defined (__vxworks) \
517 || defined (_WIN32) || defined (__PikeOS__)
518
519 /* Version that does not use link. */
520
521 int
522 __gnat_try_lock (char *dir, char *file)
523 {
524 int fd;
525 #ifdef __MINGW32__
526 TCHAR wfull_path[GNAT_MAX_PATH_LEN];
527 TCHAR wfile[GNAT_MAX_PATH_LEN];
528 TCHAR wdir[GNAT_MAX_PATH_LEN];
529
530 S2WSC (wdir, dir, GNAT_MAX_PATH_LEN);
531 S2WSC (wfile, file, GNAT_MAX_PATH_LEN);
532
533 /* ??? the code below crash on MingW64 for obscure reasons, a ticket
534 has been opened here:
535
536 https://sourceforge.net/p/mingw-w64/bugs/414/
537
538 As a workaround an equivalent set of code has been put in place below.
539
540 _stprintf (wfull_path, _T("%s%c%s"), wdir, _T(DIR_SEPARATOR), wfile);
541 */
542
543 _tcscpy (wfull_path, wdir);
544 _tcscat (wfull_path, L"\\");
545 _tcscat (wfull_path, wfile);
546
547 fd = _topen (wfull_path, O_CREAT | O_EXCL, 0600);
548 #else
549 char full_path[256];
550
551 sprintf (full_path, "%s%c%s", dir, DIR_SEPARATOR, file);
552 fd = open (full_path, O_CREAT | O_EXCL, 0600);
553 #endif
554
555 if (fd < 0)
556 return 0;
557
558 close (fd);
559 return 1;
560 }
561
562 #else
563
564 /* Version using link(), more secure over NFS. */
565 /* See TN 6913-016 for discussion ??? */
566
567 int
568 __gnat_try_lock (char *dir, char *file)
569 {
570 char full_path[256];
571 char temp_file[256];
572 GNAT_STRUCT_STAT stat_result;
573 int fd;
574
575 sprintf (full_path, "%s%c%s", dir, DIR_SEPARATOR, file);
576 sprintf (temp_file, "%s%cTMP-%ld-%ld",
577 dir, DIR_SEPARATOR, (long)getpid(), (long)getppid ());
578
579 /* Create the temporary file and write the process number. */
580 fd = open (temp_file, O_CREAT | O_WRONLY, 0600);
581 if (fd < 0)
582 return 0;
583
584 close (fd);
585
586 /* Link it with the new file. */
587 link (temp_file, full_path);
588
589 /* Count the references on the old one. If we have a count of two, then
590 the link did succeed. Remove the temporary file before returning. */
591 __gnat_stat (temp_file, &stat_result);
592 unlink (temp_file);
593 return stat_result.st_nlink == 2;
594 }
595 #endif
596
597 /* Return the maximum file name length. */
598
599 int
600 __gnat_get_maximum_file_name_length (void)
601 {
602 return -1;
603 }
604
605 /* Return nonzero if file names are case sensitive. */
606
607 static int file_names_case_sensitive_cache = -1;
608
609 int
610 __gnat_get_file_names_case_sensitive (void)
611 {
612 if (file_names_case_sensitive_cache == -1)
613 {
614 const char *sensitive = getenv ("GNAT_FILE_NAME_CASE_SENSITIVE");
615
616 if (sensitive != NULL
617 && (sensitive[0] == '0' || sensitive[0] == '1')
618 && sensitive[1] == '\0')
619 file_names_case_sensitive_cache = sensitive[0] - '0';
620 else
621 {
622 /* By default, we suppose filesystems aren't case sensitive on
623 Windows or DOS. */
624 #if defined (WINNT) || defined (__DJGPP__)
625 file_names_case_sensitive_cache = 0;
626 #elif defined (__APPLE__)
627 /* By default, macOS volumes are case-insensitive, iOS
628 volumes are case-sensitive. */
629 #if TARGET_OS_IOS
630 file_names_case_sensitive_cache = 1;
631 #else
632 file_names_case_sensitive_cache = 0;
633 #endif
634 #else /* Neither Windows nor Apple. */
635 file_names_case_sensitive_cache = 1;
636 #endif
637 }
638 }
639 return file_names_case_sensitive_cache;
640 }
641
642 /* Return nonzero if environment variables are case sensitive. */
643
644 int
645 __gnat_get_env_vars_case_sensitive (void)
646 {
647 #if defined (WINNT) || defined (__DJGPP__)
648 return 0;
649 #else
650 return 1;
651 #endif
652 }
653
654 char
655 __gnat_get_default_identifier_character_set (void)
656 {
657 return '1';
658 }
659
660 /* Return the current working directory. */
661
662 void
663 __gnat_get_current_dir (char *dir, int *length)
664 {
665 #if defined (__MINGW32__)
666 TCHAR wdir[GNAT_MAX_PATH_LEN];
667
668 _tgetcwd (wdir, *length);
669
670 WS2SC (dir, wdir, GNAT_MAX_PATH_LEN);
671
672 #else
673 char* result = getcwd (dir, *length);
674 /* If the current directory does not exist, set length = 0
675 to indicate error. That can't happen on windows, where
676 you can't delete a directory if it is the current
677 directory of some process. */
678 if (!result)
679 {
680 *length = 0;
681 return;
682 }
683 #endif
684
685 *length = strlen (dir);
686
687 if (dir [*length - 1] != DIR_SEPARATOR)
688 {
689 dir [*length] = DIR_SEPARATOR;
690 ++(*length);
691 }
692 dir[*length] = '\0';
693 }
694
695 /* Return the suffix for object files. */
696
697 void
698 __gnat_get_object_suffix_ptr (int *len, const char **value)
699 {
700 *value = HOST_OBJECT_SUFFIX;
701
702 if (*value == 0)
703 *len = 0;
704 else
705 *len = strlen (*value);
706
707 return;
708 }
709
710 /* Return the suffix for executable files. */
711
712 void
713 __gnat_get_executable_suffix_ptr (int *len, const char **value)
714 {
715 *value = HOST_EXECUTABLE_SUFFIX;
716
717 if (!*value)
718 *len = 0;
719 else
720 *len = strlen (*value);
721
722 return;
723 }
724
725 /* Return the suffix for debuggable files. Usually this is the same as the
726 executable extension. */
727
728 void
729 __gnat_get_debuggable_suffix_ptr (int *len, const char **value)
730 {
731 *value = HOST_EXECUTABLE_SUFFIX;
732
733 if (*value == 0)
734 *len = 0;
735 else
736 *len = strlen (*value);
737
738 return;
739 }
740
741 /* Returns the OS filename and corresponding encoding. */
742
743 void
744 __gnat_os_filename (char *filename ATTRIBUTE_UNUSED,
745 char *w_filename ATTRIBUTE_UNUSED,
746 char *os_name, int *o_length,
747 char *encoding ATTRIBUTE_UNUSED, int *e_length)
748 {
749 #if defined (_WIN32) && ! defined (__vxworks) && ! defined (IS_CROSS)
750 WS2SC (os_name, (TCHAR *)w_filename, (DWORD)*o_length);
751 *o_length = strlen (os_name);
752 strcpy (encoding, "encoding=utf8");
753 *e_length = strlen (encoding);
754 #else
755 strcpy (os_name, filename);
756 *o_length = strlen (filename);
757 *e_length = 0;
758 #endif
759 }
760
761 /* Delete a file. */
762
763 int
764 __gnat_unlink (char *path, int encoding ATTRIBUTE_UNUSED)
765 {
766 #if defined (__MINGW32__) && ! defined (__vxworks) && ! defined (IS_CROSS)
767 TCHAR wpath[GNAT_MAX_PATH_LEN];
768
769 if (encoding == Encoding_Unspecified)
770 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
771 else if (encoding == Encoding_UTF8)
772 S2WSU (wpath, path, GNAT_MAX_PATH_LEN);
773 else
774 S2WS (wpath, path, GNAT_MAX_PATH_LEN);
775
776 return _tunlink (wpath);
777 #else
778 return unlink (path);
779 #endif
780 }
781
782 /* Rename a file. */
783
784 int
785 __gnat_rename (char *from, char *to)
786 {
787 #if defined (__MINGW32__) && ! defined (__vxworks) && ! defined (IS_CROSS)
788 {
789 TCHAR wfrom[GNAT_MAX_PATH_LEN], wto[GNAT_MAX_PATH_LEN];
790
791 S2WSC (wfrom, from, GNAT_MAX_PATH_LEN);
792 S2WSC (wto, to, GNAT_MAX_PATH_LEN);
793 return _trename (wfrom, wto);
794 }
795 #elif defined (__vxworks) && (_WRS_VXWORKS_MAJOR == 6)
796 {
797 /* When used on a dos filesystem under VxWorks 6.9 rename will trigger a
798 S_dosFsLib_FILE_NOT_FOUND errno when the file is not found. Let's map
799 that to ENOENT so Ada.Directory.Rename can detect that and raise the
800 Name_Error exception. */
801 int ret = rename (from, to);
802
803 if (ret && (errno == S_dosFsLib_FILE_NOT_FOUND))
804 {
805 errno = ENOENT;
806 }
807 return ret;
808 }
809 #else
810 return rename (from, to);
811 #endif
812 }
813
814 /* Changing directory. */
815
816 int
817 __gnat_chdir (char *path)
818 {
819 #if defined (__MINGW32__) && ! defined (__vxworks) && ! defined (IS_CROSS)
820 {
821 TCHAR wpath[GNAT_MAX_PATH_LEN];
822
823 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
824 return _tchdir (wpath);
825 }
826 #else
827 return chdir (path);
828 #endif
829 }
830
831 /* Removing a directory. */
832
833 int
834 __gnat_rmdir (char *path)
835 {
836 #if defined (__MINGW32__) && ! defined (__vxworks) && ! defined (IS_CROSS)
837 {
838 TCHAR wpath[GNAT_MAX_PATH_LEN];
839
840 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
841 return _trmdir (wpath);
842 }
843 #elif defined (VTHREADS)
844 /* rmdir not available */
845 return -1;
846 #else
847 return rmdir (path);
848 #endif
849 }
850
851 #if defined (_WIN32) || defined (__linux__) || defined (__sun__) \
852 || defined (__FreeBSD__) || defined(__DragonFly__) || defined (__QNX__)
853 #define HAS_TARGET_WCHAR_T
854 #endif
855
856 #ifdef HAS_TARGET_WCHAR_T
857 #include <wchar.h>
858 #endif
859
860 int
861 __gnat_fputwc(int c, FILE *stream)
862 {
863 #ifdef HAS_TARGET_WCHAR_T
864 return fputwc ((wchar_t)c, stream);
865 #else
866 return fputc (c, stream);
867 #endif
868 }
869
870 FILE *
871 __gnat_fopen (char *path, char *mode, int encoding ATTRIBUTE_UNUSED)
872 {
873 #if defined (_WIN32) && ! defined (__vxworks) && ! defined (IS_CROSS)
874 TCHAR wpath[GNAT_MAX_PATH_LEN];
875 TCHAR wmode[10];
876
877 S2WS (wmode, mode, 10);
878
879 if (encoding == Encoding_Unspecified)
880 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
881 else if (encoding == Encoding_UTF8)
882 S2WSU (wpath, path, GNAT_MAX_PATH_LEN);
883 else
884 S2WS (wpath, path, GNAT_MAX_PATH_LEN);
885
886 return _tfopen (wpath, wmode);
887
888 #else
889 return GNAT_FOPEN (path, mode);
890 #endif
891 }
892
893 FILE *
894 __gnat_freopen (char *path,
895 char *mode,
896 FILE *stream,
897 int encoding ATTRIBUTE_UNUSED)
898 {
899 #if defined (_WIN32) && ! defined (__vxworks) && ! defined (IS_CROSS)
900 TCHAR wpath[GNAT_MAX_PATH_LEN];
901 TCHAR wmode[10];
902
903 S2WS (wmode, mode, 10);
904
905 if (encoding == Encoding_Unspecified)
906 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
907 else if (encoding == Encoding_UTF8)
908 S2WSU (wpath, path, GNAT_MAX_PATH_LEN);
909 else
910 S2WS (wpath, path, GNAT_MAX_PATH_LEN);
911
912 return _tfreopen (wpath, wmode, stream);
913 #else
914 return freopen (path, mode, stream);
915 #endif
916 }
917
918 int
919 __gnat_open_read (char *path, int fmode)
920 {
921 int fd;
922 int o_fmode = O_BINARY;
923
924 if (fmode)
925 o_fmode = O_TEXT;
926
927 #if defined (__vxworks)
928 fd = open (path, O_RDONLY | o_fmode, 0444);
929 #elif defined (__MINGW32__)
930 {
931 TCHAR wpath[GNAT_MAX_PATH_LEN];
932
933 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
934 fd = _topen (wpath, O_RDONLY | o_fmode, 0444);
935 }
936 #else
937 fd = GNAT_OPEN (path, O_RDONLY | o_fmode);
938 #endif
939
940 return fd < 0 ? -1 : fd;
941 }
942
943 #if defined (__MINGW32__)
944 #define PERM (S_IREAD | S_IWRITE)
945 #else
946 #define PERM (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
947 #endif
948
949 int
950 __gnat_open_rw (char *path, int fmode)
951 {
952 int fd;
953 int o_fmode = O_BINARY;
954
955 if (fmode)
956 o_fmode = O_TEXT;
957
958 #if defined (__MINGW32__)
959 {
960 TCHAR wpath[GNAT_MAX_PATH_LEN];
961
962 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
963 fd = _topen (wpath, O_RDWR | o_fmode, PERM);
964 }
965 #else
966 fd = GNAT_OPEN (path, O_RDWR | o_fmode, PERM);
967 #endif
968
969 return fd < 0 ? -1 : fd;
970 }
971
972 int
973 __gnat_open_create (char *path, int fmode)
974 {
975 int fd;
976 int o_fmode = O_BINARY;
977
978 if (fmode)
979 o_fmode = O_TEXT;
980
981 #if defined (__MINGW32__)
982 {
983 TCHAR wpath[GNAT_MAX_PATH_LEN];
984
985 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
986 fd = _topen (wpath, O_WRONLY | O_CREAT | O_TRUNC | o_fmode, PERM);
987 }
988 #else
989 fd = GNAT_OPEN (path, O_WRONLY | O_CREAT | O_TRUNC | o_fmode, PERM);
990 #endif
991
992 return fd < 0 ? -1 : fd;
993 }
994
995 int
996 __gnat_create_output_file (char *path)
997 {
998 int fd;
999 #if defined (__MINGW32__)
1000 {
1001 TCHAR wpath[GNAT_MAX_PATH_LEN];
1002
1003 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
1004 fd = _topen (wpath, O_WRONLY | O_CREAT | O_TRUNC | O_TEXT, PERM);
1005 }
1006 #else
1007 fd = GNAT_OPEN (path, O_WRONLY | O_CREAT | O_TRUNC | O_TEXT, PERM);
1008 #endif
1009
1010 return fd < 0 ? -1 : fd;
1011 }
1012
1013 int
1014 __gnat_create_output_file_new (char *path)
1015 {
1016 int fd;
1017 #if defined (__MINGW32__)
1018 {
1019 TCHAR wpath[GNAT_MAX_PATH_LEN];
1020
1021 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
1022 fd = _topen (wpath, O_WRONLY | O_CREAT | O_TRUNC | O_TEXT | O_EXCL, PERM);
1023 }
1024 #else
1025 fd = GNAT_OPEN (path, O_WRONLY | O_CREAT | O_TRUNC | O_TEXT | O_EXCL, PERM);
1026 #endif
1027
1028 return fd < 0 ? -1 : fd;
1029 }
1030
1031 int
1032 __gnat_open_append (char *path, int fmode)
1033 {
1034 int fd;
1035 int o_fmode = O_BINARY;
1036
1037 if (fmode)
1038 o_fmode = O_TEXT;
1039
1040 #if defined (__MINGW32__)
1041 {
1042 TCHAR wpath[GNAT_MAX_PATH_LEN];
1043
1044 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
1045 fd = _topen (wpath, O_WRONLY | O_CREAT | O_APPEND | o_fmode, PERM);
1046 }
1047 #else
1048 fd = GNAT_OPEN (path, O_WRONLY | O_CREAT | O_APPEND | o_fmode, PERM);
1049 #endif
1050
1051 return fd < 0 ? -1 : fd;
1052 }
1053
1054 /* Open a new file. Return error (-1) if the file already exists. */
1055
1056 int
1057 __gnat_open_new (char *path, int fmode)
1058 {
1059 int fd;
1060 int o_fmode = O_BINARY;
1061
1062 if (fmode)
1063 o_fmode = O_TEXT;
1064
1065 #if defined (__MINGW32__)
1066 {
1067 TCHAR wpath[GNAT_MAX_PATH_LEN];
1068
1069 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
1070 fd = _topen (wpath, O_WRONLY | O_CREAT | O_EXCL | o_fmode, PERM);
1071 }
1072 #else
1073 fd = GNAT_OPEN (path, O_WRONLY | O_CREAT | O_EXCL | o_fmode, PERM);
1074 #endif
1075
1076 return fd < 0 ? -1 : fd;
1077 }
1078
1079 /* Open a new temp file. Return error (-1) if the file already exists. */
1080
1081 int
1082 __gnat_open_new_temp (char *path, int fmode)
1083 {
1084 int fd;
1085 int o_fmode = O_BINARY;
1086
1087 strcpy (path, "GNAT-XXXXXX");
1088
1089 #if (defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) \
1090 || defined (__linux__) || defined (__GLIBC__) || defined (__ANDROID__) \
1091 || defined (__DragonFly__) || defined (__QNX__)) && !defined (__vxworks)
1092 return mkstemp (path);
1093 #elif defined (__Lynx__)
1094 mktemp (path);
1095 #else
1096 if (mktemp (path) == NULL)
1097 return -1;
1098 #endif
1099
1100 if (fmode)
1101 o_fmode = O_TEXT;
1102
1103 fd = GNAT_OPEN (path, O_WRONLY | O_CREAT | O_EXCL | o_fmode, PERM);
1104 return fd < 0 ? -1 : fd;
1105 }
1106
1107 int
1108 __gnat_open (char *path, int fmode)
1109 {
1110 int fd;
1111
1112 #if defined (__MINGW32__)
1113 {
1114 TCHAR wpath[GNAT_MAX_PATH_LEN];
1115
1116 S2WSC (wpath, path, GNAT_MAX_PATH_LEN);
1117 fd = _topen (wpath, fmode, PERM);
1118 }
1119 #else
1120 fd = GNAT_OPEN (path, fmode, PERM);
1121 #endif
1122
1123 return fd < 0 ? -1 : fd;
1124 }
1125
1126 /****************************************************************
1127 ** Perform a call to GNAT_STAT or GNAT_FSTAT, and extract as much information
1128 ** as possible from it, storing the result in a cache for later reuse
1129 ****************************************************************/
1130
1131 void
1132 __gnat_stat_to_attr (int fd, char* name, struct file_attributes* attr)
1133 {
1134 GNAT_STRUCT_STAT statbuf;
1135 int ret, error;
1136
1137 if (fd != -1) {
1138 /* GNAT_FSTAT returns -1 and sets errno for failure */
1139 ret = GNAT_FSTAT (fd, &statbuf);
1140 error = ret ? errno : 0;
1141
1142 } else {
1143 /* __gnat_stat returns errno value directly */
1144 error = __gnat_stat (name, &statbuf);
1145 ret = error ? -1 : 0;
1146 }
1147
1148 /*
1149 * A missing file is reported as an attr structure with error == 0 and
1150 * exists == 0.
1151 */
1152
1153 if (error == 0 || error == ENOENT)
1154 attr->error = 0;
1155 else
1156 attr->error = error;
1157
1158 attr->regular = (!ret && S_ISREG (statbuf.st_mode));
1159 attr->directory = (!ret && S_ISDIR (statbuf.st_mode));
1160
1161 if (!attr->regular)
1162 attr->file_length = 0;
1163 else
1164 /* st_size may be 32 bits, or 64 bits which is converted to long. We
1165 don't return a useful value for files larger than 2 gigabytes in
1166 either case. */
1167 attr->file_length = statbuf.st_size; /* all systems */
1168
1169 attr->exists = !ret;
1170
1171 #if !defined (_WIN32)
1172 /* on Windows requires extra system call, see __gnat_is_readable_file_attr */
1173 attr->readable = (!ret && (statbuf.st_mode & S_IRUSR));
1174 attr->writable = (!ret && (statbuf.st_mode & S_IWUSR));
1175 attr->executable = (!ret && (statbuf.st_mode & S_IXUSR));
1176 #endif
1177
1178 if (ret != 0) {
1179 attr->timestamp = (OS_Time)-1;
1180 } else {
1181 attr->timestamp = (OS_Time)statbuf.st_mtime;
1182 }
1183 }
1184
1185 /****************************************************************
1186 ** Return the number of bytes in the specified file
1187 ****************************************************************/
1188
1189 __int64
1190 __gnat_file_length_attr (int fd, char* name, struct file_attributes* attr)
1191 {
1192 if (attr->file_length == -1) {
1193 __gnat_stat_to_attr (fd, name, attr);
1194 }
1195
1196 return attr->file_length;
1197 }
1198
1199 __int64
1200 __gnat_file_length (int fd)
1201 {
1202 struct file_attributes attr;
1203 __gnat_reset_attributes (&attr);
1204 return __gnat_file_length_attr (fd, NULL, &attr);
1205 }
1206
1207 long
1208 __gnat_file_length_long (int fd)
1209 {
1210 struct file_attributes attr;
1211 __gnat_reset_attributes (&attr);
1212 return (long)__gnat_file_length_attr (fd, NULL, &attr);
1213 }
1214
1215 __int64
1216 __gnat_named_file_length (char *name)
1217 {
1218 struct file_attributes attr;
1219 __gnat_reset_attributes (&attr);
1220 return __gnat_file_length_attr (-1, name, &attr);
1221 }
1222
1223 /* Create a temporary filename and put it in string pointed to by
1224 TMP_FILENAME. */
1225
1226 void
1227 __gnat_tmp_name (char *tmp_filename)
1228 {
1229 #if defined (__MINGW32__)
1230 {
1231 char *pname;
1232 char prefix[25];
1233
1234 /* tempnam tries to create a temporary file in directory pointed to by
1235 TMP environment variable, in c:\temp if TMP is not set, and in
1236 directory specified by P_tmpdir in stdio.h if c:\temp does not
1237 exist. The filename will be created with the prefix "gnat-". */
1238
1239 sprintf (prefix, "gnat-%d-", (int)getpid());
1240 pname = (char *) _tempnam ("c:\\temp", prefix);
1241
1242 /* if pname is NULL, the file was not created properly, the disk is full
1243 or there is no more free temporary files */
1244
1245 if (pname == NULL)
1246 *tmp_filename = '\0';
1247
1248 /* If pname start with a back slash and not path information it means that
1249 the filename is valid for the current working directory. */
1250
1251 else if (pname[0] == '\\')
1252 {
1253 strcpy (tmp_filename, ".\\");
1254 strcat (tmp_filename, pname+1);
1255 }
1256 else
1257 strcpy (tmp_filename, pname);
1258
1259 free (pname);
1260 }
1261
1262 #elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__) \
1263 || defined (__OpenBSD__) || defined (__GLIBC__) || defined (__ANDROID__) \
1264 || defined (__DragonFly__) || defined (__QNX__)
1265 #define MAX_SAFE_PATH 1000
1266 char *tmpdir = getenv ("TMPDIR");
1267
1268 /* If tmpdir is longer than MAX_SAFE_PATH, revert to default value to avoid
1269 a buffer overflow. */
1270 if (tmpdir == NULL || strlen (tmpdir) > MAX_SAFE_PATH)
1271 #ifdef __ANDROID__
1272 strcpy (tmp_filename, "/cache/gnat-XXXXXX");
1273 #else
1274 strcpy (tmp_filename, "/tmp/gnat-XXXXXX");
1275 #endif
1276 else
1277 sprintf (tmp_filename, "%s/gnat-XXXXXX", tmpdir);
1278
1279 close (mkstemp(tmp_filename));
1280 #elif defined (__vxworks) && !defined (VTHREADS)
1281 int index;
1282 char *pos;
1283 char *savepos;
1284 static ushort_t seed = 0; /* used to generate unique name */
1285
1286 /* Generate a unique name. */
1287 strcpy (tmp_filename, "tmp");
1288
1289 index = 5;
1290 savepos = pos = tmp_filename + strlen (tmp_filename) + index;
1291 *pos = '\0';
1292
1293 while (1)
1294 {
1295 FILE *f;
1296 ushort_t t;
1297
1298 /* Fill up the name buffer from the last position. */
1299 seed++;
1300 for (t = seed; --index >= 0; t >>= 3)
1301 *--pos = '0' + (t & 07);
1302
1303 /* Check to see if its unique, if not bump the seed and try again. */
1304 f = fopen (tmp_filename, "r");
1305 if (f == NULL)
1306 break;
1307 fclose (f);
1308 pos = savepos;
1309 index = 5;
1310 }
1311 #else
1312 tmpnam (tmp_filename);
1313 #endif
1314 }
1315
1316 /* Open directory and returns a DIR pointer. */
1317
1318 DIR* __gnat_opendir (char *name)
1319 {
1320 #if defined (__MINGW32__)
1321 TCHAR wname[GNAT_MAX_PATH_LEN];
1322
1323 S2WSC (wname, name, GNAT_MAX_PATH_LEN);
1324 return (DIR*)_topendir (wname);
1325
1326 #else
1327 return opendir (name);
1328 #endif
1329 }
1330
1331 /* Read the next entry in a directory. The returned string points somewhere
1332 in the buffer. */
1333
1334 #if defined (__sun__)
1335 /* For Solaris, be sure to use the 64-bit version, otherwise NFS reads may
1336 fail with EOVERFLOW if the server uses 64-bit cookies. */
1337 #define dirent dirent64
1338 #define readdir readdir64
1339 #endif
1340
1341 char *
1342 __gnat_readdir (DIR *dirp, char *buffer, int *len)
1343 {
1344 #if defined (__MINGW32__)
1345 struct _tdirent *dirent = _treaddir ((_TDIR*)dirp);
1346
1347 if (dirent != NULL)
1348 {
1349 WS2SC (buffer, dirent->d_name, GNAT_MAX_PATH_LEN);
1350 *len = strlen (buffer);
1351
1352 return buffer;
1353 }
1354 else
1355 return NULL;
1356
1357 #elif defined (HAVE_READDIR_R)
1358 /* If possible, try to use the thread-safe version. */
1359 if (readdir_r (dirp, buffer) != NULL)
1360 {
1361 *len = strlen (((struct dirent*) buffer)->d_name);
1362 return ((struct dirent*) buffer)->d_name;
1363 }
1364 else
1365 return NULL;
1366
1367 #else
1368 struct dirent *dirent = (struct dirent *) readdir (dirp);
1369
1370 if (dirent != NULL)
1371 {
1372 strcpy (buffer, dirent->d_name);
1373 *len = strlen (buffer);
1374 return buffer;
1375 }
1376 else
1377 return NULL;
1378
1379 #endif
1380 }
1381
1382 /* Close a directory entry. */
1383
1384 int __gnat_closedir (DIR *dirp)
1385 {
1386 #if defined (__MINGW32__)
1387 return _tclosedir ((_TDIR*)dirp);
1388
1389 #else
1390 return closedir (dirp);
1391 #endif
1392 }
1393
1394 /* Returns 1 if readdir is thread safe, 0 otherwise. */
1395
1396 int
1397 __gnat_readdir_is_thread_safe (void)
1398 {
1399 #ifdef HAVE_READDIR_R
1400 return 1;
1401 #else
1402 return 0;
1403 #endif
1404 }
1405
1406 #if defined (_WIN32)
1407 /* Number of seconds between <Jan 1st 1601> and <Jan 1st 1970>. */
1408 static const unsigned long long w32_epoch_offset = 11644473600ULL;
1409
1410 /* Returns the file modification timestamp using Win32 routines which are
1411 immune against daylight saving time change. It is in fact not possible to
1412 use fstat for this purpose as the DST modify the st_mtime field of the
1413 stat structure. */
1414
1415 static time_t
1416 win32_filetime (HANDLE h)
1417 {
1418 union
1419 {
1420 FILETIME ft_time;
1421 unsigned long long ull_time;
1422 } t_write;
1423
1424 /* GetFileTime returns FILETIME data which are the number of 100 nanosecs
1425 since <Jan 1st 1601>. This function must return the number of seconds
1426 since <Jan 1st 1970>. */
1427
1428 if (GetFileTime (h, NULL, NULL, &t_write.ft_time))
1429 return (time_t) (t_write.ull_time / 10000000ULL - w32_epoch_offset);
1430 return (time_t) 0;
1431 }
1432
1433 /* As above but starting from a FILETIME. */
1434 static void
1435 f2t (const FILETIME *ft, __time64_t *t)
1436 {
1437 union
1438 {
1439 FILETIME ft_time;
1440 unsigned long long ull_time;
1441 } t_write;
1442
1443 t_write.ft_time = *ft;
1444 *t = (__time64_t) (t_write.ull_time / 10000000ULL - w32_epoch_offset);
1445 }
1446 #endif
1447
1448 /* Return a GNAT time stamp given a file name. */
1449
1450 OS_Time
1451 __gnat_file_time_name_attr (char* name, struct file_attributes* attr)
1452 {
1453 if (attr->timestamp == (OS_Time)-2) {
1454 #if defined (_WIN32)
1455 BOOL res;
1456 WIN32_FILE_ATTRIBUTE_DATA fad;
1457 __time64_t ret = -1;
1458 TCHAR wname[GNAT_MAX_PATH_LEN];
1459 S2WSC (wname, name, GNAT_MAX_PATH_LEN);
1460
1461 if ((res = GetFileAttributesEx (wname, GetFileExInfoStandard, &fad)))
1462 f2t (&fad.ftLastWriteTime, &ret);
1463 attr->timestamp = (OS_Time) ret;
1464 #else
1465 __gnat_stat_to_attr (-1, name, attr);
1466 #endif
1467 }
1468 return attr->timestamp;
1469 }
1470
1471 OS_Time
1472 __gnat_file_time_name (char *name)
1473 {
1474 struct file_attributes attr;
1475 __gnat_reset_attributes (&attr);
1476 return __gnat_file_time_name_attr (name, &attr);
1477 }
1478
1479 /* Return a GNAT time stamp given a file descriptor. */
1480
1481 OS_Time
1482 __gnat_file_time_fd_attr (int fd, struct file_attributes* attr)
1483 {
1484 if (attr->timestamp == (OS_Time)-2) {
1485 #if defined (_WIN32)
1486 HANDLE h = (HANDLE) _get_osfhandle (fd);
1487 time_t ret = win32_filetime (h);
1488 attr->timestamp = (OS_Time) ret;
1489
1490 #else
1491 __gnat_stat_to_attr (fd, NULL, attr);
1492 #endif
1493 }
1494
1495 return attr->timestamp;
1496 }
1497
1498 OS_Time
1499 __gnat_file_time_fd (int fd)
1500 {
1501 struct file_attributes attr;
1502 __gnat_reset_attributes (&attr);
1503 return __gnat_file_time_fd_attr (fd, &attr);
1504 }
1505
1506 extern long long __gnat_file_time(char* name)
1507 {
1508 long long result;
1509
1510 if (name == NULL) {
1511 return LLONG_MIN;
1512 }
1513 /* Number of seconds between <Jan 1st 1970> and <Jan 1st 2150>. */
1514 static const long long ada_epoch_offset = (136 * 365 + 44 * 366) * 86400LL;
1515 #if defined(_WIN32)
1516
1517 /* Number of 100 nanoseconds between <Jan 1st 1601> and <Jan 1st 2150>. */
1518 static const long long w32_epoch_offset =
1519 (11644473600LL + ada_epoch_offset) * 1E7;
1520
1521 WIN32_FILE_ATTRIBUTE_DATA fad;
1522 union
1523 {
1524 FILETIME ft_time;
1525 long long ll_time;
1526 } t_write;
1527
1528 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
1529 int name_len;
1530
1531 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
1532 name_len = _tcslen (wname);
1533
1534 if (name_len > GNAT_MAX_PATH_LEN)
1535 return LLONG_MIN;
1536
1537 if (!GetFileAttributesEx(wname, GetFileExInfoStandard, &fad)) {
1538 return LLONG_MIN;
1539 }
1540
1541 t_write.ft_time = fad.ftLastWriteTime;
1542
1543 #if defined(__GNUG__) && __GNUG__ <= 4
1544 result = (t_write.ll_time - w32_epoch_offset) * 100;
1545 #else
1546 /* Next code similar to (t_write.ll_time - w32_epoch_offset) * 100
1547 but on overflow returns LLONG_MIN value. */
1548
1549 if (__builtin_ssubll_overflow(t_write.ll_time, w32_epoch_offset, &result)) {
1550 return LLONG_MIN;
1551 }
1552
1553 if (__builtin_smulll_overflow(result, 100, &result)) {
1554 return LLONG_MIN;
1555 }
1556 #endif
1557
1558 #else
1559
1560 struct stat sb;
1561 if (stat(name, &sb) != 0) {
1562 return LLONG_MIN;
1563 }
1564
1565 #if defined(__GNUG__) && __GNUG__ <= 4
1566 result = (sb.st_mtime - ada_epoch_offset) * 1E9;
1567 #if defined(st_mtime)
1568 result += sb.st_mtim.tv_nsec;
1569 #endif
1570 #else
1571 /* Next code similar to
1572 (sb.st_mtime - ada_epoch_offset) * 1E9 + sb.st_mtim.tv_nsec
1573 but on overflow returns LLONG_MIN value. */
1574
1575 if (__builtin_ssubll_overflow(sb.st_mtime, ada_epoch_offset, &result)) {
1576 return LLONG_MIN;
1577 }
1578
1579 if (__builtin_smulll_overflow(result, 1E9, &result)) {
1580 return LLONG_MIN;
1581 }
1582
1583 #if defined(st_mtime)
1584 if (__builtin_saddll_overflow(result, sb.st_mtim.tv_nsec, &result)) {
1585 return LLONG_MIN;
1586 }
1587 #endif
1588 #endif
1589 #endif
1590 return result;
1591 }
1592
1593 /* Set the file time stamp. */
1594
1595 void
1596 __gnat_set_file_time_name (char *name, OS_Time time_stamp)
1597 {
1598 #if defined (__vxworks)
1599
1600 /* Code to implement __gnat_set_file_time_name for these systems. */
1601
1602 #elif defined (_WIN32)
1603 union
1604 {
1605 FILETIME ft_time;
1606 unsigned long long ull_time;
1607 } t_write;
1608 TCHAR wname[GNAT_MAX_PATH_LEN];
1609
1610 S2WSC (wname, name, GNAT_MAX_PATH_LEN);
1611
1612 HANDLE h = CreateFile
1613 (wname, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
1614 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
1615 NULL);
1616 if (h == INVALID_HANDLE_VALUE)
1617 return;
1618 /* Add number of seconds between <Jan 1st 1601> and <Jan 1st 1970> */
1619 t_write.ull_time = ((unsigned long long)time_stamp + w32_epoch_offset);
1620 /* Convert to 100 nanosecond units */
1621 t_write.ull_time *= 10000000ULL;
1622
1623 SetFileTime(h, NULL, NULL, &t_write.ft_time);
1624 CloseHandle (h);
1625 return;
1626
1627 #else
1628 struct utimbuf utimbuf;
1629 time_t t;
1630
1631 /* Set modification time to requested time. */
1632 utimbuf.modtime = (time_t) time_stamp;
1633
1634 /* Set access time to now in local time. */
1635 t = time (NULL);
1636 utimbuf.actime = mktime (localtime (&t));
1637
1638 utime (name, &utimbuf);
1639 #endif
1640 }
1641
1642 /* Get the list of installed standard libraries from the
1643 HKEY_LOCAL_MACHINE\SOFTWARE\Ada Core Technologies\GNAT\Standard Libraries
1644 key. */
1645
1646 char *
1647 __gnat_get_libraries_from_registry (void)
1648 {
1649 char *result = (char *) xmalloc (1);
1650
1651 result[0] = '\0';
1652
1653 #if defined (_WIN32) && ! defined (__vxworks) && ! defined (IS_CROSS)
1654
1655 HKEY reg_key;
1656 DWORD name_size, value_size;
1657 char name[256];
1658 char value[256];
1659 DWORD type;
1660 DWORD index;
1661 LONG res;
1662
1663 /* First open the key. */
1664 res = RegOpenKeyExA (HKEY_LOCAL_MACHINE, "SOFTWARE", 0, KEY_READ, &reg_key);
1665
1666 if (res == ERROR_SUCCESS)
1667 res = RegOpenKeyExA (reg_key, "Ada Core Technologies", 0,
1668 KEY_READ, &reg_key);
1669
1670 if (res == ERROR_SUCCESS)
1671 res = RegOpenKeyExA (reg_key, "GNAT", 0, KEY_READ, &reg_key);
1672
1673 if (res == ERROR_SUCCESS)
1674 res = RegOpenKeyExA (reg_key, "Standard Libraries", 0, KEY_READ, &reg_key);
1675
1676 /* If the key exists, read out all the values in it and concatenate them
1677 into a path. */
1678 for (index = 0; res == ERROR_SUCCESS; index++)
1679 {
1680 value_size = name_size = 256;
1681 res = RegEnumValueA (reg_key, index, name, &name_size, 0,
1682 &type, (LPBYTE)value, &value_size);
1683
1684 if (res == ERROR_SUCCESS && type == REG_SZ)
1685 {
1686 char *old_result = result;
1687
1688 result = (char *) xmalloc (strlen (old_result) + value_size + 2);
1689 strcpy (result, old_result);
1690 strcat (result, value);
1691 strcat (result, ";");
1692 free (old_result);
1693 }
1694 }
1695
1696 /* Remove the trailing ";". */
1697 if (result[0] != 0)
1698 result[strlen (result) - 1] = 0;
1699
1700 #endif
1701 return result;
1702 }
1703
1704 /* Query information for the given file NAME and return it in STATBUF.
1705 * Returns 0 for success, or errno value for failure.
1706 */
1707 int
1708 __gnat_stat (char *name, GNAT_STRUCT_STAT *statbuf)
1709 {
1710 #ifdef __MINGW32__
1711 WIN32_FILE_ATTRIBUTE_DATA fad;
1712 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
1713 int name_len;
1714 BOOL res;
1715 DWORD error;
1716
1717 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
1718 name_len = _tcslen (wname);
1719
1720 if (name_len > GNAT_MAX_PATH_LEN)
1721 return EINVAL;
1722
1723 ZeroMemory (statbuf, sizeof(GNAT_STRUCT_STAT));
1724
1725 res = GetFileAttributesEx (wname, GetFileExInfoStandard, &fad);
1726
1727 if (res == FALSE) {
1728 error = GetLastError();
1729
1730 /* Check file existence using GetFileAttributes() which does not fail on
1731 special Windows files like con:, aux:, nul: etc... */
1732
1733 if (GetFileAttributes(wname) != INVALID_FILE_ATTRIBUTES) {
1734 /* Just pretend that it is a regular and readable file */
1735 statbuf->st_mode = S_IFREG | S_IREAD | S_IWRITE;
1736 return 0;
1737 }
1738
1739 switch (error) {
1740 case ERROR_ACCESS_DENIED:
1741 case ERROR_SHARING_VIOLATION:
1742 case ERROR_LOCK_VIOLATION:
1743 case ERROR_SHARING_BUFFER_EXCEEDED:
1744 return EACCES;
1745 case ERROR_BUFFER_OVERFLOW:
1746 return ENAMETOOLONG;
1747 case ERROR_NOT_ENOUGH_MEMORY:
1748 return ENOMEM;
1749 default:
1750 return ENOENT;
1751 }
1752 }
1753
1754 f2t (&fad.ftCreationTime, &statbuf->st_ctime);
1755 f2t (&fad.ftLastWriteTime, &statbuf->st_mtime);
1756 f2t (&fad.ftLastAccessTime, &statbuf->st_atime);
1757
1758 statbuf->st_size =
1759 (__int64)fad.nFileSizeLow | (__int64)fad.nFileSizeHigh << 32;
1760
1761 /* We do not have the S_IEXEC attribute, but this is not used on GNAT. */
1762 statbuf->st_mode = S_IREAD;
1763
1764 if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1765 statbuf->st_mode |= S_IFDIR;
1766 else
1767 statbuf->st_mode |= S_IFREG;
1768
1769 if (!(fad.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1770 statbuf->st_mode |= S_IWRITE;
1771
1772 return 0;
1773
1774 #else
1775 return GNAT_STAT (name, statbuf) == 0 ? 0 : errno;
1776 #endif
1777 }
1778
1779 /*************************************************************************
1780 ** Check whether a file exists
1781 *************************************************************************/
1782
1783 int
1784 __gnat_file_exists_attr (char* name, struct file_attributes* attr)
1785 {
1786 if (attr->exists == ATTR_UNSET)
1787 __gnat_stat_to_attr (-1, name, attr);
1788
1789 return attr->exists;
1790 }
1791
1792 int
1793 __gnat_file_exists (char *name)
1794 {
1795 struct file_attributes attr;
1796 __gnat_reset_attributes (&attr);
1797 return __gnat_file_exists_attr (name, &attr);
1798 }
1799
1800 /**********************************************************************
1801 ** Whether name is an absolute path
1802 **********************************************************************/
1803
1804 int
1805 __gnat_is_absolute_path (char *name, int length)
1806 {
1807 #ifdef __vxworks
1808 /* On VxWorks systems, an absolute path can be represented (depending on
1809 the host platform) as either /dir/file, or device:/dir/file, or
1810 device:drive_letter:/dir/file. */
1811
1812 int index;
1813
1814 if (name[0] == '/')
1815 return 1;
1816
1817 for (index = 0; index < length; index++)
1818 {
1819 if (name[index] == ':' &&
1820 ((name[index + 1] == '/') ||
1821 (isalpha (name[index + 1]) && index + 2 <= length &&
1822 name[index + 2] == '/')))
1823 return 1;
1824
1825 else if (name[index] == '/')
1826 return 0;
1827 }
1828 return 0;
1829 #else
1830 return (length != 0) &&
1831 (IS_DIRECTORY_SEPARATOR(*name)
1832 #if defined (WINNT) || defined(__DJGPP__)
1833 || (length > 2 && ISALPHA (name[0]) && name[1] == ':'
1834 && IS_DIRECTORY_SEPARATOR(name[2]))
1835 #endif
1836 );
1837 #endif
1838 }
1839
1840 int
1841 __gnat_is_regular_file_attr (char* name, struct file_attributes* attr)
1842 {
1843 if (attr->regular == ATTR_UNSET)
1844 __gnat_stat_to_attr (-1, name, attr);
1845
1846 return attr->regular;
1847 }
1848
1849 int
1850 __gnat_is_regular_file (char *name)
1851 {
1852 struct file_attributes attr;
1853
1854 __gnat_reset_attributes (&attr);
1855 return __gnat_is_regular_file_attr (name, &attr);
1856 }
1857
1858 int
1859 __gnat_is_regular_file_fd (int fd)
1860 {
1861 int ret;
1862 GNAT_STRUCT_STAT statbuf;
1863
1864 ret = GNAT_FSTAT (fd, &statbuf);
1865 return (!ret && S_ISREG (statbuf.st_mode));
1866 }
1867
1868 int
1869 __gnat_is_directory_attr (char* name, struct file_attributes* attr)
1870 {
1871 if (attr->directory == ATTR_UNSET)
1872 __gnat_stat_to_attr (-1, name, attr);
1873
1874 return attr->directory;
1875 }
1876
1877 int
1878 __gnat_is_directory (char *name)
1879 {
1880 struct file_attributes attr;
1881
1882 __gnat_reset_attributes (&attr);
1883 return __gnat_is_directory_attr (name, &attr);
1884 }
1885
1886 #if defined (_WIN32)
1887
1888 /* Returns the same constant as GetDriveType but takes a pathname as
1889 argument. */
1890
1891 static UINT
1892 GetDriveTypeFromPath (TCHAR *wfullpath)
1893 {
1894 TCHAR wdrv[MAX_PATH];
1895 TCHAR wpath[MAX_PATH];
1896 TCHAR wfilename[MAX_PATH];
1897 TCHAR wext[MAX_PATH];
1898
1899 _tsplitpath (wfullpath, wdrv, wpath, wfilename, wext);
1900
1901 if (_tcslen (wdrv) != 0)
1902 {
1903 /* we have a drive specified. */
1904 _tcscat (wdrv, _T("\\"));
1905 return GetDriveType (wdrv);
1906 }
1907 else
1908 {
1909 /* No drive specified. */
1910
1911 /* Is this a relative path, if so get current drive type. */
1912 if (wpath[0] != _T('\\') ||
1913 (_tcslen (wpath) > 2 && wpath[0] == _T('\\')
1914 && wpath[1] != _T('\\')))
1915 return GetDriveType (NULL);
1916
1917 UINT result = GetDriveType (wpath);
1918
1919 /* Cannot guess the drive type, is this \\.\ ? */
1920
1921 if (result == DRIVE_NO_ROOT_DIR &&
1922 _tcslen (wpath) >= 4 && wpath[0] == _T('\\') && wpath[1] == _T('\\')
1923 && wpath[2] == _T('.') && wpath[3] == _T('\\'))
1924 {
1925 if (_tcslen (wpath) == 4)
1926 _tcscat (wpath, wfilename);
1927
1928 LPTSTR p = &wpath[4];
1929 LPTSTR b = _tcschr (p, _T('\\'));
1930
1931 if (b != NULL)
1932 {
1933 /* logical drive \\.\c\dir\file */
1934 *b++ = _T(':');
1935 *b++ = _T('\\');
1936 *b = _T('\0');
1937 }
1938 else
1939 _tcscat (p, _T(":\\"));
1940
1941 return GetDriveType (p);
1942 }
1943
1944 return result;
1945 }
1946 }
1947
1948 /* This MingW section contains code to work with ACL. */
1949 static int
1950 __gnat_check_OWNER_ACL (TCHAR *wname,
1951 DWORD CheckAccessDesired,
1952 GENERIC_MAPPING CheckGenericMapping)
1953 {
1954 DWORD dwAccessDesired, dwAccessAllowed;
1955 PRIVILEGE_SET PrivilegeSet;
1956 DWORD dwPrivSetSize = sizeof (PRIVILEGE_SET);
1957 BOOL fAccessGranted = FALSE;
1958 HANDLE hToken = NULL;
1959 DWORD nLength = 0;
1960 PSECURITY_DESCRIPTOR pSD = NULL;
1961
1962 GetFileSecurity
1963 (wname, OWNER_SECURITY_INFORMATION |
1964 GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
1965 NULL, 0, &nLength);
1966
1967 if ((pSD = (SECURITY_DESCRIPTOR *) HeapAlloc
1968 (GetProcessHeap (), HEAP_ZERO_MEMORY, nLength)) == NULL)
1969 return 0;
1970
1971 /* Obtain the security descriptor. */
1972
1973 if (!GetFileSecurity
1974 (wname, OWNER_SECURITY_INFORMATION |
1975 GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
1976 pSD, nLength, &nLength))
1977 goto error;
1978
1979 if (!ImpersonateSelf (SecurityImpersonation))
1980 goto error;
1981
1982 if (!OpenThreadToken
1983 (GetCurrentThread(), TOKEN_DUPLICATE | TOKEN_QUERY, FALSE, &hToken))
1984 goto error;
1985
1986 /* Undoes the effect of ImpersonateSelf. */
1987
1988 RevertToSelf ();
1989
1990 /* We want to test for write permissions. */
1991
1992 dwAccessDesired = CheckAccessDesired;
1993
1994 MapGenericMask (&dwAccessDesired, &CheckGenericMapping);
1995
1996 if (!AccessCheck
1997 (pSD , /* security descriptor to check */
1998 hToken, /* impersonation token */
1999 dwAccessDesired, /* requested access rights */
2000 &CheckGenericMapping, /* pointer to GENERIC_MAPPING */
2001 &PrivilegeSet, /* receives privileges used in check */
2002 &dwPrivSetSize, /* size of PrivilegeSet buffer */
2003 &dwAccessAllowed, /* receives mask of allowed access rights */
2004 &fAccessGranted))
2005 goto error;
2006
2007 CloseHandle (hToken);
2008 HeapFree (GetProcessHeap (), 0, pSD);
2009 return fAccessGranted;
2010
2011 error:
2012 if (hToken)
2013 CloseHandle (hToken);
2014 HeapFree (GetProcessHeap (), 0, pSD);
2015 return 0;
2016 }
2017
2018 static void
2019 __gnat_set_OWNER_ACL (TCHAR *wname,
2020 ACCESS_MODE AccessMode,
2021 DWORD AccessPermissions)
2022 {
2023 PACL pOldDACL = NULL;
2024 PACL pNewDACL = NULL;
2025 PSECURITY_DESCRIPTOR pSD = NULL;
2026 EXPLICIT_ACCESS ea;
2027 TCHAR username [100];
2028 DWORD unsize = 100;
2029
2030 /* Get current user, he will act as the owner */
2031
2032 if (!GetUserName (username, &unsize))
2033 return;
2034
2035 if (GetNamedSecurityInfo
2036 (wname,
2037 SE_FILE_OBJECT,
2038 DACL_SECURITY_INFORMATION,
2039 NULL, NULL, &pOldDACL, NULL, &pSD) != ERROR_SUCCESS)
2040 return;
2041
2042 BuildExplicitAccessWithName
2043 (&ea, username, AccessPermissions, (ACCESS_MODE) AccessMode, NO_INHERITANCE);
2044
2045 if (AccessMode == SET_ACCESS)
2046 {
2047 /* SET_ACCESS, we want to set an explicte set of permissions, do not
2048 merge with current DACL. */
2049 if (SetEntriesInAcl (1, &ea, NULL, &pNewDACL) != ERROR_SUCCESS)
2050 return;
2051 }
2052 else
2053 if (SetEntriesInAcl (1, &ea, pOldDACL, &pNewDACL) != ERROR_SUCCESS)
2054 return;
2055
2056 if (SetNamedSecurityInfo
2057 (wname, SE_FILE_OBJECT,
2058 DACL_SECURITY_INFORMATION, NULL, NULL, pNewDACL, NULL) != ERROR_SUCCESS)
2059 return;
2060
2061 LocalFree (pSD);
2062 LocalFree (pNewDACL);
2063 }
2064
2065 /* Check if it is possible to use ACL for wname, the file must not be on a
2066 network drive. */
2067
2068 static int
2069 __gnat_can_use_acl (TCHAR *wname)
2070 {
2071 return __gnat_use_acl && GetDriveTypeFromPath (wname) != DRIVE_REMOTE;
2072 }
2073
2074 #endif /* defined (_WIN32) */
2075
2076 int
2077 __gnat_is_readable_file_attr (char* name, struct file_attributes* attr)
2078 {
2079 if (attr->readable == ATTR_UNSET)
2080 {
2081 #if defined (_WIN32)
2082 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2083 GENERIC_MAPPING GenericMapping;
2084
2085 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2086
2087 if (__gnat_can_use_acl (wname))
2088 {
2089 ZeroMemory (&GenericMapping, sizeof (GENERIC_MAPPING));
2090 GenericMapping.GenericRead = GENERIC_READ;
2091 attr->readable =
2092 __gnat_check_OWNER_ACL (wname, FILE_READ_DATA, GenericMapping);
2093 }
2094 else
2095 attr->readable = GetFileAttributes (wname) != INVALID_FILE_ATTRIBUTES;
2096 #else
2097 __gnat_stat_to_attr (-1, name, attr);
2098 #endif
2099 }
2100
2101 return attr->readable;
2102 }
2103
2104 int
2105 __gnat_is_read_accessible_file (char *name)
2106 {
2107 #if defined (_WIN32)
2108 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2109
2110 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2111
2112 return !_waccess (wname, 4);
2113
2114 #elif defined (__vxworks)
2115 int fd;
2116
2117 if ((fd = open (name, O_RDONLY, 0)) < 0)
2118 return 0;
2119 close (fd);
2120 return 1;
2121
2122 #else
2123 return !access (name, R_OK);
2124 #endif
2125 }
2126
2127 int
2128 __gnat_is_readable_file (char *name)
2129 {
2130 struct file_attributes attr;
2131
2132 __gnat_reset_attributes (&attr);
2133 return __gnat_is_readable_file_attr (name, &attr);
2134 }
2135
2136 int
2137 __gnat_is_writable_file_attr (char* name, struct file_attributes* attr)
2138 {
2139 if (attr->writable == ATTR_UNSET)
2140 {
2141 #if defined (_WIN32)
2142 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2143 GENERIC_MAPPING GenericMapping;
2144
2145 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2146
2147 if (__gnat_can_use_acl (wname))
2148 {
2149 ZeroMemory (&GenericMapping, sizeof (GENERIC_MAPPING));
2150 GenericMapping.GenericWrite = GENERIC_WRITE;
2151
2152 attr->writable = __gnat_check_OWNER_ACL
2153 (wname, FILE_WRITE_DATA | FILE_APPEND_DATA, GenericMapping)
2154 && !(GetFileAttributes (wname) & FILE_ATTRIBUTE_READONLY);
2155 }
2156 else
2157 attr->writable =
2158 !(GetFileAttributes (wname) & FILE_ATTRIBUTE_READONLY);
2159
2160 #else
2161 __gnat_stat_to_attr (-1, name, attr);
2162 #endif
2163 }
2164
2165 return attr->writable;
2166 }
2167
2168 int
2169 __gnat_is_writable_file (char *name)
2170 {
2171 struct file_attributes attr;
2172
2173 __gnat_reset_attributes (&attr);
2174 return __gnat_is_writable_file_attr (name, &attr);
2175 }
2176
2177 int
2178 __gnat_is_write_accessible_file (char *name)
2179 {
2180 #if defined (_WIN32)
2181 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2182
2183 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2184
2185 return !_waccess (wname, 2);
2186
2187 #elif defined (__vxworks)
2188 int fd;
2189
2190 if ((fd = open (name, O_WRONLY, 0)) < 0)
2191 return 0;
2192 close (fd);
2193 return 1;
2194
2195 #else
2196 return !access (name, W_OK);
2197 #endif
2198 }
2199
2200 int
2201 __gnat_is_executable_file_attr (char* name, struct file_attributes* attr)
2202 {
2203 if (attr->executable == ATTR_UNSET)
2204 {
2205 #if defined (_WIN32)
2206 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2207 GENERIC_MAPPING GenericMapping;
2208
2209 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2210
2211 if (__gnat_can_use_acl (wname))
2212 {
2213 ZeroMemory (&GenericMapping, sizeof (GENERIC_MAPPING));
2214 GenericMapping.GenericExecute = GENERIC_EXECUTE;
2215
2216 attr->executable =
2217 __gnat_check_OWNER_ACL (wname, FILE_EXECUTE, GenericMapping);
2218 }
2219 else
2220 {
2221 TCHAR *l, *last = _tcsstr(wname, _T(".exe"));
2222
2223 /* look for last .exe */
2224 if (last)
2225 while ((l = _tcsstr(last+1, _T(".exe"))))
2226 last = l;
2227
2228 attr->executable =
2229 GetFileAttributes (wname) != INVALID_FILE_ATTRIBUTES
2230 && (last - wname) == (int) (_tcslen (wname) - 4);
2231 }
2232 #else
2233 __gnat_stat_to_attr (-1, name, attr);
2234 #endif
2235 }
2236
2237 return attr->regular && attr->executable;
2238 }
2239
2240 int
2241 __gnat_is_executable_file (char *name)
2242 {
2243 struct file_attributes attr;
2244
2245 __gnat_reset_attributes (&attr);
2246 return __gnat_is_executable_file_attr (name, &attr);
2247 }
2248
2249 void
2250 __gnat_set_writable (char *name)
2251 {
2252 #if defined (_WIN32)
2253 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2254
2255 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2256
2257 if (__gnat_can_use_acl (wname))
2258 __gnat_set_OWNER_ACL (wname, GRANT_ACCESS, FILE_GENERIC_WRITE);
2259
2260 SetFileAttributes
2261 (wname, GetFileAttributes (wname) & ~FILE_ATTRIBUTE_READONLY);
2262 #elif ! (defined (__vxworks) && _WRS_VXWORKS_MAJOR < 6)
2263 GNAT_STRUCT_STAT statbuf;
2264
2265 if (GNAT_STAT (name, &statbuf) == 0)
2266 {
2267 statbuf.st_mode = statbuf.st_mode | S_IWUSR;
2268 chmod (name, statbuf.st_mode);
2269 }
2270 #endif
2271 }
2272
2273 /* must match definition in s-os_lib.ads */
2274 #define S_OWNER 1
2275 #define S_GROUP 2
2276 #define S_OTHERS 4
2277
2278 void
2279 __gnat_set_executable (char *name, int mode ATTRIBUTE_UNUSED)
2280 {
2281 #if defined (_WIN32)
2282 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2283
2284 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2285
2286 if (__gnat_can_use_acl (wname))
2287 __gnat_set_OWNER_ACL (wname, GRANT_ACCESS, FILE_GENERIC_EXECUTE);
2288
2289 #elif ! (defined (__vxworks) && _WRS_VXWORKS_MAJOR < 6)
2290 GNAT_STRUCT_STAT statbuf;
2291
2292 if (GNAT_STAT (name, &statbuf) == 0)
2293 {
2294 if (mode & S_OWNER)
2295 statbuf.st_mode = statbuf.st_mode | S_IXUSR;
2296 if (mode & S_GROUP)
2297 statbuf.st_mode = statbuf.st_mode | S_IXGRP;
2298 if (mode & S_OTHERS)
2299 statbuf.st_mode = statbuf.st_mode | S_IXOTH;
2300 chmod (name, statbuf.st_mode);
2301 }
2302 #endif
2303 }
2304
2305 void
2306 __gnat_set_non_writable (char *name)
2307 {
2308 #if defined (_WIN32)
2309 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2310
2311 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2312
2313 if (__gnat_can_use_acl (wname))
2314 __gnat_set_OWNER_ACL
2315 (wname, DENY_ACCESS,
2316 FILE_WRITE_DATA | FILE_APPEND_DATA |
2317 FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES);
2318
2319 SetFileAttributes
2320 (wname, GetFileAttributes (wname) | FILE_ATTRIBUTE_READONLY);
2321 #elif ! (defined (__vxworks) && _WRS_VXWORKS_MAJOR < 6)
2322 GNAT_STRUCT_STAT statbuf;
2323
2324 if (GNAT_STAT (name, &statbuf) == 0)
2325 {
2326 statbuf.st_mode = statbuf.st_mode & 07577;
2327 chmod (name, statbuf.st_mode);
2328 }
2329 #endif
2330 }
2331
2332 void
2333 __gnat_set_readable (char *name)
2334 {
2335 #if defined (_WIN32)
2336 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2337
2338 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2339
2340 if (__gnat_can_use_acl (wname))
2341 __gnat_set_OWNER_ACL (wname, GRANT_ACCESS, FILE_GENERIC_READ);
2342
2343 #elif ! (defined (__vxworks) && _WRS_VXWORKS_MAJOR < 6)
2344 GNAT_STRUCT_STAT statbuf;
2345
2346 if (GNAT_STAT (name, &statbuf) == 0)
2347 {
2348 chmod (name, statbuf.st_mode | S_IREAD);
2349 }
2350 #endif
2351 }
2352
2353 void
2354 __gnat_set_non_readable (char *name)
2355 {
2356 #if defined (_WIN32)
2357 TCHAR wname [GNAT_MAX_PATH_LEN + 2];
2358
2359 S2WSC (wname, name, GNAT_MAX_PATH_LEN + 2);
2360
2361 if (__gnat_can_use_acl (wname))
2362 __gnat_set_OWNER_ACL (wname, DENY_ACCESS, FILE_GENERIC_READ);
2363
2364 #elif ! (defined (__vxworks) && _WRS_VXWORKS_MAJOR < 6)
2365 GNAT_STRUCT_STAT statbuf;
2366
2367 if (GNAT_STAT (name, &statbuf) == 0)
2368 {
2369 chmod (name, statbuf.st_mode & (~S_IREAD));
2370 }
2371 #endif
2372 }
2373
2374 int
2375 __gnat_is_symbolic_link_attr (char* name ATTRIBUTE_UNUSED,
2376 struct file_attributes* attr)
2377 {
2378 if (attr->symbolic_link == ATTR_UNSET)
2379 {
2380 #if defined (__vxworks)
2381 attr->symbolic_link = 0;
2382
2383 #elif defined (_AIX) || defined (__APPLE__) || defined (__unix__)
2384 int ret;
2385 GNAT_STRUCT_STAT statbuf;
2386 ret = GNAT_LSTAT (name, &statbuf);
2387 attr->symbolic_link = (!ret && S_ISLNK (statbuf.st_mode));
2388 #else
2389 attr->symbolic_link = 0;
2390 #endif
2391 }
2392 return attr->symbolic_link;
2393 }
2394
2395 int
2396 __gnat_is_symbolic_link (char *name ATTRIBUTE_UNUSED)
2397 {
2398 struct file_attributes attr;
2399
2400 __gnat_reset_attributes (&attr);
2401 return __gnat_is_symbolic_link_attr (name, &attr);
2402 }
2403
2404 #if defined (__sun__)
2405 /* Using fork on Solaris will duplicate all the threads. fork1, which
2406 duplicates only the active thread, must be used instead, or spawning
2407 subprocess from a program with tasking will lead into numerous problems. */
2408 #define fork fork1
2409 #endif
2410
2411 int
2412 __gnat_portable_spawn (char *args[] ATTRIBUTE_UNUSED)
2413 {
2414 int status ATTRIBUTE_UNUSED = 0;
2415 int finished ATTRIBUTE_UNUSED;
2416 int pid ATTRIBUTE_UNUSED;
2417
2418 #if defined (__vxworks) || defined(__PikeOS__)
2419 return -1;
2420
2421 #elif defined (__DJGPP__) || defined (_WIN32)
2422 /* args[0] must be quotes as it could contain a full pathname with spaces */
2423 char *args_0 = args[0];
2424 args[0] = (char *)xmalloc (strlen (args_0) + 3);
2425 strcpy (args[0], "\"");
2426 strcat (args[0], args_0);
2427 strcat (args[0], "\"");
2428
2429 status = spawnvp (P_WAIT, args_0, (char ** const)args);
2430
2431 /* restore previous value */
2432 free (args[0]);
2433 args[0] = (char *)args_0;
2434
2435 if (status < 0)
2436 return -1;
2437 else
2438 return status;
2439
2440 #else
2441
2442 pid = fork ();
2443 if (pid < 0)
2444 return -1;
2445
2446 if (pid == 0)
2447 {
2448 /* The child. */
2449 execv (args[0], MAYBE_TO_PTR32 (args));
2450
2451 /* execv() returns only on error */
2452 _exit (1);
2453 }
2454
2455 /* The parent. */
2456 finished = waitpid (pid, &status, 0);
2457
2458 if (finished != pid || WIFEXITED (status) == 0)
2459 return -1;
2460
2461 return WEXITSTATUS (status);
2462 #endif
2463
2464 return 0;
2465 }
2466
2467 /* Create a copy of the given file descriptor.
2468 Return -1 if an error occurred. */
2469
2470 int
2471 __gnat_dup (int oldfd)
2472 {
2473 #if defined (__vxworks) && !defined (__RTP__)
2474 /* Not supported on VxWorks 5.x, but supported on VxWorks 6.0 when using
2475 RTPs. */
2476 return -1;
2477 #else
2478 return dup (oldfd);
2479 #endif
2480 }
2481
2482 /* Make newfd be the copy of oldfd, closing newfd first if necessary.
2483 Return -1 if an error occurred. */
2484
2485 int
2486 __gnat_dup2 (int oldfd ATTRIBUTE_UNUSED, int newfd ATTRIBUTE_UNUSED)
2487 {
2488 #if defined (__vxworks) && !defined (__RTP__)
2489 /* Not supported on VxWorks 5.x, but supported on VxWorks 6.0 when using
2490 RTPs. */
2491 return -1;
2492 #elif defined (__PikeOS__)
2493 /* Not supported. */
2494 return -1;
2495 #elif defined (_WIN32)
2496 /* Special case when oldfd and newfd are identical and are the standard
2497 input, output or error as this makes Windows XP hangs. Note that we
2498 do that only for standard file descriptors that are known to be valid. */
2499 if (oldfd == newfd && newfd >= 0 && newfd <= 2)
2500 return newfd;
2501 else
2502 return dup2 (oldfd, newfd);
2503 #else
2504 return dup2 (oldfd, newfd);
2505 #endif
2506 }
2507
2508 int
2509 __gnat_number_of_cpus (void)
2510 {
2511 int cores = 1;
2512
2513 #if defined (_SC_NPROCESSORS_ONLN)
2514 cores = (int) sysconf (_SC_NPROCESSORS_ONLN);
2515
2516 #elif defined (__QNX__)
2517 cores = (int) _syspage_ptr->num_cpu;
2518
2519 #elif defined (__hpux__)
2520 struct pst_dynamic psd;
2521 if (pstat_getdynamic (&psd, sizeof (psd), 1, 0) != -1)
2522 cores = (int) psd.psd_proc_cnt;
2523
2524 #elif defined (_WIN32)
2525 SYSTEM_INFO sysinfo;
2526 GetSystemInfo (&sysinfo);
2527 cores = (int) sysinfo.dwNumberOfProcessors;
2528
2529 #elif defined (_WRS_CONFIG_SMP)
2530 unsigned int vxCpuConfiguredGet (void);
2531
2532 cores = vxCpuConfiguredGet ();
2533
2534 #endif
2535
2536 return cores;
2537 }
2538
2539 /* WIN32 code to implement a wait call that wait for any child process. */
2540
2541 #if defined (_WIN32)
2542
2543 /* Synchronization code, to be thread safe. */
2544
2545 #ifdef CERT
2546
2547 /* For the Cert run times on native Windows we use dummy functions
2548 for locking and unlocking tasks since we do not support multiple
2549 threads on this configuration (Cert run time on native Windows). */
2550
2551 static void EnterCS (void) {}
2552 static void LeaveCS (void) {}
2553 static void SignalListChanged (void) {}
2554
2555 #else
2556
2557 CRITICAL_SECTION ProcListCS;
2558 HANDLE ProcListEvt = NULL;
2559
2560 static void EnterCS (void)
2561 {
2562 EnterCriticalSection(&ProcListCS);
2563 }
2564
2565 static void LeaveCS (void)
2566 {
2567 LeaveCriticalSection(&ProcListCS);
2568 }
2569
2570 static void SignalListChanged (void)
2571 {
2572 SetEvent (ProcListEvt);
2573 }
2574
2575 #endif
2576
2577 static HANDLE *HANDLES_LIST = NULL;
2578 static int *PID_LIST = NULL, plist_length = 0, plist_max_length = 0;
2579
2580 static void
2581 add_handle (HANDLE h, int pid)
2582 {
2583 /* -------------------- critical section -------------------- */
2584 EnterCS();
2585
2586 if (plist_length == plist_max_length)
2587 {
2588 plist_max_length += 100;
2589 HANDLES_LIST =
2590 (HANDLE *) xrealloc (HANDLES_LIST, sizeof (HANDLE) * plist_max_length);
2591 PID_LIST =
2592 (int *) xrealloc (PID_LIST, sizeof (int) * plist_max_length);
2593 }
2594
2595 HANDLES_LIST[plist_length] = h;
2596 PID_LIST[plist_length] = pid;
2597 ++plist_length;
2598
2599 SignalListChanged();
2600 LeaveCS();
2601 /* -------------------- critical section -------------------- */
2602 }
2603
2604 int
2605 __gnat_win32_remove_handle (HANDLE h, int pid)
2606 {
2607 int j;
2608 int found = 0;
2609
2610 /* -------------------- critical section -------------------- */
2611 EnterCS();
2612
2613 for (j = 0; j < plist_length; j++)
2614 {
2615 if ((HANDLES_LIST[j] == h) || (PID_LIST[j] == pid))
2616 {
2617 CloseHandle (h);
2618 --plist_length;
2619 HANDLES_LIST[j] = HANDLES_LIST[plist_length];
2620 PID_LIST[j] = PID_LIST[plist_length];
2621 found = 1;
2622 break;
2623 }
2624 }
2625
2626 LeaveCS();
2627 /* -------------------- critical section -------------------- */
2628
2629 if (found)
2630 SignalListChanged();
2631
2632 return found;
2633 }
2634
2635 static void
2636 win32_no_block_spawn (char *command, char *args[], HANDLE *h, int *pid)
2637 {
2638 BOOL result;
2639 STARTUPINFO SI;
2640 PROCESS_INFORMATION PI;
2641 SECURITY_ATTRIBUTES SA;
2642 int csize = 1;
2643 char *full_command;
2644 int k;
2645
2646 /* compute the total command line length */
2647 k = 0;
2648 while (args[k])
2649 {
2650 csize += strlen (args[k]) + 1;
2651 k++;
2652 }
2653
2654 full_command = (char *) xmalloc (csize);
2655
2656 /* Startup info. */
2657 SI.cb = sizeof (STARTUPINFO);
2658 SI.lpReserved = NULL;
2659 SI.lpReserved2 = NULL;
2660 SI.lpDesktop = NULL;
2661 SI.cbReserved2 = 0;
2662 SI.lpTitle = NULL;
2663 SI.dwFlags = 0;
2664 SI.wShowWindow = SW_HIDE;
2665
2666 /* Security attributes. */
2667 SA.nLength = sizeof (SECURITY_ATTRIBUTES);
2668 SA.bInheritHandle = TRUE;
2669 SA.lpSecurityDescriptor = NULL;
2670
2671 /* Prepare the command string. */
2672 strcpy (full_command, command);
2673 strcat (full_command, " ");
2674
2675 k = 1;
2676 while (args[k])
2677 {
2678 strcat (full_command, args[k]);
2679 strcat (full_command, " ");
2680 k++;
2681 }
2682
2683 {
2684 int wsize = csize * 2;
2685 TCHAR *wcommand = (TCHAR *) xmalloc (wsize);
2686
2687 S2WSC (wcommand, full_command, wsize);
2688
2689 free (full_command);
2690
2691 result = CreateProcess
2692 (NULL, wcommand, &SA, NULL, TRUE,
2693 GetPriorityClass (GetCurrentProcess()), NULL, NULL, &SI, &PI);
2694
2695 free (wcommand);
2696 }
2697
2698 if (result == TRUE)
2699 {
2700 CloseHandle (PI.hThread);
2701 *h = PI.hProcess;
2702 *pid = PI.dwProcessId;
2703 }
2704 else
2705 {
2706 *h = NULL;
2707 *pid = 0;
2708 }
2709 }
2710
2711 static int
2712 win32_wait (int *status)
2713 {
2714 DWORD exitcode, pid;
2715 HANDLE *hl;
2716 HANDLE h;
2717 int *pidl;
2718 DWORD res;
2719 int hl_len;
2720 int found;
2721 int pos;
2722
2723 START_WAIT:
2724
2725 if (plist_length == 0)
2726 {
2727 errno = ECHILD;
2728 return -1;
2729 }
2730
2731 /* -------------------- critical section -------------------- */
2732 EnterCS();
2733
2734 /* ??? We can't wait for more than MAXIMUM_WAIT_OBJECTS due to a Win32
2735 limitation */
2736 if (plist_length < MAXIMUM_WAIT_OBJECTS)
2737 hl_len = plist_length;
2738 else
2739 {
2740 errno = EINVAL;
2741 return -1;
2742 }
2743
2744 #ifdef CERT
2745 hl = (HANDLE *) xmalloc (sizeof (HANDLE) * hl_len);
2746 memmove (hl, HANDLES_LIST, sizeof (HANDLE) * hl_len);
2747 pidl = (int *) xmalloc (sizeof (int) * hl_len);
2748 memmove (pidl, PID_LIST, sizeof (int) * hl_len);
2749 #else
2750 /* Note that index 0 contains the event handle that is signaled when the
2751 process list has changed */
2752 hl = (HANDLE *) xmalloc (sizeof (HANDLE) * (hl_len + 1));
2753 hl[0] = ProcListEvt;
2754 memmove (&hl[1], HANDLES_LIST, sizeof (HANDLE) * hl_len);
2755 pidl = (int *) xmalloc (sizeof (int) * (hl_len + 1));
2756 memmove (&pidl[1], PID_LIST, sizeof (int) * hl_len);
2757 hl_len++;
2758 #endif
2759
2760 LeaveCS();
2761 /* -------------------- critical section -------------------- */
2762
2763 res = WaitForMultipleObjects (hl_len, hl, FALSE, INFINITE);
2764
2765 /* If there was an error, exit now */
2766 if (res == WAIT_FAILED)
2767 {
2768 free (hl);
2769 free (pidl);
2770 errno = EINVAL;
2771 return -1;
2772 }
2773
2774 /* if the ProcListEvt has been signaled then the list of processes has been
2775 updated to add or remove a handle, just loop over */
2776
2777 if (res - WAIT_OBJECT_0 == 0)
2778 {
2779 free (hl);
2780 free (pidl);
2781 goto START_WAIT;
2782 }
2783
2784 /* Handle two distinct groups of return codes: finished waits and abandoned
2785 waits */
2786
2787 if (res < WAIT_ABANDONED_0)
2788 pos = res - WAIT_OBJECT_0;
2789 else
2790 pos = res - WAIT_ABANDONED_0;
2791
2792 h = hl[pos];
2793 GetExitCodeProcess (h, &exitcode);
2794 pid = pidl [pos];
2795
2796 found = __gnat_win32_remove_handle (h, -1);
2797
2798 free (hl);
2799 free (pidl);
2800
2801 /* if not found another process waiting has already handled this process */
2802
2803 if (!found)
2804 {
2805 goto START_WAIT;
2806 }
2807
2808 *status = (int) exitcode;
2809 return (int) pid;
2810 }
2811
2812 #endif
2813
2814 int
2815 __gnat_portable_no_block_spawn (char *args[] ATTRIBUTE_UNUSED)
2816 {
2817
2818 #if defined (__vxworks) || defined (__PikeOS__)
2819 /* Not supported. */
2820 return -1;
2821
2822 #elif defined(__DJGPP__)
2823 if (spawnvp (P_WAIT, args[0], args) != 0)
2824 return -1;
2825 else
2826 return 0;
2827
2828 #elif defined (_WIN32)
2829
2830 HANDLE h = NULL;
2831 int pid;
2832
2833 win32_no_block_spawn (args[0], args, &h, &pid);
2834 if (h != NULL)
2835 {
2836 add_handle (h, pid);
2837 return pid;
2838 }
2839 else
2840 return -1;
2841
2842 #else
2843
2844 int pid = fork ();
2845
2846 if (pid == 0)
2847 {
2848 /* The child. */
2849 execv (args[0], MAYBE_TO_PTR32 (args));
2850
2851 /* execv() returns only on error */
2852 _exit (1);
2853 }
2854
2855 return pid;
2856
2857 #endif
2858 }
2859
2860 int
2861 __gnat_portable_wait (int *process_status)
2862 {
2863 int status = 0;
2864 int pid = 0;
2865
2866 #if defined (__vxworks) || defined (__PikeOS__)
2867 /* Not sure what to do here, so do nothing but return zero. */
2868
2869 #elif defined (_WIN32)
2870
2871 pid = win32_wait (&status);
2872
2873 #elif defined (__DJGPP__)
2874 /* Child process has already ended in case of DJGPP.
2875 No need to do anything. Just return success. */
2876 #else
2877
2878 pid = waitpid (-1, &status, 0);
2879 status = status & 0xffff;
2880 #endif
2881
2882 *process_status = status;
2883 return pid;
2884 }
2885
2886 int
2887 __gnat_portable_no_block_wait (int *process_status)
2888 {
2889 int status = 0;
2890 int pid = 0;
2891
2892 #if defined (__vxworks) || defined (__PikeOS__) || defined (_WIN32)
2893 /* Not supported. */
2894 status = -1;
2895
2896 #else
2897
2898 pid = waitpid (-1, &status, WNOHANG);
2899 status = status & 0xffff;
2900 #endif
2901
2902 *process_status = status;
2903 return pid;
2904 }
2905
2906 void
2907 __gnat_os_exit (int status)
2908 {
2909 exit (status);
2910 }
2911
2912 int
2913 __gnat_current_process_id (void)
2914 {
2915 #if defined (__vxworks) || defined (__PikeOS__)
2916 return -1;
2917
2918 #elif defined (_WIN32)
2919
2920 return (int)GetCurrentProcessId();
2921
2922 #else
2923
2924 return (int)getpid();
2925 #endif
2926 }
2927
2928 /* Locate file on path, that matches a predicate */
2929
2930 char *
2931 __gnat_locate_file_with_predicate (char *file_name, char *path_val,
2932 int (*predicate)(char *))
2933 {
2934 char *ptr;
2935 char *file_path = (char *) alloca (strlen (file_name) + 1);
2936 int absolute;
2937
2938 /* Return immediately if file_name is empty */
2939
2940 if (*file_name == '\0')
2941 return 0;
2942
2943 /* Remove quotes around file_name if present */
2944
2945 ptr = file_name;
2946 if (*ptr == '"')
2947 ptr++;
2948
2949 strcpy (file_path, ptr);
2950
2951 ptr = file_path + strlen (file_path) - 1;
2952
2953 if (*ptr == '"')
2954 *ptr = '\0';
2955
2956 /* Handle absolute pathnames. */
2957
2958 absolute = __gnat_is_absolute_path (file_path, strlen (file_name));
2959
2960 if (absolute)
2961 {
2962 if (predicate (file_path))
2963 return xstrdup (file_path);
2964
2965 return 0;
2966 }
2967
2968 /* If file_name include directory separator(s), try it first as
2969 a path name relative to the current directory */
2970 for (ptr = file_name; *ptr && !IS_DIRECTORY_SEPARATOR(*ptr); ptr++)
2971 ;
2972
2973 if (*ptr != 0)
2974 {
2975 if (predicate (file_name))
2976 return xstrdup (file_name);
2977 }
2978
2979 if (path_val == 0)
2980 return 0;
2981
2982 {
2983 /* The result has to be smaller than path_val + file_name. */
2984 char *file_path =
2985 (char *) alloca (strlen (path_val) + strlen (file_name) + 2);
2986
2987 for (;;)
2988 {
2989 /* Skip the starting quote */
2990
2991 if (*path_val == '"')
2992 path_val++;
2993
2994 for (ptr = file_path; *path_val && *path_val != PATH_SEPARATOR; )
2995 *ptr++ = *path_val++;
2996
2997 /* If directory is empty, it is the current directory*/
2998
2999 if (ptr == file_path)
3000 {
3001 *ptr = '.';
3002 }
3003 else
3004 ptr--;
3005
3006 /* Skip the ending quote */
3007
3008 if (*ptr == '"')
3009 ptr--;
3010
3011 if (!IS_DIRECTORY_SEPARATOR(*ptr))
3012 *++ptr = DIR_SEPARATOR;
3013
3014 strcpy (++ptr, file_name);
3015
3016 if (predicate (file_path))
3017 return xstrdup (file_path);
3018
3019 if (*path_val == 0)
3020 return 0;
3021
3022 /* Skip path separator */
3023
3024 path_val++;
3025 }
3026 }
3027
3028 return 0;
3029 }
3030
3031 /* Locate an executable file, give a Path value. */
3032
3033 char *
3034 __gnat_locate_executable_file (char *file_name, char *path_val)
3035 {
3036 return __gnat_locate_file_with_predicate
3037 (file_name, path_val, &__gnat_is_executable_file);
3038 }
3039
3040 /* Locate a regular file, give a Path value. */
3041
3042 char *
3043 __gnat_locate_regular_file (char *file_name, char *path_val)
3044 {
3045 return __gnat_locate_file_with_predicate
3046 (file_name, path_val, &__gnat_is_regular_file);
3047 }
3048
3049 /* Locate an executable given a Path argument. This routine is only used by
3050 gnatbl and should not be used otherwise. Use locate_exec_on_path
3051 instead. */
3052
3053 char *
3054 __gnat_locate_exec (char *exec_name, char *path_val)
3055 {
3056 const unsigned int len = strlen (HOST_EXECUTABLE_SUFFIX);
3057 char *ptr;
3058
3059 if (len > 0 && !strstr (exec_name, HOST_EXECUTABLE_SUFFIX))
3060 {
3061 char *full_exec_name = (char *) alloca (strlen (exec_name) + len + 1);
3062
3063 strcpy (full_exec_name, exec_name);
3064 strcat (full_exec_name, HOST_EXECUTABLE_SUFFIX);
3065 ptr = __gnat_locate_executable_file (full_exec_name, path_val);
3066
3067 if (ptr == 0)
3068 return __gnat_locate_executable_file (exec_name, path_val);
3069 return ptr;
3070 }
3071 else
3072 return __gnat_locate_executable_file (exec_name, path_val);
3073 }
3074
3075 /* Locate an executable using the Systems default PATH. */
3076
3077 char *
3078 __gnat_locate_exec_on_path (char *exec_name,
3079 int current_dir_on_windows ATTRIBUTE_UNUSED)
3080 {
3081 char *apath_val;
3082
3083 #if defined (_WIN32)
3084 TCHAR *wpath_val = _tgetenv (_T("PATH"));
3085 #define EXPAND_BUFFER_SIZE 32767
3086 apath_val = (char *) alloca (EXPAND_BUFFER_SIZE);
3087
3088 if (current_dir_on_windows) {
3089 TCHAR *wapath_val;
3090 /* In Win32 systems we expand the PATH as for XP environment
3091 variables are not automatically expanded. We also prepend the
3092 ".;" to the path to match normal NT path search semantics */
3093
3094 wapath_val = (TCHAR *) alloca (EXPAND_BUFFER_SIZE);
3095
3096 wapath_val [0] = '.';
3097 wapath_val [1] = ';';
3098
3099 DWORD res = ExpandEnvironmentStrings
3100 (wpath_val, &wapath_val[2], EXPAND_BUFFER_SIZE - 2);
3101
3102 if (!res) wapath_val [0] = _T('\0');
3103
3104 WS2SC (apath_val, wapath_val, EXPAND_BUFFER_SIZE);
3105 } else {
3106 WS2SC (apath_val, wpath_val, EXPAND_BUFFER_SIZE);
3107 }
3108
3109 #else
3110 const char *path_val = getenv ("PATH");
3111
3112 /* If PATH is not defined, proceed with __gnat_locate_exec anyway, so we can
3113 find files that contain directory names. */
3114
3115 if (path_val == NULL) path_val = "";
3116 apath_val = (char *) alloca (strlen (path_val) + 1);
3117 strcpy (apath_val, path_val);
3118 #endif
3119
3120 return __gnat_locate_exec (exec_name, apath_val);
3121 }
3122
3123 /* Dummy functions for Osint import for non-VMS systems.
3124 ??? To be removed. */
3125
3126 int
3127 __gnat_to_canonical_file_list_init (char *dirspec ATTRIBUTE_UNUSED,
3128 int onlydirs ATTRIBUTE_UNUSED)
3129 {
3130 return 0;
3131 }
3132
3133 char *
3134 __gnat_to_canonical_file_list_next (void)
3135 {
3136 static char empty[] = "";
3137 return empty;
3138 }
3139
3140 void
3141 __gnat_to_canonical_file_list_free (void)
3142 {
3143 }
3144
3145 char *
3146 __gnat_to_canonical_dir_spec (char *dirspec, int prefixflag ATTRIBUTE_UNUSED)
3147 {
3148 return dirspec;
3149 }
3150
3151 char *
3152 __gnat_to_canonical_file_spec (char *filespec)
3153 {
3154 return filespec;
3155 }
3156
3157 char *
3158 __gnat_to_canonical_path_spec (char *pathspec)
3159 {
3160 return pathspec;
3161 }
3162
3163 char *
3164 __gnat_to_host_dir_spec (char *dirspec, int prefixflag ATTRIBUTE_UNUSED)
3165 {
3166 return dirspec;
3167 }
3168
3169 char *
3170 __gnat_to_host_file_spec (char *filespec)
3171 {
3172 return filespec;
3173 }
3174
3175 void
3176 __gnat_adjust_os_resource_limits (void)
3177 {
3178 }
3179
3180 #if defined (__mips_vxworks)
3181 int
3182 _flush_cache (void)
3183 {
3184 CACHE_USER_FLUSH (0, ENTIRE_CACHE);
3185 }
3186 #endif
3187
3188 #if defined (_WIN32)
3189 int __gnat_argument_needs_quote = 1;
3190 #else
3191 int __gnat_argument_needs_quote = 0;
3192 #endif
3193
3194 /* This option is used to enable/disable object files handling from the
3195 binder file by the GNAT Project module. For example, this is disabled on
3196 Windows (prior to GCC 3.4) as it is already done by the mdll module.
3197 Stating with GCC 3.4 the shared libraries are not based on mdll
3198 anymore as it uses the GCC's -shared option */
3199 #if defined (_WIN32) \
3200 && ((__GNUC__ < 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ < 4)))
3201 int __gnat_prj_add_obj_files = 0;
3202 #else
3203 int __gnat_prj_add_obj_files = 1;
3204 #endif
3205
3206 /* char used as prefix/suffix for environment variables */
3207 #if defined (_WIN32)
3208 char __gnat_environment_char = '%';
3209 #else
3210 char __gnat_environment_char = '$';
3211 #endif
3212
3213 /* This functions copy the file attributes from a source file to a
3214 destination file.
3215
3216 mode = 0 : In this mode copy only the file time stamps (last access and
3217 last modification time stamps).
3218
3219 mode = 1 : In this mode, time stamps and read/write/execute attributes are
3220 copied.
3221
3222 mode = 2 : In this mode, only read/write/execute attributes are copied
3223
3224 Returns 0 if operation was successful and -1 in case of error. */
3225
3226 int
3227 __gnat_copy_attribs (char *from ATTRIBUTE_UNUSED, char *to ATTRIBUTE_UNUSED,
3228 int mode ATTRIBUTE_UNUSED)
3229 {
3230 #if (defined (__vxworks) && _WRS_VXWORKS_MAJOR < 6)
3231 return -1;
3232
3233 #elif defined (_WIN32)
3234 TCHAR wfrom [GNAT_MAX_PATH_LEN + 2];
3235 TCHAR wto [GNAT_MAX_PATH_LEN + 2];
3236 BOOL res;
3237 FILETIME fct, flat, flwt;
3238 HANDLE hfrom, hto;
3239
3240 S2WSC (wfrom, from, GNAT_MAX_PATH_LEN + 2);
3241 S2WSC (wto, to, GNAT_MAX_PATH_LEN + 2);
3242
3243 /* Do we need to copy the timestamp ? */
3244
3245 if (mode != 2) {
3246 /* retrieve from times */
3247
3248 hfrom = CreateFile
3249 (wfrom, GENERIC_READ, 0, NULL, OPEN_EXISTING,
3250 FILE_ATTRIBUTE_NORMAL, NULL);
3251
3252 if (hfrom == INVALID_HANDLE_VALUE)
3253 return -1;
3254
3255 res = GetFileTime (hfrom, &fct, &flat, &flwt);
3256
3257 CloseHandle (hfrom);
3258
3259 if (res == 0)
3260 return -1;
3261
3262 /* retrieve from times */
3263
3264 hto = CreateFile
3265 (wto, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
3266 FILE_ATTRIBUTE_NORMAL, NULL);
3267
3268 if (hto == INVALID_HANDLE_VALUE)
3269 return -1;
3270
3271 res = SetFileTime (hto, NULL, &flat, &flwt);
3272
3273 CloseHandle (hto);
3274
3275 if (res == 0)
3276 return -1;
3277 }
3278
3279 /* Do we need to copy the permissions ? */
3280 /* Set file attributes in full mode. */
3281
3282 if (mode != 0)
3283 {
3284 DWORD attribs = GetFileAttributes (wfrom);
3285
3286 if (attribs == INVALID_FILE_ATTRIBUTES)
3287 return -1;
3288
3289 res = SetFileAttributes (wto, attribs);
3290 if (res == 0)
3291 return -1;
3292 }
3293
3294 return 0;
3295
3296 #else
3297 GNAT_STRUCT_STAT fbuf;
3298
3299 if (GNAT_STAT (from, &fbuf) == -1) {
3300 return -1;
3301 }
3302
3303 #if (defined (__vxworks) && _WRS_VXWORKS_MAJOR < 7)
3304
3305 /* VxWorks prior to 7 only has utime. */
3306
3307 /* Do we need to copy the timestamp ? */
3308 if (mode != 2) {
3309 struct utimbuf tbuf;
3310
3311 tbuf.actime = fbuf.st_atime;
3312 tbuf.modtime = fbuf.st_mtime;
3313
3314 if (utime (to, &tbuf) == -1)
3315 return -1;
3316 }
3317
3318 #elif _POSIX_C_SOURCE >= 200809L
3319 struct timespec tbuf[2];
3320
3321 if (mode != 2) {
3322 tbuf[0] = fbuf.st_atim;
3323 tbuf[1] = fbuf.st_mtim;
3324
3325 if (utimensat (AT_FDCWD, to, tbuf, 0) == -1) {
3326 return -1;
3327 }
3328 }
3329
3330 #else
3331 struct timeval tbuf[2];
3332 /* Do we need to copy timestamp ? */
3333
3334 if (mode != 2) {
3335 tbuf[0].tv_sec = fbuf.st_atime;
3336 tbuf[1].tv_sec = fbuf.st_mtime;
3337
3338 #if defined(st_mtime)
3339 tbuf[0].tv_usec = fbuf.st_atim.tv_nsec / 1000;
3340 tbuf[1].tv_usec = fbuf.st_mtim.tv_nsec / 1000;
3341 #else
3342 tbuf[0].tv_usec = 0;
3343 tbuf[1].tv_usec = 0;
3344 #endif
3345
3346 if (utimes (to, tbuf) == -1) {
3347 return -1;
3348 }
3349 }
3350 #endif
3351
3352 /* Do we need to copy file permissions ? */
3353 if (mode != 0 && (chmod (to, fbuf.st_mode) == -1)) {
3354 return -1;
3355 }
3356
3357 return 0;
3358 #endif
3359 }
3360
3361 int
3362 __gnat_lseek (int fd, long offset, int whence)
3363 {
3364 return (int) lseek (fd, offset, whence);
3365 }
3366
3367 /* This function returns the major version number of GCC being used. */
3368 int
3369 get_gcc_version (void)
3370 {
3371 #ifdef IN_RTS
3372 return __GNUC__;
3373 #else
3374 return (int) (version_string[0] - '0');
3375 #endif
3376 }
3377
3378 /*
3379 * Set Close_On_Exec as indicated.
3380 * Note: this is used for both GNAT.OS_Lib and GNAT.Sockets.
3381 */
3382
3383 int
3384 __gnat_set_close_on_exec (int fd ATTRIBUTE_UNUSED,
3385 int close_on_exec_p ATTRIBUTE_UNUSED)
3386 {
3387 #if defined (F_GETFD) && defined (FD_CLOEXEC) && ! defined (__vxworks)
3388 int flags = fcntl (fd, F_GETFD, 0);
3389 if (flags < 0)
3390 return flags;
3391 if (close_on_exec_p)
3392 flags |= FD_CLOEXEC;
3393 else
3394 flags &= ~FD_CLOEXEC;
3395 return fcntl (fd, F_SETFD, flags);
3396 #elif defined(_WIN32)
3397 HANDLE h = (HANDLE) _get_osfhandle (fd);
3398 if (h == (HANDLE) -1)
3399 return -1;
3400 if (close_on_exec_p)
3401 return ! SetHandleInformation (h, HANDLE_FLAG_INHERIT, 0);
3402 return ! SetHandleInformation (h, HANDLE_FLAG_INHERIT,
3403 HANDLE_FLAG_INHERIT);
3404 #else
3405 /* TODO: Unimplemented. */
3406 return -1;
3407 #endif
3408 }
3409
3410 /* Indicates if platforms supports automatic initialization through the
3411 constructor mechanism */
3412 int
3413 __gnat_binder_supports_auto_init (void)
3414 {
3415 return 1;
3416 }
3417
3418 /* Indicates that Stand-Alone Libraries are automatically initialized through
3419 the constructor mechanism */
3420 int
3421 __gnat_sals_init_using_constructors (void)
3422 {
3423 #if defined (__vxworks) || defined (__Lynx__)
3424 return 0;
3425 #else
3426 return 1;
3427 #endif
3428 }
3429
3430 #if defined (__linux__) || defined (__ANDROID__)
3431 /* There is no function in the glibc to retrieve the LWP of the current
3432 thread. We need to do a system call in order to retrieve this
3433 information. */
3434 #include <sys/syscall.h>
3435 void *
3436 __gnat_lwp_self (void)
3437 {
3438 return (void *) syscall (__NR_gettid);
3439 }
3440 #endif
3441
3442 #if defined (__APPLE__)
3443 # if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060
3444 # include <mach/thread_info.h>
3445 # include <mach/mach_init.h>
3446 # include <mach/thread_act.h>
3447 # else
3448 # include <pthread.h>
3449 # endif
3450
3451 /* System-wide thread identifier. Note it could be truncated on 32 bit
3452 hosts.
3453 Previously was: pthread_mach_thread_np (pthread_self ()). */
3454 void *
3455 __gnat_lwp_self (void)
3456 {
3457 #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060
3458 thread_identifier_info_data_t data;
3459 mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
3460 kern_return_t kret;
3461
3462 kret = thread_info (mach_thread_self (), THREAD_IDENTIFIER_INFO,
3463 (thread_info_t) &data, &count);
3464 if (kret == KERN_SUCCESS)
3465 return (void *)(uintptr_t)data.thread_id;
3466 else
3467 return 0;
3468 #else
3469 return (void *)pthread_mach_thread_np (pthread_self ());
3470 #endif
3471 }
3472 #endif
3473
3474 #if defined (__linux__)
3475 #include <sched.h>
3476
3477 /* glibc versions earlier than 2.7 do not define the routines to handle
3478 dynamically allocated CPU sets. For these targets, we use the static
3479 versions. */
3480
3481 #ifdef CPU_ALLOC
3482
3483 /* Dynamic cpu sets */
3484
3485 cpu_set_t *
3486 __gnat_cpu_alloc (size_t count)
3487 {
3488 return CPU_ALLOC (count);
3489 }
3490
3491 size_t
3492 __gnat_cpu_alloc_size (size_t count)
3493 {
3494 return CPU_ALLOC_SIZE (count);
3495 }
3496
3497 void
3498 __gnat_cpu_free (cpu_set_t *set)
3499 {
3500 CPU_FREE (set);
3501 }
3502
3503 void
3504 __gnat_cpu_zero (size_t count, cpu_set_t *set)
3505 {
3506 CPU_ZERO_S (count, set);
3507 }
3508
3509 void
3510 __gnat_cpu_set (int cpu, size_t count, cpu_set_t *set)
3511 {
3512 /* Ada handles CPU numbers starting from 1, while C identifies the first
3513 CPU by a 0, so we need to adjust. */
3514 CPU_SET_S (cpu - 1, count, set);
3515 }
3516
3517 #else /* !CPU_ALLOC */
3518
3519 /* Static cpu sets */
3520
3521 cpu_set_t *
3522 __gnat_cpu_alloc (size_t count ATTRIBUTE_UNUSED)
3523 {
3524 return (cpu_set_t *) xmalloc (sizeof (cpu_set_t));
3525 }
3526
3527 size_t
3528 __gnat_cpu_alloc_size (size_t count ATTRIBUTE_UNUSED)
3529 {
3530 return sizeof (cpu_set_t);
3531 }
3532
3533 void
3534 __gnat_cpu_free (cpu_set_t *set)
3535 {
3536 free (set);
3537 }
3538
3539 void
3540 __gnat_cpu_zero (size_t count ATTRIBUTE_UNUSED, cpu_set_t *set)
3541 {
3542 CPU_ZERO (set);
3543 }
3544
3545 void
3546 __gnat_cpu_set (int cpu, size_t count ATTRIBUTE_UNUSED, cpu_set_t *set)
3547 {
3548 /* Ada handles CPU numbers starting from 1, while C identifies the first
3549 CPU by a 0, so we need to adjust. */
3550 CPU_SET (cpu - 1, set);
3551 }
3552 #endif /* !CPU_ALLOC */
3553 #endif /* __linux__ */
3554
3555 /* Return the load address of the executable, or 0 if not known. In the
3556 specific case of error, (void *)-1 can be returned. Beware: this unit may
3557 be in a shared library. As low-level units are needed, we allow #include
3558 here. */
3559
3560 #if defined (__APPLE__)
3561 #include <mach-o/dyld.h>
3562 #elif defined (__linux__)
3563 #include <features.h>
3564 #include <link.h>
3565 #endif
3566
3567 const void *
3568 __gnat_get_executable_load_address (void)
3569 {
3570 #if defined (__APPLE__)
3571 return _dyld_get_image_header (0);
3572
3573 #elif defined (__linux__) && (defined (__GLIBC__) || defined (__UCLIBC__))
3574 struct link_map *map = _r_debug.r_map;
3575 return (const void *)map->l_addr;
3576
3577 #elif defined (_WIN32)
3578 return GetModuleHandle (NULL);
3579
3580 #else
3581 return NULL;
3582 #endif
3583 }
3584
3585 void
3586 __gnat_kill (int pid, int sig)
3587 {
3588 #if defined(_WIN32)
3589 HANDLE h;
3590
3591 switch (sig) {
3592 case 9: // SIGKILL is not declared in Windows headers
3593 case SIGINT:
3594 case SIGBREAK:
3595 case SIGTERM:
3596 case SIGABRT:
3597 h = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
3598 if (h != NULL) {
3599 TerminateProcess (h, sig);
3600 CloseHandle (h);
3601 }
3602 }
3603
3604 #elif defined (__vxworks)
3605 /* Not implemented */
3606 #else
3607 kill (pid, sig);
3608 #endif
3609 }
3610
3611 void __gnat_killprocesstree (int pid, int sig_num)
3612 {
3613 #if defined(_WIN32)
3614 PROCESSENTRY32 pe;
3615
3616 memset(&pe, 0, sizeof(PROCESSENTRY32));
3617 pe.dwSize = sizeof(PROCESSENTRY32);
3618
3619 HANDLE hSnap = CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0);
3620
3621 /* cannot take snapshot, just kill the parent process */
3622
3623 if (hSnap == INVALID_HANDLE_VALUE)
3624 {
3625 __gnat_kill (pid, sig_num);
3626 return;
3627 }
3628
3629 if (Process32First(hSnap, &pe))
3630 {
3631 BOOL bContinue = TRUE;
3632
3633 /* kill child processes first */
3634
3635 while (bContinue)
3636 {
3637 if (pe.th32ParentProcessID == (DWORD)pid)
3638 __gnat_killprocesstree (pe.th32ProcessID, sig_num);
3639
3640 bContinue = Process32Next (hSnap, &pe);
3641 }
3642 }
3643
3644 CloseHandle (hSnap);
3645
3646 /* kill process */
3647
3648 __gnat_kill (pid, sig_num);
3649
3650 #elif defined (__vxworks)
3651 /* not implemented */
3652
3653 #elif defined (__linux__)
3654 DIR *dir;
3655 struct dirent *d;
3656
3657 /* read all processes' pid and ppid */
3658
3659 dir = opendir ("/proc");
3660
3661 /* cannot open proc, just kill the parent process */
3662
3663 if (!dir)
3664 {
3665 __gnat_kill (pid, sig_num);
3666 return;
3667 }
3668
3669 /* kill child processes first */
3670
3671 while ((d = readdir (dir)) != NULL)
3672 {
3673 if ((d->d_type & DT_DIR) == DT_DIR)
3674 {
3675 char statfile[64];
3676 int _pid, _ppid;
3677
3678 /* read /proc/<PID>/stat */
3679
3680 if (strlen (d->d_name) >= sizeof (statfile) - strlen ("/proc//stat"))
3681 continue;
3682 strcpy (statfile, "/proc/");
3683 strcat (statfile, d->d_name);
3684 strcat (statfile, "/stat");
3685
3686 FILE *fd = fopen (statfile, "r");
3687
3688 if (fd)
3689 {
3690 const int match = fscanf (fd, "%d %*s %*s %d", &_pid, &_ppid);
3691 fclose (fd);
3692
3693 if (match == 2 && _ppid == pid)
3694 __gnat_killprocesstree (_pid, sig_num);
3695 }
3696 }
3697 }
3698
3699 closedir (dir);
3700
3701 /* kill process */
3702
3703 __gnat_kill (pid, sig_num);
3704 #else
3705 __gnat_kill (pid, sig_num);
3706 #endif
3707 /* Note on Solaris it is possible to read /proc/<PID>/status.
3708 The 5th and 6th words are the pid and the 7th and 8th the ppid.
3709 See: /usr/include/sys/procfs.h (struct pstatus).
3710 */
3711 }
3712
3713 #ifdef __cplusplus
3714 }
3715 #endif