Как установить masm на windows 10

In this guide you will learn how to install MASM32 on a Windows 10 machine, and also how to modify the Path environment variable to use the MASM tools directly from the command prompt. By the end of the guide you will have an environment to start writing software in assembly.

Let’s begin.

Download MASM for Windows 10

The first thing you need to do is head over to the MASM32 SDK download page. Select a mirror and your download should begin.

Next open up the archive and extract the installer to your desktop.

Installing MASM on Windows 10

Double click on the installer. It will ask for administrator privileges. This application is deemed to be safe so you can safely press yes. After you have granted permissions you will see a dialog similar to the one below:

Click on the install icon on the top left and select the drive you want to use to install MASM. I will select my D:\ partition. MASM will install all the necessary files to the root directory of whatever partition you select.

Tip: I like to create a separate partition for my assembly projects and install MASM to the root directory of the partition. This makes it much easier to include libraries and includes such as windows.inc and friends.

MASM will proceed to run a bunch of tests to see if you’re computer is compatible and able to run MASM32. You will see a number of dialog boxes appear that require you to press the ok button.

Once the tests are complete press the extract button.

After the extraction has completed you will see another dialog box that informs you a command prompt will appear to complete the installation. Press ok and let the installation finish. It should only take a few moments.

After the installation has finished you will once again see a couple of dialog boxes that require you to press ok. You will also see a different type of dialog box similar to the one below. This runs a VB script to add an icon to your desktop for the MASM editor. If you want an icon on your desktop press yes.

Finally if everything went well you will see the final dialog box telling you the installation is complete.

Don’t run off just yet

I don’t use the default MASM editor. Instead I use Vim, or Sublime. This means I need to call the MASM compiler and linker directly from the command line to build my code. To do this you need to add the location of the MASM32 installation directory to your Path environment variable.

Adding a directory to environment variable Path on Windows 10

Open up the system properties dialog by entering the following command on the command prompt:

sysdm.cpl SystemProperties

Click the advanced tab, and click the Environment Variables button.

Next select the Path item from the list and click Edit.

On the next dialog press New and enter the path to the MASM bin directory. This contains the tools needed to compile and link assembly. For me the path is D:\masm32\bin. In most cases just change the drive letter if you installed to a different partition. The rest of the path is the same.

Press the ok button, and then then the apply button to save and close the system properties dialog.

Open a new command prompt and enter the following command to run the MASM assembler:

ml 

If everything installed correctly and your Path is setup correctly you will see some output similar to the image below:

💡 Assembly Language Weekly Newsletter

Every week I publish a newsletter that contains tutorials, tips, tricks and resources related to assembly language. If you would like to receive this newsletter subscribe here: http://eepurl.com/ghximb

All Done!

And that’s all there is to it folks. If you want to hit the ground running check out my guide on how to compile and link MASM assembly to produce an executable on Windows 10.

If you’re having any issues following this guide please leave a comment and I will help you the best I can. You can also check out the official documentation includes detailed installation instructions and FAQ’s to solve common problems.

Хочу установить ассемблер на windows 10 x32. С чего начать? Masm или masm32 (Разница есть)?
Попытался установить с https://www.microsoft.com/en-us/download/confirmat… , но при установке окно исчезает и всё. Еще нашел masm32.com , но чего-то боюсь. Что делать?


  • Вопрос задан

  • 11656 просмотров

Просто используйте современный компилятор — YASM или FASM.

Supported Operating System
Windows 2000 Service Pack 3, Windows Server 2003, Windows XP Service Pack 2

В режиме совместимости попробуй запустить.

Да, ещё требует

Visual C++ 2005 Express Edition

Пользуйтесь fasm или виртуалкой с XP

Пригласить эксперта

Войдите, чтобы написать ответ


  • Показать ещё
    Загружается…

Минуточку внимания

Последнее обновление: 01.07.2023

Установка MASM

Для работы с MASM надо установить для Visual Studio инструменты разработки для C/C++. Установщик для среды Visual Studio можно загрузить по следующему адресу:
Microsoft Visual Studio 2022. После загрузки программы установщика Visual Studio запустим ее и в окне устанавливаемых
опций выберем пункт Разработка классических приложений на C++:

Установка MASM 64 в Windows

Visual Studio включает как 32-разрядные, так и 64-разрядные версии MASM. 32-раздяная версия представляет файл ml.exe,
а 64-разрядная — файл ml64.exe. Точное расположение файлов может варьироваться от версии Visual Studio. Например, в моем случае это папка
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.35.32215\bin\Hostx64\x64

Ассемблер MASM64 в Windows

Для использования MASM64 перейдем к меню Пуск и в списке программ найдем пункт Visual Studio и подпункт
x64 Native Tools Command Prompt for VS 2022

Build Tools for Visual Studio 2022 и MASM64 в Windows

Нам должна открыться консоль. Введем в нее ml64, и нам отобразится версия ассемблера и некоторая дополнительная информация:

**********************************************************************
** Visual Studio 2022 Developer Command Prompt v17.5.5
** Copyright (c) 2022 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'

C:\Program Files\Microsoft Visual Studio\2022\Community>ml64
Microsoft (R) Macro Assembler (x64) Version 14.35.32217.1
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: ML64 [ options ] filelist [ /link linkoptions]
Run "ML64 /help" or "ML64 /?" for more info

C:\Program Files\Microsoft Visual Studio\2022\Community>

Стоит отметить, что запуск этой этой утилиты фактически представляет запуск файла C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat —
он по сути вызывает другой файл — vcvarsall.bat, который собственно и настраивает окружение для выполнения ассемблера.

Структура программы на ассемблере MASM

Типичная программа на MASM содержит одну или несколько секций, которые определяют, как содержимое программы будет располагаться в памяти. Эти секции
начинаются с таких директив MASM, как .code или .data. Данные, используемые в программе, обычно определяются в секции .data.
Инструкции ассембра определяются в секции .code.

В общем случае программа на ассемблере MASM имеет следующий вид:

.code

main proc
 
  ret
main endp

end

Директива .code указывает MASM сгруппировать операторы, следующие за ней, в специальный раздел памяти, зарезервированный для машинных инструкций.

Ассемблер преобразует каждую машинную инструкцию в последовательность из одного или нескольких байт. CPU интерпретирует эти значения байт как машинные инструкции во
время выполнения программы.

Далее с помощью операторов main proc определяется процедура main. Операторы main endp указывают на конец функции main.
Между main proc и main endp располагаются выполняемые инструкции ассемблера. Причем в самом конце функции идет инструкция ret,
с помощью которой выполнение возвращается в окружение, в котором была вызвана даннуа процедура.

В конце файла кода идет инструкция end

Программа может содержать комментарии, которые располагаются после точки с запятой:

.code   ; начало секции с кодом программы

main proc   ; Функция main
 
 ret ; возвращаемся в вызывающий код
 
main endp ; окончание функции main

end ; конец файла кода

Комментарии на работу программы никак не влияют и при компиляции не учитываются.

Компиляция программы

Компиляция программы на MASM обычно происходит в командной строке. Например, воспользуемся кодом выше и напишем простейшую программу на ассемблере, которая ничего
не делает. Для этого определим на жестком диске папку для файлов с исходным кодом. Допустим, она будет называться
C:\asm. И в этой папке создадим новый файл, который назовем hello.asm и в котором определим следующий код:

.code   ; начало секции с кодом программы

main PROC   ; Функция main
 
 ret ; возвращаемся в вызывающий код
 
main ENDP

END ; конец файла кода

Откроем программу x64 Native Tools Command Prompt for VS 2022 и перейдем в ней к папке, где располагается файл hello.asm. Затем выполним следующую команду

ml64 hello.asm /link /entry:main

В данном случае вызываем приложение ml64.exe и передаем ему для компиляции файл hello.asm. А флаг /link указывает MASM
скомпоновать скомпилированный файл в файл приложения exe, а все дальнейшие параметры (в частности, параметр /entry:main) передаются компоновщику.
Параметр /entry:main передает компоновщику имя основной процедуры/функции, с которой начинается выполнение программы.
Компоновщик сохраняет этот адрес этой процедуры/функции в специальном месте исполняемого файла, чтобы Windows могла определить начальный адрес основной программы после загрузки исполняемого файла в память.

В результате ассемблер скомпилирует ряд файлов

**********************************************************************
** Visual Studio 2022 Developer Command Prompt v17.5.5
** Copyright (c) 2022 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'

C:\Program Files\Microsoft Visual Studio\2022\Community>cd c:\asm

c:\asm>ml64 hello.asm /link /entry:main
Microsoft (R) Macro Assembler (x64) Version 14.35.32217.1
Copyright (C) Microsoft Corporation.  All rights reserved.

 Assembling: hello.asm
Microsoft (R) Incremental Linker Version 14.35.32217.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/OUT:hello.exe
hello.obj
/entry:main

c:\asm>

В итоге в каталоге программы будут сгенерированы объектный файл hello.obj и собственно файл программы — hello.exe.

  • Ty Myrddin Home
  • Unseen University
  • Improbability Blog
  • About
  • Contact

Developing shells for Windows is best done on Windows. MASM is not available as a separate application. To make use of this assembler, Visual Studio needs to be installed.

Install VSCode

At the time of writing, the Visual Studio Community edition for Windows can be found at https://visualstudio.microsoft.com/vs/community/. If no longer true, do a web-based search for Microsoft Visual Studio.

VSCode

When setting it up, choose the Microsoft Visual C++ desktop tools.

VSCode

Create a CLI prompt for MASM

To use the Microsoft Visual C++ (MSVC) compiler and MASM, initialise the environment by using a batch file provided by Visual Studio and then leave the command line interpreter (CLI) open for building and running programs.

  1. Find the batch file named vcvars64.bat (or something similar). I found the vcvars64.bat file in: C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\.

VSCode

Note: vcvars.bat or vcvars32.bat will not work (these set up the environment variables for the 32-bit version of the assembler and C++ compiler).

  1. Create a shortcut to vcvars64.bat on the Desktop. Rename it to something sensible like VSCLI.

  2. Right-click the shortcut icon on the desktop and click Properties -> Shortcut. Find the Target text box that contains the path to the vcvars64.bat file and add the prefix cmd /k in front of this path:

cmd /k "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"

The /k option tells cmd.exe to execute the command that follows and then leave the window open when the command finishes execution.

Now, when double-clicking the shortcut icon on the desktop, it will initialise all the environment variables and leave the command window open for using execute the Visual Studio tools (like MASM and MSVC) from the command line.

  1. Before closing the Properties dialog, modify the Start In text box to contain C:\ or another directory where you will normally be working when first starting the Visual Studio command line tools. I chose:

C:\Users\Nina\Development
  1. Double-click on the icon:

VSCode

On the command line, type ml64. This should produce output similar to:

C:\Users\Nina\Development>ml64
Microsoft (R) Macro Assembler (x64) Version 14.35.32216.1
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: ML64 [ options ] filelist [ /link linkoptions]
Run "ML64 /help" or "ML64 /?" for more info

This message means that ml64.exe is in the execution path, so the system has properly set up the environment variables to run the Microsoft Macro Assembler.

  1. Execute the cl command to verify being able to run MSVC.

C:\Users\Nina\Development>cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.35.32216.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]
  1. Locate the Visual Studio application in the Start menu. Click it and verify that this brings up the Visual Studio IDE. I made a shortcut on the Desktop for that too.

Editing, assembling, and running a MASM source file

  1. Launch Visual Studio and create an Empty Project (C++). It will ask for a project name and for setting a path.

VSCode

  1. In the solution explorer right-click on the project name, navigate to Build Dependencies -> Build Customizations. Check masm, and click OK.

VSCode

  1. Right-click on the project name again, navigate to Add -> New item, choose the c++ template, and at the bottom change the name of the file to, for example hw64.asm, then Add to the project.

VSCode

Add some code:

includelib kernel32.lib
        extrn __imp_GetStdHandle:proc
        extrn __imp_WriteFile:proc
    
        .CODE

hwStr   byte    "Hello World!"
hwLen   =       $-hwStr
main    PROC

; On entry, stack is aligned at 8 mod 16. Setting aside 8
; bytes for "bytesWritten" ensures that calls in main have
; their stack aligned to 16 bytes (8 mod 16 inside function).

lea     rbx, hwStr
sub     rsp, 8
mov     rdi, rsp    ; Hold # of bytes written here

; Note: must set aside 32 bytes (20h) for shadow registers for
; parameters (just do this once for all functions).
; Also, WriteFile has a 5th argument (which is NULL),
; so we must set aside 8 bytes to hold that pointer (and
; initialize it to zero). Finally, the stack must always be
; 16-byte-aligned, so reserve another 8 bytes of storage
; to ensure this.

; Shadow storage for args (always 30h bytes).

sub     rsp, 030h

; Handle = GetStdHandle(-11);
; Single argument passed in ECX.
; Handle returned in RAX.

mov     rcx, -11    ; STD_OUTPUT
call    qword ptr __imp_GetStdHandle

; WriteFile(handle, "Hello World!", 12, &bytesWritten, NULL);
; Zero out (set to NULL) "LPOverlapped" argument:

        mov     qword ptr [rsp + 4 * 8], 0  ; 5th argument on stack

        mov     r9, rdi     ; Address of "bytesWritten" in R9
        mov     r8d, hwLen  ; Length of string to write in R8D
        lea     rdx, hwStr  ; Ptr to string data in RDX
        mov     rcx, rax    ; File handle passed in RCX
        call    qword ptr __imp_WriteFile
        add     rsp, 38h
        ret
main    ENDP
        END
  1. In the CLI window, assemble:

C:\Users\Nina\Development\Shellcoding>ml64 hw64.asm /link /subsystem:console /entry:main
Microsoft (R) Macro Assembler (x64) Version 14.35.32216.1
Copyright (C) Microsoft Corporation.  All rights reserved.

 Assembling: hw64.asm
Microsoft (R) Incremental Linker Version 14.35.32216.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/OUT:hw64.exe
hw64.obj
/subsystem:console
/entry:main

C:\Users\Nina\Development\Shellcoding>
  1. Run the hw64.exe output file that this assembly produces by typing the command hw64 at the command line prompt:

C:\Users\Nina\Development\Shellcoding>hw64
Hello World!

Create a project template

In the top menu of the just created project, navigate to Project -> Export Template.

Now all that’s needed to do build an assembly project is to create a new project in visual studio and look up the template name in the search bar.


Masm Tutorials Pdf Software Development Computer Engineering

Masm Tutorials Pdf Software Development Computer Engineering Here’s how you can install Windows 95 on a modern computer This cool Windows 95 app can be run not only on Windows 10 but also on Linux and macOS Download the app from Github and run the same It is now available to Windows 10 users in the Release Preview Channel (via), but you can manually download and install it on the stable Windows 10 versions Just do not confuse the new Windows

Masm Programs Pdf

Masm Programs Pdf When planning a recovery strategy for your Windows 10 device, creating a full system backup should be your top priority It is the most reliable method to safeguard your system against potential This week, and perhaps even today, Microsoft will be releasing the first official Windows 11 Insider Preview some people forget to install the Guest Additions, which installs drivers to

How To Run Or Install Masm Software On Windows 32 Or 64 Bit Using

How To Run Or Install Masm Software On Windows 32 Or 64 Bit Using

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Медиаплеер не воспроизводит видео windows 10
  • Как заменить меню пуск в windows 10
  • Пропал микрофон на ноутбуке windows 10
  • Ps3 emulator for pc windows 10
  • Как создать live cd windows xp на флешку