This blog article shows you how to run Assembly Language using Visual Studio Code. This article expects you to have already used Visual Studio Code somewhere. Open Visual Studio Code, click on the Extension. Install MASM/TASM.
Click on Explorer. Add a new file with the extension asm, for example I used test.asm.
Type the following code.
.model small
.stack
.data
msg db “Hello World!”, 13, 10, “$”
.code
start:
mov ax, @data
mov ds, ax ; set DS to point to data segment
mov dx, offset msg ; point to the string
mov ah, 09h ; function to print the string
int 21h ; execute the function
mov ax, 4C00h ; function to terminate the program
int 21h ; execute
end start
Right click on the code page and select Run ASM code.
The result is on the following screen.
Source code download: https://github.com/chanmmn/general/tree/master/2024/asm/?WT.mc_id=DP-MVP-36769
Reference: https://github.com/fredimachado/Assembly/blob/master/tasm/01/hello.asm
https://youtu.be/pBh29mURXLk/?WT.mc_id=DP-MVP-36769
About chanmingman
Since March 2011 Microsoft Live Spaces migrated to WordPress (http://www.pcworld.com/article/206455/Microsoft_Live_Spaces_Moves_to_WordPress_An_FAQ.html) till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years.
Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
Assemble and Compile Script with NASM and GCC
This simple bash script, named ‘assemble,’ streamlines the process of assembling and compiling assembly code for your host platform using NASM (Netwide Assembler) and GCC (GNU Compiler Collection). With ‘assemble,’ you can quickly turn your assembly source code into an executable binary with a ‘main’ section instead of ‘_start,’ making it compatible with C-style program entry points.
:warning: These extensions currently doesn’t provide proper support for Windows Machines. So, please consider before installing it.
Features
- Simplifies the process of assembling and compiling assembly code.
- Automatically detects the host platform and compiles the code accordingly.
- Generates an executable binary with a ‘main’ section for C-style program entry points.
Requirements
- This extension explicitly depends on Code Runner. So, you will need to be installed Code Runner extension to run assembly script.
- To ensure that the assemble script runs correctly, certain requirements must be installed globally on your system. The installation methods may vary depending on your operating system. Below, you will find some popular guides, but you may need to adapt the instructions to your specific system.
Basic Requrements
- NASM (Netwide Assembler, widely used assembly language compiler, https://www.nasm.us/)
- GCC (GNU Compiler Collection, widely used compiler for the C and C++, https://gcc.gnu.org/install/binaries.html)
Installing NASM and GCC on Windows:
NASM (Netwide Assembler):
-
Download NASM from (https://www.nasm.us/pub/nasm/releasebuilds).
-
Run the Installer and follow the instructions.
-
You may need to add NASM installation binary path to the environment variable for systemwide execution. More details.
-
Verify the Installation:
- Open Command Prompt or PowerShell and run:
nasm --version - It should display the installed NASM version.
- Open Command Prompt or PowerShell and run:
GCC (GNU Compiler Collection):
-
Downlaod GCC from (https://gcc.gnu.org/install/binaries.html)
-
Run the Installer and follow the instructions.
-
You may need to add NASM installation binary path to the environment variable for systemwide execution. More details.
-
Verify the Installation:
- In the MSYS2 terminal, run:
gcc --version - It should display the installed GCC version.
- In the MSYS2 terminal, run:
Installing NASM and GCC on Linux (e.g., Ubuntu):
- Run the following command to install NASM:
sudo apt-get install nasm gcc - Run the following command to verify installtion:
- For NASM:
nasm --version - For GCC:
gcc --version
- For NASM:
- It should display the installed NASM and GCC version.
Installing NASM and GCC on macOS:
NASM (Netwide Assembler):
-
Install NASM via Homebrew:
- If you don’t have Homebrew installed, follow the instructions here.
- Run the following command in terminal to install NASM:
brew install nasm gcc
-
Verify the Installation:
- In Terminal, run:
nasm --version - Again for GCC, run:
gcc --version - It should display the installed NASM and GCC version.
- In Terminal, run:
Example
The ‘main’ section is needed because it serves as the entry point for the program when compiled and linked with GCC. When you use GCC to compile and link your code, it expects to find a ‘main’ function as the starting point of your program.
Here’s a brief explanation of the process:
-
Assembly Code: You write your assembly code, including the ‘main’ section, which contains the code that will be executed when the program starts.
-
Assembling: You use NASM to assemble your assembly code into object code. This step generates a binary file containing machine code instructions.
-
Linking with GCC: When you link the object code with GCC, it performs several tasks, including resolving external dependencies and creating an executable binary. GCC expects a ‘main’ section as the program entry point.
-
Program Execution: When you run the resulting executable, the operating system loads it into memory and begins execution at the ‘main’ section, effectively starting your program.
In summary, the ‘main’ section is essential because it defines where program execution begins when using GCC to create an executable from assembly code. It ensures that your assembly program integrates seamlessly with the C-style program entry point expected by the compiler and the operating system.
Sample assembly code in ‘hello.asm’ with a ‘main’ section:
For Linux and Windows Platform:
section .data
hello db 'Hello, World!',0
section .text
global main
main:
mov eax, 4
mov ebx, 1
mov ecx, hello
mov edx, 13
int 0x80
mov eax, 1
int 0x80
For macOS (Due to Compiler Dependency):
global _main
extern _puts
section .text
_main:
sub rsp, 8
lea rdi, [message] ; Use this instead of 'mov rdi, message'
call _puts
add rsp, 8
ret
section .data
message:
default rel ; Add 'default rel' under label
db "Hello, world",0
Abdullah AL Shohag (HackerShohag@outlook.com)
Feel free to further customize the description with your own details and any additional features or usage instructions you think are relevant.
License
Copyright (C) 2023 Abdullah AL Shohag
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.
-
Mikl___
Супермодератор
Команда форума- Публикаций:
-
14
- Регистрация:
- 25 июн 2008
- Сообщения:
- 3.930
Visual Studio Code ― популярный редактор кода, бесплатный, с открытым исходным кодом.
Устанавливаем Visual Studio Code
Скачайте последнюю версию Visual Studio Code с официального сайта. Рекомендуется загрузить системный установщик (System Installer), но если у вас нет прав администратора, то пользовательский установщик (User Installer) тоже подойдет. Выполните все обычные шаги по установке. Не доверяете установщику? Скачайте и распакуйте zip-файл.
Настраиваем внешний вид редактора
Открываем asm-файл (Файл → Открыть… Ctrl+O)
Первое, что мы сделаем ― установим русский язык. Нажимаем «View → Extensions» (Ctrl+Shift+X), набираем «russian language»
Жмем на «install»
Жмем на «Restart»
«Вид → Расширения» (Ctrl+Shift+X) набираем «masm», выбираем и устанавливаем masm-code (подсветка синтаксиса) и masm runner (запуск компилятора, линкера, готового приложения)
«Command Palete» (Ctrl+Shift+P)
набираем «Change Language Mode»
Выбираем «asm»
Ищем в папке
C:\Users\...\.vcode\extensionsкаталогistareatscreens.masm-runner-0.4.5, удаляем его и заменяем на содержимое запакованное в файле istareatscreens.zip. В каталогеistareatscreens.masm-runner-0.4.5\outищем файлextension.js, в нем строкуconst getPath = getPathBuilder("d:\\masm39");и меняемd:\\masm39на положение masm64 на вашем компьютере.Работа в VSCode
Открываем asm-файл (Файл → Открыть… Ctrl+O) Нажимаем Ctrl+Shift+P набираем
Masm runner: Compile and run code→ запускается компилятор, линкер и будет создано GUI/ CONSOLE/ DLL-приложение, в соответствии с содержимым первой закомментированной строки в asm-файле. Если в текущей папке есть rc-файл с тем же именем, что и у asm-файла → запустится компилятор ресурсов и к EXE/DLL-файлу будут прилинкованы ресурсы.Вложения:
Последнее редактирование: 25 апр 2023
-
mantissa
Administrator
Команда форума- Публикаций:
-
0
- Регистрация:
- 9 сен 2022
- Сообщения:
- 174
- Как запустить x64dbg с командной строки не в полноэкранном, а в оконном режиме?
Запускается в том режиме, в котором он был в последний раз открыт. (Перепробовал все ключи при запуске — не работает, в оф. документации тоже ничего не нашел.) - Как с командной строки «x64dbg test.exe» перейти на начало test.exe в памяти? Аналог нажатия на F9
x64dbg -> Параметры -> Параметры -> События ->
В Прерываться на: убрать системную точку останова и вызове TLS, тогда сразу при запуске бряк будет на EntryPoint
-
Mikl___
Супермодератор
Команда форума- Публикаций:
-
14
- Регистрация:
- 25 июн 2008
- Сообщения:
- 3.930
-
mantissa
Administrator
Команда форума- Публикаций:
-
0
- Регистрация:
- 9 сен 2022
- Сообщения:
- 174
Прокачиваем VS Code до IDE
Visual Studio Code — это прежде всего редактор, и он включает в себя функции, необходимые для высокопродуктивного редактирования исходного кода. Но, с помощью таких высокоуровневых средств как: расширения, интеграция с системами контроля версий, настройка среда разработки, поддержка отладки и др. — его можно превратить в настоящий IDE для любого языка программирования, в том числе MASM.IntelliSense
IntelliSense — это комплекс функций редактирования кода, включающий авто дополнение кода, информацию о директивах и параметрах функций, краткую справку. Эти возможности IntelliSense могут также называться иными терминами, например, «авто завершение кода», «помощь в работе с содержимым» или «подсказки кода».
К сожалению, VS Code не поддерживает язык программирования MASM с коробки, но мы можем это исправить, добавив для этого расширение.Расширения
Расширения можно разделить на две группы:1. Декларативная группа расширений
Это такие расширения, которые определяются в конфигурационных файлах, они позволяют добавить:- Подсветка синтаксиса
- Завершение фрагмента кода (сниппеты)
- Сворачивание фрагментов кода (фолдинг)
- Авто закрытие скобок
2. Программная группа расширений
Данные расширения включают: авто завершение, проверку ошибок, форматирование, рефактор и др. Эти возможности часто обеспечиваются сервером языка — программой, которая анализирует ваш проект для обеспечения динамических возможностей.Для начала остановимся на декларативных расширениях и добавим возможности, которые они предоставляют.
«Вид → Расширения» (Ctrl+Shift+X) вводим «masm» и скачиваем расширение «MASM» от blindtiger. Далее мы будем лишь расширять функционал данного расширения, чтобы не писать все с нуля.Подсветка синтаксиса
Расширение добавляет подсветку синтаксиса для констант, директив и инструкций. Полный список ключевых слов, которые распознаются расширением можно посмотреть по пути C:\Users\…\.vcode\extensions\blindtiger.masm-0.0.5\syntaxes в файле masm.tmLanguage.json. Там же, можно добавить свои ключевые слова, дополнив соответствующее регулярное выражение.Завершение фрагментов кода (сниппеты)
При программировании на языке ассемблера, в связи с краткостью мнемоник и директив, по моему мнению, сниппеты редко могут пригодиться. Но для тех, кто использует «высокоуровневые» директивы (.IF .WHILE .FOR и др.) эта возможность весьма полезна.
Настроить список сниппетов (изменить, добавить, удалить) можно по пути C:\Users\…\.vcode\extensions\blindtiger.masm-0.0.5\snippets
В данной директории содержатся 3 файла:
1. flow.json – содержит определение сниппетов для директив контроля выполнения.Поле prefix – это сам сниппет, при вводе которого, он развернется в то, что написано в поле body. Тут же есть небольшое описание и поле scope – оно определяет, в файлах с каким расширением данный сниппет будет работать.
2. macro.json – определяет сниппеты для макроопределений.
3. segment.json – определяет сниппеты для сегментов.
Данное разделение по файлам – лишь семантика. В какой файл из этих добавлять новые сниппеты – дело ваше. Обратите внимание на поле scope, не забудьте указать расширения файлов, в которых будут применяться сниппеты.
Сворачивание фрагментов кода (фолдинг)
По умолчанию, в VS code сворачивание стоит для уровней табуляции.Добавим также распознавание процедур и структур, даже если они находятся на одном уровне: в уже знакомой нам директории blindtiger.masm-0.0.5 открываем файл language-configuration.json и добавляем в конце поле “folding”:
Включив туда два регулярных выражения:
- Start: «^\\S*\\s+(proc|struc)(\\s|$)+(\\s|\\S)*»
- End: «^\\S*\\s+(endp|ends)(\\s|$)+(\\s|\\S)*»
Авто закрытие скобок уже настроено разработчиком расширения в этом же файле, в полях surroundingPairs, autoClosingPairs, brackets.
E.N.D. и Mikl___ нравится это.
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Updated on January 1, 2021⚑Retro AssemblerVS Code
(This post has been updated for the latest version of the assembler.)
Visual Studio Code is perhaps the best programming environment to use Retro Assembler with. I have a frequently updated Extension in the VS Code Marketplace that offers multiple themes, syntax highlighting and command execution integration. Here is a screenshot of the latest Blue theme, showing a code file used for highlighting testing.
This application is available on all major operating systems and can be downloaded from https://code.visualstudio.com/
Setting it up is easy. After you installed it, click on the Extensions icon on the left side, or choose View -> Extensions. Enter Retro Assembler into the search field and install the extension from the marketplace. Choose one of the offered color themes for the assembler. You can change this later in Preferences -> Color Theme
(The Preferences menu option will be referenced below, so I better clarify that it’s under File in Windows and Linux, and under the application name Code on macOS.)
For best practices select the installed Retro Assembler Extension on the Extensions page and read the Details page. (In an ideal world this is where this guide would finish.)
Settings
Go into Preferences -> Settings and search for Retro Assembler. Or you can just open its section up directly under the Extensions tree branch. You’ll find 3 editable fields.
Retroassembler: Path
You have to enter the full path to the Retro Assembler executable file that you already installed somewhere. On Windows you should use the «retroassembler.exe» file. On other systems you need to enter the command «dotnet ~/retroassembler/retroassembler.dll» substituting the actual directory path from your system. If you followed my .NET installation guide, you can use that command alias ra (or similar) that you created for this.
Retroassembler: Args
Optional command line arguments that will be passed in for the assembler when you compile the selected code file. Refer to the documentation.
Retroassembler: Mainfile
If you are working on a bigger assembly project with multiple files, perhaps even in a deeper directory structure, you can enter the full path to your main code file that should always be compiled, instead of the currently edited file.
This whole Settings is saved as a JSON file and can be edited directly by clicking on { } on the right side. Here are my settings, for inspiration, in case you also need to disable visible white spaces, use tabs, and enjoy a cleaner editor interface in general.
{
"retroassembler.path": "C:\\RetroAssembler\\retroassembler.exe",
"retroassembler.args": "-x",
"retroassembler.mainfile": "",
"workbench.colorTheme": "Retro Assembler Blue",
"window.zoomLevel": 0,
"editor.fontFamily": "'Lucida Console', Consolas, monospace",
"editor.fontSize": 13,
"editor.insertSpaces": false,
"editor.detectIndentation": false,
"editor.renderIndentGuides": false,
"editor.multiCursorModifier": "ctrlCmd",
"editor.minimap.enabled": false,
"editor.renderWhitespace": "none",
"editor.renderControlCharacters": false,
"breadcrumbs.enabled": false
}
Keyboard Shortcuts
Go into Preferences -> Keyboard Shortcuts and search for retroassembler. You’ll find 3 editable commands. Bind your desired keyboard shortcuts to them if you want to alter the defaults.
Retro Assembler: Build
This opens the Terminal and compiles the currently edited file, or the Mainfile if set in Settings.
Default shortcut: Ctrl+Shift+B
Retro Assembler: Build & Start
This opens the Terminal and compiles the currently edited file, or the Mainfile if set in Settings. It also passes in the -L command line argument to the assembler, which can start the compiled binary file with an emulator. In the compiled source code file you need to have a line similar to this example:
.setting "LaunchCommand", "C:\\Emulator\\emulator.exe {0}"
Default shortcuts: Shift+F5 and F6
Retro Assembler: Build & Debug
This opens the Terminal and compiles the currently edited file, or the Mainfile if set in Settings. It also passes in the -g command line argument to the assembler, which can start the compiled binary file with a debugger. In the compiled source code file you need to have a line similar to this example:
.setting "DebugCommand", "C:\\Emulator\\debugger.exe {0}"
Default shortcut: F5
File Naming Conventions
Visual Studio Code is a great editor but needs a little help with the file type detection. There wouldn’t be much use to see 6502 instruction highlighting in a Z80 assembly code file, so you need to tag your files with the CPU type you use in them. You can do this by adding a secondary file extension between the file name and the .asm (or .s, .inc) extension, like this:
- MyCode.6502.asm
- MyCode.65c02.asm (Use this tag for 65SC02, too)
- MyCode.65816.asm
- MyCode.4510.asm
- MyCode.45gs02.asm
- MyCode.mega65.asm (Same as 45GS02)
- MyCode.4004.asm
- MyCode.4040.asm
- MyCode.8008.asm
- MyCode.8080.asm
- MyCode.8085.asm
- MyCode.gameboy.asm
- MyCode.z80.asm
Code Snippets
Using built-in features IntelliSense and Code Completion, the extension can help entering Directives like .macro and it can display a short description and examples for each. Just type «.» and hit Ctrl+Space to show the available Directives, or you can start typing what you need and hit Tab to insert the Code Snippet for the chosen Directive.
These helper entries don’t list all possible parameters and full description due to the space limitation in the code editor window, but the most common cases are covered. It makes writing code a lot easier. For further information on the minute details you should still refer to the assembler’s documentation.
Get to work!
Now you’re ready to code for some good old CPUs. Just edit and save your files as usual, then press the keyboard shortcut you set up for Build or Build & Start to compile your selected file. You will see in the terminal window slotted somewhere inside the IDE whether your code compiled correctly or it has some error you need to fix. You can Alt+Click the VS Code link of the error report to open the referenced file and jump to the problematic line of code.
