armsys 32.2 KB
Newer Older
Neil Turton's avatar
Neil Turton committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Copyright 1996 Acorn Computers Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* armsys.c:  Copyright (C) Codemist Ltd., 1988       */
/* Copyright (C) Acorn Computers Ltd., 1988           */
/* Very ARM (and Brazil & Arthur) specific routines.  */

/* version 11 */

#define __system_io 1                           /* to get at flag bits */
Ben Avison's avatar
Ben Avison committed
23
#define _LARGEFILE64_SOURCE /* define 64-bit file pointer stuff in stdio.h */
Neil Turton's avatar
Neil Turton committed
24

25 26
#include "VersionNum"

Neil Turton's avatar
Neil Turton committed
27 28 29 30 31 32 33 34 35
#include "hostsys.h"                            /* things like _initio() */
#include "territory.h"
#include "kernel.h"
#include "swis.h"
#include <stdio.h>                              /* for EOF               */
#include <stdlib.h>                             /* for exit()            */
#include <ctype.h>                              /* isprint(), isspace()  */
#include <string.h>                             /* for strlen()          */
#include <time.h>                               /* for clock             */
Kevin Bracey's avatar
Kevin Bracey committed
36
#include <errno.h>
37
#include <stdbool.h>
Neil Turton's avatar
Neil Turton committed
38 39 40 41 42 43

/* IMPORTS */
extern int main(int argc, char **argv);         /* the point of it all   */
extern FILEHANDLE __dup(int new, int old);
extern void _ctype_init(void);
extern int _fprintf_lf(FILE *fp, const char *fmt, ...);
44
extern int _sprintf(char *buff, const char *fmt, ...);
Neil Turton's avatar
Neil Turton committed
45
extern int _sprintf_lf(char *buff, const char *fmt, ...);
46
extern _kernel_oserror *_kernel_peek_last_oserror(void);
Neil Turton's avatar
Neil Turton committed
47 48 49 50 51

/* HIDDEN EXPORTS */
void _main(char *s, int (*main)(int, char **));
void _backtrace(int why, int *address, _kernel_unwindblock *uwb);
const char *_clib_version(void);
52 53
int _sys_msg_1(const char *s, const char *but);
int _desktop_task(void);
Neil Turton's avatar
Neil Turton committed
54 55 56 57

#define str(x)  #x
#define xstr(x) str(x)
const char *_clib_version(void)
58 59 60 61 62 63 64 65
{
    return LIB_SHARED "C Library vsn " xstr(Module_Version) "/"
    #ifdef __APCS_32
           "32"
    #else
           "R"
    #endif
           " [" __DATE__ "]\n";
Neil Turton's avatar
Neil Turton committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
}
#undef str
#undef xstr

static int unused[3];

/* timing things... */

/* struct bbctime objects are used to hold bbc/brazil 5-byte timer value -
   conventionally centi-seconds since 1-Jan-1900.
*/

struct bbctime {unsigned int l,h;};

static clock_t _time0;

Ben Avison's avatar
Ben Avison committed
82
static clock_t _clock(void)
Neil Turton's avatar
Neil Turton committed
83
{   struct bbctime bt;
84
    _kernel_osword(1, (int *)&bt);
Neil Turton's avatar
Neil Turton committed
85 86 87
    return bt.l;
}

Ben Avison's avatar
Ben Avison committed
88
static void _clock_init(void)   /* private - for initialisation */
Neil Turton's avatar
Neil Turton committed
89 90 91 92 93 94 95 96 97 98
{   _time0 = _clock();
}

static void _clock_ignore(clock_t t)
/* ignores ticks from t to now - used to remove terminal input waits */
{   _time0 += (_clock() - _time0) - t;
}

/* Exported... */

Ben Avison's avatar
Ben Avison committed
99
clock_t clock(void)
Neil Turton's avatar
Neil Turton committed
100 101 102 103
{   return _clock() - _time0;     /* clock runs even if date not set */
}

time_t time(time_t *timer)
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
{
    /* ISO9899 7.23.1 (1) defines either 'calendar time' or 'local time'           */
    /* Local time is further defined as incorporating timezone and daylight saving */
    /* information, therefore calendar time is implicitly taken to mean UTC.       */
    /* ISO9899 7.23.2.4 (3) this function determines the calendar time.            */
    /* This implementation uses seconds since the UNIX epoch 01-Jan-1970.          */
    time_t result;
    struct bbctime bt, w, w2;

    bt.l = 3;                       /* 'request time' arg */
    _kernel_osword(14, (int *)&bt); /* read time as UTC 5 byte integer  */

    /* to two 3-byte things - for divide */
    w.h = ((bt.h & 255) << 8) | (bt.l >> 24);
    w.l = bt.l & 0xffffff;
    /* turn csecs to secs */
    w2.h = w.h / 100;
    w2.l = ((w.h % 100 << 24) | w.l) / 100;
    /* back to 8 byte binary */
    bt.h = w2.h >> 8;
    bt.l = (w2.h << 24) | w2.l;
    /* normalise to Jan70 instead of Jan00... */
Neil Turton's avatar
Neil Turton committed
126
#define secs0070 (((unsigned)86400)*(365*70+17))  /* less than 2^32 */
127 128 129 130
    if (bt.l < secs0070) bt.h--;
    bt.l -= secs0070;
    /* if high word is non-zero then date is unset/out of unix range... */
    result = bt.h ? -1 : bt.l;
Neil Turton's avatar
Neil Turton committed
131

132 133
    if (timer) *timer = result;
    return result;
Neil Turton's avatar
Neil Turton committed
134 135 136 137
}

/* system dependent I/O routines ... */

Kevin Bracey's avatar
Kevin Bracey committed
138 139 140 141 142 143 144 145
/* Riscos has a second distinguished FILEHANDLE value, to indicate that  */
/* a file is a keyboard and/or vdu, which can't be read or written using */
/* Riscos file operations (or at any rate, couldn't when the library was */
/* originally implemented).                                              */
#define TTYHANDLE 0

#define istty(fh) ((fh) == TTYHANDLE)

146 147 148 149 150
/*
 * We're a desktop task if we're in user mode, TaskWindow_TaskInfo 0 returns 0 (or an error),
 * and Wimp_ReadSysInfo 3 says we're in the desktop, and Wimp_ReadSysInfo 5 gives us a
 * task handle.
 */
Ben Avison's avatar
Ben Avison committed
151
int _desktop_task(void)
152
{
153
    _kernel_swi_regs r;
154
    if (_kernel_processor_mode() & 0xF) return 0;
155 156 157 158 159 160 161 162 163
    r.r[0] = 0;
    if (_kernel_swi(TaskWindow_TaskInfo, &r, &r) || r.r[0])
        return 0;
    r.r[0] = 3;
    _kernel_swi(Wimp_ReadSysInfo, &r, &r);
    if (r.r[0] == 0) return 0;
    r.r[0] = 5;
    _kernel_swi(Wimp_ReadSysInfo, &r, &r);
    return r.r[0];
164 165 166 167
}

static int _desktop_report(const char *s, const char *but)
{
168
    _kernel_swi_regs r;
169 170
    _kernel_oserror err, *e;
    char *p, *end;
171
    int flags, h = _desktop_task();
172 173 174 175 176 177 178
    if (h == 0) return 0;

    flags = 0x102; /* New error, cancel button */

    if ((e = _kernel_last_oserror()) != NULL && s == e->errmess)
    {
        flags |= 2 << 9;
179
        err = *e;
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
    }
    else
    {
        while (*s == ' ')
            s++;

        if (s[0] == '*') /* If leading '*'s then make it a serious one */
        {
            while (*s == '*' || *s == ' ') /* Strip off the '*'s */
                s++;
            flags |= 3 << 9;
            err.errnum = 0x1B << 24;
        }
        else
        {
            flags |= 2 << 9;
            err.errnum = 0;
        }

        for (p = err.errmess, end = err.errmess + sizeof err.errmess - 1; p < end && *s >= ' '; )
            *p++ = *s++;

        *p = '\0';
        err.errmess[0] = toupper(err.errmess[0]);
    }
205 206 207 208 209
    r.r[0] = h;
    if (_kernel_swi(TaskManager_TaskNameFromHandle, &r, &r) == 0)
        r.r[2] = r.r[0];
    else
        r.r[2] = 0;
210
    r.r[0] = (int) &err;
211 212 213 214 215 216 217 218
    r.r[1] = flags;
    r.r[3] = 0;
    r.r[4] = 1;
    r.r[5] = (int) but;
    if (_kernel_swi(Wimp_ReportError, &r, &r) == 0)
        return r.r[1];
    else
        return 0;
219 220
}

221
bool _sys__assert(const char *s, const char *expr, const char *func, const char *file, int line)
222 223
{
    char buffer[252];
224
    int len, funclen, exprlen, filelen;
225 226 227 228 229 230 231

    if (!istty(stderr->__file)) return false;

    if (!_desktop_task()) return false;

    if (strlen(s) > 200) return false; /* Be safe */

232 233 234
    len = func ? _sprintf(buffer, s, "", "", "", line)
               : _sprintf(buffer, s, "", "", line);
    funclen = func ? strlen(func) : 0;
235 236
    exprlen = strlen(expr);
    filelen = strlen(file);
237
    if (len + funclen + exprlen + filelen < 251)
238
    {
239 240
        func ? _sprintf(buffer, s, expr, func, file, line)
             : _sprintf(buffer, s, expr, file, line);
241 242 243 244
    }
    else
    {
        char expr2[200];
245
        char func2[50];
246 247 248 249
        char file2[100];

        #define min(a,b) a<b?a:b
        exprlen = min(exprlen, 199);
250
        funclen = min(funclen, 49);
251
        filelen = min(filelen, 99);
252
        filelen = min(filelen, 251-len-funclen-exprlen);
253
        if (filelen < 0) filelen = 0;
254 255 256
        funclen = min(funclen, 251-len-exprlen-filelen);
        if (funclen < 0) funclen = 0;
        exprlen = min(exprlen, 251-len-funclen-filelen);
257
        memcpy(expr2, expr, exprlen);
258
        memcpy(func2, func, funclen);
259 260
        memcpy(file2, file, filelen);
        expr2[exprlen]='\0';
261
        func2[funclen]='\0';
262
        file2[filelen]='\0';
263 264
        func ? _sprintf(buffer, s, expr2, func2, file2, line)
             : _sprintf(buffer, s, expr2, file2, line);
265 266 267 268
    }
    return _desktop_report(buffer, NULL);
}

Neil Turton's avatar
Neil Turton committed
269
static int _error_recursion;
270 271 272 273 274 275 276 277 278
int _sys_msg_1(const char *s, const char *but)
{
    if (istty(stderr->__file))
    {
        int r = _desktop_report(s, but);
        if (r) return r;
    }

    /* write out s carefully for intimate system use.                      */
Neil Turton's avatar
Neil Turton committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292
    if ((stderr->__flag & _IOWRITE) && !_error_recursion)
    {
        _error_recursion = 1;
        fputc('\n', stderr);
        while (*s >= ' ')
            fputc(*s++, stderr);
        fputc('\n', stderr);
        _error_recursion = 0;
    }
    else
    {   _ttywrite((unsigned char *)"\n", 1, 0);
        _ttywrite((unsigned char *)s, strlen(s), 0);
        _ttywrite((unsigned char *)"\n", 1, 0);
    }
293 294 295 296 297 298 299

    return 0;
}

void _sys_msg(const char *s)
{
    _sys_msg_1(s, NULL);
Neil Turton's avatar
Neil Turton committed
300 301 302
}

#define LF '\n'
303
#define CR '\r'
Neil Turton's avatar
Neil Turton committed
304 305 306 307 308 309 310 311 312

static int isttyname(const char *s)
{   if (s[0] == ':' && (s[1]|0x20) == 't' && (s[2]|0x20) == 't' && s[3] == 0)
        return 1;   /* string specification (:tt) of terminal stream */
    return 0;
}

FILEHANDLE _sys_open(const char *filename, int openmode)
{ /* nasty magic number interface for openmode */
Kevin Bracey's avatar
Kevin Bracey committed
313 314 315
  static const int modtab[6] = { /* r = */ 0x04c, /* r+ = */ 0x0cc,
                                 /* w = */ 0x4cc, /* w+ = */ 0x4cc,
                                 /* a = */ 0x3cc, /* a+ = */ 0x3cc };
Neil Turton's avatar
Neil Turton committed
316 317 318 319 320 321 322 323 324
  if (isttyname(filename)) return TTYHANDLE;
  else {
    char *name = (char *)filename;                 /*  yuk yuk yuk yuk yuk  */
    FILEHANDLE fh;
    int size = 16 * 1024;                    /* first try for created files */
    int osmode = modtab[(openmode >> 1) & 7];    /* forget the 'b'inary bit */
    _kernel_osfile_block fb;

    /* maybe stamp file with current datestamp */
Kevin Bracey's avatar
Kevin Bracey committed
325 326 327 328
    if ((openmode & OPEN_T) ||                /* update timestamp requested */
        (openmode & OPEN_W) ||
        (openmode & ~OPEN_B) == OPEN_A)           /* or mode = w, w+, or a */
    {   if (_kernel_osfile(9, name, &fb) == _kernel_ERROR)
329 330
        {   if (_kernel_peek_last_oserror()->errnum == 0x108c9)
            {   errno = -1;
Neil Turton's avatar
Neil Turton committed
331 332 333 334 335 336
                return NONHANDLE;                       /* (Protected disc) */
            }
        }
    }
retry_open:
    fh = _kernel_osfind(osmode & 0xff, name);
Kevin Bracey's avatar
Kevin Bracey committed
337 338
    if (osmode <= 0x0cc) {                                       /* r or r+ */
      if (fh == _kernel_ERROR) errno = -1;
Neil Turton's avatar
Neil Turton committed
339 340
      return (fh <= 0) ? NONHANDLE :                           /* not found */
                         fh;
Kevin Bracey's avatar
Kevin Bracey committed
341 342
    } else if (fh > 0) {
      if ((osmode == 0x4cc) || (size == 0))
Neil Turton's avatar
Neil Turton committed
343 344
          if (_kernel_osargs(3, fh, 0) == _kernel_ERROR) {
              _kernel_osfind(0, (char *)fh);
Kevin Bracey's avatar
Kevin Bracey committed
345
              errno = -1;
Neil Turton's avatar
Neil Turton committed
346 347 348
              return NONHANDLE;
          }
      return fh;
Kevin Bracey's avatar
Kevin Bracey committed
349
    } else if (fh <= 0) {
Neil Turton's avatar
Neil Turton committed
350 351 352 353 354
        /* _kernel_osfile(11) creates an empty file of size 'size', of type */
        /* given by fb.load, stamped with the current date & time           */
      fb.load = (openmode & 1) ? 0xffd : 0xfff;              /* data : text */
      fb.start = 0;
      for (; ; size >>= 1) {
Kevin Bracey's avatar
Kevin Bracey committed
355
        if (size < 512) { errno = -1; return NONHANDLE; }
Neil Turton's avatar
Neil Turton committed
356 357 358 359 360 361
        fb.end = size;
        if (_kernel_osfile(11, name, &fb) > 0) break;
      }
      size = 0;
      goto retry_open;
    }
Kevin Bracey's avatar
Kevin Bracey committed
362
    if (fh == _kernel_ERROR) errno = -1;
Neil Turton's avatar
Neil Turton committed
363 364 365 366
    return NONHANDLE;
  }
}

Kevin Bracey's avatar
Kevin Bracey committed
367 368 369 370 371
int _sys_istty(FILE *stream)
{
    return istty(stream->__file);
}

Ben Avison's avatar
Ben Avison committed
372
int _sys_seek(FILEHANDLE fh, off64_t pos)
Kevin Bracey's avatar
Kevin Bracey committed
373 374
{
    if istty(fh) return 0;
Ben Avison's avatar
Ben Avison committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388
#if 1
    /* Can't use _kernel_osargs, even for 32-bit file pointers, because it can't handle files of size 4G-2 .*/
    /* Use _kernel_swi instead so that _kernel_last_oserror is set up on failure like it always was. */
    _kernel_swi_regs r;
    r.r[0] = 1;
    r.r[1] = fh;
    r.r[2] = (unsigned int) pos;
    if (_kernel_swi(OS_Args, &r, &r) != NULL)
    {
        errno = -1;
        return _kernel_ERROR;
    }
    return 0;
#else
Kevin Bracey's avatar
Kevin Bracey committed
389 390 391 392
    {   int rc = _kernel_osargs(1, fh, (int)pos);
        if (rc == _kernel_ERROR) errno = -1;
        return rc;
    }
Ben Avison's avatar
Ben Avison committed
393
#endif
Kevin Bracey's avatar
Kevin Bracey committed
394 395
}

Ben Avison's avatar
Ben Avison committed
396
off64_t _sys_flen(FILEHANDLE fh)
Kevin Bracey's avatar
Kevin Bracey committed
397
{
Ben Avison's avatar
Ben Avison committed
398 399 400 401 402 403 404 405 406 407 408 409 410
#if 1
    /* Can't use _kernel_osargs, even for 32-bit file pointers, because it can't handle files of size 4G-2 .*/
    /* Use _kernel_swi instead so that _kernel_last_oserror is set up on failure like it always was. */
    _kernel_swi_regs r;
    r.r[0] = 2;
    r.r[1] = fh;
    if (_kernel_swi(OS_Args, &r, &r) != NULL)
    {
        errno = -1;
        return _kernel_ERROR;
    }
    return (unsigned int) r.r[2];
#else
Kevin Bracey's avatar
Kevin Bracey committed
411 412 413
    int rc = _kernel_osargs(2, fh, 0);
    if (rc == _kernel_ERROR) errno = -1;
    return rc;
Ben Avison's avatar
Ben Avison committed
414
#endif
Kevin Bracey's avatar
Kevin Bracey committed
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
}

int _sys_write(FILEHANDLE fh, const unsigned char *buf, unsigned len, int mode)
{   if (istty(fh))
        return _ttywrite(buf, len, mode);
    else {
        _kernel_osgbpb_block b;
        b.dataptr = (void *)buf;
        b.nbytes = (int)len;
        if (_kernel_osgbpb(2, fh, &b) == _kernel_ERROR) {
            errno = -1;
            return _kernel_ERROR;
        } else
            return b.nbytes;
    }
}

int _sys_read(FILEHANDLE fh, unsigned char *buf, unsigned len, int mode)
{
    if (istty(fh))
        return _ttyread(buf, (int)len, mode);
    else {
        _kernel_osgbpb_block b;
        b.dataptr = (void *)buf;
        b.nbytes = (int)len;
        if (_kernel_osgbpb(4, fh, &b) == _kernel_ERROR) {
            errno = -1;
            return _kernel_ERROR;
        } else
            return b.nbytes;
    }
}

int _sys_ensure(FILEHANDLE fh)
{
    if (istty(fh)) return 0;
    {   int rc = _kernel_osargs(0xFF, fh, 0);
        if (rc == _kernel_ERROR) errno = -1;
        return rc;
    }
}

int _sys_close(FILEHANDLE fh)
{   if (istty(fh)) return 0;
    {   int rc = _kernel_osfind(0, (char *)fh);
        if (rc == _kernel_ERROR) errno = -1;
        return rc;
    }
}

int _ttywrite(const unsigned char *buf, unsigned int len, int flag)
Neil Turton's avatar
Neil Turton committed
466
/* behaves like Kgbpb, but outputs to console.                              */
467
/* if 'flag' has _IOBIN set then LF's ('\n's) do not have CR suffixed.      */
Neil Turton's avatar
Neil Turton committed
468 469 470 471
{   while (len-- > 0)
    {   int ch = *buf++;
        if (!(flag & _IOBIN)) {
          if (ch == '\n') {
472 473
            if (_kernel_oswrch(LF) < 0) return -1;
            ch = CR;
474
          } else if (ch < 32 && ch != 0x07 && ch != 0x08 && !isspace(ch)) {
Neil Turton's avatar
Neil Turton committed
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
            if (_kernel_oswrch('|') < 0) return -1;
            ch = (ch & 31) | 64;
          }
        }
        if (_kernel_oswrch(ch) < 0) return -1;
    }
    return 0;    /* number of chars unwritten */
}

int _ttyread(unsigned char *buff, int size, int flag)
{
/* behaviour similar to Kgbpb but reads from keyboard, performing local  */
/* edits as necessary.  Control chars echo as ^<upper case>.             */
/* AM: ignore clock ticks while waiting for keyboard                     */
/* If _IOBIN is set return 1st char read with no echo.
 * If _IONBF is set return 1st char read with echo.
 * Else read till CR LF ^D or EOF and return line.  Refuse echo if buffer full.
 */
    int count=0;
    time_t t = clock();
    do
    {   int ch;
        do {
            ch = _kernel_osrdch();
        } while (ch == -27) /* ESCAPE */;
        if (flag & _IOBIN && ch != EOF && ch != _kernel_ERROR)
            buff[count++] = ch;             /* binary - no echo */
        else switch (ch)
        {
case _kernel_ERROR:
case EOF:                                   /* see _osrdch for EOF */
case 0x04:  _clock_ignore(t);               /* ^D */
            return(0x80000000+size-count);
case '\n':                                  /* treat CR as LF */
case '\r':  if(count>=size) continue;
            _kernel_oswrch('\r'); _kernel_oswrch(LF);
            buff[count++] = '\n';
            _clock_ignore(t);
            return(size-count);
case 0x08:                                  /* BS     */
case 0x7f:  if(count!=0)                    /* rubout */
            {   _kernel_oswrch(0x7f);
                if (buff[--count] < ' ') _kernel_oswrch(0x7f);
            }
            break;
case 0x15:  while(count>0)                  /* ctrl-U kills line */
            {   _kernel_oswrch(0x7f);
                if (buff[--count] < ' ') _kernel_oswrch(0x7f);
            }
            break;
default:    if(count>=size) continue;
            if (ch < ' ' && ch != 0x07)
               _kernel_oswrch('|'), _kernel_oswrch(ch | '@');
            else
               _kernel_oswrch(ch);
            buff[count++] = ch;
            break;
        }
    } while (!(flag & _IOBIN+_IONBF));
    _clock_ignore(t);
    return(size-count);
}

int remove(const char *pathname)
{
    _kernel_osfile_block fb;
    if (_kernel_osfile(6, pathname, &fb) <= 0) return 1;
    return 0;
}

int rename(const char *old, const char *new)
{
547 548 549 550 551
    _kernel_swi_regs r;
    r.r[0] = 25;
    r.r[1] = (int) old;
    r.r[2] = (int) new;
    if (_kernel_swi(OS_FSControl, &r, &r)) return 1;
Neil Turton's avatar
Neil Turton committed
552 553 554 555 556 557 558 559 560 561 562 563
    return 0;
}

void _sys_tmpnam_(char *name, int sig)
{
    if (_kernel_getenv("wimp$scrapdir", name, L_tmpnam-10) != NULL)
      strcpy(name, "$.tmp");
    name += strlen(name);
    sprintf(name, ".x%.8x", sig);
}

static char *_getenv_value;
564
static size_t _getenv_size;
Neil Turton's avatar
Neil Turton committed
565 566 567

char *getenv(const char *name)
{
568 569 570
    _kernel_swi_regs r, rout;
    _kernel_oserror *e;

571 572 573 574
    /* Allocate a buffer of 256 bytes if we don't already have one */
    if (_getenv_value == NULL)
    {
      _getenv_size=256;
575
      if ( (_getenv_value = _kernel_RMAalloc(_getenv_size)) == NULL)
576 577 578 579 580 581
      {
         _getenv_size = 0;
         return NULL;      /* Could not allocate buffer */
      }
    }

582 583 584 585 586
    /* Whilst we keep getting buffer overflow errors, try to extend the buffer
     * a bit and try again.  Note that you CANNOT rely on OS_ReadVarVal returning
     * (NOT length) in R2 since this doesn't work for number or macro variables.
     * It doesn't work.
     */
587

588 589 590
    r.r[0] = (int) name;
    r.r[3] = 0;
    r.r[4] = 3;
591 592 593
    do {
      /* Try to read into the current buffer */
      r.r[1] = (int) _getenv_value;
594
      r.r[2] = _getenv_size - 1;   /* Leave one byte in buffer for terminating null to be added later */
595 596
      if ((e = _kernel_swi(OS_ReadVarVal, &r, &rout)) != NULL)
      {
597
          /* What was the error? */
598
          if (e->errnum != 0x1E4)
599
              return NULL;   /* It wasn't buffer overflow, so return NULL */
600

601
          /* Buffer overflow occurred, so try to reallocate the buffer */
602 603
          _kernel_RMAfree(_getenv_value);
          _getenv_value = _kernel_RMAalloc(_getenv_size += 256);
604 605 606 607 608 609
          if (_getenv_value == NULL) {
              _getenv_size = 0;
              return NULL;
          }
      }
    } while (e);
610 611 612 613 614

    /* Terminate the value */
    _getenv_value[rout.r[2]] = '\0';

    return _getenv_value;
Neil Turton's avatar
Neil Turton committed
615 616
}

Richard Manby's avatar
Richard Manby committed
617 618 619
void _terminate_getenv(void)
{
    if (_getenv_value)
620
        _kernel_RMAfree(_getenv_value);
Richard Manby's avatar
Richard Manby committed
621 622 623 624

    _getenv_value = NULL;
}

Neil Turton's avatar
Neil Turton committed
625 626 627
#ifdef DDE
#define DDEUtils_SetCLSize 0x42581
#define DDEUtils_SetCL     0x42582
628
#define DDEUtils_FlushCL   0x4258B
Neil Turton's avatar
Neil Turton committed
629 630 631 632 633 634 635 636 637 638 639 640 641
#endif

int system(const char *string)
{
#define CALL  0
#define CHAIN 1
    int rc;
#ifdef DDE
    int type;
    char *cmd_string, *cmd;
    char *s, *t;
    _kernel_swi_regs r;
#endif
642 643 644
    int procmode = _kernel_processor_mode() & 0xF; /* Privileged mode iff procmode != 0 */
    if (string==NULL) return (procmode == 0);
    if (procmode != 0) return -2;
Neil Turton's avatar
Neil Turton committed
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
#ifdef DDE
    type = CALL;
#endif
    if ((string[0] | 0x20)=='c') {
      char c = string[1] | 0x20;
      if (c=='a') {
        if ((string[2] | 0x20)=='l' && (string[3] | 0x20)=='l' &&
            string[4]==':') string = string+5;
      } else if (c=='h') {
        if ((string[2] | 0x20)=='a' && (string[3] | 0x20)=='i' &&
            (string[4] | 0x20)=='n' && string[5]==':') {
          string = string+6;
#ifdef DDE
          type = CHAIN;
#else
          _lib_shutdown();
          _kernel_system(string, CHAIN);
          /* which never returns */
#endif
        }
      }
    }
#ifdef DDE
    cmd_string = 0;
    if (strlen(string) > 255) {
        s = (char *)string;
        while (*s == ' ') s++;
        cmd = s;
        while (*s > ' ') s++;
        while (*s == ' ') s++;
        r.r[0] = strlen(s) + 1;
        if (!_kernel_swi(DDEUtils_SetCLSize, &r, &r)) {
            r.r[0] = (int)s;
            if (!_kernel_swi(DDEUtils_SetCL, &r, &r)) {
                cmd_string = malloc(s - cmd + 1);
                if (cmd_string) {
                    s = cmd;
                    t = cmd_string;
                    while (*s > ' ') *t++ = *s++;
                    *t++ = 0;
                    string = cmd_string;
                }
            }
        }
689 690
    } else {
        _kernel_swi(DDEUtils_FlushCL, &r, &r);
Neil Turton's avatar
Neil Turton committed
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
    }
    if (type == CHAIN)
        _lib_shutdown();
    rc = _kernel_system(string, type);
    if (cmd_string)
        free(cmd_string);
#else
    rc = _kernel_system(string, CALL);
#endif
    if (rc != 0) return rc;
    else
    { char *env;
      env = getenv("Sys$ReturnCode");
      if (env == NULL) return 0;
      else return (atoi(env));
    }
    /* -2 Kernel Fail, 0 = OK. Any other = result code from subprogram exit */
#undef CALL
#undef CHAIN
}

char *decimal_point = ".";

void _armsys_lib_init(void)
{   char *stdinfile  = TTYFILENAME,
         *stdoutfile = TTYFILENAME,
         *stderrfile = TTYFILENAME;
Ben Avison's avatar
Ben Avison committed
718
    (void) unused;
Neil Turton's avatar
Neil Turton committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    _getenv_value = NULL;
    _error_recursion = 0;
    _ctype_init();          /* C locale */
    _exit_init();           /* must happen before exit() can be called   */
    _signal_init();         /* had better be done pretty early           */
    _clock_init();          /* set Cpu time zero point                   */
    _init_alloc();          /* as had the allocator                      */
/* SIGINT events are not safe until about now.                           */
    _raise_stacked_interrupts();       /* enable SIGINT                  */
    if (!_kernel_client_is_module())
        _initio(stdinfile, stdoutfile, stderrfile);
}

void _main(char *s, int (*main)(int, char **))
#define LINE_SIZE 256
#define BAD_REDIRECTION {goto bad_redirection;}
#define NO_REDIRECTION goto no_redirection
{   char ch;
    static char **argv;
    static char *args;
    int curarg = 0, in_quotes = 0, was_quoted = 0;
    int after_file_name = 0, redirection = 0;
    int argc = 1, i = 0;
    int pre_digit = 0, dup_arg_1 = 0;
    char mode[2];

    while (s[i] != 0)
    {  while (isspace(s[i])) i++;
       while ((!isspace(s[i])) && s[i] != 0) i++;
       argc++;
    }
    argv = _sys_alloc(argc*sizeof(char *));
    args = _sys_alloc(++i);
    _init_user_alloc();

    i = 0; argc = 0;
    do
    {   ch = *s++;
        if (!in_quotes)
        {   if (ch == '"')
            {   was_quoted = in_quotes = 1;
                ch = *s++;
            }
            else if ((i == curarg) && (!after_file_name))
            {   char *next = s - 1;
                pre_digit = -1; dup_arg_1 = -1;
                mode[0] = 0; mode[1] = 0;
                if (*next >= '0' && *next <= '9') pre_digit = *next++ - '0';
                if ((*next == '>') || (*next == '<'))
                {   if (*next == '>') /* stdout or stderr */
                    {   mode[0] = 'w';
                        if (pre_digit == 0 || pre_digit > 2) BAD_REDIRECTION
                        else if (*++next == '>') { mode[0] = 'a'; next++; }
                    } else
                    {   char *p;
                        next++;
                        for (p = next; (*p != 0) && (*p != ' '); p++)
                            if (*p == '>') NO_REDIRECTION;
                        if (pre_digit > 0) BAD_REDIRECTION
                        mode[0] = 'r';
                    }
                    if (*next == '&')
                    {   if (pre_digit != -1) /* was a preceeding digit */
                        {   if ((pre_digit > 0) &&
                                ((*++next >= '0') && (*next <= '2')) &&
                                (*next++ == (pre_digit % 2 + 1) + '0'))
                            {   /* 2>&1 or 1>&2 */
                                mode[0] = 0; /* no fopen required */
                                dup_arg_1 = pre_digit;
                            } else BAD_REDIRECTION
                        } else /* no preceeding digit */
                        {   next++;
                            dup_arg_1 = 2;
                            pre_digit = (mode[0] != 'r'); /* default = 0 or 1 */                        }
                    }
                    else if (pre_digit == -1)
                        pre_digit = (mode[0] != 'r'); /* default = 0 or 1 */

                    if (mode[0] != 0)
                    {   after_file_name = 1;
                        while (isspace(*next)) next++;
                        if (*next == '"') { in_quotes = 1; next++; }
                    }
                    else if ((*next != 0) && (!isspace(*next)))
                        BAD_REDIRECTION
                    redirection = 1;
                    s = next; ch = *s++;
                }
            }
        }
        if (in_quotes)
        {   if ((ch == '\\') && ((*s == '"') || (*s == '\\')))
                ch = *s++;
            else
                while (ch == '"') {in_quotes = !in_quotes;  ch = *s++;}
        }

no_redirection:
        if (ch != 0 && (in_quotes || !isspace(ch)))
        {   args[i++] = ch;
            continue;
        }
        /* Assert: ((ch == 0) || (isspace(ch) && !in_quotes)) */
        /* ------- possible end of arg ---------------------- */
        if (i != curarg || was_quoted || (redirection && !after_file_name))
        {   /* end of arg */
            args[i++] = 0;
            if (redirection)
            {   if (after_file_name &&
                       freopen(&args[curarg], mode, &__iob[pre_digit]) == 0) {
                    _fprintf_lf(stderr,
                       _kernel_getmessage("can't open '%s' for I/O redirection", "C19"),
                       &args[curarg]);
                    fputc('\n', stderr);
                    exit(EXIT_FAILURE);
                }
                if ((dup_arg_1 > -1) &&
                    (__dup(dup_arg_1, dup_arg_1 % 2 + 1) != TTYHANDLE))
                {   /* data to go to file */
                    FILE *s_new = &__iob[dup_arg_1];
                    FILE *s_old = &__iob[dup_arg_1 % 2 + 1];
                    setvbuf(s_new, _sys_alloc(LINE_SIZE), _IOLBF, LINE_SIZE);
                    s_new->__flag |= _IOSBF;
                    setvbuf(s_old, _sys_alloc(LINE_SIZE), _IOLBF, LINE_SIZE);
                    s_old->__flag |= _IOSBF;
                }
                redirection = 0; after_file_name = 0; i = curarg;
            }
            else
            {   argv[argc++] = &args[curarg];
                curarg = i;
            }
        }
        if (ch != 0) { in_quotes = was_quoted = 0; }
    }
    while (ch != 0);

    if (in_quotes) {
        _fprintf_lf(stderr, _kernel_getmessage("missing double quotes", "C20"));
        fputc('\n', stderr);
        exit(EXIT_FAILURE);
    }

    argv[argc] = 0;      /* for ANSI spec */
    exit(/* hmm, relies on lots of things, but fast! */
         (argc > 0 && (*(int *)argv[0] & ~0x20202020) == *(int *)"RUN") ?
              _call_client_2(main, argc-1, argv+1) :
              _call_client_2(main, argc, argv));

bad_redirection:
    _fprintf_lf(stderr,
                _kernel_getmessage("unsupported or illegal I/O redirection '%s'", "C21"),
                --s);
    fputc('\n', stderr);
    exit(EXIT_FAILURE);
#undef NO_REDIRECTION
#undef LINE_SIZE
#undef BAD_REDIRECTION
}

879
static void p_in(unsigned int pc)
Neil Turton's avatar
Neil Turton committed
880
{
881
    _fprintf_lf(stderr, _kernel_getmessage("%x in ", "C22"), pc);
Neil Turton's avatar
Neil Turton committed
882 883 884 885 886 887 888
}

#define ERROR_ILLEGALREAD 0x80800ea0
#define ERROR_ILLEGALWRITE 0x80800ea1

void _backtrace(int why, int *address, _kernel_unwindblock *uwb)
{   /* all the messages in the following should go to stderr             */
889
    const unsigned int psr_mask = (_kernel_processor_mode() & 0x1C) != 0 ? 0 : 0xFC000003;
Neil Turton's avatar
Neil Turton committed
890 891
    FILE *err = stderr;
    char *lang = _kernel_language(uwb->pc);
892
    unsigned cl_base, cl_limit;
Neil Turton's avatar
Neil Turton committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
    _kernel_swi_regs r;

    r.r[0] = 18;
    r.r[1] = (int)"SharedCLibrary";
    cl_base = 0;
    cl_limit = 0;
    if (!_kernel_swi(OS_Module, &r, &r)) {
        cl_base = r.r[3];
        cl_limit = cl_base + *((int *)(cl_base - 4));
    }
    if (why==ERROR_ILLEGALREAD || why == ERROR_ILLEGALWRITE) {
        _fprintf_lf(err, _kernel_getmessage("(address %p)", "C23"), address);
        fputc('\n', err);
    } else {
        fputc('\n', err);
        _fprintf_lf(err, _kernel_getmessage("Postmortem requested", "C24"));
    }
    fputc('\n', err);

/* Now unwind the stack. I keep track of sp here (as well as fp), but for */
/* the moment I make no use of it.                                       */
    while (uwb->fp!=0)
    {   int *z, i, nargs, *argp;
        char *name = 0;
        int *fp = (int *) uwb->fp;
Neil Turton's avatar
Neil Turton committed
918
        _kernel_swi_regs r;
Neil Turton's avatar
Neil Turton committed
919
        if (lang[0]=='C' && lang[1]==0) {
920
            z = (int *)(fp[0] &~ psr_mask);
921 922
/* Check that when I save pc in a STM instruction it could save PC+8 or  */
/* PC+12 beyond the instruction.                                         */
Neil Turton's avatar
Neil Turton committed
923 924 925 926 927
            r.r[0] = 0;
            if (!_kernel_swi(OS_PlatformFeatures, &r, &r) && (r.r[0] & 8))
                z -= 2;
            else
                z -= 3;
Neil Turton's avatar
Neil Turton committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
/* If the word before the STM is itself STM sp!, {a1-a4} that shows      */
/* where I should find args, and suggests that there are >= 5.           */
/* (this needs to work whether sp is r12 or r13)                         */
            argp = fp+1;
            if ((*(z-1) & ~0x00010000) ==0xe92c000f) {
                nargs = 5;
            } else {
                int mask = *z & 0xffff;
/* Otherwise args were stored as part of the main STM. Find out where &  */
/* how many.                                                             */
                nargs = 0;
                while (mask != 0)
                {   argp--;
                    if (mask & 0xf) ++nargs;
                    mask ^= mask & (-mask);
                }
            }
/* Print args from the highest one downwards, in hex and decimal         */
            argp += nargs;
            while (nargs!=0) {
                int v = *(--argp);
                int carry;

                _fprintf_lf(err,
                            _kernel_getmessage("  Arg%d: %#.8x %d", "C25"),
                            nargs--, v, v);
/* Indirect through addresses that might be legal...                     */
955 956 957 958 959 960 961 962 963 964
                if (v && !(v & 3)) {
                    r.r[0] = (int)v;
                    r.r[1] = (int)v + 4 * 4 - 1;
                    if (!_kernel_swi_c(OS_ValidateAddress, &r, &r, &carry)) {
                        if (!carry) {
                            unsigned *vp = (unsigned *)v;

                            fprintf(err, " -> [%#.8x %#.8x %#.8x %#.8x]",
                                    vp[0], vp[1], vp[2], vp[3]);
                        }
Neil Turton's avatar
Neil Turton committed
965 966 967 968 969 970 971 972 973 974 975 976 977
                    }
                }
                fputc('\n', err);
            }
/* I search up to 10 words before the STM looking for the marker that    */
/* shows me where the function name is.                                  */
            for (i=0; i<10; i++)
            {   int w = *--z;
                if ((w & 0xffff0000) == 0xff000000)
                {   name = (char *)z - (w & 0xffff);
                    break;
                }
            }
978
            p_in(uwb->pc & ~psr_mask);
Neil Turton's avatar
Neil Turton committed
979
            if (name == 0)
980
            {   if ((unsigned)z >= cl_base && (unsigned)z < cl_limit)
Neil Turton's avatar
Neil Turton committed
981 982 983 984 985 986 987
                    _fprintf_lf(err, _kernel_getmessage("shared library function", "C26"));
                else
                    _fprintf_lf(err, _kernel_getmessage("anonymous function", "C27"));
            }
            else
                _fprintf_lf(err, _kernel_getmessage("function %s", "C28"), name);
        } else {
988
            p_in(uwb->pc & ~psr_mask);
Neil Turton's avatar
Neil Turton committed
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
            if (lang==NULL) {
                _fprintf_lf(err, _kernel_getmessage("unknown procedure", "C29"));
            } else {
                char *procname = _kernel_procname(uwb->pc);
                if (procname!=NULL) {
                    _fprintf_lf(err,
                                _kernel_getmessage("%s procedure %s", "C30"),
                                lang, procname);
                } else {
                    _fprintf_lf(err,
                                _kernel_getmessage("anonymous %s procedure", "C31"),
                                lang);
                }
            }
        }
        fputc('\n', err);
        if (_kernel_unwind(uwb, &lang) < 0) {
            fputc('\n', err);
            _fprintf_lf(err, _kernel_getmessage("stack overwritten", "C32"));
            fputc('\n', err);
            break;
        }
    }
    exit(EXIT_FAILURE);
}

/* end of armsys.c */