Article: 5963 of alt.sources
Newsgroups: alt.sources
Path: bloom-picayune.mit.edu!bloom-beacon!micro-heart-of-gold.mit.edu!wupost!uunet!noc.near.net!wpi.WPI.EDU!wpi.WPI.EDU!rcarter
From: rcarter@wpi.WPI.EDU (Randolph Carter <Joseph H. Allen>)
Subject: Absolute linker for MS-DOS .OBJ files
Message-ID: <1992May30.191830.28037@wpi.WPI.EDU>
Sender: news@wpi.WPI.EDU (USENET News System)
Nntp-Posting-Host: wpi.wpi.edu
Organization: Worcester Polytechnic Institute
Date: Sat, 30 May 1992 19:18:30 GMT
Lines: 1664

Archive-name: alink
Submitted-by: rcarter@wpi.wpi.edu (Joseph H. Allen)

Ahhhhhgggghh!  The segments! They don't go where I want them to!  I put the
_BSS segment at 0, but it messes up the org in the _TEXT segment
Ahhhggggghhh!  It should be easy to stick a turbo-c program in ROM but it
isn't.  Die MS-DOS, Die kill microsoft, Bill Gates will not be
tolerated....  Nuke intel...  I refuse to pay $400 for lettuce C...  Ack. 
Bureaucratic totalitarianism.


= - = - = - = - =

Well I've written a new linker to solve the above problem (compile in MS-DOS
large model or on Xenix).  It's key feature is that you tell it where you
want the segments to be placed.  For example, it says:  

	Public segments: _TEXT _BSS _DATA
	Private segments:

And you respond

	>00000 _BSS
	>0F000 _TEXT _DATA

to place _BSS at zero and _TEXT followed by _DATA at F000 (the EPROM
address, for example).  It will then make a binary image file suitable for
use in the ROM burner (or as a boot program or as a device driver or as a
.COM file even...)

Sounds good?  Well here's the catch:  I can't find the format of .LIB files
documented anywhere and I can't find the format of the 386 32-bit .OBJ
records. 

I would love to make the linker complete, so if you have know these
formats please send them to me.  I've been able to live without them for the
small project I'm working on (I'm sticking Turbo-C code into an EPROM for a
little 8088 embedded system).

Also be warned: I wrote this in three days for a project I'm desperately
trying to finish.  It's likely to have bugs.

Let me know if have any other suggestions for this program.

= - = - = - =

Here's the goods:

#! /bin/sh
# This is a shell archive.  Remove anything before this line, then unpack
# it by saving it into a file and typing "sh file".  To overwrite existing
# files, type "sh file -c".  You can also feed this as standard input via
# unshar, or by typing "sh <file", e.g..  If this archive is complete, you
# will see the following message at the end:
#		"End of shell archive."
# Contents:  COPYING README alink.c
# Wrapped by rcarter@wpi on Sat May 30 14:48:34 1992
PATH=/bin:/usr/bin:/usr/ucb ; export PATH
if test -f 'COPYING' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'COPYING'\"
else
echo shar: Extracting \"'COPYING'\" \(12488 characters\)
sed "s/^X//" >'COPYING' <<'END_OF_FILE'
X
X		    GNU GENERAL PUBLIC LICENSE
X		     Version 1, February 1989
X
X Copyright (C) 1989 Free Software Foundation, Inc.
X                    675 Mass Ave, Cambridge, MA 02139, USA
X Everyone is permitted to copy and distribute verbatim copies
X of this license document, but changing it is not allowed.
X
X			    Preamble
X
X  The license agreements of most software companies try to keep users
Xat the mercy of those companies.  By contrast, our General Public
XLicense is intended to guarantee your freedom to share and change free
Xsoftware--to make sure the software is free for all its users.  The
XGeneral Public License applies to the Free Software Foundation's
Xsoftware and to any other program whose authors commit to using it.
XYou can use it for your programs, too.
X
X  When we speak of free software, we are referring to freedom, not
Xprice.  Specifically, the General Public License is designed to make
Xsure that you have the freedom to give away or sell copies of free
Xsoftware, that you receive source code or can get it if you want it,
Xthat you can change the software or use pieces of it in new free
Xprograms; and that you know you can do these things.
X
X  To protect your rights, we need to make restrictions that forbid
Xanyone to deny you these rights or to ask you to surrender the rights.
XThese restrictions translate to certain responsibilities for you if you
Xdistribute copies of the software, or if you modify it.
X
X  For example, if you distribute copies of a such a program, whether
Xgratis or for a fee, you must give the recipients all the rights that
Xyou have.  You must make sure that they, too, receive or can get the
Xsource code.  And you must tell them their rights.
X
X  We protect your rights with two steps: (1) copyright the software, and
X(2) offer you this license which gives you legal permission to copy,
Xdistribute and/or modify the software.
X
X  Also, for each author's protection and ours, we want to make certain
Xthat everyone understands that there is no warranty for this free
Xsoftware.  If the software is modified by someone else and passed on, we
Xwant its recipients to know that what they have is not the original, so
Xthat any problems introduced by others will not reflect on the original
Xauthors' reputations.
X
X  The precise terms and conditions for copying, distribution and
Xmodification follow.
X
X		    GNU GENERAL PUBLIC LICENSE
X   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
X
X  0. This License Agreement applies to any program or other work which
Xcontains a notice placed by the copyright holder saying it may be
Xdistributed under the terms of this General Public License.  The
X"Program", below, refers to any such program or work, and a "work based
Xon the Program" means either the Program or any work containing the
XProgram or a portion of it, either verbatim or with modifications.  Each
Xlicensee is addressed as "you".
X
X  1. You may copy and distribute verbatim copies of the Program's source
Xcode as you receive it, in any medium, provided that you conspicuously and
Xappropriately publish on each copy an appropriate copyright notice and
Xdisclaimer of warranty; keep intact all the notices that refer to this
XGeneral Public License and to the absence of any warranty; and give any
Xother recipients of the Program a copy of this General Public License
Xalong with the Program.  You may charge a fee for the physical act of
Xtransferring a copy.
X
X  2. You may modify your copy or copies of the Program or any portion of
Xit, and copy and distribute such modifications under the terms of Paragraph
X1 above, provided that you also do the following:
X
X    a) cause the modified files to carry prominent notices stating that
X    you changed the files and the date of any change; and
X
X    b) cause the whole of any work that you distribute or publish, that
X    in whole or in part contains the Program or any part thereof, either
X    with or without modifications, to be licensed at no charge to all
X    third parties under the terms of this General Public License (except
X    that you may choose to grant warranty protection to some or all
X    third parties, at your option).
X
X    c) If the modified program normally reads commands interactively when
X    run, you must cause it, when started running for such interactive use
X    in the simplest and most usual way, to print or display an
X    announcement including an appropriate copyright notice and a notice
X    that there is no warranty (or else, saying that you provide a
X    warranty) and that users may redistribute the program under these
X    conditions, and telling the user how to view a copy of this General
X    Public License.
X
X    d) You may charge a fee for the physical act of transferring a
X    copy, and you may at your option offer warranty protection in
X    exchange for a fee.
X
XMere aggregation of another independent work with the Program (or its
Xderivative) on a volume of a storage or distribution medium does not bring
Xthe other work under the scope of these terms.
X
X  3. You may copy and distribute the Program (or a portion or derivative of
Xit, under Paragraph 2) in object code or executable form under the terms of
XParagraphs 1 and 2 above provided that you also do one of the following:
X
X    a) accompany it with the complete corresponding machine-readable
X    source code, which must be distributed under the terms of
X    Paragraphs 1 and 2 above; or,
X
X    b) accompany it with a written offer, valid for at least three
X    years, to give any third party free (except for a nominal charge
X    for the cost of distribution) a complete machine-readable copy of the
X    corresponding source code, to be distributed under the terms of
X    Paragraphs 1 and 2 above; or,
X
X    c) accompany it with the information you received as to where the
X    corresponding source code may be obtained.  (This alternative is
X    allowed only for noncommercial distribution and only if you
X    received the program in object code or executable form alone.)
X
XSource code for a work means the preferred form of the work for making
Xmodifications to it.  For an executable file, complete source code means
Xall the source code for all modules it contains; but, as a special
Xexception, it need not include source code for modules which are standard
Xlibraries that accompany the operating system on which the executable
Xfile runs, or for standard header files or definitions files that
Xaccompany that operating system.
X
X  4. You may not copy, modify, sublicense, distribute or transfer the
XProgram except as expressly provided under this General Public License.
XAny attempt otherwise to copy, modify, sublicense, distribute or transfer
Xthe Program is void, and will automatically terminate your rights to use
Xthe Program under this License.  However, parties who have received
Xcopies, or rights to use copies, from you under this General Public
XLicense will not have their licenses terminated so long as such parties
Xremain in full compliance.
X
X  5. By copying, distributing or modifying the Program (or any work based
Xon the Program) you indicate your acceptance of this license to do so,
Xand all its terms and conditions.
X
X  6. Each time you redistribute the Program (or any work based on the
XProgram), the recipient automatically receives a license from the original
Xlicensor to copy, distribute or modify the Program subject to these
Xterms and conditions.  You may not impose any further restrictions on the
Xrecipients' exercise of the rights granted herein.
X
X  7. The Free Software Foundation may publish revised and/or new versions
Xof the General Public License from time to time.  Such new versions will
Xbe similar in spirit to the present version, but may differ in detail to
Xaddress new problems or concerns.
X
XEach version is given a distinguishing version number.  If the Program
Xspecifies a version number of the license which applies to it and "any
Xlater version", you have the option of following the terms and conditions
Xeither of that version or of any later version published by the Free
XSoftware Foundation.  If the Program does not specify a version number of
Xthe license, you may choose any version ever published by the Free Software
XFoundation.
X
X  8. If you wish to incorporate parts of the Program into other free
Xprograms whose distribution conditions are different, write to the author
Xto ask for permission.  For software which is copyrighted by the Free
XSoftware Foundation, write to the Free Software Foundation; we sometimes
Xmake exceptions for this.  Our decision will be guided by the two goals
Xof preserving the free status of all derivatives of our free software and
Xof promoting the sharing and reuse of software generally.
X
X			    NO WARRANTY
X
X  9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
XFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
XOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
XPROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
XOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
XMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
XTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
XPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
XREPAIR OR CORRECTION.
X
X  10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
XWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
XREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
XINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
XOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
XTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
XYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
XPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
XPOSSIBILITY OF SUCH DAMAGES.
X
X		     END OF TERMS AND CONDITIONS
X
X	Appendix: How to Apply These Terms to Your New Programs
X
X  If you develop a new program, and you want it to be of the greatest
Xpossible use to humanity, the best way to achieve this is to make it
Xfree software which everyone can redistribute and change under these
Xterms.
X
X  To do so, attach the following notices to the program.  It is safest to
Xattach them to the start of each source file to most effectively convey
Xthe exclusion of warranty; and each file should have at least the
X"copyright" line and a pointer to where the full notice is found.
X
X    <one line to give the program's name and a brief idea of what it does.>
X    Copyright (C) 19yy  <name of author>
X
X    This program is free software; you can redistribute it and/or modify
X    it under the terms of the GNU General Public License as published by
X    the Free Software Foundation; either version 1, or (at your option)
X    any later version.
X
X    This program is distributed in the hope that it will be useful,
X    but WITHOUT ANY WARRANTY; without even the implied warranty of
X    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
X    GNU General Public License for more details.
X
X    You should have received a copy of the GNU General Public License
X    along with this program; if not, write to the Free Software
X    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
X
XAlso add information on how to contact you by electronic and paper mail.
X
XIf the program is interactive, make it output a short notice like this
Xwhen it starts in an interactive mode:
X
X    Gnomovision version 69, Copyright (C) 19xx name of author
X    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
X    This is free software, and you are welcome to redistribute it
X    under certain conditions; type `show c' for details.
X
XThe hypothetical commands `show w' and `show c' should show the
Xappropriate parts of the General Public License.  Of course, the
Xcommands you use may be called something other than `show w' and `show
Xc'; they could even be mouse-clicks or menu items--whatever suits your
Xprogram.
X
XYou should also get your employer (if you work as a programmer) or your
Xschool, if any, to sign a "copyright disclaimer" for the program, if
Xnecessary.  Here a sample; alter the names:
X
X  Yoyodyne, Inc., hereby disclaims all copyright interest in the
X  program `Gnomovision' (a program to direct compilers to make passes
X  at assemblers) written by James Hacker.
X
X  <signature of Ty Coon>, 1 April 1989
X  Ty Coon, President of Vice
X
XThat's all there is to it!
END_OF_FILE
if test 12488 -ne `wc -c <'COPYING'`; then
    echo shar: \"'COPYING'\" unpacked with wrong size!
fi
# end of 'COPYING'
fi
if test -f 'README' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'README'\"
else
echo shar: Extracting \"'README'\" \(1227 characters\)
sed "s/^X//" >'README' <<'END_OF_FILE'
X              Absolute Linker for MS-DOS .OBJ Files (BETA TEST)
X
XCompile in XENIX or in MS-DOS large model (I used Turbo-C).
X
X= - = - = - = - =
X
XALINK is a linker for MS-DOS .OBJ files which makes binary images.
X
XThe key feature which ALINK provides is absolute segment positioning.  For
Xexample, if you have a program with three segments:
X
X	_TEXT, _BSS, _DATA
X
XYou can tell the linker exactly where you want the segments to exist:
X
X	00000 _BSS		Places _BSS at 0
X	0F000 _TEXT _DATA	Places _TEXT followed by _DATA at 0F000
X
XThe purpose of this is to allow you to use the low-cost MS-DOS programming
Xtools to make code for boot disks and embedded systems (ROM).
X
X= - = - = - = - =
X
XMissing features:
X
X	(1) This will only work for 8086 and 80286 code.  32-bit 386 code is
Xnot supported.  If you know the format of the 32-bit .OBJ records, I will
Xgladly add 32-bit support if you send me the information.
X
X	(2) (This is the biggy) No .LIB file support.  If you know the file
Xformat for .LIB files, please send it to me.
X
X= - = - = - = - =
X
XJust run the program with no args to get a list of options.  Otherwise,
Xuseage should be obvious.
X
XOh, the binary image file which is created begins at the first generated
Xcode, not at zero.
END_OF_FILE
if test 1227 -ne `wc -c <'README'`; then
    echo shar: \"'README'\" unpacked with wrong size!
fi
# end of 'README'
fi
if test -f 'alink.c' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'alink.c'\"
else
echo shar: Extracting \"'alink.c'\" \(31091 characters\)
sed "s/^X//" >'alink.c' <<'END_OF_FILE'
X/* Absolute linker for MS-DOS .OBJ files or Xenix .o files
X   Copyright (C) 1992 Joseph H. Allen
X
XALINK is free software; you can redistribute it and/or modify it under the
Xterms of the GNU General Public License as published by the Free Software
XFoundation; either version 1, or (at your option) any later version.  
X
XALINK is distributed in the hope that it will be useful, but WITHOUT ANY
XWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
XA PARTICULAR PURPOSE.  See the GNU General Public License for more details.  
X
XYou should have received a copy of the GNU General Public License
Xalong with ALINK; see the file COPYING.  If not, write to
Xthe Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
X
X#include <stdio.h>
X#include <stdlib.h>
X/* #include <io.h> */	/* Uncomment for MS-DOS */
X#include <fcntl.h>
X#include <sys/types.h>
X#include <sys/stat.h>
X#include <string.h>
X
X/* Modes */
X
Xint quiet=0;
Xint errval=0;
Xchar *outfile=NULL;
Xchar *listfile=NULL;
X
X/* Hash function */
X
Xunsigned long hash(unsigned char *name)
X{
Xunsigned long accu=0;
Xwhile(*name) accu=accu*34857+*name++;
Xreturn accu;
X}
X
X/* Copy a size/string field from .OBJ file to buffer.  String gets zero
X * terminated
X */
X
Xvoid ncpy(char *d,char *s)
X{
Xunsigned len= *s++;
Xwhile(len--) *d++= *s++;
X*d=0;
X}
X
X/***********/
X/* A label */
X/***********/
X
Xunsigned nlabels=0;
X
Xstruct label
X {
X struct label *next;	/* Next label with same hash value */
X char *name;		/* Name of this label */
X char *file;		/* Object module where this was defined */
X 			/* NULL if not yet defined */
X unsigned long offset;	/* Value of label */
X
X /* Segment label is relative to */
X struct segment *seg;
X
X /* Group label is relatice to: must be zero if 'seg' is zero */
X /* What is this for? */
X struct segment *group;
X
X /* If 'seg' and 'group' above are zero, absolute paragraph number which label
X  * is relative to.  Usually (always?) this will be zero for EQU constants */
X unsigned frame;
X
X /* List of references to the label */
X /* Used to generate cross-reference listing */
X char **ref;
X unsigned nref;
X unsigned bksiz;
X };
X
X/**************************/
X/* A segment and/or group */
X/**************************/
X
Xstruct segment
X {
X struct segment *next;		/* Next segment/group with same hash value */
X char *name;			/* Name of this segment/group */
X
X /* Segment bound to name */
X char *file;		/* File where this was first defined */
X 			/* NULL if no segment bound to this name */
X int alignment;		/* 0=Absolute, 1=byte, 2=word, 3=para, 4=page */
X int combine;		/* 0=private, 2,4,5,7=concatenate, 6=union */
X unsigned frame;	/* Paragraph number if alignment==0 */
X
X /* During first pass for a given module, 'nlength' is length added to
X  * segment for just that module.  'length' is length of segment from
X  * previous modules */
X unsigned long length;	/* Segment size */
X unsigned long nlength;	/* New length for current module */
X
X /* Same as above, but for second pass */
X unsigned pos;		/* Current position withing segment */
X unsigned inc;		/* Increment to get next position */
X
X unsigned long addr;	/* Address assigned to this segment by 'position' */
X int set;		/* Set if address is assigned */
X
X /* A 64K segment may only have 2K of data in it (for example).  These record
X  * where the the 2K is in the segment (for example).  This is done in the
X  * first pass.
X  */
X unsigned long start;	/* Lowest code offset in segment */
X unsigned long end;	/* Highest code offset in segment */
X
X /* This is allocated before second pass using above information.  Size of
X  * malloc block is end-start.  First byte in this block is absolute
X  * address addr+start.
X  */
X unsigned char *buf;	/* Buffer where code and data goes in second pass */
X
X /* Group bound to name */
X char *gfile;		/* obj file where this was defined/NULL if undefined */
X struct segment **seglst;	/* Malloc array of segments in the group */
X unsigned lstsiz;		/* Number of segments in the group */
X unsigned long gaddr;	/* Group base address.  This is the 'addr' of the
X                           lowest segment in the group */
X };
X
X/* Hash table of labels */
X
Xstruct label *labels[512];
X
X/* Label lookup function.  Creates new structure if requested label is not
X * found */
X
Xstruct label *labelfind(char *name)
X{
Xunsigned hval=(hash(name)%511);
Xstruct label *l;
Xfor(l=labels[hval];l;l=l->next) if(!strcmp(name,l->name)) return l;
Xl=(struct label *)calloc(1,sizeof(struct label));
Xl->name=strdup(name);
Xl->next=labels[hval];
Xif(listfile)
X {
X l->ref=(char **)malloc((l->bksiz=10)*sizeof(char *));
X l->nref=0;
X }
X++nlabels;
Xlabels[hval]=l;
Xreturn l;
X}
X
X/* Hash table of segments/groups */
X
Xstruct segment *segments[512];
X
X/* Group/ public segment lookup function.  Creates new structure if given
X * name is not found */
X
Xstruct segment *segmentfind(char *name)
X{
Xunsigned hval=(hash(name)%511);
Xstruct segment *l;
Xfor(l=segments[hval];l;l=l->next) if(!strcmp(name,l->name)) return l;
Xl=(struct segment *)calloc(1,sizeof(struct segment));
Xl->start=0xffffffff;
Xl->name=strdup(name);
Xl->next=segments[hval];
Xsegments[hval]=l;
Xreturn l;
X}
X
X/* Table of private segments */
X
Xstruct segment *psegs[512];
Xunsigned psegidx=0;
X
X/* Private segment creation function.  'seg' is (possible unused) public
X * segment structure bound to private segment name.  'obj' is name of object
X * file where private segment is defined */
X
Xstruct segment *segprivate(struct segment *seg,char *obj)
X{
Xstruct segment *l;
Xl=(struct segment *)calloc(1,sizeof(struct segment));
Xl->name=seg->name;
Xl->file=obj;
Xpsegs[psegidx++]=l;
Xreturn l;
X}
X
X/* Find private segment: name should be given as SEGMENT(MODULE) */
X
Xstruct segment *privatefind(char *name)
X{
Xint x,y,z;
Xchar c1,c2;
Xfor(x=0;name[x] && name[x]!='(';++x);
Xif(!name[x]) return 0;
Xc1=name[x]; name[x]=0;
X++x;
Xfor(y=x;name[y] && name[y]!=')';++y);
Xc2=name[y]; name[y]=0;
Xfor(z=0;z!=psegidx;++z)
X if(!strcmp(name,psegs[z]->name) && !strcmp(name+x,psegs[z]->file))
X  {
X  name[x-1]=c1;
X  name[y]=c2;
X  return psegs[z];
X  }
Xname[x-1]=c1;
Xname[y]=c2;
Xreturn 0;
X}
X
X/* Find with names seperated.  (yeah yeah... so this is a little
X * confusing.  Just remember how much you paid for it :-)
X */
X
Xstruct segment *private1find(char *name,char *objname)
X{
Xint z;
Xfor(z=0;z!=psegidx;++z)
X if(!strcmp(name,psegs[z]->name) && !strcmp(objname,psegs[z]->file))
X  return psegs[z];
Xreturn 0;
X}
X
X/************************************/
X/* Macros to help access .obj files */
X/************************************/
X
X#define SIZ(x) (pgm[x]+(pgm[x+1]<<8))
X#define SIZINC(x) ((x)+=2, pgm[x-2]+(pgm[x-1]<<8))
X#define IDX(x) ((pgm[x]&0x80)?((pgm[x]&0x7F)<<8)+pgm[x+1]:pgm[x])
X#define IDXINC(x) \
X ((pgm[x]&0x80)?(x+=2,((pgm[x-2]&0x7F)<<8)+pgm[x-1]):pgm[(x)++])
X
X/**********************************************************/
X/* Indexable array of names relative to current .obj file */
X/* (Limits are those imposed by LINK)                     */
X/**********************************************************/
X
Xstruct segment *namearray[256];
Xint nameidx;
X
Xstruct segment *grouparray[22];
Xint groupidx;
X
Xstruct segment *segarray[256];
Xint segidx;
X
Xstruct label *externarray[1024];
Xint externidx;
X
X/* Function to determine size of repeated data block */
X
Xunsigned iteratedsz(unsigned char *pgm,unsigned *x,int n)
X{
Xunsigned amnt=0;
Xwhile(n--)
X {
X unsigned rpt=SIZINC(*x);
X unsigned blk=SIZINC(*x);
X if(!blk)
X  {
X  amnt+=rpt*pgm[*x];
X  *x+=pgm[*x]+1;
X  }
X else amnt+=iteratedsz(pgm,x,blk);
X }
Xreturn amnt;
X}
X
X/* Function to generate repeated data block */
X
Xvoid iterated(unsigned char *pgm,unsigned *x,int n,unsigned char **ptr)
X{
Xwhile(n--)
X {
X unsigned rpt=SIZINC(*x);
X unsigned blk=SIZINC(*x);
X if(!blk)
X  {
X  while(rpt--) memcpy(*ptr,pgm+*x+1,pgm[*x]), *ptr+=pgm[*x];
X  *x+=pgm[*x]+1;
X  }
X else iterated(pgm,x,blk,ptr);
X }
X}
X
X/* Function to add stupid common variables */
X
Xvoid addbss(char *name,char *objname,unsigned long size)
X{
Xstruct segment *seg=segmentfind("_bss");
Xstruct label *pub;
Xif(seg->file==NULL)
X {
X seg->file=objname;
X seg->alignment=2;
X seg->combine=2;
X }
Xpub=labelfind(name);
Xif(pub->file==NULL)
X {
X /* Alignment? */
X pub->file=objname;
X pub->offset=seg->length+seg->nlength;
X seg->nlength+=size;
X pub->seg=seg;
X }
X}
X
Xvoid addfar(char *name, char *objname,unsigned long size)
X{
Xstruct segment *seg=segmentfind("_bss");
Xstruct label *pub;
Xif(seg->file==NULL)
X {
X seg->file=objname;
X seg->alignment=2;
X seg->combine=2;
X }
Xpub=labelfind(name);
Xif(pub->file==NULL)
X {
X /* Alignment? */
X pub->file=objname;
X pub->offset=seg->length+seg->nlength;
X seg->nlength+=size;
X pub->seg=seg;
X }
X}
X
Xvoid pass1(char *objname)
X{
Xunsigned char *pgm;
Xunsigned x, nxt, size;
Xchar buf[256];
X
X/* Clear indexes */
Xexternidx=segidx=groupidx=nameidx=0;
X
X/* Load .OBJ file */
X {
X int fd=open(objname,O_RDONLY);
X struct stat buf;
X if(fd== -1) { fprintf(stderr,"Couldn\'t open file \'%s\'\n",objname); errval=1; return; }
X fstat(fd,&buf);
X pgm=(unsigned char *)malloc(buf.st_size);
X read(fd,pgm,buf.st_size);
X close(fd);
X size=buf.st_size;
X }
X
X/* Process .OBJ file */
Xfor(x=0;x!=size;x=nxt+1)
X {
X nxt=x+SIZ(x+1)+2;
X switch(pgm[x++])
X  {
X case 0x80:			/* Module name */
X case 0x88:			/* Comment */
X case 0x8E:			/* Type definition */
X case 0x94:			/* Line number */
X case 0x9C:			/* Fixup (skip on first pass) */
X  break;		/* Just ignore 'em */
X
X case 0xA0:			/* Code/Data (only record start & size) */
X  {
X  unsigned sz=SIZINC(x)-1;
X  unsigned ox=x;
X  struct segment *seg=segarray[IDXINC(x)-1];
X  unsigned ofst=SIZINC(x);
X  sz-=x-ox;
X  if(ofst+seg->length<seg->start) seg->start=ofst+seg->length;
X  if(ofst+sz+seg->length>seg->end) seg->end=ofst+sz+seg->length;
X  }
X  break;
X
X case 0xA2:			/* 'Dup' data (only record start & size) */
X  {
X  struct segment *seg=segarray[x+=2, IDXINC(x)-1];
X  unsigned ofst=SIZINC(x);
X  unsigned sz=iteratedsz(pgm,&x,1);
X  if(ofst+seg->length<seg->start) seg->start=ofst+seg->length;
X  if(ofst+sz+seg->length>seg->end) seg->end=ofst+sz+seg->length;
X  }
X  break;
X
X case 0x8A:			/* End of module */
X  {
X  int z;
X  for(z=0;z!=segidx;++z)
X   {
X   segarray[z]->length+=segarray[z]->nlength, segarray[z]->nlength=0;
X   if(segarray[z]->length>65536) fprintf(stderr,"Segment overflow \'%s\'\n",segarray[z]->name), errval=1;
X   }
X  externidx=segidx=groupidx=nameidx=0;
X  }
X  break;
X
X case 0x96:			/* List of names (segment, group or class) */
X  for(x+=2;x!=nxt;x+=pgm[x]+1)
X   {
X   ncpy(buf,pgm+x);
X   namearray[nameidx++]=segmentfind(buf);
X   }
X  break;
X
X case 0x8C:			/* External names */
X  for(x+=2;x!=nxt;x+=pgm[x]+1, IDXINC(x))
X   {
X   struct label *label;
X   ncpy(buf,pgm+x);
X   label=externarray[externidx++]=labelfind(buf);
X   if(listfile!=NULL)
X    {
X    if(label->bksiz==label->nref)
X     label->ref=(char **)realloc(label->ref,(label->bksiz+=20)*sizeof(char *));
X    label->ref[label->nref++]=objname;
X    }
X   }
X  break;
X
X case 0x9A:			/* Group definition */
X  {
X  struct segment *grp;
X  unsigned y;
X  x+=2; y=IDXINC(x);
X  grp=namearray[y-1];
X  if(grp->seglst!=NULL)
X   {
X   for(y=0;x!=nxt;++y)
X    {
X    unsigned z;
X    struct segment *seg=segarray[++x, IDXINC(x)-1];
X    for(z=0;z!=grp->lstsiz;++z) if(grp->seglst[z]==seg) goto over;
X    grp->seglst=(struct segment **)realloc(grp->seglst,sizeof(struct segment *)*++grp->lstsiz);
X    grp->seglst[z]=seg;
X    over:;
X    }
X   }
X  else
X   {
X   unsigned ox=x;
X   for(y=0;x!=nxt;++x, IDXINC(x)) ++y;
X   grp->lstsiz=y;
X   grp->seglst=(struct segment **)calloc(y,sizeof(struct segment *));
X   for(y=0, x=ox;x!=nxt;) grp->seglst[y++]=segarray[++x, IDXINC(x)-1];
X   grp->gfile=objname;
X   }
X  grouparray[groupidx++]=grp;
X  }
X  break;
X
X case 0x98:			/* Segment definition */
X  {
X  int align,combine;
X  unsigned frame=0;
X  int ofst=0;
X  long len=0;
X  int nidx, cidx, oidx;
X  struct segment *seg;
X  x+=2;
X  align=(pgm[x]>>5);
X  combine=(7&(pgm[x]>>2));
X  if(pgm[x]&2) len=0x10000;
X  ++x;
X  if(!align) frame=SIZINC(x), ofst=pgm[x++];
X  if(!len) len=SIZ(x);
X  x+=2;
X  nidx=IDXINC(x);
X  cidx=IDXINC(x);
X  oidx=IDXINC(x);
X
X  seg=namearray[nidx-1];
X  if(!combine)
X   { /* Private segment */
X   seg=segprivate(seg,objname);
X   segarray[segidx++]=seg;
X   seg->alignment=align;
X   seg->combine=combine;
X   seg->frame=frame;
X   seg->nlength=len;
X   }
X  else
X   {
X   segarray[segidx++]=seg;
X   if(seg->file!=NULL)
X    { /* Segment already defined.  Check for mismatch */
X    if(align!=seg->alignment)
X     fprintf(stderr,"Segment mismatch (alignment) %s(%s) %s\n",seg->name,objname,seg->file), errval=1;
X    if(combine!=seg->combine)
X     fprintf(stderr,"Segment mismatch (combine) %s(%s) %s\n",seg->name,objname,seg->file), errval=1;
X    if(frame!=seg->frame)
X     fprintf(stderr,"Segment mismatch (at) %s(%s) %s\n",seg->name,objname,seg->file), errval=1;
X    if(seg->combine==6)
X     { if(len>seg->length) seg->length=len; }
X    else
X     if(!seg->nlength)
X      switch(seg->alignment)
X       {
X      case 2: seg->length=((seg->length+1)&~1); break;
X      case 3: seg->length=((seg->length+15)&~15); break;
X      case 4: seg->length=((seg->length+255)&~255); break;
X       }
X     else
X      switch(seg->alignment)
X       {
X      case 2: seg->nlength=((seg->nlength+1)&~1); break;
X      case 3: seg->nlength=((seg->nlength+15)&~15); break;
X      case 4: seg->nlength=((seg->nlength+255)&~255); break;
X       }
X    seg->nlength+=len;
X    }
X   else
X    { /* New public segment */
X    seg->alignment=align;
X    seg->combine=combine;
X    seg->frame=frame;
X    seg->nlength=len;
X    seg->file=objname;
X    }
X   }
X  }
X  break;
X
X case 0x90:			/* Public names */
X  {
X  unsigned gidx;
X  unsigned sidx;
X  unsigned frame=0;
X  x+=2;
X  gidx=IDXINC(x);
X  sidx=IDXINC(x);
X  if(!gidx && !sidx) frame=SIZINC(x);
X  while(x!=nxt)
X   {
X   struct label *label;
X   ncpy(buf,pgm+x);
X   x+=pgm[x]+1;
X   label=labelfind(buf);
X   if(label->file!=NULL) fprintf(stderr,"Multiply defined symbol: %s(%s) (%s)\n",label->name,objname,label->file), errval=1;
X   else
X    {
X    label->frame=frame;
X    label->file=objname;
X    if(sidx)
X     {
X     label->seg=segarray[sidx-1];
X     label->offset=SIZ(x)+label->seg->length;
X     }
X    else label->offset=SIZ(x);
X    if(gidx) label->group=grouparray[gidx-1];
X    }
X   x+=2;
X   IDXINC(x);
X   }
X  }
X  break;
X
X case 0xB0:			/* Common variable */
X  while(x!=nxt)
X   {
X   ncpy(buf,pgm+x);
X   x+=pgm[x]+1;
X   IDXINC(x);
X   if(pgm[x++]==0x61)
X    {
X    unsigned long size;
X    if(!pgm[x&0x80]) size=pgm[x++];
X    else switch(pgm[x++])
X     {
X    case 0x81: size=pgm[x]+(pgm[x+1]<<8); x+=2; break;
X    case 0x84: size=pgm[x]+(pgm[x+1]<<8)+(pgm[x+2]<<16); x+=3; break;
X    case 0x88: size=pgm[x]+(pgm[x+1]<<8)+(pgm[x+2]<<16)+(pgm[x+3]<<24); x+=4; break;
X     }
X    addbss(buf,objname,size);
X    }
X   else
X    {
X    unsigned long size;
X    unsigned long amnt;
X    if(!pgm[x&0x80]) size=pgm[x++];
X    else switch(pgm[x++])
X     {
X    case 0x81: size=pgm[x]+(pgm[x+1]<<8); x+=2; break;
X    case 0x84: size=pgm[x]+(pgm[x+1]<<8)+(pgm[x+2]<<16); x+=3; break;
X    case 0x88: size=pgm[x]+(pgm[x+1]<<8)+(pgm[x+2]<<16)+(pgm[x+3]<<24); x+=4; break;
X     }
X    if(!pgm[x&0x80]) amnt=pgm[x++];
X    else switch(pgm[x++])
X     {
X     case 0x81: amnt=pgm[x]+(pgm[x+1]<<8); x+=2; break;
X     case 0x84: amnt=pgm[x]+(pgm[x+1]<<8)+(pgm[x+2]<<16);  x+=3; break;
X     case 0x88: amnt=pgm[x]+(pgm[x+1]<<8)+(pgm[x+2]<<16)+(pgm[x+3]<<24); x+=4; break;
X     }
X    size*=amnt;
X    addfar(buf,objname,size);
X    }
X   }
X  break;
X
X default:
X  fprintf(stderr,"Unknown record type $%2X in object module \'%s\'\n",pgm[x-1],objname), errval=1;
X  }
X }
Xfree(pgm);
X}
X
Xvoid pass2(char *objname)
X{
Xunsigned char *pgm;
Xunsigned x, nxt, size;
Xchar buf[256];
Xstruct segment *last;
Xunsigned char *lastptr;
X
Xstruct
X {
X int method;
X struct segment *seg;
X struct label *label;
X } threads[8];
X
X/* Clear indexes */
Xexternidx=segidx=groupidx=nameidx=0;
X
X/* Load .OBJ file */
X {
X int fd=open(objname,O_RDONLY);
X struct stat buf;
X if(fd== -1) { fprintf(stderr,"Couldn\'t open file \'%s\'\n",objname); errval=1; return; }
X fstat(fd,&buf);
X pgm=(unsigned char *)malloc(buf.st_size);
X read(fd,pgm,buf.st_size);
X close(fd);
X size=buf.st_size;
X }
X
X/* Process .OBJ file */
Xfor(x=0;x!=size;x=nxt+1)
X {
X nxt=x+SIZ(x+1)+2;
X switch(pgm[x++])
X  {
X case 0x80:			/* Module name */
X case 0x88:			/* Comment */
X case 0x8E:			/* Type definition */
X case 0x94:			/* Line number */
X case 0x90:			/* Public name */
X case 0xB0:			/* Common variable */
X  break;		/* Just ignore 'em */
X
X case 0xA0:			/* Code/Data */
X  {
X  unsigned sz=SIZINC(x)-1;
X  unsigned ox=x;
X  struct segment *seg=segarray[IDXINC(x)-1];
X  unsigned ofst=SIZINC(x);
X  last=seg;
X  sz-=x-ox;
X  lastptr=seg->buf+ofst+seg->pos-seg->start;
X  memcpy(seg->buf+ofst+seg->pos-seg->start,pgm+x,sz);
X  }
X  break;
X
X case 0xA2:			/* 'Dup' data */
X  {
X  struct segment *seg=segarray[x+=2, IDXINC(x)-1];
X  unsigned ofst=SIZINC(x);
X  unsigned char *ptr=seg->buf+ofst+seg->pos-seg->start;
X  last=seg;
X  lastptr=ptr;
X  iterated(pgm,&x,1,&ptr);
X  }
X  break;
X
X case 0x9c:			/* Fixup */
X  {
X  unsigned seg,seg1;
X  unsigned off,off1;
X  for(x+=2;x!=nxt;)
X   {
X   char c=pgm[x++];
X   if(!(c&128))
X    {
X    int idx=(c&3)+(4&(c>>4));
X    threads[idx].method=(7&(c>>2));
X    if(c&64)
X     switch(threads[idx].method)
X      {
X     case 0: threads[idx].seg=segarray[IDXINC(x)-1]; break;
X     case 1: threads[idx].seg=grouparray[IDXINC(x)-1]; break;
X     case 2: threads[idx].label=externarray[IDXINC(x)-1]; break;
X      }
X    else
X     switch(threads[idx].method&3)
X      {
X     case 0: threads[idx].seg=segarray[IDXINC(x)-1]; break;
X     case 1: threads[idx].seg=grouparray[IDXINC(x)-1]; break;
X     case 2: threads[idx].label=externarray[IDXINC(x)-1]; break;
X      }
X    }
X   else
X    {
X    int locat=pgm[x++]+((c&3)<<8);	/* Offset from 'last' */
X    int rel=!(c&64);			/* Set if branch fix */
X    int what=(7&(c>>2));		/* What is being fixed */
X    int fmethod;
X    struct segment *fseg;
X    struct label *flabel;
X    int tmethod;
X    struct segment *tseg;
X    struct label *tlabel;
X    unsigned disp;
X    c=pgm[x++];
X    if(c&128)
X     {
X     int idx=((c>>4)&3)+4;
X     fmethod=threads[idx].method;
X     fseg=threads[idx].seg;
X     flabel=threads[idx].label;
X     }
X    else
X     {
X     fmethod=(c>>4);
X     switch(fmethod)
X      {
X     case 0: fseg=segarray[IDXINC(x)-1]; break;
X     case 1: fseg=grouparray[IDXINC(x)-1]; break;
X     case 2: flabel=externarray[IDXINC(x)-1]; break;
X      }
X     }
X    if(c&8)
X     {
X     int idx=c&3;
X     tmethod=(~4&threads[idx].method)+(c&4);
X     tseg=threads[idx].seg;
X     tlabel=threads[idx].label;
X     }
X    else
X     {
X     tmethod=(c&7);
X     switch(tmethod&3)
X      {
X     case 0: tseg=segarray[IDXINC(x)-1]; break;
X     case 1: tseg=grouparray[IDXINC(x)-1]; break;
X     case 2: tlabel=externarray[IDXINC(x)-1]; break;
X      }
X     }
X    if(tmethod>=4) tmethod-=4, disp=0;
X    else disp=SIZINC(x);
X    switch(fmethod)
X     {
X    case 4: fmethod=0;
X            fseg=last;
X            break;
X    case 5: fmethod=tmethod;
X            fseg=tseg;
X            flabel=tlabel;
X            break;
X     }
X    
X    switch(tmethod)
X     {
X    case 0: seg=(tseg->addr>>4); off=(tseg->addr&15); break;
X    case 1: seg=(tseg->gaddr>>4); off=(tseg->gaddr&15); break;
X    case 2: if(tlabel->seg!=NULL)
X             {
X             seg=(tlabel->seg->addr>>4);
X             off=(tlabel->seg->addr&15)+tlabel->offset;
X             }
X            else
X             {
X             seg=tlabel->frame;
X             off=tlabel->offset;
X             }
X     }
X
X    switch(fmethod)
X     {
X    case 0: seg1=(fseg->addr>>4); off1=(fseg->addr&15); break;
X    case 1: seg1=(fseg->gaddr>>4); off1=(fseg->gaddr&15); break;
X    case 2: if(flabel->seg!=NULL)
X             {
X             if(flabel->group!=NULL)
X              { /* Do I do this? */
X              seg1=(flabel->group->gaddr>>4);
X              off1=(flabel->group->gaddr&15)+flabel->offset;
X              }
X             else
X              {
X              seg1=(flabel->seg->addr>>4);
X              off1=(flabel->seg->addr&15)+flabel->offset;
X              }
X             }
X            else
X             {
X             seg1=flabel->frame;
X             off1=flabel->offset;
X             }
X     }
X
X    /* Make seg/off relative to seg1/off1 */
X    /* Oh never mind.  Segment always guarenteed to begin on
X     * paragraph bounderies.  off1==0 always */
X    off+=(seg-seg1)*16;
X    seg=seg1;
X    /* Add in displacement */
X    off+=disp;
X    /* Adjust for self relative */
X    /* Segment for this had better match segment fixup if for... */
X    if(rel)
X     {
X     switch(what)
X      {
X     case 5: case 1:
X      off-=1;
X
X     case 0:
X      off-=1;
X      break;
X
X     case 2:
X      off-=2;
X       break;
X       
X     case 3:
X      off-=4;
X      break;
X      }
X
X     off-=locat+lastptr-last->buf+last->addr+last->start;
X     }
X
X    /* Do the fixup */
X    switch(what)
X     {
X    /* Fix an offset */
X    case 5:
X    case 1: lastptr[locat+1]=(off>>8);
X    
X    /* Fix only low byte of an offset */
X    case 0: lastptr[locat]=off;
X            break;
X
X    /* Fix a segment */
X    case 2: lastptr[locat]=seg;
X            lastptr[locat+1]=(seg>>8);
X            break;
X
X    /* Fix a pointer */
X    case 3: lastptr[locat]=off;
X            lastptr[locat+1]=(off>>8);
X            lastptr[locat+2]=seg;
X            lastptr[locat+3]=(seg>>8);
X            break;
X
X    defualt: fprintf(stderr,"Unknown fixup object\n"), errval=1;
X     }
X    }
X   }
X  }
X  break;
X
X case 0x8A:			/* End of module */
X  {
X  struct segment *seg;
X  int z;
X  for(z=0;z!=segidx;++z)
X   segarray[z]->pos+=segarray[z]->inc, segarray[z]->inc=0;
X  externidx=segidx=groupidx=nameidx=0;
X  }
X  break;
X
X case 0x96:			/* List of names (segment, group or class) */
X  for(x+=2;x!=nxt;x+=pgm[x]+1)
X   {
X   ncpy(buf,pgm+x);
X   namearray[nameidx++]=segmentfind(buf);
X   }
X  break;
X
X case 0x8C:			/* External names */
X  for(x+=2;x!=nxt;x+=pgm[x]+1, IDXINC(x))
X   {
X   ncpy(buf,pgm+x);
X   externarray[externidx++]=labelfind(buf);
X   }
X  break;
X
X case 0x9A:			/* Group definition */
X  {
X  struct segment *grp;
X  unsigned y;
X  x+=2; y=IDXINC(x);
X  grp=namearray[y-1];
X  grouparray[groupidx++]=grp;
X  }
X  break;
X
X case 0x98:			/* Segment definition */
X  {
X  int align,combine;
X  unsigned frame=0;
X  int ofst=0;
X  long len=0;
X  int nidx, cidx, oidx;
X  struct segment *seg;
X  x+=2;
X  align=(pgm[x]>>5);
X  combine=(7&(pgm[x]>>2));
X  if(pgm[x]&2) len=0x10000;
X  ++x;
X  if(!align) frame=SIZINC(x), ofst=pgm[x++];
X  if(!len) len=SIZ(x);
X  x+=2;
X  nidx=IDXINC(x);
X  cidx=IDXINC(x);
X  oidx=IDXINC(x);
X
X  seg=namearray[nidx-1];
X  if(!combine) seg=private1find(seg->name,objname);
X  segarray[segidx++]=seg;
X
X  if(seg->combine!=6)
X   {
X   if(!seg->inc)
X    switch(seg->alignment)
X     {
X    case 2: seg->pos=((seg->pos+1)&~1); break;
X    case 3: seg->pos=((seg->pos+15)&~15); break;
X    case 4: seg->pos=((seg->pos+255)&~255); break;
X     }
X   else
X    switch(seg->alignment)
X     { /* I think this can never happen */
X       /* Except maybe with common blocks */
X    case 2: seg->inc=((seg->inc+1)&~1); break;
X    case 3: seg->inc=((seg->inc+15)&~15); break;
X    case 4: seg->inc=((seg->inc+255)&~255); break;
X     }
X   seg->inc+=len;
X   }
X
X  }
X  break;
X
X  }
X }
Xfree(pgm);
X}
X
X/* Show segments */
X
Xvoid showsegs(void)
X{
Xstruct segment *seg;
Xint x;
X
Xprintf("\n");
Xprintf("Enter segment positioning and ordering information for segments\n\n");
Xprintf("Each line should look like this: XXXXX NameList\n");
Xprintf("       Where: XXXXX is the starting address in hexadecimal\n");
Xprintf("         and: NameList is space seperated list of segments\n");
Xprintf("              Give private segments in this format: NAME(MODULE)\n");
Xprintf("\nThe segments will be placed in the order given in the NameList\n");
Xprintf("Entry will terminate when all segments are entered\n\n");
X
Xprintf("Public segments:");
Xfor(x=0;x!=512;++x)
X for(seg=segments[x];seg;seg=seg->next)
X  if(seg->file!=NULL) printf(" %s",seg->name);
Xprintf("\n");
X
Xprintf("Private segments:");
Xfor(x=0;x!=psegidx;++x)
X printf(" %s(%s)",psegs[x]->name,psegs[x]->file);
Xprintf("\n\n");
X}
X
X/* Output the compiled program */
X
Xchar zeros[1024];
X
Xvoid emit(char *outfile)
X{
Xint fd, x;
Xunsigned long addr=0;
Xstruct segment *seg, *lowseg=0, *prevseg;
Xunsigned long lowest; 
X
X/* Find lowest segment */
Xlowest=0xffffffff; lowseg=0;
Xfor(x=0;x!=512;++x)
X for(seg=segments[x];seg;seg=seg->next)
X  if(seg->buf!=NULL && seg->addr+seg->start<lowest)
X   lowseg=seg, lowest=seg->addr+seg->start;
Xfor(x=0;x!=psegidx;++x)
X if(psegs[x]->buf!=NULL && psegs[x]->addr+psegs[x]->start<lowest)
X  lowseg=psegs[x], lowest=psegs[x]->addr+psegs[x]->start;
X
X/* Write it out */
Xfd=creat(outfile,0777);
Xif(fd== -1)
X {
X fprintf(stderr,"Couldn\'t open output file\n"), errval=1;
X return;
X }
X
Xif(lowseg!=NULL)
X {
X prevseg=lowseg;
X write(fd,lowseg->buf,lowseg->end-lowseg->start);
X addr=lowest+lowseg->end-lowseg->start;
X lowseg->buf=0;
X
X loop:
X
X lowest=0xffffffff; lowseg=0;
X for(x=0;x!=512;++x)
X  for(seg=segments[x];seg;seg=seg->next)
X   if(seg->buf!=NULL && seg->addr+seg->start<lowest)
X    lowseg=seg, lowest=seg->addr+seg->start;
X for(x=0;x!=psegidx;++x)
X  if(psegs[x]->buf!=NULL && psegs[x]->addr+psegs[x]->start<lowest)
X   lowseg=psegs[x], lowest=psegs[x]->addr+psegs[x]->start;
X
X if(lowseg!=NULL)
X  {
X  unsigned long naddr=lowseg->addr+lowseg->start;
X  if(naddr<addr)
X   {
X   fprintf(stderr,"Segment \'%s\' overlaps segment \'%s\'\n",lowseg->name,prevseg->name);
X   errval=1;
X   }
X  else
X   {
X   prevseg=lowseg;
X   while(naddr>addr+1024)
X    {
X    write(fd,zeros,1024);
X    addr+=1024;
X    }
X   if(naddr!=addr) write(fd,zeros,naddr-addr);
X   addr=naddr;
X   write(fd,lowseg->buf,lowseg->end-lowseg->start);
X   addr+=lowseg->end-lowseg->start;
X   }
X  lowseg->buf=0;
X  goto loop;
X  }
X }
X
Xclose(fd);
X}
X
X/* Position the segments */
X
Xvoid position(void)
X{
Xchar buf[512];
Xunsigned long addr;
Xstruct segment *seg;
Xint x,y;
X
X/* Position absolute segments */
Xfor(x=0;x!=512;++x)
X for(seg=segments[x];seg;seg=seg->next)
X  if(seg->file!=NULL && seg->alignment==0)
X   {
X   seg->addr=((unsigned long)seg->frame<<4);
X   seg->set=1;
X   if(seg->end>seg->start)
X    seg->buf=(unsigned char *)malloc(seg->end-seg->start);
X   }
Xfor(x=0;x!=psegidx;++x)
X if(psegs[x]->alignment==0)
X  {
X  psegs[x]->addr=((unsigned long)psegs[x]->frame<<4);
X  psegs[x]->set=1;
X  if(psegs[x]->end>psegs[x]->start)
X   psegs[x]->buf=(unsigned char *)malloc(psegs[x]->end-psegs[x]->start);
X  }
X
Xgoto start;
Xloop1:
Xif(!quiet) printf(">");
Xgets(buf);
Xx=0;
Xwhile(buf[x]==' ' || buf[x]=='\t') ++x;
Xfor(y=x;buf[y] && buf[y]!=' ' && buf[y]!='\t';++y);
Xsscanf(buf+x,"%lx",&addr);
Xloop:
Xfor(x=y;buf[x]==' ' || buf[x]=='\t';++x);
Xfor(y=x;buf[y] && buf[y]!=' ' && buf[y]!='\t';++y);
Xif(x!=y)
X {
X char c=buf[y]; buf[y]=0;
X seg=segmentfind(buf+x);
X if(seg->file==NULL) seg=privatefind(buf+x);
X if(seg==NULL) printf("No such segment \'%s\'\n",buf+x);
X else
X  if(seg->set)
X   {
X   printf("Segment \'%s\' is already assigned\n",seg->name);
X   }
X  else
X   {
X   if(seg->alignment==4) addr=((addr+255)&~255);
X   else addr=((addr+15)&~15);
X   seg->addr=addr;
X   addr+=seg->length;
X   seg->set=1;
X   if(seg->end>seg->start)
X    seg->buf=(unsigned char *)malloc(seg->end-seg->start);
X   }
X buf[y]=c;
X goto loop;
X }
Xstart:
Xfor(x=0;x!=512;++x)
X for(seg=segments[x];seg;seg=seg->next)
X  if(seg->file!=NULL && !seg->set) goto loop1;
Xfor(x=0;x!=psegidx;++x)
X if(!psegs[x]->set) goto loop1;
X}
X
X/* Do group associations */
X
Xvoid groups(void)
X{
Xint x;
Xstruct segment *seg;
Xfor(x=0;x!=512;++x)
X for(seg=segments[x];seg;seg=seg->next)
X  if(seg->gfile!=NULL)
X   {
X   int y;
X   unsigned long lowest=0xFFFFF;
X   unsigned long highest=0;
X   for(y=0;y!=seg->lstsiz;++y)
X    {
X    if(seg->seglst[y]->addr<lowest) lowest=seg->seglst[y]->addr;
X    if(seg->seglst[y]->addr+seg->seglst[y]->length>highest)
X     highest=seg->seglst[y]->addr+seg->seglst[y]->length;
X    }
X   if(highest-lowest>65536)
X    fprintf(stderr,"Error: Group overflow \'%s\'\n",seg->name), errval=1;
X   seg->gaddr=lowest;
X   }
X}
X
X/* Show all variables and segments (incomplete listing file) */
X
Xint cmplab(struct label **a,struct label **b)
X{ return strcmp((*a)->name,(*b)->name); }
X
Xvoid show(char *listfile)
X{
Xint x,y;
Xstruct label *l;
Xstruct segment *seg;
Xchar sbuf[256];
XFILE *fd;
Xstruct label **lbls;
Xfd=fopen(listfile,"w+");
Xif(fd==NULL)
X {
X fprintf(stderr,"Couldn\'t open listing file\n"), errval=1;
X return;
X }
X
Xfprintf(fd,"Public segments         Address Size Data at\n---------------         ------- ---- -------\n");
Xfor(x=0;x!=512;++x)
X for(seg=segments[x];seg;seg=seg->next)
X  if(seg->file!=NULL)
X   if(seg->start<seg->end) fprintf(fd,"%-23s %7lX %4lX (%lX-%lX)\n",seg->name,seg->addr,seg->length,seg->start,seg->end);
X   else fprintf(fd,"%-23s %7lX %4lX\n",seg->name,seg->addr,seg->length);
X
Xfprintf(fd,"\nPrivate segments        Address Size Data at\n----------------        ------- ---- -------\n");
Xfor(x=0;x!=psegidx;++x)
X {
X sprintf(sbuf,"%s(%s)",psegs[x]->name,psegs[x]->file);
X if(seg->start<seg->end) fprintf(fd,"%-23s %7lX %4lX (%lX-%lX)\n",sbuf,psegs[x]->addr,psegs[x]->length,psegs[x]->start,psegs[x]->end);
X else fprintf(fd,"%-23s %7lX %4lX\n",sbuf,psegs[x]->addr,psegs[x]->length);
X }
X
Xfprintf(fd,"\nGroups                  Address Contents\n------                  ------- --------\n");
Xfor(x=0;x!=512;++x)
X for(seg=segments[x];seg;seg=seg->next)
X  if(seg->seglst!=NULL)
X   {
X   int z;
X   sprintf(sbuf,"%s(%s)",seg->name,seg->gfile);
X   fprintf(fd,"%-23s %7lX",sbuf,seg->gaddr);
X   for(z=0;z!=seg->lstsiz;++z) fprintf(fd," %s",seg->seglst[z]->name);
X   fprintf(fd,"\n");
X   }
X
Xif(nlabels)
X {
X lbls=(struct label **)malloc(nlabels*sizeof(char *));
X
X for(x=0,y=0;x!=512;++x) for(l=labels[x];l;l=l->next) lbls[y++]=l;
X qsort(lbls,nlabels,sizeof(struct label *),cmplab);
X
X fprintf(fd,"\nLabels                  Ofst Segment References\n------                  ---- ------- ----------\n");
X for(x=0;x!=nlabels;++x)
X  {
X  l=lbls[x];
X  if(l->file!=NULL) sprintf(sbuf,"%s(%s)",l->name,l->file);
X  else sprintf(sbuf,"%s(UNDEFINED)",l->name);
X  fprintf(fd,"%-23s %4lX",sbuf,l->offset);
X  if(l->seg!=NULL)
X   if(!l->seg->combine) fprintf(fd," %s(%s)",l->seg->name,l->seg->file);
X   else fprintf(fd," %7s",l->seg->name);
X  else fprintf(fd," %7lX",l->frame);
X  for(y=0;y!=l->nref;++y) fprintf(fd," %s",l->ref[y]);
X  fprintf(fd,"\n");
X  }
X }
Xfclose(fd);
X}
X
Xint main(int argc,char *argv[])
X{
Xint x;
Xif(argc<2)
X {
X fprintf(stderr,"Joe's absolute linker version: beta test\n");
X fprintf(stderr,"Syntax (q is for quiet): alink [-q] [-l listfile] [-o outputfile] objfiles\n");
X errval=1;
X }
Xelse
X {
X for(x=1;argv[x];++x)
X  if(!strcmp(argv[x],"-q")) quiet=1;
X  else if(!strcmp(argv[x],"-l"))
X   {
X   if(argv[x+1]==NULL)
X    {
X    fprintf(stderr,"Missing listing file name\n");
X    exit(1);
X    }
X   listfile=argv[++x];
X   }
X  else if(!strcmp(argv[x],"-o"))
X   {
X   if(argv[x+1]==NULL)
X    {
X    fprintf(stderr,"Missing output file name\n");
X    exit(1);
X    }
X   outfile=argv[++x];
X   }
X  else pass1(argv[x]);
X if(!quiet) showsegs();
X position();
X groups();
X for(x=1;argv[x];++x)
X  if(!strcmp(argv[x],"-q")) ;
X  else if(!strcmp(argv[x],"-l") || !strcmp(argv[x],"-o")) ++x;
X  else pass2(argv[x]);
X if(listfile!=NULL) show(listfile);
X if(outfile!=NULL) emit(outfile);
X }
Xreturn errval;
X}
END_OF_FILE
if test 31091 -ne `wc -c <'alink.c'`; then
    echo shar: \"'alink.c'\" unpacked with wrong size!
fi
# end of 'alink.c'
fi
echo shar: End of shell archive.
exit 0

-- 
/*  rcarter@wpi.wpi.edu */      /* Amazing */             /* Joseph H. Allen */
int a[1817];main(z,p,q,r){for(p=80;q+p-80;p-=2*a[p])for(z=9;z--;)q=3&(r=time(0)
+r*57)/7,q=q?q-1?q-2?1-p%79?-1:0:p%79-77?1:0:p<1659?79:0:p>158?-79:0,q?!a[p+q*2
]?a[p+=a[p+=q]=q]=q:0:0;for(;q++-1817;)printf(q%79?"%c":"%c\n"," #"[!a[q-1]]);}


