summaryrefslogtreecommitdiff
path: root/pc/gawkmisc.pc
blob: 64b42396e543353eb5cc00cee4f2388dac8d0882 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/*
 * gawkmisc.c --- miscellaneous gawk routines that are OS specific.
 */

/* 
 * Copyright (C) 1986, 1988, 1989, 1991 - 2003 the Free Software Foundation, Inc.
 * 
 * This file is part of GAWK, the GNU implementation of the
 * AWK Progamming Language.
 * 
 * GAWK is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GAWK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

char quote = '\'';
char envsep = ';';

# ifdef DEFPATH
char *defpath = DEFPATH;
# else
char *defpath = ".;c:\\lib\\awk;c:\\gnu\\lib\\awk";
# endif

#ifdef __EMX__
#include<io.h>

static int _os2_is_abs_path(const char *dirname);
static char* _os2_unixroot(const char *path);
static const char* _os2_unixroot_path(const char *path);
#endif

/* gawk_name --- pull out the "gawk" part from how the OS called us */

char *
gawk_name(filespec)
const char *filespec;
{
	char *p, *q;

	p = (char *) filespec;  /* Sloppy... */

	/* OS/2 allows / for directory separator too */
	if ((q = strrchr(p, '\\')) != NULL)
		p = q + 1;
	if ((q = strrchr(p, '/')) != NULL
	    && (p == NULL || q > p)) /* support mixed d:\foo/bar\gawk.exe */
		p = q + 1;
	if ((q = strchr(p, '.')) != NULL)
		*q = '\0';
	return strlwr(p);
}


/*
 * memcpy_long() & memset_ulong() are 32-bit replacements for MSC which
 * has a 16-bit size_t.
 */
char *
memcpy_ulong (dest, src, l)
register char *dest;
register const char *src;
register unsigned long l;
{
	register char *ret = dest;

	while (l--)
		*dest++ = *src++;

	return ret;
}


void *
memset_ulong(dest, val, l)
void *dest;
register int val;
register unsigned long l;
{
	register char *ret = dest;
	register char *d = dest;

	while (l--)
		*d++ = val;

	return ((void *) ret);
}


/* os_arg_fixup --- fixup the command line */

void
os_arg_fixup(argcp, argvp)
int *argcp;
char ***argvp;
{
#ifdef __EMX__
# ifdef initialize_main
	initialize_main(argcp, argvp);
# else
	_wildcard(argcp, argvp);
	_response(argcp, argvp);
# endif

	setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
	defpath = (char*) _os2_unixroot_path(defpath);
#endif /* __EMX__ */
	return;
}

/* os_devopen --- open special per-OS devices */

int
os_devopen(name, flag)
const char *name;
int flag;
{
#ifdef __EMX__
	/* do not use open(name, flag) here !!! */
	return -1;
#else
	if (strcmp(name, "/dev/null") == 0)
		return open("NUL", flag);
	/* FIXME: */
	/* else if (strcmp(name, "/dev/tty") == 0)
	 * 	return open("???", flag);
	 */
	return -1;
#endif
}

/* optimal_bufsize --- determine optimal buffer size */

size_t
optimal_bufsize(fd, stb)
int fd;
struct stat *stb;
{
	/* force all members to zero in case OS doesn't use all of them. */
	memset(stb, '\0', sizeof(struct stat));

	/*
	 * DOS doesn't have the file system block size in the
	 * stat structure. So we have to make some sort of reasonable
	 * guess. We use stdio's BUFSIZ, since that is what it was
	 * meant for in the first place.
	 */
#define	DEFBLKSIZE	BUFSIZ

	if (fstat(fd, stb) == -1)
		fatal("can't stat fd %d (%s)", fd, strerror(errno));
	if (S_ISREG(stb->st_mode)
	    && 0 < stb->st_size && stb->st_size < DEFBLKSIZE) /* small file */
		return stb->st_size;
	return DEFBLKSIZE;
}

/* ispath --- return true if path has directory components */

int
ispath(file)
const char *file;
{
#ifdef __EMX__
	return (strpbrk(file, "/\\") != NULL ||
		(toupper(file[0]) >= 'A' && toupper(file[0]) <= 'Z' && file[1] == ':'));
#else
	for (; *file; file++) {
		switch (*file) {
		case '/':
		case '\\':
		case ':':
			return 1;
		}
	}
	return 0;
#endif
}

/* isdirpunct --- return true if char is a directory separator */

int
isdirpunct(c)
int c;
{
	return (strchr(":\\/", c) != NULL);
}

/* os_close_on_exec --- set close on exec flag, print warning if fails */

void
os_close_on_exec(fd, name, what, dir)
int fd;
const char *name, *what, *dir;
{
#if ! defined(_MSC_VER) && ! defined(__MINGW32__)
# if (defined(__DJGPP__) && (__DJGPP__ > 2 || __DJGPP_MINOR__ >= 4)) || defined __EMX__
	if (fd <= 2)	/* sanity */
		return;

	if (fcntl(fd, F_SETFD, 1) < 0)
		warning("%s %s `%s': could not set close-on-exec: %s",
			what, dir, name, strerror(errno));
# endif
#endif
}

/* os_isdir --- is this an fd on a directory? */

#if ! defined(S_ISDIR) && defined(S_IFDIR)
#define	S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#endif

int
os_isdir(fd)
int fd;
{
	struct stat sbuf;

	return (fstat(fd, &sbuf) == 0 && S_ISDIR(sbuf.st_mode));
}

/* os_is_setuid --- true if running setuid root */

int
os_is_setuid()
{
#ifdef __EMX__
      	long uid, euid;

	uid = getuid();
	euid = geteuid();

	return (euid == 0 && euid != uid);
#else
	return 0;
#endif
}

/* os_setbinmode --- set binary mode on file */

#ifdef __DJGPP__
#include <sys/exceptn.h>
#endif
static int orig_tty_mode = -1;

int
os_setbinmode(fd, mode)
int fd, mode;
{
	int prev_mode = setmode(fd, mode);

#ifdef __DJGPP__
	if ((mode & O_BINARY) != 0)
		__djgpp_set_ctrl_c(1); /* allow to interrupt with Ctrl-C */
#endif
	/* Save the original tty mode as we found it.  */
	if (orig_tty_mode == -1 && fd >= 0 && fd <= 2)
		orig_tty_mode = prev_mode;
	return prev_mode;
}

/* os_restore_mode --- restore the original mode of the console device */

void
os_restore_mode (fd)
int fd;
{
	if (orig_tty_mode != -1) {
		setmode(fd, orig_tty_mode);
	}
}

/* os_isatty --- return true if fd is a tty */

int
os_isatty(int fd)
{
#if defined(__MINGW32__) || defined(_MSC_VER)
	return (isatty(fd) && lseek(fd, SEEK_CUR, 0) == -1);
#else
	return isatty(fd);
#endif
}
 
/* files_are_same --- return true if files are identical */

int
files_are_same(char *path, SRCFILE *src)
{
	struct stat st;
	size_t pathlen;
	char *p, *s;

	if (stat (path, & st) == 0) {
		/* If they have a working `stat', honor that.  */
		if (!(st.st_dev == src->sbuf.st_dev
		      && st.st_ino == src->sbuf.st_ino))
			return 0;

		/* Compare modification times.  */
		if (st.st_mtime != src->mtime)
			return 0;

		/* Compare absolute file names case-insensitively, and
		   treat forward- and back-slashes as equal.  */
		pathlen = strlen(path);
		for (p = path, s = src->fullpath;
		     p <= path + pathlen;
		     p++, s++) {
			if (tolower(*p) != tolower(*s)
			    && !((*p == '/' || *p == '\\')
				 && (*s == '/' || *s == '\\')))
				return 0;
		}
		return 1;
	}
	return 0;
}


#ifdef __EMX__ 
# ifndef PATH_SEPARATOR
#  define PATH_SEPARATOR ';'
# endif

/* result is 0 if dirname is no absolute path, 1 otherwise */

static int
_os2_is_abs_path(const char *dirname)
{
  int result = 0;
  if (dirname != NULL && dirname[0] != '\0') {
    /* if dirname contains a valid drive letter like "c:" */
    if (((dirname[0] >= 'A' && dirname[0] <= 'Z') || (dirname[0] >= 'a' && dirname[0] <= 'z'))
        && dirname[1] == ':') dirname += 2; /* remove the drive letter */

    if (dirname[0] == '/' || dirname[0] == '\\') result = 1; /* asbolute path */
  }

  return result;
}


/* path is assumed to be a list of directories separated by PATH_SEPARATOR.
   This function determines if the first directory of path is on the
   drive specified by the environment variable UNIXROOT.
   If it is the case, NULL is returned, otherwise a new directory name
   is allocated using the drive letter from UNIXROOT and returned as result.
   If the first directory is a relative path NULL is returned, too.
   The new directory name is allocated by malloc().
   Example (UNIXROOT is set to "e:"):
     "c:/usr/share" -> "e:/usr/share"
     "e:/usr/share" -> NULL             (already on the $UNIXROOT drive)
     "/usr/share"   -> "e:/usr/share"
     "."            -> NULL             (not an absolute path)
     "usr/share"    -> NULL             (not an absolute path)
     "c:usr/share"  -> NULL             (not an absolute path)
     "c:/usr/share;d:/etc" -> "e:/usr/share" (only the first directory in path is used) */

static char*
_os2_unixroot(const char *path)
{
  static const char *unixroot = NULL;
  static int unixroot_init = 0; 
  char *result = NULL; 

  if (unixroot_init == 0) {
    /* get $UNIXROOT only one time */
    unixroot = getenv("UNIXROOT");

    /* check whether unixroot is valid (must be "x:") */
    if (unixroot != NULL) {
      int drive = toupper(unixroot[0]);
      if (drive < 'A' || drive > 'Z' || unixroot[1] != ':' || unixroot[2] != '\0')
        unixroot = NULL; /* unixroot not valid */
    }

    unixroot_init = 1; /* initialized */
  }

  /* note: if unixroot != NULL then it contains a valid drive letter */
  if (unixroot != NULL && _os2_is_abs_path(path)) {
    /* dirname is an absolute path and unixroot is a drive letter, "c:" for example */
    size_t old_path_len = strlen(path);

    /* end points to the first ';' in path or to NULL */
    const char *end = strchr(path, PATH_SEPARATOR);

    /* dir_len is the length of the first directory in path */
    size_t dir_len = (end) ? end - path : old_path_len;

    if (toupper(unixroot[0]) != toupper(path[0]) || path[1] != ':') {
      /* the first directory of path does not start with the string $UNIXROOT */
      if (path[1] == ':') {
        /* if there is a drive letter remove it */
        dir_len -= 2;
        path += 2;
      } 

      result = malloc(dir_len + 3);
      if (result) { /* do nothing if we are out of memory */
        result[0] = unixroot[0];
        result[1] = unixroot[1];
        memcpy(result + 2, path, dir_len);
        result[dir_len + 2] = '\0';
      }
    }
  }
  return result;
}

/* path is assumed to be a list of directories separated by PATH_SEPARATOR.
   Every directory is processed. _os2_unixroot() is used to find out whether
   these directories are on the drive specified by the environment variable
   UNIXROOT. If this is not the case the same directory on the UNIXROOT drive
   is added to the end of path. If path is a valid path this function returns a valid path, too.
   Example ($UNIXROOT is set to "e:"):
   ".;c:/usr/local;d:/usr/local;d:/etc;e:/etc"
   -> ".;c:/usr/local;d:/usr/local;d:/etc;e:/etc;e:/usr/local;e:/usr/local;e:/etc" */

static const char*
_os2_unixroot_path(const char *path)
{
  char *result = NULL;
  const char *p = path;
  unsigned dir_count = 1;

  if (path == NULL || path[0] == '\0') return NULL; /* empty path */

  /* save number of path components in dir_count */
  while(*p) {
    if (*p++ == PATH_SEPARATOR && *p != '\0' && *p != PATH_SEPARATOR)
      dir_count += 1;
  }

  {
    const char *list[dir_count]; /* list of char pointers */
    size_t dir_len[dir_count]; /* the according directory length */
    size_t old_path_len = strlen(path); /* the old path length */
    size_t total_len;
    unsigned i = 0;

    if (path[old_path_len - 1] == PATH_SEPARATOR) /* last character is ';' */
      old_path_len--;

    list[0] = p = path; /* first directory */

    while(*p) {
    if (*p++ == PATH_SEPARATOR && *p != '\0' && *p != PATH_SEPARATOR)
      list[++i] = p;
    }
    /* now list[i] contains the ith directory of path (no 0-terminated strings!!!) */

    /* determine the total length for the new path */
    total_len = old_path_len;

    for(i = 0; i < dir_count; i++) {
      list[i] = _os2_unixroot(list[i]);
      if (list[i] != NULL) {
        dir_len[i] = strlen(list[i]);
        total_len += dir_len[i] + 1; /* one character for ';' or '\0' */
      }
      else dir_len[i] = 0;
    }
    /* now list[] contains the according directories on the UNIXROOT drive or NULL
       total_len contains the total length for the new path */
    result = malloc(total_len + 1);

    if (result) {
      /* copy the old path and the new directories into the new path */
      char *q = result;
      memcpy(q, path, old_path_len);
      q += old_path_len;

      for(i = 0; i < dir_count; i++) {
        if (dir_len[i] != 0) {
          *q++ = PATH_SEPARATOR;
          memcpy(q, list[i], dir_len[i]);
          q += dir_len[i];
        }
      }

      *q = '\0'; /* terminating '\0' */
    }

    for(i = 0; i < dir_count; i++) free((void*) list[i]);
  }

  return (result) ? (const char*) result : path;
}
#endif /* __EMX__ */

#ifdef __MINGW32__

extern void *xmalloc (size_t);

int
setenv (const char *name, const char *value, int rewrite)
{
  char *entry;

  if (*value == '=')
    ++value;

  if (getenv (name) && !rewrite)
    return 0;

  entry = xmalloc (strlen (name) + 1 + strlen (value) + 1);
  strcat (strcat (strcpy (entry, name), "="), value);
  if (putenv (entry) != 0)
    {
      free (entry);
      return -1;
    }
  return 0;
}

int
unsetenv (const char *name)
{
  if (!name || !*name || strchr (name, '=') != NULL)
    return -1;

  return setenv (name, "", 1);
}

#include <windows.h>

int
usleep(unsigned int usec)
{
  double msecf = usec / 1000.0;

  Sleep ((DWORD)msecf);

  return usec - msecf * 1000 < 0 ? 0 : (int)(usec - msecf * 1000);
}

/* The implementation of wctob in the MS runtime is problematic
   because it doesn't allow to distinguish between WEOF and 0xff, due
   to integer sign extension.  It also causes failures in dfa.c when
   characters with the 8th bit set are involved.  This replacement
   version fixes that.  */

#include <wchar.h>

int
wctob (wint_t wc)
{
  char buf[64];

  if (!(MB_CUR_MAX <= sizeof (buf)))
    abort ();
  /* Handle the case where WEOF is a value that does not fit in a wchar_t.  */
  if (wc == (wchar_t)wc)
    if (wctomb (buf, (wchar_t)wc) == 1)
      return (unsigned char) buf[0];
  return EOF;
}

#endif	/* __MINGW32__ */

#ifdef __DJGPP__

int
unsetenv (const char *name)
{
  if (!name || !*name || strchr (name, '=') != NULL)
    return -1;

  return putenv (name);
}

#endif /* __DJGPP__ */