`
huozheleisi
  • 浏览: 1238829 次
文章分类
社区版块
存档分类
最新评论

Source Code of exe2com.

 
阅读更多

/*
exe2com-exe2binreplacementbyChrisDunford/CoveSoftware

usage:exe2com[/I]infile[outfile]

usageisthesameasexe2binexcept:
1.OutputdefaultstoCOMratherthanBIN
2.Binaryfixupoptionnotsupported
3.Checksumnotverified
4.Providesmoreusefulerrormessagesandawarningifa
COMfileisbeingcreatedwithinitialIP!=0x100
5./IswitchprovidesEXEfileinfoinsteadofconverting

Compilernotes:
ThissourcewaswrittenforMicrosoftCversion5.0.It
shouldbereasonablyportable.Watchoutforfseek();
whatitreturnsseemstovarywidelybetweencompilers.

TocompilewithMSC,use:

clexe2com.c(noswitchesnecessary)

Wehavecheckedthatthesource(asofversion1.04)compiles
withouterrorunderTurboC1.5.Itappearstooperatecorrectly,
butweranonlysomequicktests;theremaybesubtleerrorshere.

Theoriginalversionofthisprogramwasknockedtogetherinabout
anhourinresponsetotheremovalofEXE2BINfromthestandardDOS
distributiondisks.Improvements/correctionsareencouraged,but
pleasetrytocoordinatepublicreleasesthroughme.

Programdonatedtothepublicdomainbytheauthor.

cjd4/17/87


Versionhistory
---------------
Version1.0403/02/88(CJD)
Cleanedupsomeuglycodefromtheoriginalquickie.Added
/I(info)switch.Inpreviousversions,wedefinedan
errorcodefornonzeroCSbutdidn'tactuallycheckit;now
wedo.SourcewillnowcompileundereitherMicrosoftCor
TurboC.

Version1.0312/30/87(CJD)
C86versionconvertedtoMicrosoftC(5.0)byChris
Dunford.IncreasedsizeofI/Obufferto4Ktoimprove
speed;EXE2COM1.03istwiceasfastas1.02andisnow
slightlyfasterthanEXE2BIN.TheC86versionwillno
longerbedistributed.

Version1.0211/22/87
byChrisBlum(CompuServe76625,1041)
Fixforeven512-byteboundaryfilelosinglast512bytes.
AlsocorrectedsignonperrequestofChrisDunford(hisname
waslostinthetranslationtoTurboC).Version1.02
existedinbothTurboCandC86versions,althoughonly
theC86executablewas"officially"distributed.

Version1.01wasaTurboCconversion.

Version1.0004/17/87
OriginalC86versionbyChrisDunford

*/

#include<stdio.h>
#include<string.h>
#include<ctype.h>

/*Versioncoding*/
#defineMAJVER1
#defineMINVER0
#defineREVISION4

/*Conversionerrorcodes*/
#defineBADREAD0
#defineBADWRITE1
#defineBADSIG2
#defineHASRELO3
#defineHAS_SS4
#defineHAS_CS5
#defineBAD_IP6
#defineTOO_BIG7
/*Thismustbethelastcode*/
#defineUNKNOWN8

/*Definesizeofconsoleoutputbuffer*/
#defineCONBUFSIZ2048

/*
**Definestructureoffixed-formatpartofEXEfileheader
*/
structexe_header{
charexe_sig[2];/*EXEfilesignature:"MZ"*/
unsignedexcess,/*Imagesizemod512(validbytesinlastpage)*/
pages,/*#512-bytepagesinimage*/
relo_ct,/*Countofrelocationtableentries*/
hdr_size,/*Sizeofheader,inparagraphs*/
min_mem,/*Minrequiredmemory*/
max_mem,/*Maxrequiredmemory*/
ss,/*Stacksegoffsetinloadmodule*/
sp,/*InitialvalueofSP*/
cksum,/*Filechecksum*/
ip,/*InitialvalueofIP*/
cs,/*CSoffsetinloadmodule*/
relo_start,/*Offsetoffirstreloitem*/
ovl_num;/*Overlaynumber*/
}xh;

FILE*fi,/*Inputfilestream*/
*fo;/*Outputfilestream*/

charfin[129],/*Inputfilename*/
fon[129];/*Outputfilename*/

intinfo=0;/*Nonzeroif/Ifound*/

charbuf[CONBUFSIZ];/*printfI/Obuffer*/

chardefext[]=".com";/*Defaultoutputextension-changeifyouwant*/

unsignedlongcode_start,/*OffsetofprogramimageinEXEfile*/
code_size;/*Sizeofprogramimage,inbytes*/

/*Functionprototypes*/
voidinit(unsigned,char*[]);
voidread_hdr(void);
voiddisp_info(void);
voidconvert(void);
voiderr_xit(unsigned);
voidusage(void);

/*
**programmainline
*/
main(argc,argv)
unsignedargc;
char*argv[];
{
init(argc,argv);
read_hdr();
if(info)
disp_info();
else
convert();
}


/*
**Initialize-parsearguments,getfilenames,open/createfiles
*/
voidinit(argc,argv)
unsignedargc;
char**argv;
{
charc,*cp;
inti;

/*Setupbufferedoutput,displaylogo*/
setvbuf(stdout,buf,_IOFBF,CONBUFSIZ);
printf("exe2com%u.%u%ubyChrisDunford/TheCoveSoftwareGroup/n",
MAJVER,MINVER,REVISION);

/*Getarguments*/
cp=*(++argv);
for(i=1;i< argc; i++) {
while ( (cp = strchr (cp, '/')) != (char *) NULL) {
*cp++ = '/0';
c = *cp++;
switch (toupper (c)) {
case 'I':
info = 1;
break;
default:
usage ();
}
}

if (**argv)
if (fin[0] == '/0')
strcpy (fin, strlwr (*argv));
else if (fon[0] == '/0')
strcpy (fon, strlwr (*argv));
else
usage ();

cp = *(++argv);
}

/* Check to ensure that an input filename was found *.
if (fin[0] == '/0') usage ();

/* If the input file has no extension, add .EXE */
if (strchr (fin, '.') == (char *) NULL)
strcat (fin, ".exe");

/* Copy input name to output if unspecified */
if (fon[0] == '/0')
strcpy (fon, fin);

/* Check output extension--change EXE to COM, or add COM */
if ((cp = strchr (fon, '.')) == (char *) NULL)
strcat (fon, defext);
else if (strcmp (cp, ".exe") == 0)
strcpy (cp, defext);

/* Try to open input file */
if ((fi = fopen (fin, "rb")) == (FILE *) NULL) {
fprintf (stderr, "exe2com: can't find input file %s/n", fin);
exit (1);
}

/* Try to create output file, if INFO not requested */
if (!info)
if ((fo = fopen (fon, "wb")) == (FILE *) NULL) {
fprintf (stderr, "exe2com: can't open output file %s/n", fin);
exit (1);
}
}


/*
** usage display
*/
void usage (void)
{
fprintf (stderr, "usage: exe2com [/I] infile [outfile]/n");
exit (1);
}


/*
** Read and check the EXE file header
*/
void read_hdr(void)
{
char *cp;

/* Read the formatted portion of the header */
if (!fread (&xh, sizeof (struct exe_header), 1, fi))
err_xit (BADREAD);

/* Check for "MZ" signature */
if (strncmp (xh.exe_sig, "MZ", 2))
err_xit (BADSIG);

/* Compute offset of program image in module, and program size.
**
** The program size is computed as follows; it cannot exceed 64Kbytes:
**512*(#EXEpages-1)
**+validbytesinlastEXEpage
**-offsetofprogramimageinEXEfile
**
**NotethatiftheIPisnonzero,wewillskipthefirst
**IPbytesoftheprogramimage,andcopyIPbytesfewer
**thantheactualsize.
*/
code_start=((unsignedlong)xh.hdr_size)<< 4;
code_size = (unsigned long) (xh.pages-1) * 512
+ (xh.excess ? xh.excess : 512) /* fixed 11/19/87 - CJB */
- code_start;

/* Don't check anything else if /I requested */
if (info) return;

/* Check header; to be convertible, must have:
** -- no relocatable items
** -- no stack segment
** -- no code segment
** -- IP == 0 or 100
** -- code size < 65536
*/
if (xh.relo_ct)
err_xit (HASRELO);
if (xh.ss || xh.sp)
err_xit (HAS_SS);
if (xh.cs)
err_xit (HAS_CS);
if (xh.ip != 0 && xh.ip != 0x100)
err_xit (BAD_IP);
if (code_size ><?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /><chmetcnv w:st="on" unitname="l" sourcevalue="65536" hasspace="False" negative="False" numbertype="1" tcsc="0">65536L</chmetcnv>)
err_xit(TOO_BIG);

/*IssueawarningifCOMfileandIP!=0x100*/
if(!strcmp(strchr(fon,'.'),".com")&&xh.ip!=0x100)
fprintf(stderr,"exe2comwarning:COMfile,initialIPnot100H/n");

}


/*
**/ioutput:displayEXEfileinfo
*/
voiddisp_info(void)
{
char*cp;
unsignedlongk;

cp=strrchr(fin,'//');
if(!cp)cp=strchr(fin,':');
cp=cp?cp++:fin;
printf("/n%-20s(hex)(dec)/n",cp);

k=(unsignedlong)(xh.pages-1)*512+(xh.excess?xh.excess:512);
printf("EXEfilesize%5lX%7lu/n",k,k);

printf("EXEheadersize(para)%4X%7u/n",xh.hdr_size,xh.hdr_size);

putchar(code_size><chmetcnv w:st="on" unitname="l" sourcevalue="65536" hasspace="False" negative="False" numbertype="1" tcsc="0">65536L</chmetcnv>?'*':'');
printf("Programimagesize(bytes)%5lX%7lu/n",code_size,code_size);

k=(unsignedlong)xh.min_mem*16+code_size;
printf("Minimumloadsize(bytes)%5lX%7lu/n",k,k);

printf("Minallocation(para)%4X%7u/n",xh.min_mem,xh.min_mem);

printf("Maxallocation(para)%4X%7u/n",xh.max_mem,xh.max_mem);

putchar(xh.cs||(xh.ip!=0x100)?'*':'');
printf("InitialCS:IP%04X:%04X/n",xh.cs,xh.ip);

putchar(xh.ss||xh.sp?'*':'');
printf("InitialSS:SP%04X:%04X%7u(stacksize)/n",xh.ss,xh.sp,xh.sp);

putchar(xh.relo_ct?'*':'');
printf("Relocationcount%4X%7u/n",xh.relo_ct,xh.relo_ct);

printf("Relotablestart%04X%7u/n",xh.relo_start,xh.relo_start);

printf("EXEfilechecksum%04X%7u/n",xh.cksum,xh.cksum);

printf("Overlaynumber%4X%7u/n",xh.ovl_num,xh.ovl_num);

printf("*=thisitempreventsconversiontoBIN/COM/n");
}

/*
**Convertthefile.Nothingtodo,really,otherthan
**readingtheimage(whichfollowstheheader),and
**dumpingitbackouttodisk.
*/
voidconvert(void)
{
#defineBUFSIZE16384
staticcharbuffer[BUFSIZE];/*Forcesbufferoutofprogramstack*/
unsignedbsize;

/*Seektostartofprogramimage,skippingIPbytes*/
if(fseek(fi,code_start+xh.ip,0))
err_xit(BADREAD);

/*Readblocksandcopytooutput*/
for(code_size-=xh.ip;code_size;code_size-=bsize){

/*Setcountofbytestoread/write*/
bsize=code_size>BUFSIZE?BUFSIZE:code_size;

/*Readandwriteblock*/
if(!fread(buffer,bsize,1,fi))
err_xit(BADREAD);
if(!fwrite(buffer,bsize,1,fo))
err_xit(BADWRITE);
}

/*Alldone,closethetwofiles*/
fclose(fi);
fclose(fo);
}


/*
**Displayanerrormessage,deleteoutputfile,exit.
*/
voiderr_xit(code)
unsignedcode;
{
staticchar*msg[UNKNOWN+1]={
"errorreadingEXEheader",
"errorwritingoutputfile",
"invalidEXEfilesignature",
"EXEhasrelocatableitems",
"EXEhasstacksegment",
"EXEhasnonzeroCS",
"IPnot0or100H",
"programexceeds64K",
"unknowninternalerror"
};

if(code>UNKNOWN)code=UNKNOWN;
fprintf(stderr,"exe2com:%s,can'tconvert/n",msg[code]);

/*Closetwofilesanddeletepartialoutput*/
fclose(fi);
fclose(fo);
unlink(fon);

/*Exitwitherrorlevel1*/
exit(1);
}

分享到:
评论

相关推荐

    TeeChart2013_130818_SourceCode

    TeeChart Pro source code, TeeChart Pro manual and help file or everything else contained in this software without receiving our written permission. You are NOT allowed to distribute the TeeChart ...

    7zip LZMA920经典版 SDK

    l ANSI-C compatible source code for LZMA / LZMA2 / XZ compression and decompression l ANSI-C compatible source code for 7z decompression with example l C# source code for LZMA compression and ...

    VB代码1000例第一部分 1000s of Visual Basic Source Code examples

    如题所示,VB代码1000例 1000s of Visual Basic Source Code examples 由于文件较大,所以我是分开来压的~ 这个文件可以单独使用~~~~ 我不是学VB的,但是我觉得这个还是很有用的~给你们看看更目录,你们就知道有什么...

    jd-gui.exe

    JD-Core may be used to recover lost source code and explore the source of Java runtime libraries. New features of Java 5, such as annotations, generics or type “enum”, are supported. JD-GUI and JD-...

    jad.exe+readme.txt

    -nocode - don't generate the source code for methods -noconv - don't convert Java identifiers (default: do) -noctor - suppress the empty constructors -noinner - turn off the support of inner ...

    uCOS-II源代码下载

    This directory contains the source code for EXAMPLE #2 (see section 1.08, Example #2) which is intended to run under DOS (or a DOS window under Windows 95). \SOFTWARE\uCOS-II\EX3_x86L This directory ...

    Woll2Woll FirePower X v13.0.2.13 for RAD Studio 10.4.2.exe (Full Source)

    We recommend adding the following line of code to your project source before the initialize which uses metal graphics and is faster to paint. ​begin FMX.Types.GlobalUseMetal := True; // add ...

    Source.Insight.v3.50.0066.Incl.Keymaker-ZWT.zip

    Source Insight is a revolutionary project oriented program code editor and code browser, with built-in analysis for C/C++, C#, and Java programs, as well as other languages. Source Insight parses...

    pycdas.exe可执行文件

    Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in ...

    TeeChart2013_131216_SourceCode

    TeeChart Pro source code, TeeChart Pro manual and help file or everything else contained in this software without receiving our written permission. You are NOT allowed to distribute the TeeChart ...

    ImageEn v2.2.0 for De3-7/D2005

    ImageEn Version 2.2.0 for Delphi 3/4/5/6/...ImageEn 2.2.0 help file.zip 帮助keygen.exe XX机source code of all ImageEn demos.zip是demo扬帆 2005.10.17 祝贺神舟发射/回收成功!个人网站:http://www.wesoho.com

    VB代码1000例第二部分 1000s of Visual Basic Source Code examples 学VB必备

    如题所示,VB代码1000例 1000s of Visual Basic Source Code examples 由于文件较大,所以我是分开来压的~ 这个文件可以单独使用~~~~ 我不是学VB的,但是我觉得这个还是很有用的~给你们看看更目录,你们就知道有什么...

    VB代码1000例—第三部分 1000s of Visual Basic Source Code examples 学VB必备

    如题所示,VB代码1000例 1000s of Visual Basic Source Code examples 由于文件较大,所以我是分开来压的~ 这个文件可以单独使用~~~~ 我不是学VB的,但是我觉得这个还是很有用的~给你们看看更目录,你们就知道有什么...

    Microsoft CDIMAGE v2.52

    -k (keep) create image even if fail to open some of the source files -m ignore maximum image size of 681,984,000 bytes -a allocation summary shows file and directory sizes -q scan source files ...

    串口通讯控件

    Source code for CommBase.dll assembly. Build in a Visual Studio C# Class Library project. Set the XML Documentation File option in configuration properties to rebuild the Intellisense comments. ...

    nvxdsync.exe

    Notwithstanding the foregoing terms of Section 2.1.1, SOFTWARE designed exclusively for use on the Linux or FreeBSD operating systems, or other operating systems derived from the source code to these...

    FastReport.v4.9.81 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版

    FastReport is shipped with full source code (Professional and Enterprise only). You can adapt the sources for your own needs. Documentation: FastReport contains detailed documentation (user manual, ...

    RSATool2.exe

    favourite lib.Sourcecode in C for the base64 conversion comes bundled with this Tool. 7. Credits and Greetings This tool has been coded in C by tE! Compiled with MSVC 5. Greetings fly over to: ...

    EhLib 6.3 Build 6.3.176 Russian version. Full source included.

    .\Demos\Bin\MainDemo.Exe. (Compiled Demo files are available in the Evaluation version of the library) Then you can read a summary of the new features and changes in the file history-eng.html. More ...

Global site tag (gtag.js) - Google Analytics