Скачать презентацию Linking to VC Section 8 6 and chapter Скачать презентацию Linking to VC Section 8 6 and chapter

fcac68d83ca065b8f632aabe52165cc7.ppt

  • Количество слайдов: 65

Linking to VC++ Section 8. 6 and chapter 12 in Irvine Linking to VC++ Section 8. 6 and chapter 12 in Irvine

Preliminary material about the linker • Extern: any symbol used in this module but 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.

More remarks • Ml. exe is the assembler. • Various switches are used in 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.

A main using public and extern. model small. stack 100 h. 386 dseg segment A main using public and extern. model small. stack 100 h. 386 dseg segment para public 'data' message byte 0 ah, 0 dh, "hello$" dseg ends extern Var 1: word, Var 2: word, Proc 1: near CSEG segment para public 'code' assume cs: cseg, ds: dseg main proc mov ax, dseg mov ds, ax mov Var 1, 20 mov Var 2, 45 call Proc 1 mov dx, var 1 mov ah, 2 int 21 h mov dx, offset message mov ah, 9 int 21 h mov ax, 4 c 00 h int 21 h main endp CSEG ends end main

sub public Var 1, Var 2, Proc 1 DSEG segment para public 'data' Var sub public Var 1, Var 2, Proc 1 DSEG segment para public 'data' Var 1 word ? Var 2 word ? DSEG ends CSEG Proc 1 CSEG segment para public 'code' assume cs: cseg, ds: dseg proc near mov ax, Var 1 add ax, Var 2 mov Var 1, ax ret endp ends end

Assemble and link main and sub C: Masm 615Examplesch 08>ML /nologo -Zi -c -Fl Assemble and link main and sub C: Masm 615Examplesch 08>ML /nologo -Zi -c -Fl -Sg main. asm Assembling: main. asm C: Masm 615Examplesch 08>link main sub Microsoft (R) Segmented Executable Linker Version 5. 60. 339 Dec 5 1994 Copyright (C) Microsoft Corp 1984 -1993. All rights reserved. Run File [main. exe]: List File [nul. map]: Libraries [. lib]: Definitions File [nul. def]: C: Masm 615Examplesch 08>main A hello C: Masm 615Examplesch 08>

Another example: a concatenating sub . model small. data extrn finalstring: byte. code public Another example: a concatenating sub . model small. data extrn finalstring: byte. code public concat proc cld mov di, seg finalstring mov es, di mov di, offset finalstring mov si, ax s 1 loop: lodsb and al, al jz dos 2 stosb jmp s 1 loop dos 2: mov si, bx s 2 loop: lodsb stosb and al, al jnz s 2 loop ret concat endp end

Main for 2 nd example . model small. stack 100 h. data s 1 Main for 2 nd example . model small. stack 100 h. data s 1 byte 'hello', 0; ; ; we will concatenate the two strings with a proc call s 2 byte ' world', 0 ah, 0 dh, '$', 0 public finalstring byte 50 dup (? ). code extern concat: proc main proc mov ax, @data mov ds, ax mov ax, offset s 1 mov bx, offset s 2 call concat mov ah, 9 mov dx, offset finalstring int 21 h mov ax, 4 c 00 h int 21 h main endp end main

Assemble and run of ex #2 C: MASM 615>ml -c -Cx -Fl -Zi mainprog. Assemble and run of ex #2 C: MASM 615>ml -c -Cx -Fl -Zi mainprog. asm Microsoft (R) Macro Assembler Version 6. 15. 8803 Copyright (C) Microsoft Corp 1981 -2000. All rights reserved. Assembling: mainprog. asm C: MASM 615>ml -c -Cx -Fl -Zi subprog. asm Microsoft (R) Macro Assembler Version 6. 15. 8803 Copyright (C) Microsoft Corp 1981 -2000. All rights reserved. Assembling: subprog. asm(12) : error A 2008: syntax error : in instruction C: MASM 615>ml -c -Cx -Fl -Zi subprog. asm Microsoft (R) Macro Assembler Version 6. 15. 8803 Copyright (C) Microsoft Corp 1981 -2000. All rights reserved. Assembling: subprog. asm C: MASM 615>link mainprog. obj subprog. obj Microsoft (R) Segmented Executable Linker Version 5. 60. 339 D Copyright (C) Microsoft Corp 1984 -1993. All rights reserved. Run File [mainprog. exe]: List File [nul. map]: Libraries [. lib]: Definitions File [nul. def]: C: MASM 615>mainprog hello world C: MASM 615>

Assembly, compile, linkage • Generally, switches need to be used to specify how to 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.

Example with arrays in Borland C: the proc model small dataseg newline db 0 Example with arrays in Borland C: the proc model small dataseg newline db 0 ah, 0 dh, '$' codeseg PUBLIC _arrayproc include decout. asm; ; ; these are just the procs or macros, included in this file include macs. asm _arrayproc 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 looptop pop bp ret _arrayproc endp end

Example with arrays in Borland C continued: the main #include <stdio. h> extern void Example with arrays in Borland C continued: the main #include 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("%dn", x[i]); }

Running array. c…first two pieces of output were generated in the sub W: assemblyturbo. Running array. c…first two pieces of output were generated in the sub W: assemblyturbo. CBIN>array 65486 20 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105

double a, b;" src="https://present5.com/presentation/fcac68d83ca065b8f632aabe52165cc7/image-14.jpg" alt="Another borland c example…using coprocessor extern "C" funct(double); #include double a, b;" /> Another borland c example…using coprocessor extern "C" funct(double); #include double a, b; void main(){ a=1234. 567; funct(a); printf("answer %f", b); }

What does “C” mean? • Cpp compilers use “name mangling” to handle function overloads. 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.

The function. model small. data extrn _b: qword. code public _funct proc near push The function. model small. data extrn _b: qword. code public _funct proc near push bp mov bp, sp fld qword ptr [bp+4] fstp _b fwait pop bp ret _funct endp end

Borland example 2, using coprocessor run W: assemblyturbo. CBIN>copro answer 1234. 567000 Borland example 2, using coprocessor run W: assemblyturbo. CBIN>copro answer 1234. 567000

Another coprocessor example • #include 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); }

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

Run of copro 2 W: assemblyturbo. CBIN>copro 2 answer 2469. 134000 W: assemblyturbo. CBIN> Run of copro 2 W: assemblyturbo. CBIN>copro 2 answer 2469. 134000 W: assemblyturbo. CBIN>

. model small. stack 100 h dataseg val dw ? num dw ? prompt . model small. stack 100 h dataseg val dw ? num dw ? prompt db 'enter', 0 ah, 0 dh, '$' p 2 db 'value is', 0 ah, 0 dh, '$' crlf db 0 ah, 0 dh, '$' include macs. asm codeseg EXTRN _addnums: proc include decin. asm include decout. asm main proc near mov ax, @data mov ds, ax message prompt call dec_in push bx message crlf call _addnums message p 2 call dec_out mov ax, 4 c 00 h int 21 h main endp end main An assembly main

The c function • extern The c function • extern "C" int addnums(int, int); • int addnums(int a, int b){ • return a+b; }

run W: assemblyturbo. CBIN>asmtoc enter 123 enter 456 value is 579 W: assemblyturbo. CBIN> run W: assemblyturbo. CBIN>asmtoc enter 123 enter 456 value is 579 W: assemblyturbo. CBIN>

Linking assembly and C • • You can use assembly inline You can link 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.

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

Directory listing. 586. MODEL flat, C ; Standard C library functions: system PROTO, p. Directory listing. 586. MODEL flat, C ; Standard C library functions: system PROTO, p. Command: PTR BYTE printf PROTO, p. String: PTR BYTE, args: VARARG scanf PROTO, p. Format: PTR BYTE, p. Buffer: PTR BYTE, args: VARARG fopen PROTO, mode: PTR BYTE, filename: PTR BYTE fclose PROTO, p. File: DWORD BUFFER_SIZE = 5000. data str 1 BYTE "cls", 0 str 2 BYTE "dir/w", 0 str 3 BYTE "Enter the name of a file: ", 0 str 4 BYTE "%s", 0 str 5 BYTE "cannot open file", 0 dh, 0 ah, 0 str 6 BYTE "The file has been opened and closed", 0 dh, 0 ah, 0 mode. Str BYTE "r", 0 file. Name BYTE 60 DUP(0) p. Buf DWORD ? p. File DWORD ?

Asm code part. code asm_main PROC ; clear the screen, display disk directory INVOKE Asm code part. code asm_main PROC ; clear the screen, display disk directory INVOKE system, ADDR str 1 INVOKE system, ADDR str 2 ; ask for a filename INVOKE printf, ADDR str 3 INVOKE scanf, ADDR str 4, ADDR file. Name ; try to open the file INVOKE fopen, ADDR file. Name, ADDR mode. Str mov p. File, eax. IF eax == 0 ; cannot open file? INVOKE printf, ADDR str 5 jmp quit. ELSE INVOKE printf, ADDR str 6. ENDIF ; Close the file INVOKE fclose, p. File quit: ret ; return to C++ main asm_main ENDP END

Directory listing: running exe in debug Directory listing: running exe in debug

Creating your own obj modules Assemble directory to obj C: Program FilesMicrosoft Visual Studio Creating your own obj modules Assemble directory to obj C: Program FilesMicrosoft Visual Studio 8VC>ML /nologo -Zi -c -Fl -Sg -coff Directory. asm Assembling: Directory. asm Compile Dir. C. cpp to obj (/c means compile only) C: Program FilesMicrosoft Visual Studio 8VC>cl /c dir. C. cpp Microsoft (R) 32 -bit C/C++ Optimizing Compiler Version 14. 00. 50727. 42 for 80 x 86 Copyright (C) Microsoft Corporation. All rights reserved. dir. C. cpp Create the Exe /EHsc is error handling and /Gy enables function linkage C: Program FilesMicrosoft Visual Studio 8VC>cl /EHsc /Gy dir. C. obj directory. obj

Running from VC++ dos prompt Running from VC++ dos prompt

public and external • public, in an assembly module, declares that a symbol defined 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

main. cpp (Borland C) // main. cpp // Calls the external Long. Random function, main. cpp (Borland C) // main. cpp // Calls the external Long. Random function, written in // assembly language, that returns an unsigned 32 -bit // random integer. Compile in the Large memory model. #include extern "C" unsigned long Long. Random(); //"C" indicates to the compiler not to use name mangling but standard C naming //long will return long (32 bit) int in dx: ax const int ARRAY_SIZE = 500; int main() { // Allocate array storage and fill with 32 -bit // unsigned random integers. unsigned long * r. Array = new unsigned long[ARRAY_SIZE]; for(unsigned i = 0; i < ARRAY_SIZE; i++) { r. Array[i] = Long. Random(); //call the external (assembly) function cout << r. Array[i] << ', '; } cout << endl; return 0; }

asm proc longrandom ; Long. Random procedure module (longrand. asm) . model large. 386 asm proc longrandom ; Long. Random procedure module (longrand. asm) . model large. 386 Public _Long. Random. data seed dd 12345678 h//seed should be odd, not even ; Return an unsigned pseudo-random 32 -bit integer ; in DX: AX, in the range 0 - FFFFh. . code _Long. Random 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 _Long. Random endp end

longrand. exe • text examples come with (some) compiled cpp and assembled asm examples. 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

Free compiler from borland • Link for compiler: http: //community. borland. com/article/0, 1410, 20633, Free compiler from borland • Link for compiler: http: //community. borland. com/article/0, 1410, 20633, 00. html

IDEs available for Borland compiler IDEs available for Borland compiler

IDE continued& Software. Dave site • You can “easily” integrate borland C compiler with IDE continued& Software. Dave site • You can “easily” integrate borland C compiler with textpad, also.

(some of the) output C: MASM 615EXAMPLESCH 12BORLAN~1LONGRAND>longrand 3018423131, 1530878130, 3423460525, 3768712380, 1536596111, 3080048918, (some of the) output C: MASM 615EXAMPLESCH 12BORLAN~1LONGRAND>longrand 3018423131, 1530878130, 3423460525, 3768712380, 1536596111, 3080048918, 405865345, 3338 983488, 2101941763, 875374778, 3701378197, 761367812, 142804919, 3419349918, 218704873, 3429891848, 1470939563, 563267010, 3913012605, 2845790796, 1275647967, 4244656934, 4140 39377, 341437136, 1709710931, 3514126282, 2757121893, 143223956, 2904402183, 3569909678 , 1119967161, 2589637528, 2108869627, 1764615890, 2858594893, 1329724380, 2363169583, 37 30491702, 3727334177, 2285801824, 3123210915, 3454642906, 2824439349, 1633624100, 21641 82615, 2533248958, 3079939977, 2860878888, 508074571, 3173628898, 305623837, 3714775404 , 3194643071, 781071174, 3555499249, 887344112, 1198979827, 3041081834, 1769806085, 1231 267764, 2476963751, 402232270, 3202784089, 3603001528, 804990107, 2917090546, 330242029 , 2403027708, 4082347471, 1774424406, 1769521857, 532322944, 25218883, 2692414714, 32352 54229, 3377988420, 248030455, 243485662, 2556277545, 874473800, 4153901803, 3773268482, 1644077245, 1595142284, 7601439, 3311657830, 3801353361, 3514039568, 1379067795, 117086 3114, 2948164261, 1899836116, 2255181383, 4070864878, 1071542009, 2733667800, 147918777 1, 555447058, 1083903373, 2526407196, 3437777007, 1075325302, 658733665, 3858822048, 177 3814755, 145301274, 800860533, 3897833060, 1221102487, 228988926, 1032703689, 159000740 0, 587299723, 1855199266, 1396268637, 1587689388, 2718803903, 2982765446, 2479623217, 26 26846256, 2391008307, 164724266, 45304901, 2099121652, 2925348071, 2316381198, 19766196 73, 2389691128, 1739136475, 246051122, 1842254637, 1331288380, 2072052495, 3684733334, 3 367158273, 1738120384, 1832700035, 926683450, 2192823061, 3042687364, 1776714295, 22092 64670, 4182538857, 3556774792, 3287188523, 2616688194, 1687137277, 1953484, 1461674591, 2013705126, 2059181009, 2093436752, 1758589139, 1545721930, 1913830885, 3725474068, 363 0252935, 394768430, 3571828281, 3704057880, 3017715323, 374619986, 3690047693, 25427375 00, 2231748015, 1252313526, 1122933153, 1695323616, 3933232419, 821810010, 3412397237, 2 608237732, 1359644887, 1944395838, 3787568649, 4049002664, 3787889867, 4074353762, 4137 63997, 1536079340, 4153486591, 811848646, 1854782321, 2358931568, 2978286963, 180374794 6, 2441068421, 2031465524, 1969181223, 3897558094, 2504346073, 2239718712, 1983074075, 7 36157042, 3484175981, 1094559612, 2472450127, 795660758, 3474915649, 3538018048, 599589 315, 3467666810, 2675430997, 2041360324, 2166136695, 4119944286, 3507847593, 3360816584 , 1743897963, 1359133314, 4130273085, 2096950540, 2135623583, 2267595750, 2322033425, 44 5899152, 2634365459, 985463946, 2023903525, 2805759828, 2587848903, 1571956846, 3004652 6360559, 2991106806, 932705761, 2555478304, 1625201507, 3506051226, 1167015157, 4069063 652, 2132818711, 3283945854, 133102153, 1370493928, 202900235, 1171161506, 2383421917, 7 6279084, C: MASM 615EXAMPLESCH 12BORLAN~1LONGRAND>

what should c do, what should asm do? • C should do things like 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

cpp for read sector example // Sector. Main. cpp - Calls Read. Sector Procedure cpp for read sector example // Sector. Main. cpp - Calls Read. Sector Procedure #include #include #include const int SECTOR_SIZE = 512; extern "C" Read. Sector( char * buffer, long start. Sector, int drive. Num, int num. Sectors ); void Display. Buffer( const char * buffer, long start. Sector, int num. Sectors ) { int n = 0; long last = start. Sector + num. Sectors; for(long s. Num = start. Sector; s. Num < last; s. Num++) { cout << "n. Sector " << s. Num << " --------------" << "---------------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(); } }

main. cpp int main() { char * buffer; long start. Sector; int drive. Num; main. cpp int main() { char * buffer; long start. Sector; int drive. Num; int num. Sectors; system("CLS"); cout << "Sector display program. nn" << "Enter drive number [1=A, 2=B, 3=C, 4=D, 5=E, . . . ]: "; cin >> drive. Num; cout << "Starting sector number to read: "; cin >> start. Sector; cout << "Number of sectors to read: "; cin >> num. Sectors; buffer = new char[num. Sectors * SECTOR_SIZE]; cout << "nn. Reading sectors " << start. Sector << " - " << (start. Sector + num. Sectors) << " from Drive " << drive. Num << endl; Read. Sector( buffer, start. Sector, drive. Num, num. Sectors ); Display. Buffer( buffer, start. Sector, num. Sectors ); system("CLS"); return 0; }

asm part of reading sectors TITLE Reading Disk Sectors (Read. Sec. asm) ; The asm part of reading sectors TITLE Reading Disk Sectors (Read. Sec. asm) ; The Read. Sector procedure is called from a 16 -bit ; Real-mode application written in Borland C++ 5. 01. ; It can read FAT 12, FAT 16, and FAT 32 disks under ; MS-DOS, and Windows 95/98/Me. ; Last update: 12/5/01 Public _Read. Sector. model small. 386 Disk. IO STRUC strt. Sector DD ? nm. Sectors DW 1 buffer. Ofs DW ? buffer. Seg DW ? Disk. IO ENDS. data disk. Struct Disk. IO <> ; starting sector number ; number of sectors ; buffer offset ; buffer segment

read sectors continued. code ; -----------------------------_Read. Sector PROC NEAR C ARG buffer. Ptr: WORD, read sectors continued. code ; -----------------------------_Read. Sector PROC NEAR C ARG buffer. Ptr: WORD, start. Sector: DWORD, drive. Number: WORD, num. Sectors: 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, 0 pusha mov eax, start. Sector mov disk. Struct. strt. Sector, eax mov ax, num. Sectors mov disk. Struct. nm. Sectors, ax mov ax, buffer. Ptr mov disk. Struct. buffer. Ofs, ax push ds pop disk. Struct. buffer. Seg mov ax, 7305 h mov cx, 0 FFFFh mov dx, drive. Number mov bx, OFFSET disk. Struct mov si, 0 ; read mode int 21 h popa leave ret _Read. Sector ENDP END ; ABSDisk. Read. Write ; always this value ; drive number ; sector number ; read disk sector

readsectors. exe readsectors. exe

arraysum in C void My. Sub() { char A = 'A'; int B = arraysum in C void My. Sub() { char A = 'A'; int B = 10; char name[20]; name[0] = 'B'; double c = 1. 2; } int Array. Sum( 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 = Array. Sum( Array, 50 ); }

the array sum. asm showing name mangling • • • • • • • the array sum. asm showing name mangling • • • • • • • • • • TITLE D: KipAsm. Book 4ExamplesHLL_LinkingVisual. CPPArray. Sum. cpp. 386 P include listing. inc if @Version gt 510. model FLAT else _TEXT SEGMENT PARA USE 32 PUBLIC 'CODE' _TEXT ENDS _DATA SEGMENT DWORD USE 32 PUBLIC 'DATA' _DATA ENDS CONST SEGMENT DWORD USE 32 PUBLIC 'CONST' CONST ENDS _BSS SEGMENT DWORD USE 32 PUBLIC 'BSS' _BSS ENDS _TLS SEGMENT DWORD USE 32 PUBLIC 'TLS' _TLS ENDS ; COMDAT ? My. Sub@@YAXXZ _TEXT SEGMENT PARA USE 32 PUBLIC 'CODE' _TEXT ENDS ; COMDAT ? Array. Sum@@YAHQAHH@Z _TEXT SEGMENT PARA USE 32 PUBLIC 'CODE' _TEXT ENDS ; COMDAT _main _TEXT SEGMENT PARA USE 32 PUBLIC 'CODE' _TEXT ENDS FLAT GROUP _DATA, CONST, _BSS ASSUME CS: FLAT, DS: FLAT, SS: FLAT endif PUBLIC ? My. Sub@@YAXXZ EXTRN __fltused: NEAR ; COMDAT ? My. Sub@@YAXXZ _TEXT SEGMENT ? My. Sub@@YAXXZ PROC NEAR ; File D: KipAsm. Book 4ExamplesHLL_LinkingVisual. CPPArray. Sum. cpp ; Line 9 ret 0 ? My. Sub@@YAXXZ ENDP ; My. Sub _TEXT ENDS ; My. Sub, COMDAT

the array sum. asm showing name mangling PUBLIC ? Array. Sum@@YAHQAHH@Z ; COMDAT ? the array sum. asm showing name mangling PUBLIC ? Array. Sum@@YAHQAHH@Z ; COMDAT ? Array. Sum@@YAHQAHH@Z _TEXT SEGMENT _array$ = 8 _count$ = 12 ? Array. Sum@@YAHQAHH@Z PROC NEAR ; Line 16 mov edx, DWORD PTR _count$[esp-4] xor eax, eax test edx, edx jle SHORT $L 279 mov ecx, DWORD PTR _array$[esp-4] push esi $L 277: ; Line 17 mov esi, DWORD PTR [ecx] add ecx, 4 add eax, esi dec edx jne SHORT $L 277 pop esi $L 279: ; Line 20 ret 0 ? Array. Sum@@YAHQAHH@Z ENDP _TEXT ENDS PUBLIC _main ; COMDAT _main _TEXT SEGMENT _Array$ = -200 _main PROC NEAR ; Line 24 sub esp, 200 ; Line 27 lea eax, DWORD PTR _Array$[esp+200] push 50 push eax call ? Array. Sum@@YAHQAHH@Z ; Line 30 add esp, 208 ret 0 _main ENDP _TEXT ENDS END ; Array. Sum, COMDAT ; Array. Sum ; COMDAT ; 000000 c 8 H ; 00000032 H ; Array. Sum ; 000000 d 0 H

the example comes with an exe (no output) the example comes with an exe (no output)

in line asm example • • #pragma warning (disable: 4101) // disable warning about in line asm example • • #pragma warning (disable: 4101) // disable warning about unreferenced local variables • #include • • • int main() { std: : cout << "(this program generates no output)nn"; • • • • struct Package { long origin. Zip; // 4 long destination. Zip; // 4 float shipping. Price; // 4 }; • • char my. Char; bool my. Bool; short my. Short; int my. Int; long my. Long; float my. Float; double my. Double; Package my. Package; long double my. Long. Double; long my. Long. Array[10];

inline example continued __asm { mov eax, my. Package. destination. Zip; mov eax, LENGTH inline example continued __asm { mov eax, my. Package. destination. Zip; mov eax, LENGTH my. Int; // 1 mov eax, LENGTH my. Long. Array; // 10 mov mov mov eax, TYPE my. Char; // 1 eax, TYPE my. Bool; // 1 eax, TYPE my. Short; // 2 eax, TYPE my. Int; // 4 eax, TYPE my. Long; // 4 eax, TYPE my. Float; // 4 eax, TYPE my. Double; // 8 eax, TYPE my. Package; // 12 eax, TYPE my. Long. Double; // 8 eax, TYPE my. Long. Array; // 4 mov eax, SIZE my. Long; // 4 mov eax, SIZE my. Package; // 12 mov eax, SIZE my. Long. Array; // 40 } return 0; }

C++ and inline asm • C allows the use of inline asm • I 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++)

Add. Main • Add. Main is a C main program which calls an (external) Add. Main • Add. Main 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

Compile and run addmain • • • C: Program FilesMicrosoft Visual Studio 8VC> ML Compile and run addmain • • • C: Program FilesMicrosoft Visual Studio 8VC> ML /nologo -Zi -c -Fl -Sg -coff ad dem. asm Assembling: addem. asm • • • C: Program FilesMicrosoft Visual Studio 8VC>cl /Gy Add. Main. obj addem. obj Microsoft (R) 32 -bit C/C++ Optimizing Compiler Version 14. 00. 50727. 42 for 80 x 86 Copyright (C) Microsoft Corporation. All rights reserved. • • Microsoft (R) Incremental Linker Version 8. 00. 50727. 42 Copyright (C) Microsoft Corporation. All rights reserved. • • • /out: Add. Main. exe Add. Main. obj addem. obj • • C: Program FilesMicrosoft Visual Studio 8VC>Add. Main Total = 50 • C: Program FilesMicrosoft Visual Studio 8VC>

Add. Main. cpp “C” function means no name mangling // Addem Main Program (Add. Add. Main. cpp “C” function means no name mangling // Addem Main Program (Add. Main. cpp) #include extern "C" int addem(int p 1, int p 2, int p 3); int main() { int total = addem( 10, 15, 25 ); cout << "Total = " << total << endl; return 0; }

Addem. asm – note underscores title The addem Subroutine (addem. asm) ; This subroutine Addem. asm – note underscores title The addem Subroutine (addem. asm) ; This subroutine links to Visual C++ 6. 0. . 386 P. model flat public _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 endp end

Findarray header part //#include <stdlib>//this didn’t seem to work #include <iostream>//remove. h extern Findarray header part //#include //this didn’t seem to work #include //remove. h extern "C" { bool Find. Array( long n, long array[], long count ); // Assembly language version // CPP version } bool Find. Array 2( long n, long array[], long count ); //took this out of extern

Findarray: I made some changes int main() { const unsigned ARRAY_SIZE = 10000; long Findarray: I made some changes int 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 << "nn"; long search. Val; std: : cout << "Enter an integer to find [0 to " << RAND_MAX << ": "; std: : cin >> search. Val; if( Find. Array 2( search. Val, array, ARRAY_SIZE )) std: : cout << "Your number was found. n"; else std: : cout << "Your number was not found. n"; // Call Find. Array 2 for the CPP version. return 0; }

C version bool Find. Array 2( long search. Val, long array[], long count )//and C version bool Find. Array 2( long search. Val, long array[], long count )//and put it down here { for(int i = 0; i < count; i++) if( search. Val == array[i] ) return true; return false; }

Assembly routine. 386 P. model flat public _Find. Array true = 1 false = Assembly routine. 386 P. model flat public _Find. Array true = 1 false = 0 ; Stack parameters: srch. Val equ [ebp+08] array. Ptr equ [ebp+12] count equ [ebp+16]. code _Find. Array proc near push ebp mov ebp, esp push edi mov eax, srch. Val ; search value mov ecx, count ; number of items mov edi, array. Ptr ; pointer to array repne scasd ; do the search jz return. True ; ZF = 1 if found return. False: mov al, false jmp short exit return. True: mov al, true exit: pop edi pop ebp ret _Find. Array endp end

Compile, assemble, link C: >ML /nologo -Zi -c -Fl -Sg –coff find. asm This Compile, assemble, link C: >ML /nologo -Zi -c -Fl -Sg –coff find. asm This creates find. obj C: > cl /c /EHsc Find. It. cpp This creates Findit. obj C: >cl /Gy Findit. obj find. obj Links and sets up extern fn references

I unedited cout values in Find. Array program I unedited cout values in Find. Array program

Encode 2. cpp in text uses inline assembly code #include <iostream> #include <fstream> using Encode 2. cpp in text uses inline assembly code #include #include using namespace std; // Translate a buffer of bytes, using an encryption // character . Uses an XOR operation (ASM function). const int BUFSIZE = 200; char buffer[BUFSIZE]; int main() { unsigned count; // character count unsigned short encrypt. Code; std: : cout << "Encryption code [0 -255]? "; std: : cin >> encrypt. Code; unsigned char encrypt. Char = (unsigned char) encrypt. Code; ifstream infile( "outfile. txt", ios: : binary ); ofstream outfile( "infile. txt", ios: : binary ); std: : cout << "Reading INFILE. TXT and creating OUTFILE. TXT. . . n";

Inline asm while (!infile. eof() ) { infile. read(buffer, BUFSIZE ); count = infile. Inline asm while (!infile. eof() ) { infile. read(buffer, BUFSIZE ); count = infile. gcount(); __asm { lea esi, buffer mov ecx, count mov al, encrypt. Char L 1: xor [esi], al inc esi Loop L 1 } // asm outfile. write(buffer, count); } return 0; }

Xor encryption yet again: encode infile as outfile C: Program FilesMicrosoft Visual Studio 8VC>cl Xor encryption yet again: encode infile as outfile C: Program FilesMicrosoft Visual Studio 8VC>cl /EHsc Encode. cpp Microsoft (R) 32 -bit C/C++ Optimizing Compiler Version 14. 00. 50727. 42 for 80 x 86 Copyright (C) Microsoft Corporation. All rights reserved. Encode. cpp Microsoft (R) Incremental Linker Version 8. 00. 50727. 42 Copyright (C) Microsoft Corporation. All rights reserved. /out: Encode. exe Encode. obj C: Program FilesMicrosoft Visual Studio 8VC>Encode Encryption code [0 -255]? 200 Reading INFILE. TXT and creating OUTFILE. TXT. . . C: Program FilesMicrosoft Visual Studio 8VC>type outfile. txt » ºº¼¬▒¡┼┬á¡ññº┼┬á¡║¡Φí╗Φ╝á¡Φ «íñ¡┼┬┼┬░▒▓┼┬⌐¬½┼┬∙·√ⁿ²ⁿ C: Program FilesMicrosoft Visual Studio 8VC>cl /EHsc Encode. cpp Microsoft (R) 32 -bit C/C++ Optimizing Compiler Version 14. 00. 50727. 42 for 80 x 86 Copyright (C) Microsoft Corporation. All rights reserved.

Swapping infile with outfile to decode Encode. cpp Microsoft (R) Incremental Linker Version 8. Swapping infile with outfile to decode Encode. cpp Microsoft (R) Incremental Linker Version 8. 00. 50727. 42 Copyright (C) Microsoft Corporation. All rights reserved. /out: Encode. exe Encode. obj C: Program FilesMicrosoft Visual Studio 8VC>Encode Encryption code [0 -255]? 200 Reading INFILE. TXT and creating OUTFILE. TXT. . . C: Program FilesMicrosoft Visual Studio 8VC>type outfile. txt » ºº¼¬▒¡┼┬á¡ññº┼┬á¡║¡Φí╗Φ╝á¡Φ «íñ¡┼┬┼┬░▒▓┼┬⌐¬½┼┬∙·√ⁿ²ⁿ C: Program FilesMicrosoft Visual Studio 8VC>type infile. txt goodbye hello here is the file xyz abc 123454