/* 
 * utility to print the value of _stksize from gcc-cc1.ttp
 *
 *	Usage: printstk [<filename>]
 *		if <filename> is not specified defaults to .\gcc-cc1.ttp
 *	++jrb
 */

#include <stdio.h>
#include <stdlib.h>
#include <unixlib.h>
#include <string.h>
#include <st-out.h>

long lseek(int, long, int);

long find_offset (fd, fn)
int fd;
char *fn;
{
    struct aexec head;
    struct asym  sym;
    
    if(read(fd, &head, sizeof(head)) != sizeof(head))
    {
	perror(fn);
	exit(2);
    }
    if(head.a_magic != CMAGIC)
    {
	fprintf(stderr,"Invalid magic number %x\n", head.a_magic);
	exit(3);
    }
    if(head.a_syms == 0)
    {
	fprintf(stderr,"%s: no symbol table\n", fn);
	exit(4);
    }
    if(lseek(fd, head.a_text+head.a_data, 1) != 
       (head.a_text+head.a_data+sizeof(head)))
    {
	perror(fn);
	exit(5);
    }
    do {
	if(read(fd, &sym, sizeof(sym)) != sizeof(sym))
	{
	    fprintf(stderr, "symbol _stksize not found\n");
	    exit(6);
	}
    } while(strncmp("__stksiz", sym.a_name, 8) != 0);
    
    if( !(sym.a_type & A_DATA) )
    {
	fprintf(stderr, "symbol _stksize is undefined\n");
	exit(9);
    }
    return sym.a_value + sizeof(head);
}

int main(argc, argv)
int argc;
char **argv;
{
    int fd;
    long stksize, offset;
    char fn[FILENAME_MAX];
    
    if(argc > 1)
	(void) strcpy(fn, *++argv);
    else
	(void) strcpy(fn, "gcc-cc1.ttp");
    
    if((fd = open(fn, 0)) < 0)
    {
	perror(fn);
	exit(1);
    }
    
    offset = find_offset(fd, fn);
    
    if(lseek(fd, offset, 0) != offset)
    {
	perror(fn);
	exit(7);
    }
    read(fd, &stksize, sizeof(long));
    printf("%s: stksize is %ld (%dK)\n", fn, stksize, (int)(stksize/1024));
    
    return close(fd);
}

