65
Linking to VC++ Section 8.6 and chapter 12 in Irvine

Linking to VC++ Section 8.6 and chapter 12 in Irvine

Embed Size (px)

Citation preview

Page 1: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Linking to VC++

Section 8.6 and chapter 12 in Irvine

Page 2: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Preliminary material about the linker

• Extern: any symbol used in this module but defined elsewhere must be declared extern (with its type specified) so the linker can resolve the reference. The extern must appear in the appropriate segment.

• Public: any symbol defined in this module but needed elsewhere must be declared public so the linker knows to use its address in other modules.

• Symbols may be declared public and not used elsewhere. Symbols declared as Extern must be defined elsewhere and the addressing must be resolved at link time.

Page 3: Linking to VC++ Section 8.6 and chapter 12 in Irvine

More remarks• Ml.exe is the assembler.• Various switches are used in the assembly some of which get

explained later on. In particular, it is possible to compile C modules into obj files for linkage to assembly modules. This is shown later in the show.

• Para means paragraph boundary.• Older version of the assembler used cseg, dseg, sseg and so on for

code segment, data segment, stack segment etc.• The assume directive, which we haven’t used, tells the assembler

to assume that the various segment registers will be pointing at the indicated segments for purposes of assembly. (The assume does not point them there, it is up to the programmer to do that.)

• The underscore notation is used to indicate (assembly) labels which will be referenced from C and whose addresses the linker must resolve.

Page 4: Linking to VC++ Section 8.6 and chapter 12 in Irvine

A main using public and extern.model small.stack 100h.386dseg segment para public 'data'message byte 0ah,0dh,"hello$"dseg ends

extern Var1:word, Var2:word, Proc1:nearCSEG segment para public 'code' assume cs:cseg, ds:dsegmain proc mov ax,dseg mov ds,ax mov Var1, 20 mov Var2, 45 call Proc1 mov dx,var1 mov ah,2 int 21h mov dx,offset message mov ah,9 int 21h mov ax,4c00h int 21h main endpCSEG ends end main

Page 5: Linking to VC++ Section 8.6 and chapter 12 in Irvine

sub public Var1, Var2, Proc1DSEG segment para public 'data'Var1 word ?Var2 word ?DSEG ends

CSEG segment para public 'code' assume cs:cseg, ds:dsegProc1 proc near mov ax, Var1 add ax, Var2 mov Var1, ax retProc1 endpCSEG ends end

Page 6: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Assemble and link main and sub

C:\Masm615\Examples\ch08>ML /nologo -Zi -c -Fl -Sg main.asm Assembling: main.asm

C:\Masm615\Examples\ch08>link main sub

Microsoft (R) Segmented Executable Linker Version 5.60.339 Dec 5 1994Copyright (C) Microsoft Corp 1984-1993. All rights reserved.

Run File [main.exe]:List File [nul.map]:Libraries [.lib]:Definitions File [nul.def]:

C:\Masm615\Examples\ch08>mainAhelloC:\Masm615\Examples\ch08>

Page 7: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Another example: a concatenating sub.model small.dataextrn finalstring:byte.codepublic concatconcat proccldmov di, seg finalstringmov es,dimov di,offset finalstringmov si,axs1loop: lodsb and al,al jz dos2 stosb jmp s1loopdos2: mov si,bxs2loop: lodsb

stosband al,aljnz s2loopret

concat endpend

Page 8: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Main for 2nd example.model small.stack 100h.datas1 byte 'hello',0;;;;;we will concatenate the two strings with a proc calls2 byte ' world',0ah,0dh,'$',0public finalstringfinalstring byte 50 dup (?).codeextern concat:procmain procmov ax,@datamov ds,axmov ax,offset s1mov bx, offset s2call concatmov ah,9mov dx, offset finalstringint 21hmov ax,4c00hint 21hmain endpend main

Page 9: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Assemble and run of ex #2C:\MASM615>ml -c -Cx -Fl -Zi mainprog.asmMicrosoft (R) Macro Assembler Version 6.15.8803Copyright (C) Microsoft Corp 1981-2000. All rights reserved.

Assembling: mainprog.asmC:\MASM615>ml -c -Cx -Fl -Zi subprog.asmMicrosoft (R) Macro Assembler Version 6.15.8803Copyright (C) Microsoft Corp 1981-2000. All rights reserved.

Assembling: subprog.asmsubprog.asm(12) : error A2008: syntax error : in instructionC:\MASM615>ml -c -Cx -Fl -Zi subprog.asmMicrosoft (R) Macro Assembler Version 6.15.8803Copyright (C) Microsoft Corp 1981-2000. All rights reserved. Assembling: subprog.asmC:\MASM615>link mainprog.obj subprog.obj

Microsoft (R) Segmented Executable Linker Version 5.60.339 DCopyright (C) Microsoft Corp 1984-1993. All rights reserved.

Run File [mainprog.exe]:List File [nul.map]:Libraries [.lib]:Definitions File [nul.def]:C:\MASM615>mainproghello world

C:\MASM615>

Page 10: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Assembly, compile, linkage

• Generally, switches need to be used to specify how to assemble or compile and link.

• Sometimes special assemblers or linkers are needed.

• To interface with VC++ is straightforward. (See examples from text chapter 12 later in slideshow). Linking to Borland is harder, since 16 and 32 bit turbo assemblers are hard to get hold of and do not come with free compiler distributions.

• I have omitted the assembly and linkage for the Borland example which appears next.

Page 11: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Example with arrays in Borland C: the procmodel smalldataseg newline db 0ah,0dh,'$' codesegPUBLIC _arrayprocinclude decout.asm;;;these are just the procs or macros, included in this file include macs.asm_arrayproc proc near push bp mov bp,sp mov ax,[bp+4] call dec_out message newline mov ax,[bp+6] call dec_out message newline mov di,[bp+4] mov cx,[bp+6]looptop: add word ptr [di],10 inc di inc di loop looptop pop bp ret_arrayproc endpend

Page 12: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Example with arrays in Borland C continued: the main

#include <stdio.h>extern void arrayproc(int [],int);void main(){int i,x[20]; //fill array anyhow for(i=0;i<20;i++)x[i]=i*5; arrayproc(x,20); for(i=0;i<20;i++)printf("%d\n",x[i]);}

Page 13: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Running array.c…first two pieces of output were generated in the sub

W:\assembly\turboC\BIN>array6548620101520253035404550556065707580859095100105

Page 14: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Another borland c example…using coprocessor

extern "C" funct(double);#include <stdio.h>double a,b;void main(){a=1234.567;funct(a);printf("answer %f",b);}

Page 15: Linking to VC++ Section 8.6 and chapter 12 in Irvine

What does “C” mean?

• Cpp compilers use “name mangling” to handle function overloads. Internally, those overloaded functions wind up with names distinguished by their argument lists.

• To turn off name mangling, you can ask the compiler to use “C” compiler conventions for compiling functions.

Page 16: Linking to VC++ Section 8.6 and chapter 12 in Irvine

The function.model small.dataextrn _b:qword.codepublic _funct

_funct proc near push bp mov bp,sp fld qword ptr [bp+4] fstp _b fwait pop bp ret _funct endp end

Page 17: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Borland example 2, using coprocessor run

W:\assembly\turboC\BIN>copro

answer 1234.567000

Page 18: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Another coprocessor example

• #include "stdio.h"• extern "C" funct(double,double *);

• double a,b;• void main(){• a=1234.567;• funct(a,&b);• printf("answer %f",b);• }

Page 19: Linking to VC++ Section 8.6 and chapter 12 in Irvine

function.model small

.codepublic _funct

_funct proc near push bp mov bp,sp fld qword ptr [bp+4] fld qword ptr [bp+4] fadd st,st(1) mov si,[bp+12] fstp qword ptr [si] fwait pop bp ret _funct endp end

Page 20: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Run of copro2

W:\assembly\turboC\BIN>copro2

answer 2469.134000

W:\assembly\turboC\BIN>

Page 21: Linking to VC++ Section 8.6 and chapter 12 in Irvine

An assembly main.model small.stack 100hdataseg

val dw ?num dw ?prompt db 'enter',0ah,0dh,'$'p2 db 'value is',0ah,0dh,'$'crlf db 0ah,0dh,'$'include macs.asmcodesegEXTRN _addnums:procinclude decin.asminclude decout.asmmain proc near

mov ax, @datamov ds,axmessage prompt call dec_in push bx message crlf message prompt call dec_in push bx message crlf call _addnums message p2

call dec_outmov ax,4c00hint 21h main endp

end main

Page 22: Linking to VC++ Section 8.6 and chapter 12 in Irvine

The c function

• extern "C" int addnums(int,int);

• int addnums(int a,int b){

• return a+b;}

Page 23: Linking to VC++ Section 8.6 and chapter 12 in Irvine

run

W:\assembly\turboC\BIN>asmtocenter123enter456value is579W:\assembly\turboC\BIN>

Page 24: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Linking assembly and C

• You can use assembly inline • You can link c functions to an assembly main• Or visa versa• Some versions of Borland C are available in the

labs• I used the text’s VC++ examples.• As mentioned earlier, you need 32 bit TASM

(Borland assembler) to properly configure assembly with borland c programs.

Page 25: Linking to VC++ Section 8.6 and chapter 12 in Irvine

main

extern "C" void asm_main(); // asm startup proc

void main()

{

asm_main();

}

Page 26: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Directory listing.586.MODEL flat,C

; Standard C library functions:system PROTO, pCommand:PTR BYTEprintf PROTO, pString:PTR BYTE, args:VARARGscanf PROTO, pFormat:PTR BYTE,pBuffer:PTR BYTE, args:VARARGfopen PROTO, mode:PTR BYTE, filename:PTR BYTEfclose PROTO, pFile:DWORD

BUFFER_SIZE = 5000.datastr1 BYTE "cls",0str2 BYTE "dir/w",0str3 BYTE "Enter the name of a file: ",0str4 BYTE "%s",0str5 BYTE "cannot open file",0dh,0ah,0str6 BYTE "The file has been opened and closed",0dh,0ah,0modeStr BYTE "r",0

fileName BYTE 60 DUP(0)pBuf DWORD ?pFile DWORD ?

Page 27: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Asm code part.codeasm_main PROC

; clear the screen, display disk directory INVOKE system,ADDR str1 INVOKE system,ADDR str2 ; ask for a filename INVOKE printf,ADDR str3 INVOKE scanf, ADDR str4, ADDR fileName

; try to open the file INVOKE fopen, ADDR fileName, ADDR modeStr mov pFile,eax

.IF eax == 0 ; cannot open file? INVOKE printf,ADDR str5 jmp quit .ELSE INVOKE printf,ADDR str6 .ENDIF

; Close the file INVOKE fclose, pFile

quit: ret ; return to C++ mainasm_main ENDP

END

Page 28: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Directory listing: running exe in debug

Page 29: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Creating your own obj modules

Assemble directory to obj

C:\Program Files\Microsoft Visual Studio 8\VC>ML /nologo -Zi -c -Fl -Sg -coff Directory.asm

Assembling: Directory.asm

Compile DirC.cpp to obj (/c means compile only)

C:\Program Files\Microsoft Visual Studio 8\VC>cl /c dirC.cpp

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86

Copyright (C) Microsoft Corporation. All rights reserved.

dirC.cpp

Create the Exe /EHsc is error handling and /Gy enables function linkage

C:\Program Files\Microsoft Visual Studio 8\VC>cl /EHsc /Gy dirC.obj directory.obj

Page 30: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Running from VC++ dos prompt

Page 31: Linking to VC++ Section 8.6 and chapter 12 in Irvine

public and external

• public, in an assembly module, declares that a symbol defined in this module should be made available (by linker) to other modules being linked.

• extern indicates that a symbol used in this module is not defined here, but in another module

Page 32: Linking to VC++ Section 8.6 and chapter 12 in Irvine

main.cpp (Borland C)// main.cpp

// Calls the external LongRandom function, written in// assembly language, that returns an unsigned 32-bit// random integer. Compile in the Large memory model.

#include <iostream.h>

extern "C" unsigned long LongRandom();//"C" indicates to the compiler not to use name mangling but standard C naming

//long will return long (32 bit) int in dx:axconst int ARRAY_SIZE = 500;

int main(){ // Allocate array storage and fill with 32-bit // unsigned random integers. unsigned long * rArray = new unsigned long[ARRAY_SIZE]; for(unsigned i = 0; i < ARRAY_SIZE; i++) { rArray[i] = LongRandom();//call the external (assembly) function cout << rArray[i] << ','; } cout << endl; return 0;}

Page 33: Linking to VC++ Section 8.6 and chapter 12 in Irvine

asm proc longrandom; LongRandom procedure module (longrand.asm)

.model large

.386Public _LongRandom.dataseed dd 12345678h//seed should be odd, not even

; Return an unsigned pseudo-random 32-bit integer; in DX:AX,in the range 0 - FFFFFFFFh.

.code_LongRandom proc far, C mov eax, 214013 mul seed xor edx,edx add eax, 2531011 mov seed, eax ; save the seed for the next call shld edx,eax,16 ; copy upper 16 bits of EAX to DX ret_LongRandom endpend

Page 34: Linking to VC++ Section 8.6 and chapter 12 in Irvine

longrand.exe

• text examples come with (some) compiled cpp and assembled asm examples.

• you would need to find a borland c compiler to undertake this work.

• there is a free c compiler (commandline only – no ide) available from inprise (borland)

• you would link the two obj files to create an exe

Page 35: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Free compiler from borland• Link for

compiler:http://community.borland.com/article/0,1410,20633,00.html

Page 36: Linking to VC++ Section 8.6 and chapter 12 in Irvine

IDEs available for Borland compiler

Page 37: Linking to VC++ Section 8.6 and chapter 12 in Irvine

IDE continued& SoftwareDave site• You can “easily” integrate borland C compiler

with textpad, also.

Page 38: Linking to VC++ Section 8.6 and chapter 12 in Irvine

(some of the) outputC:\MASM615\EXAMPLES\CH12\BORLAN~1\LONGRAND>longrand3018423131,1530878130,3423460525,3768712380,1536596111,3080048918,405865345,3338983488,2101941763,875374778,3701378197,761367812,142804919,3419349918,218704873,3429891848,1470939563,563267010,3913012605,2845790796,1275647967,4244656934,414039377,341437136,1709710931,3514126282,2757121893,143223956,2904402183,3569909678,1119967161,2589637528,2108869627,1764615890,2858594893,1329724380,2363169583,3730491702,3727334177,2285801824,3123210915,3454642906,2824439349,1633624100,2164182615,2533248958,3079939977,2860878888,508074571,3173628898,305623837,3714775404,3194643071,781071174,3555499249,887344112,1198979827,3041081834,1769806085,1231267764,2476963751,402232270,3202784089,3603001528,804990107,2917090546,330242029,2403027708,4082347471,1774424406,1769521857,532322944,25218883,2692414714,3235254229,3377988420,248030455,243485662,2556277545,874473800,4153901803,3773268482,1644077245,1595142284,7601439,3311657830,3801353361,3514039568,1379067795,1170863114,2948164261,1899836116,2255181383,4070864878,1071542009,2733667800,1479187771,555447058,1083903373,2526407196,3437777007,1075325302,658733665,3858822048,1773814755,145301274,800860533,3897833060,1221102487,228988926,1032703689,1590007400,587299723,1855199266,1396268637,1587689388,2718803903,2982765446,2479623217,2626846256,2391008307,164724266,45304901,2099121652,2925348071,2316381198,1976619673,2389691128,1739136475,246051122,1842254637,1331288380,2072052495,3684733334,3367158273,1738120384,1832700035,926683450,2192823061,3042687364,1776714295,2209264670,4182538857,3556774792,3287188523,2616688194,1687137277,1953484,1461674591,2013705126,2059181009,2093436752,1758589139,1545721930,1913830885,3725474068,3630252935,394768430,3571828281,3704057880,3017715323,374619986,3690047693,2542737500,2231748015,1252313526,1122933153,1695323616,3933232419,821810010,3412397237,2608237732,1359644887,1944395838,3787568649,4049002664,3787889867,4074353762,413763997,1536079340,4153486591,811848646,1854782321,2358931568,2978286963,1803747946,2441068421,2031465524,1969181223,3897558094,2504346073,2239718712,1983074075,736157042,3484175981,1094559612,2472450127,795660758,3474915649,3538018048,599589315,3467666810,2675430997,2041360324,2166136695,4119944286,3507847593,3360816584,1743897963,1359133314,4130273085,2096950540,2135623583,2267595750,2322033425,445899152,2634365459,985463946,2023903525,2805759828,2587848903,1571956846,30046526360559,2991106806,932705761,2555478304,1625201507,3506051226,1167015157,4069063652,2132818711,3283945854,133102153,1370493928,202900235,1171161506,2383421917,76279084,

C:\MASM615\EXAMPLES\CH12\BORLAN~1\LONGRAND>

Page 39: Linking to VC++ Section 8.6 and chapter 12 in Irvine

what should c do, what should asm do?

• C should do things like i/o and real computations

• asm should handle low level operations including graphics--- activities which might involve rom-bios or dos function calls

Page 40: Linking to VC++ Section 8.6 and chapter 12 in Irvine

cpp for read sector example// SectorMain.cpp - Calls ReadSector Procedure

#include <iostream.h>#include <conio.h>#include <stdlib.h>const int SECTOR_SIZE = 512;extern "C" ReadSector( char * buffer, long startSector, int driveNum, int numSectors );void DisplayBuffer( const char * buffer, long startSector, int numSectors ){ int n = 0; long last = startSector + numSectors; for(long sNum = startSector; sNum < last; sNum++) { cout << "\nSector " << sNum << " ---------------------------" << "-----------------------------\n"; for(int i = 0; i < SECTOR_SIZE; i++) { char ch = buffer[n++]; if( unsigned(ch) < 32 || unsigned(ch) > 126) cout << '.'; else cout << ch; } cout << endl; getch(); }}

Page 41: Linking to VC++ Section 8.6 and chapter 12 in Irvine

main.cppint main(){ char * buffer; long startSector; int driveNum; int numSectors;

system("CLS"); cout << "Sector display program.\n\n" << "Enter drive number [1=A, 2=B, 3=C, 4=D, 5=E,...]: "; cin >> driveNum; cout << "Starting sector number to read: "; cin >> startSector; cout << "Number of sectors to read: "; cin >> numSectors; buffer = new char[numSectors * SECTOR_SIZE];

cout << "\n\nReading sectors " << startSector << " - " << (startSector + numSectors) << " from Drive " << driveNum << endl;

ReadSector( buffer, startSector, driveNum, numSectors ); DisplayBuffer( buffer, startSector, numSectors );

system("CLS"); return 0;}

Page 42: Linking to VC++ Section 8.6 and chapter 12 in Irvine

asm part of reading sectorsTITLE Reading Disk Sectors (ReadSec.asm)

; The ReadSector procedure is called from a 16-bit; Real-mode application written in Borland C++ 5.01.; It can read FAT12, FAT16, and FAT32 disks under; MS-DOS, and Windows 95/98/Me.; Last update: 12/5/01

Public _ReadSector.model small.386

DiskIO STRUCstrtSector DD ? ; starting sector numbernmSectors DW 1 ; number of sectorsbufferOfs DW ? ; buffer offsetbufferSeg DW ? ; buffer segment

DiskIO ENDS

.datadiskStruct DiskIO <>

Page 43: Linking to VC++ Section 8.6 and chapter 12 in Irvine

read sectors continued.code;----------------------------------------------------------_ReadSector PROC NEAR C ARG bufferPtr:WORD, startSector:DWORD, driveNumber:WORD, \ numSectors:WORD;; Read n sectors from a specified disk drive.; Receives: pointer to buffer that will hold the sector,; data, starting sector number, drive number,; and number of sectors.; Returns: nothing;----------------------------------------------------------

enter 0,0pushamov eax,startSectormov diskStruct.strtSector,eaxmov ax,numSectorsmov diskStruct.nmSectors,axmov ax,bufferPtrmov diskStruct.bufferOfs,axpush dspop diskStruct.bufferSeg

mov ax,7305h ; ABSDiskReadWritemov cx,0FFFFh ; always this valuemov dx,driveNumber ; drive numbermov bx,OFFSET diskStruct ; sector numbermov si,0 ; read modeint 21h ; read disk sectorpopaleaveret

_ReadSector ENDPEND

Page 44: Linking to VC++ Section 8.6 and chapter 12 in Irvine

readsectors.exe

Page 45: Linking to VC++ Section 8.6 and chapter 12 in Irvine

arraysum in Cvoid MySub(){

char A = 'A';int B = 10;char name[20];name[0] = 'B';double c = 1.2;

}int ArraySum( int array[], int count ){

int sum = 0;

for(int i = 0; i < count; i++) sum += array[i];

return sum;}

void main(){

int Array[50];int sum = ArraySum( Array, 50 );

}

Page 46: Linking to VC++ Section 8.6 and chapter 12 in Irvine

the array sum.asm showing name mangling• TITLE D:\Kip\AsmBook4\Examples\HLL_Linking\VisualCPP\ArraySum\ArraySum.cpp• .386P• include listing.inc• if @Version gt 510• .model FLAT• else• _TEXT SEGMENT PARA USE32 PUBLIC 'CODE'• _TEXT ENDS• _DATA SEGMENT DWORD USE32 PUBLIC 'DATA'• _DATA ENDS• CONST SEGMENT DWORD USE32 PUBLIC 'CONST'• CONST ENDS• _BSS SEGMENT DWORD USE32 PUBLIC 'BSS'• _BSS ENDS• _TLS SEGMENT DWORD USE32 PUBLIC 'TLS'• _TLS ENDS• ; COMDAT ?MySub@@YAXXZ• _TEXT SEGMENT PARA USE32 PUBLIC 'CODE'• _TEXT ENDS• ; COMDAT ?ArraySum@@YAHQAHH@Z• _TEXT SEGMENT PARA USE32 PUBLIC 'CODE'• _TEXT ENDS• ; COMDAT _main• _TEXT SEGMENT PARA USE32 PUBLIC 'CODE'• _TEXT ENDS• FLAT GROUP _DATA, CONST, _BSS• ASSUME CS: FLAT, DS: FLAT, SS: FLAT• endif• PUBLIC ?MySub@@YAXXZ ; MySub• EXTRN __fltused:NEAR• ; COMDAT ?MySub@@YAXXZ• _TEXT SEGMENT• ?MySub@@YAXXZ PROC NEAR ; MySub, COMDAT• ; File D:\Kip\AsmBook4\Examples\HLL_Linking\VisualCPP\ArraySum\ArraySum.cpp• ; Line 9• ret 0• ?MySub@@YAXXZ ENDP ; MySub• _TEXT ENDS

Page 47: Linking to VC++ Section 8.6 and chapter 12 in Irvine

the array sum.asm showing name manglingPUBLIC ?ArraySum@@YAHQAHH@Z ; ArraySum; COMDAT ?ArraySum@@YAHQAHH@Z_TEXT SEGMENT_array$ = 8_count$ = 12?ArraySum@@YAHQAHH@Z PROC NEAR ; ArraySum, COMDAT; Line 16

mov edx, DWORD PTR _count$[esp-4]xor eax, eaxtest edx, edxjle SHORT $L279mov ecx, DWORD PTR _array$[esp-4]push esi

$L277:; Line 17

mov esi, DWORD PTR [ecx]add ecx, 4add eax, esidec edxjne SHORT $L277pop esi

$L279:; Line 20

ret 0?ArraySum@@YAHQAHH@Z ENDP ; ArraySum_TEXT ENDSPUBLIC _main; COMDAT _main_TEXT SEGMENT_Array$ = -200_main PROC NEAR ; COMDAT; Line 24

sub esp, 200 ; 000000c8H; Line 27

lea eax, DWORD PTR _Array$[esp+200]push 50 ; 00000032Hpush eaxcall ?ArraySum@@YAHQAHH@Z ; ArraySum

; Line 30add esp, 208 ; 000000d0Hret 0

_main ENDP_TEXT ENDSEND

Page 48: Linking to VC++ Section 8.6 and chapter 12 in Irvine

the example comes with an exe (no output)

Page 49: Linking to VC++ Section 8.6 and chapter 12 in Irvine

in line asm example• #pragma warning (disable:4101)• // disable warning about unreferenced local variables

• #include <iostream>

• int main()• {• std::cout << "(this program generates no output)\n\n";

• struct Package {• long originZip; // 4• long destinationZip; // 4• float shippingPrice; // 4• };• • char myChar;• bool myBool;• short myShort;• int myInt;• long myLong;• float myFloat;• double myDouble;• Package myPackage;

• long double myLongDouble;• long myLongArray[10];

Page 50: Linking to VC++ Section 8.6 and chapter 12 in Irvine

inline example continued__asm { mov eax,myPackage.destinationZip;

mov eax,LENGTH myInt; // 1 mov eax,LENGTH myLongArray; // 10

mov eax,TYPE myChar; // 1 mov eax,TYPE myBool; // 1 mov eax,TYPE myShort; // 2 mov eax,TYPE myInt; // 4 mov eax,TYPE myLong; // 4 mov eax,TYPE myFloat; // 4 mov eax,TYPE myDouble; // 8 mov eax,TYPE myPackage; // 12 mov eax,TYPE myLongDouble; // 8 mov eax,TYPE myLongArray; // 4

mov eax,SIZE myLong; // 4 mov eax,SIZE myPackage; // 12 mov eax,SIZE myLongArray; // 40}

return 0;}

Page 51: Linking to VC++ Section 8.6 and chapter 12 in Irvine

C++ and inline asm

• C allows the use of inline asm

• I could not find an exe for this example (and I didn’t load/run it in VC++)

Page 52: Linking to VC++ Section 8.6 and chapter 12 in Irvine

AddMain

• AddMain is a C main program which calls an (external) assembly function.

• We need to tell the compiler the function is external.

• We need to turn off C++ name-mangling using “C”

• We need to create both obj files

Page 53: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Compile and run addmain• C:\Program Files\Microsoft Visual Studio 8\VC> ML /nologo -Zi -c -Fl -Sg -coff ad• dem.asm• Assembling: addem.asm

• C:\Program Files\Microsoft Visual Studio 8\VC>cl /Gy AddMain.obj addem.obj• Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86• Copyright (C) Microsoft Corporation. All rights reserved.

• Microsoft (R) Incremental Linker Version 8.00.50727.42• Copyright (C) Microsoft Corporation. All rights reserved.

• /out:AddMain.exe• AddMain.obj• addem.obj

• C:\Program Files\Microsoft Visual Studio 8\VC>AddMain• Total = 50

• C:\Program Files\Microsoft Visual Studio 8\VC>

Page 54: Linking to VC++ Section 8.6 and chapter 12 in Irvine

AddMain.cpp “C” function means no name mangling

// Addem Main Program (AddMain.cpp)

#include <iostream.h>

extern "C" int addem(int p1, int p2, int p3);

int main(){ int total = addem( 10, 15, 25 ); cout << "Total = " << total << endl;

return 0;}

Page 55: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Addem.asm – note underscorestitle The addem Subroutine (addem.asm)

; This subroutine links to Visual C++ 6.0.

.386P

.model flatpublic _addem

.code_addem proc near push ebp mov ebp,esp mov eax,[ebp+16] ; first argument add eax,[ebp+12] ; second argument add eax,[ebp+8] ; third argument pop ebp ret _addem endpend

Page 56: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Findarray header part

//#include <stdlib>//this didn’t seem to work#include <iostream>//remove .hextern "C" {bool FindArray( long n, long array[], long count );// Assembly language version// CPP version}bool FindArray2( long n, long array[], long

count );//took this out of extern

Page 57: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Findarray: I made some changesint main(){ const unsigned ARRAY_SIZE = 10000; long array[ARRAY_SIZE];//Fill the array with pseudorandom integers. for(unsigned i = 0; i < ARRAY_SIZE; i++)

{ array[i] = rand();

std::cout << array[i] << ","; // display each value}std::cout << "\n\n";

long searchVal; std::cout << "Enter an integer to find [0 to " << RAND_MAX << ": "; std::cin >> searchVal;

if( FindArray2( searchVal, array, ARRAY_SIZE )) std::cout << "Your number was found.\n"; else std::cout << "Your number was not found.\n";

// Call FindArray2 for the CPP version. return 0;}

Page 58: Linking to VC++ Section 8.6 and chapter 12 in Irvine

C version

bool FindArray2( long searchVal, long array[], long count )//and put it down here

{ for(int i = 0; i < count; i++) if( searchVal == array[i] ) return true;

return false;}

Page 59: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Assembly routine.386P.model flatpublic _FindArraytrue = 1false = 0; Stack parameters:srchVal equ [ebp+08]arrayPtr equ [ebp+12]count equ [ebp+16].code_FindArray proc near push ebp mov ebp,esp push edi mov eax, srchVal ; search value mov ecx, count ; number of items mov edi, arrayPtr ; pointer to array repne scasd ; do the search jz returnTrue ; ZF = 1 if foundreturnFalse: mov al, false jmp short exit

returnTrue: mov al, trueexit: pop edi pop ebp ret _FindArray endpend

Page 60: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Compile, assemble, link

C:>ML /nologo -Zi -c -Fl -Sg –coff find.asm

This creates find.obj

C:> cl /c /EHsc FindIt.cpp

This creates Findit.obj

C:>cl /Gy Findit.obj find.obj

Links and sets up extern fn references

Page 61: Linking to VC++ Section 8.6 and chapter 12 in Irvine

I unedited cout values in FindArray program

Page 62: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Encode2.cpp in text uses inline assembly code

#include <iostream>#include <fstream>using namespace std;// Translate a buffer of <count> bytes, using an encryption// character <eChar>. Uses an XOR operation (ASM function).

const int BUFSIZE = 200;char buffer[BUFSIZE];int main() { unsigned count; // character count unsigned short encryptCode; std::cout << "Encryption code [0-255]? "; std::cin >> encryptCode; unsigned char encryptChar = (unsigned char) encryptCode; ifstream infile( "outfile.txt",ios::binary ); ofstream outfile( "infile.txt",ios::binary ); std::cout << "Reading INFILE.TXT and creating OUTFILE.TXT...\n";

Page 63: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Inline asmwhile (!infile.eof() ) { infile.read(buffer, BUFSIZE ); count = infile.gcount();

__asm { lea esi,buffer mov ecx,count mov al, encryptChar L1: xor [esi],al inc esi Loop L1 } // asm outfile.write(buffer, count); }

return 0;}

Page 64: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Xor encryption yet again: encode infile as outfile

C:\Program Files\Microsoft Visual Studio 8\VC>cl /EHsc Encode.cppMicrosoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86Copyright (C) Microsoft Corporation. All rights reserved.

Encode.cppMicrosoft (R) Incremental Linker Version 8.00.50727.42Copyright (C) Microsoft Corporation. All rights reserved.

/out:Encode.exeEncode.obj

C:\Program Files\Microsoft Visual Studio 8\VC>EncodeEncryption code [0-255]? 200Reading INFILE.TXT and creating OUTFILE.TXT...

C:\Program Files\Microsoft Visual Studio 8\VC>type outfile.txt»ºº¼¬▒¡┼┬á¡ññº┼┬á¡║¡Φí╗Φ╝á¡Φ«íñ¡┼┬┼┬░▒▓┼┬⌐¬½┼┬∙·√ⁿ²ⁿC:\Program Files\Microsoft Visual Studio 8\VC>cl /EHsc Encode.cppMicrosoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86Copyright (C) Microsoft Corporation. All rights reserved.

Page 65: Linking to VC++ Section 8.6 and chapter 12 in Irvine

Swapping infile with outfile to decode

Encode.cppMicrosoft (R) Incremental Linker Version 8.00.50727.42Copyright (C) Microsoft Corporation. All rights reserved.

/out:Encode.exeEncode.obj

C:\Program Files\Microsoft Visual Studio 8\VC>EncodeEncryption code [0-255]? 200Reading INFILE.TXT and creating OUTFILE.TXT...

C:\Program Files\Microsoft Visual Studio 8\VC>type outfile.txt»ºº¼¬▒¡┼┬á¡ññº┼┬á¡║¡Φí╗Φ╝á¡Φ«íñ¡┼┬┼┬░▒▓┼┬⌐¬½┼┬∙·√ⁿ²ⁿC:\Program Files\Microsoft Visual Studio 8\VC>type infile.txtgoodbyehellohere is the file

xyzabc123454