00001
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026 #include <stdio.h>
00027 #include <stdlib.h>
00028 #include <unistd.h>
00029 #include <fcntl.h>
00030 #include <sys/stat.h>
00031 #include <errno.h>
00032 #include <netinet/in.h>
00033 #include <string.h>
00034
00035 #include <lx.h>
00036
00037
00038 #define ASSURED_WRITE(fd,buf,len) \
00039 if((rc=write(fd,buf,len))!=(len)) { \
00040 close(fd); \
00041 return rc; \
00042 }
00043
00044 #define ASSURED_READ(fd,buf,len) \
00045 if((rc=read(fd,buf,len))!=(len)) { \
00046 close(fd); \
00047 return rc; \
00048 }
00049
00050
00051 int lx_write(const lx_t *lx,const unsigned char *filename) {
00052 #if defined(_WIN32)
00053 int i,rc,fd=open(filename,O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,S_IRUSR | S_IWUSR | S_IRGRP);
00054 #else
00055 int i,rc,fd=creat(filename,S_IRUSR | S_IWUSR | S_IRGRP);
00056 #endif
00057 unsigned short tmp;
00058
00059 if(fd<0)
00060 return fd;
00061
00062
00063
00064 ASSURED_WRITE(fd,"brickOS",8);
00065
00066
00067 for(i=0; i<HEADER_FIELDS; i++) {
00068 tmp=htons( ((unsigned short*)lx)[i] );
00069 ASSURED_WRITE(fd,&tmp,2);
00070 }
00071
00072
00073
00074 ASSURED_WRITE(fd,lx->text,lx->text_size + lx->data_size);
00075
00076
00077
00078 for(i=0; i<lx->num_relocs; i++) {
00079 tmp=htons( lx->reloc[i] );
00080 ASSURED_WRITE(fd,&tmp,2);
00081 }
00082
00083 close(fd);
00084 return 0;
00085 }
00086
00087 int lx_read(lx_t *lx,const unsigned char *filename) {
00088 #if defined(_WIN32)
00089 int i,rc,fd=open(filename,O_RDONLY | O_BINARY);
00090 #else
00091 int i,rc,fd=open(filename,O_RDONLY);
00092 #endif
00093 unsigned char buffer[8];
00094 unsigned short tmp;
00095
00096 if(fd<0)
00097 return fd;
00098
00099
00100
00101 ASSURED_READ(fd,buffer,8);
00102 if(strcmp(buffer,"brickOS")) {
00103 close(fd);
00104 return -1;
00105 }
00106
00107
00108
00109 for(i=0; i<HEADER_FIELDS; i++) {
00110 ASSURED_READ(fd,&tmp,2);
00111 ((unsigned short*)lx)[i]= ntohs(tmp);
00112 }
00113
00114
00115
00116 if((lx->text=malloc(lx->text_size + lx->data_size))==0) {
00117 close(fd);
00118 return -1;
00119 }
00120 ASSURED_READ(fd,lx->text,lx->text_size + lx->data_size);
00121
00122
00123
00124 if(lx->num_relocs) {
00125 if((lx->reloc=malloc(sizeof(unsigned short)*lx->num_relocs))==0) {
00126 close(fd);
00127 return -1;
00128 }
00129
00130 for(i=0; i<lx->num_relocs; i++) {
00131 ASSURED_READ(fd,&tmp,2);
00132 lx->reloc[i]=ntohs(tmp);
00133 }
00134 }
00135
00136 return 0;
00137 }
00138
00139 void lx_relocate(lx_t *lx,unsigned short base) {
00140 unsigned short diff=base-lx->base;
00141
00142 int i;
00143
00144 for(i=0; i<lx->num_relocs; i++) {
00145 unsigned char *ptr=lx->text+lx->reloc[i];
00146 unsigned short off =(ptr[0]<<8) | ptr[1];
00147
00148 off+=diff;
00149 ptr[0]=off >> 8;
00150 ptr[1]=off & 0xff;
00151 }
00152
00153 lx->base=base;
00154 }