1. Главная страница » Компьютеры

Masm visual studio 2017

Автор: | 16.12.2019

Самая актуальная документация по Visual Studio 2017: Документация по Visual Studio 2017.

Блок, относящийся только к системам Майкрософт

Язык ассемблера может служить для целого ряда целей, например для повышения скорости работы программы, сокращения потребления памяти и управления оборудованием. Встроенный код на ассемблере можно использовать для внедрения инструкций языка ассемблера непосредственно в исходные программы С и С++ без дополнительных шагов по сборке и компоновке. Встроенный код на ассемблере встроен в компилятор, поэтому вам не требуется отдельный сборщик для языка ассемблера, такой как Microsoft Macro Assembler (MASM).

Примечание

Программы со встроенным кодом на языке ассемблера не всегда можно перенести на другие аппаратные платформы. При разработке переносимой версии старайтесь не использовать встроенный код ассемблера.

Встроенный код на ассемблере не поддерживается в процессорах ARM и x64. В следующих разделах объясняется, как использовать встроенный код на ассемблере в программах Visual C/C++ для процессоров x86.

This tutorial assumes that you are using the Seventh Edition of Assembly Language for x86 Processors, and you are using Visual Studio 2017 Community Edition.

Here’s how to get started:
Right-click here to download the code examples and required libraries for the book. Unzip the downloaded file into a directory named Irvine on Drive C. Next, Right-click here to download a zip file containing a 32-bit Visual Studio 2017 project. You can extract this file into any folder on your computer. Finally, Right-click here to download a zip file containing a 64-bit Visual Studio 2017 project. You can extract this file into any folder on your computer. Now you are ready to begin the tutorials listed below.

Читайте также:  Ccproxy настройка и возможности

Found an error in this document? Please email the author.

Required Setup for 32-bit Applications

Note: If you do not see Visual C++ in the list, click the Open Visual Studio installer hyperlink. It runs a separate program. If your computer is in a college laboratory, your account may not have sufficient privileges to run this program, so you can ask your lab supervisor to do it.

If you were able to run the VS installer, close the main Visual Studio window (not the installer), and in the installer window, click the Desktop development with C++ button in the installer window, look at the Summary list on the right side to verify that VC++ is selected, and click the Modify button in the lower right corner of the window.

You will have to wait a while for the installation to finish. Meanwhile, why don’t you read Chapter 1 of my book?

The Visual C++ language includes the Microsoft Assembler (MASM). To verify that MASM was installed, open a Windows Explorer window and look for the file named ml.exe in the Visual Studio installation directory, such as C:Program Files (x86)Microsoft Visual Studio2017CommunityVCToolsMSVC14.10.25017inHostX64x86.

The Book’s Example Programs

The folllowing files should appear in the c:Irvine directory:

Filename Description
b16.asm, b32.asm Blank templates for 16-bit and 32-bit assembly language source files
GraphWin.inc Include file for writing Windows applications
Irvine16.inc Include file used with the Irvine16 link library (16-bit applications)
Irvine16.lib 16-bit link function library used with this book
Irvine32.inc Include file used with the Irvine32 link library (32-bit applications)
Irvine32.lib Irvine’s 32-bit link library
Kernel32.lib 32-bit link library for Windows API
Link16.exe 16-bit Microsoft linker
Macros.inc Irvine’s macro include file (see Chapter 10)
make16_vs2012.bat Visual Studio 2012 batch file for building 16-bit applications
make16_vs2013.bat Visual Studio 2013 batch file for building 16-bit applications
SmallWin.inc Small-sized include file containing MS-Windows definitions, used by Irvine32.inc
User32.lib MS-Windows basic I/O link library
VirtualKeys.inc Keyboard code definitions file, used by Irvine32.inc

A subdirectory named Examples will contain all the example programs shown in the book, source code for the book’s 16-, 32-, and 64-bit libraries, and two sample projects for earlier versions of Visual Studio.

Setting up Visual Studio

Select the C++ Configuration

Optional Step: Set the tab indent size

Set the Tab Size and Indent Size to 5.

Optional Step: Add the Start Without Debugging command

In fact, you can use a similar sequence to customize any of the menus and toolbars in Visual Studio.

Tutorial: Building and running a 32-bit program

Opening a Project

Visual Studio requires assembly language source files to belong to a project, which is a kind of container. A project holds configuration information such as the locations of the assembler, linker, and required libraries. A project has its own folder, and it holds the names and locations of all files belonging to it.

If you have not already done so,Right-click here to download a zip file containing an up-to-date Visual Studio 2017 project that has been configured for assembly language. After downloading this file, un-zip it into your working directory. It contains a sample asm test file named AddTwo.asm.

Follow these steps:

  1. Start Visual Studio.
  2. Open our sample Visual Studio project file by selecting File/Open/Project from the Visual Studio menu.
  3. Navigate to your working folder where you unzipped our project file, and select the file named Project.sln.
  4. Once the project has been opened, you will see the project name in Visual Studio’s Solution Explorer window. You should also see an assembly language source file in the project named AddTwo.asm. Double-click the file name to open it in the editor.

You should see the following program in the editor window:

In the future, you can use this file as a starting point to create new programs by copying it and renaming the copy in the Solution Explorer window.

Build the Program

Now you will build (assemble and link) the sample program. Select Build Project from the Build menu. In the Output window for Visual Studio at the bottom of the screen, you should see messages similar to the following, indicating the build progress:

If you do not see these messages, the project has probably not been modified since it was last built. No problem—just select Rebuild Project from the Build menu.

Run the Program in Debug Mode

The easiest way to run your first program is to use the debugger. First, you must set a breakpoint. When you set a breakpoint in a program, you can use the debugger to execute the program a full speed (more or less) until it reaches the breakpoint. At that point, the debugger drops into single-step mode. Here’s how to do it:

  1. Make sure the ASM source code file is open in the editor window.
  2. Click the mouse along the border to the left of the mov eax,5 statement. A large red dot should appear in the margin.
  3. Select Start Debugging from the Debug menu. The program should run and pause on the line with the breakpoint.
  4. Press the F10 key (called Step Over) to execute the current statement. Continue pressing F10 until the program is about to execute the invoke statement.
  5. A small black window icon should appear on your Windows status bar. Open it and look at the contents of the Command window. The window should be blank because this program does not display any output.
  6. Press F10 one more time to end the program.

You can remove a breakpoint by clicking its dot with the mouse. Take a few minutes to experiment with the Debug menu commands. Set more breakpoints and run the program again.

Here’s what your program will look like when paused at the breakpoint:

To remove a source file from the Visual Studio window, right-click its filename and select Remove. The file will not be deleted from the file system. On the other hand, if you want to delete the file, select it and press the Del key.

Registers

Soon you will want to display CPU registers when debugging your programs. Here’s how to make them visible: First, under the Tools >> Options menu, select Debbuging in the left panel, and select Enable address-level debugging. Next, set a breakpoint in your source code on an executable statement, run your program in Debug mode, select Windows from the Debug menu, and then select Registers from the drop-down list.

The Registers window may appear docked to the top of the workspace, but you may find it helpful to float the window on top of your workspace. Just grab the window header with the mouse and pull it to the center area. You will also want to display the CPU flags. To do that, right click inside the Registers window and check the word Flags from the popup menu.

You can interrupt a debugging session at any time by selecting Stop Debugging from the Debug menu. You can do the same by clicking the maroon-colored square button on the toolbar. To remove a breakpoint from a program, click its red dot to make it disappear.

A reminder, you might want to review our tutorial: Using the Visual Studio debugger

Building and Running Other Programs

Suppose you want to run another example program, or possibly create your own program. You can remove the existing assembly language file from the Solution Explorer window and insert a new .asm file into the project.

  • To remove a program from a project without deleting the file, right-click its name in the Solution Explorer window. In the context menu, select Remove. If you change your mind and decide to add it back to the project, right-click in the same window, select Add, select Existing item, and select the file you want to add.

Adding a File to a Project

An easy way to add an assembly language source file to an open project is to drag its filename with the mouse from a Windows Explorer window onto the name of your project in the Solution Explorer window. The physical file will not be copied—the project only holds a reference to the file’s location. Try this now:

  1. Remove the AddTwo.asm file from your project.
  2. Add a reference to the file Examplesch03AddTwoSum.asm to the project.
  3. Build and run the project.

Copying a Source File

One way to make a copy of an existing source code file is to use Windows Explorer to copy the file into your project directory. Then, right-click the project name in Solution Explorer, select Add, select Existing Item, and select the filename.

Tutorial: Building and running a 64-bit program

Do the following steps, in order:

  1. Right-click here to download the Project64_VS2017.zip file and unzip it into your working directory.
  2. In Visual Studio 2017, select Open Project from the File menu, navigate to the Project64_VS2017 folder, and select the file named Project.sln.
  3. You are about to add an existing source code file to the project. To do that, right-click on Project in the Solution Explorer window, select Add, select Existing Item, navigate to the book’s Examplesch0364 bit" folder, select AddTwoSum_64.asm, and click the Add button to close the dialog window.
  4. Open the AddTwoSum_64.asm file for editing by double-clicking its filename in the Solution Explorer window.

You should see the following program in the editor window:

(Notice that the program’s entry point is the main procedure. If you wish to use a different name for your startup procedure in your own programs, you can modify this option by selecting Properties from the Project menu, and then selecting Linker / Advanced / Entry Point.)

Build the Program

You use the same Visual Studio commands to run and debug 64-bit programs as you would for 32-bit programs.

Building 16-bit programs (Chapters 14-17)

Only Chapters 14 through 17 require you to build 16-bit applications. Except for a few exceptions, which are noted in the book, your 16-bit applications will run under the 32-bit versions of Windows (Windows XP, Windows Vista, Windows 7).

The book’s example programs in Chapters 1-13 have been successfully tested in 32-bit Windows 7,8, and 10. On the other hand, many programs in Chapters 14-17 will not run in any Microsoft OS later than Windows 98, because they rely on direct access to hardware and system memory. You cannot directly run 16-bit applications in any 64-bit version of Windows.

If you plan to build 16-bit applications, you need to add two new commands to the Visual Studio Tools menu. To add a command, select External Tools from the Tools menu. The following dialog will appear, although many of the items in your list on the left side will be missing. Download the batch file here (rename the .txt extension to .bat after downloading): make16_vs2017.txt.

Step 1: Create the Build 16-bit ASM Command

Click the Add button and fill in the Title, Command, Arguments, and Initial directory fields as shown in the screen snapshot. If you click the buttons with arrows on the right side of the Arguments and Initial directory fields, a convenient list appears. You can select an item without having to worry about spelling:

Click the Apply button to save the command.

Step 2: Create the Run 16-bit ASM Command

Click the Add button again, and create a new command named Run 16-bit ASM:

Uncheck the "Close on exit" option and click the OK button to save the command and close the External Tools dialog.

Testing Your new 16-Bit Commands

To test your new 16-bit commands, close any Visual Studio project that happens to be open. Then, select File | Open | File from the menu and choose the file named 16-bit.asm from the ch03 folder in the book’s example programs. Select Build 16-bit ASM from the Tools menu. The following command window should appear, showing the successful execution of the assembler and linker, followed by a listing of all files related to this program:

Press a key to close the window. Next, you will run the program. Select Run 16-bit ASM from the Tools menu. The following window will appear, although the contents of all registers except EAX will be different:

Press a key to close the window.

You have completed the setup for building and running 16-bit assembly language programs.

Generating a Source Listing File

Syntax highlighting in your source code

When a text editor uses syntax highlighting, language keywords, strings, and other elements appear in different colors. Visual Studio highlights MASM reserved words and strings, as shown in the following example:

This won’t happen automatically, but you can create a syntax definition file named Usertype.dat that contains MASM keywords. Then when Visual Studio starts, it reads the syntax file and highlights MASM keywords.

If you decide to use Visual Studio’s built-in MASM syntax highlighter, here are the required steps to set it up:

1) Download this Usertype.dat file (enclosed in a ZIP file) given here to a folder in which you have read/write permissions. Extract it from the zip archive.

2) Copy Usertype.dat to the C:Program Files (x86)Microsoft Visual Studio2017CommunityCommon7IDE folder.

Windows will display a confirmation dialog before copying the file.

3) Open Visual Studio, select Options from the Tools menu, select Text Editor, and select File Extension. On the right side of the dialog (shown below), enter asm as the extension, select Microsoft Visual C++ from the Editor list, and click the Add button. Click the OK button to save your changes.

Close Visual Studio and restart it. Open your project and display an ASM file. You should see syntax highlighting in the editor. There is a glitch in the highlighting—assembly language comment line starts start with a semicolon, which C++ doesn’t recognize. But this is a simple workaround: add an extra // right after the semicolon, like this, which will cause the comments to appear in their usual green color: Return to top

Type the following command to assemble and link a source file named main.asm:

You should see the following messages:

In fact, several files were produced.

  • main.obj — the object file
  • main.ilk — incremental link status file
  • main.pdb — debug symbol file

If there were syntax errors in your program, you would see error messages generated by the assembler. Here is an example:

You would then open the main.asm file with a text editor (such as Notepad), fix the errors, and run the asm32 batch file again.

Although we used a file named main.asm in this example, the asm32.bat batch file will work for any assembly language file, regardless of the name. The only requirement is that your assembly language source file have a .asm filename extension.

Assembling Programs in Other Directories

No doubt, you will want to assemble programs in various different disk folders, not just the batch_sample folder used in the foregoing example. All you need to do is copy the cmd.exe shortcut we gave you to your working directory, where your assembly language source files are located. When you double-click to run the shortcut, it will open a Command window in the current folder.

Assembling, Linking, and Debugging

In addition to assembling and linking, you can use the asm32.bat file to launch your program in the Visual Studio debugger. Try the following command:

If the program assembles and links with no errors, your program should load in Visual Studio. The first time you do this with a new program, the source code will not appear. All you have to do is press the F10 key to begin debugging, and your program should appear with a yellow band across the first executable line:

(Depending on how Visual Studio is configured, you might have to press F8 to do the same thing.)

From here, you can step through the program. When you get to the call to WriteString, you can even trace into its code by pressing the F11 key (trace to). When you finish, close Visual Studio.

From this time on, when you load the same program in the Visual Studio debugger, your source code will appear right away.

Assembling without Linking

Occasionally, you may want to assemble programs but not link them. This happens, for example, when you are creating a multimodule project and you want to assemble each asm file into an obj file separately before linking them into the final exe program. Or, you might be assembling a module to be inserted into a link library (like Irvine32.lib).

To assemble a source file only, inser the /C option before the name of the file being assembled:

You should see the following output:

If you are interested in learning more about how batch file commands work, here are some reference links we found:

  • Microsoft TechNet article: Creating Truly Powerful Batch Files, by Brien Posey
  • Microsoft TechNet article: Using Batch Files in Windows NT, by Troy Thompson

Links go out of date quickly, but you can do a web search for Windows batch files and get plenty of hits.

Многие из нас изучали ассемблер в университете, но почти всегда это ограничивалось простыми алгоритмами под DOS. При разработке программ для Windows может возникнуть необходимость написать часть кода на ассемблер, в этой статье я хочу рассказать вам, как использовать ассемблер в ваших программах под Visual Studio 2005.

Создание проекта

В статье мы рассмотрим как вызывать ассемблер из С++ кода и обратно, передавать данные, а также использовать отладчик встроенный в Visual Studio 2005 для отладки кода на ассемблер.

Для начала нам нужно создать проект. Включаем Visual Studio, выбираем File > New > Project. В Visual Studio нет языка ассемблер в окне выбора типа проекта, поэтому создаем С++ Win32 проект. В окне настроек нового проекта выбираем «Empty Project».

По умолчанию Visual Studio не распознает файлы с кодом на ассемблер. Для того чтобы включить поддержку ассемблер нам необходимо настроить в проекте условия сборки указав какой программой необходимо компилировать файлы *.asm. Для этого выбираем пункт меню «Custom Build Rules. ».

В открывшемся окне мы можем указать специальные правила компиляции для различных файлов, Visual Studio 2005 уже имеет готовое правило для файлов *.asm, нам необходимо лишь включить его, установив напротив правила «Microsoft Macro Assembler» галочку.

Добавление исходного кода

Перейдем к написанию исходного кода нашего проекта. Начнем с добавления исходного кода на c++. Добавим новый файл в папку Source Files. В качестве Template выбираем C++ File и вводим желаемое имя файла, например main.cpp. Напишем функцию, которая будет считывать имя введенное пользователем, оформив это в виде функции readName() которая будет возвращать ссылку на считанное имя. Мы получим примерно следующее содержимое файла:

Теперь, когда мы знаем имя пользователя мы можем вывести приветствие, его будет выводить функция sayHello() которую мы напишем на ассемблер, чтобы использовать эту функцию сначала мы должны указать что она будет определена в другом файле, для этого добавим блок к main.cpp:

Этот блок говорит компилятору, что функция sayHello() будет объявлена в другом файле и будет иметь правила вызова «C». Компилятор C++ искажает имена функций так, что указание правил вызова обязательно. Кроме того мы хотим использовать функцию readName() из функции sayHello(), для этого необходимо добавить extern «C» перед определением функции readName(), это позволит вызывать эту функцию из других файлов используя правила вызова «C».

Пришло время добавить код на ассемблер, для этого добавим в Source Folder новый файл. Выбираем тип Text File (.txt) и в поле название заменяем .txt на .asm, назовем наш файл hello.asm. Объявим функцию sayHello() и укажем внешние функции, которые мы хотим использовать. Получим следующий код:

Теперь мы можем запустить проект, для этого просто выбираем Debug > Start Without Debugging или нажимаем комбинацию Ctrl-F5. Если все сделано верно, вы увидите окно программы:

Немного усложним задачу, попробуем написать на ассемблер функцию принимающую параметр и возвращающую значение. Для примера напишем функцию calcSumm() которая будет принимать целое число и возвращать сумму его цифр. Изменим наш код на С++ добавив в него информацию о функции calcSumm, ввод числа и собственно вызов функции. Добавим функцию в файл hello.asm, возвращаемое значение помещается в eax, параметры объявляются после ключевого слова PROC. Все параметры можно использовать в коде процедуры, они автоматически извлекутся из стека. Также в процедурах можно использовать локальные переменные. Вы не можете использовать эти переменные вне процедуры. Они сохранены в стеке и удаляются при возврате из процедуры:

Запустив проект мы увидим следующий результат выполнения:

Отладка

Конечно в данной задаче нет ничего сложного и она вовсе не требует использования ассемблер. Более интересным будет рассмотреть, а что же нам дает Visual Studio для разработки на ассемблер. Попробуем включить режим отладки и установим точку остановки в hello.asm, запустим проект, мы увидим следующее:

Окно Disassembly (Debug > Windows > Disassembly) показываем команды ассемблер для данного объектного файла. Код который мы написали на С++ показывается черным цветом. Disassembled code показывается серым после соответствующего ему кода на C++/ассемблер. Окно Disassembly позволяет отлаживать код и осуществлять stepping по нему.

Окно регистров (Debug > Windows > Registers) позволяет посмотреть значение регистров.

Окно памяти (Debug > Windows > Memory) позволяет посмотреть дамп памяти, слева мы видим шестнадцатеричные адрес, справа шеснадцатеричные значения соответствующих ячеек памяти, можно перемещаться, вводя адрес в соответствующее поле в верху окна.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *