【全网首个】用中文写汇编代码CASM

【全网首个】用中文写汇编代码CASM汇编语言

casm是以nasm为基础的汇编语言

一、下载

网上只有Windows64的程序下载,但是可以用它的开源代码自己写

官网:CASM官网

下载按钮全部点了

按下载程序源代码可以看到源代码

二、运行

 注意:需要有GCC的环境,这里假设已经设置好环境变量

双击运行CODE_OF_CASM.exe

点击模式,选择casm

点击文件->打开,打开 测试.汇编 文件

可以看到里面的内容

双击打开CASM.exe

模式输入 -r 

源文件输入 测试.汇编

目标文件写123

运行成功! 

在打开终端,输入.\123也很成功地打印 123hhh

三、解析

发现生成了汇编asm文件,obj目标文件和exe可执行文件

类似一个编译器

使用nasm型语法和gcc链接器

根据以下规则编译

    std::unordered_map<std::string, std::string> conversionDict = {
            {"导入", "%include"},
            {"声明", "extern"},
            {"打印", "puts"},
            {",", ","},
            {"。", "."},
            {":", ":"},
            {";", ";"},
            {"¥", "$"},
            {"【", "["},
            {"】", "]"},
            {"“", "'"},
            {"”", "'"},
            {"回车", "0ah"},
            {"定义段", "SECTION .data"},
            {"代码段", "SECTION .text"},
            {"预留段", "SECTION .bss"},
            {"定义常量", "equ"},
            {"定义", "db"},
            {"预留字节", "resb"},
            {"预留字", "resw"},
            {"预留双字", "resd"},
            {"预留双精度浮点数", "resq"},
            {"预留扩展精度浮点数", "rest"},
            {"全局", "global"},
            {"主函数", "main"},
            {"赋值", "mov"},
            {"中断", "int"},
            {"跳转", "jmp"},
            {"比较", "cmp"},
            {"相等跳转", "je"},
            {"非相等跳转", "jne"},
            {"大于跳转", "jg"},
            {"小于跳转", "jl"},
            {"大等跳转", "jge"},
            {"小等跳转", "jle"},
            {"非大于跳转", "jng"},
            {"非小于跳转", "jnl"},
            {"加", "add"},
            {"减", "sub"},
            {"乘", "mul"},
            {"除", "div"},
            {"出栈", "pop"},
            {"进栈", "push"},
            {"返回", "ret"},
            {"调用", "call"},
            {"栈顶", "rsp"}
    };

程序很简单,上源代码

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <exception>

void assembleWithNasm(const std::string& objFilePath, const std::string& asmFilePath, const std::string& exeFilePath) {
    std::string nasmCommand = "nasm -f win64 -o " + objFilePath + " " + asmFilePath;
    int result = std::system(nasmCommand.c_str());
    if (result!= 0) {
        throw std::runtime_error("编译失败");
    }
    std::string gccCommand = "gcc " + objFilePath + " -o " + exeFilePath;
    int result2 = std::system(gccCommand.c_str());
    if (result2!= 0) {
        throw std::runtime_error("编译失败");
    }
    std::cout << "编译完成,目标文件已生成至: " << exeFilePath << std::endl;
    return;
}

std::string SasmToAsm(const std::string& asmCode) {
    std::unordered_map<std::string, std::string> conversionDict = {
            {"导入", "%include"},
            {"声明", "extern"},
            {"打印", "puts"},
            {",", ","},
            {"。", "."},
            {":", ":"},
            {";", ";"},
            {"¥", "$"},
            {"【", "["},
            {"】", "]"},
            {"“", "'"},
            {"”", "'"},
            {"回车", "0ah"},
            {"定义段", "SECTION .data"},
            {"代码段", "SECTION .text"},
            {"预留段", "SECTION .bss"},
            {"定义常量", "equ"},
            {"定义", "db"},
            {"预留字节", "resb"},
            {"预留字", "resw"},
            {"预留双字", "resd"},
            {"预留双精度浮点数", "resq"},
            {"预留扩展精度浮点数", "rest"},
            {"全局", "global"},
            {"主函数", "main"},
            {"赋值", "mov"},
            {"中断", "int"},
            {"跳转", "jmp"},
            {"比较", "cmp"},
            {"相等跳转", "je"},
            {"非相等跳转", "jne"},
            {"大于跳转", "jg"},
            {"小于跳转", "jl"},
            {"大等跳转", "jge"},
            {"小等跳转", "jle"},
            {"非大于跳转", "jng"},
            {"非小于跳转", "jnl"},
            {"加", "add"},
            {"减", "sub"},
            {"乘", "mul"},
            {"除", "div"},
            {"出栈", "pop"},
            {"进栈", "push"},
            {"返回", "ret"},
            {"调用", "call"},
            {"栈顶", "rsp"}
    };
    std::string modifiedAsmCode = asmCode; // Create a non-const copy of asmCode
    for (const auto& pair : conversionDict) {
        size_t pos = 0;
        while ((pos = modifiedAsmCode.find(pair.first, pos)) != std::string::npos) {
            modifiedAsmCode.replace(pos, pair.first.length(), pair.second);
            pos += pair.second.length();
        }
    }
    return modifiedAsmCode;
}

std::string readFile(const std::string& filePath) {
    std::ifstream file(filePath);
    if (!file) {
        throw std::runtime_error("错误:文件 " + filePath + " 未找到。");
    }
    std::stringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

void writeFile(const std::string& filePath, const std::string& content) {
    std::ofstream file(filePath);
    if (!file) {
        throw std::runtime_error("写入文件时发生错误");
    }
    file << content;
}


int main() {
    std::string M;
    std::cout << "模式>>";
    std::cin >> M;
    std::string sourceFilePath, targetFilePath;
    std::cout << "请输入汇编源文件>>";
    std::cin >> sourceFilePath;
    std::cout << "请输入目标文件>>";
    std::cin >> targetFilePath;

    if(M == "-r"){
        try {
            std::string sasmCode = readFile(sourceFilePath);
            std::string asmCode = SasmToAsm(sasmCode);
            writeFile("asm.asm", asmCode);
            std::string writtenAsmCode = readFile("asm.asm");
            std::cout << "写入后的内容:" << writtenAsmCode << std::endl;

            std::cout << "编译成功!" << std::endl;
            assembleWithNasm("obj.obj", "asm.asm", targetFilePath);
            std::cout << "正在运行..." << std::endl;
            int result1 = std::system(targetFilePath.c_str());
            if (result1!= 0) {
                throw std::runtime_error("运行失败");
            }
        } catch (const std::exception& e) {
            std::cerr << "错误:" << e.what() << std::endl;
        }
    }
    else if(M == "-o"){
        try {
            std::string sasmCode = readFile(sourceFilePath);
            std::string asmCode = SasmToAsm(sasmCode);
            writeFile("asm.asm", asmCode);
            std::string writtenAsmCode = readFile("asm.asm");
            std::cout << "写入后的内容:" << writtenAsmCode << std::endl;

            std::cout << "编译成功!" << std::endl;
            assembleWithNasm("obj.obj", "asm.asm", targetFilePath);

        } catch (const std::exception& e) {
            std::cerr << "错误:" << e.what() << std::endl;
        }
    }
    else if(M == "-a"){
        try {
            std::string sasmCode = readFile(sourceFilePath);
            std::string asmCode = SasmToAsm(sasmCode);
            writeFile("asm.asm", asmCode);
            std::string writtenAsmCode = readFile("asm.asm");
            std::cout << "写入后的内容:" << writtenAsmCode << std::endl;

            std::cout << "编译成功!" << std::endl;
        } catch (const std::exception& e) {
            std::cerr << "错误:" << e.what() << std::endl;
        }
    }
    else {
        std::cout << "模式错误";
    }
    std::system("pause");
    return 0;
}


勉强能算得上是编译器

再看高亮代码编辑器

IDA反汇编后,明显不是C++/C,看来是python

尝试反写python代码 

import tkinter as tk
from tkinter import filedialog, messagebox
class CodeEditor(tk.Tk):
    def __init__(self):
        super().__init__()

        self.title('高亮代码编辑器')
        self.geometry('600x400')

        # 创建用于显示行号的Canvas组件
        self.lineno = tk.Canvas(self, width=40, bg='light grey')
        self.lineno.pack(side=tk.LEFT, fill=tk.Y)

        # 创建垂直滚动条
        self.vsb = tk.Scrollbar(self, orient="vertical")
        self.vsb.pack(side=tk.RIGHT, fill=tk.Y)

        self.text_editor = tk.Text(self, bg='black', fg='white', insertbackground='white')
        self.text_editor.pack(fill=tk.BOTH, expand=True)

        # 绑定 <<Modified>> 事件到 text_editor_change 方法
        self.text_editor.bind("<<Modified>>", self.text_editor_change)

        self.create_menu()

        # 初始化keywords字典
        self.keywords = {
            '赋值': '#00ffff',
            '加': '#00ffff',
            '减': '#00ffff',
            '调用': '#00ffff',
            '定义': '#00ffff',
            ';': '#aaaaaa',
            '“': '#00ff00',
            '”': '#00ff00',
            '主函数': '#ff0000',
            '返回': '#ff0000',
            '声明': '#aa00ff',
            '全局': '#aa00ff',
            '代码段': '#aa00ff',
            '0': '#ffff00',
            '1': '#ffff00',
            '2': '#ffff00',
            '3': '#ffff00',
            '4': '#ffff00',
            '5': '#ffff00',
            '6': '#ffff00',
            '7': '#ffff00',
            '8': '#ffff00',
            '9': '#ffff00',
            '0x': '#ffff00',
            '栈顶': '#848400',
            'rax': '#848400',
            'rbx': '#848400',
            'rcx': '#848400',
            'rdx': '#848400'
        }

        self.highlight_keywords()

        # 更新行号
        self.update_line_numbers()

        # 配置滚动条
        self.vsb['command'] = self.on_vsb_move

    def on_text_yview(self, *args):
        # 更新行号
        self.update_line_numbers()
        # 调用垂直滚动条的set方法
        self.vsb.set(*args)
    def create_menu(self):
        menu_bar = tk.Menu(self)
        self.config(menu=menu_bar)

        file_menu = tk.Menu(menu_bar, tearoff=0)
        menu_bar.add_cascade(label='文件', menu=file_menu)
        file_menu.add_command(label='打开', command=self.open_file)
        file_menu.add_command(label='保存', command=self.save_file)
        mode_menu = tk.Menu(menu_bar, tearoff=0)
        menu_bar.add_cascade(label='模式', menu=mode_menu)
        mode_menu.add_command(label='CASM', command=self.CASM)
        mode_menu.add_command(label='NASM', command=self.NASM)
        other_menu = tk.Menu(menu_bar, tearoff=0)
        menu_bar.add_cascade(label='其他', menu=other_menu)
        other_menu.add_command(label='关于', command=self.about)
        other_menu.add_command(label='...', command=self.nothing)

    def open_file(self):
        filepath = filedialog.askopenfilename()
        if filepath:
            with open(filepath, 'r') as file:
                content = file.read()
                self.text_editor.delete(1.0, tk.END)
                self.text_editor.insert(1.0, content)
                # 调用 text_editor_change 以高亮显示新内容
                self.text_editor_change(None)

    def save_file(self):
        filepath = filedialog.asksaveasfilename(defaultextension='.txt')
        if filepath:
            content = self.text_editor.get(1.0, tk.END)
            with open(filepath, 'w') as file:
                file.write(content)

    def highlight_keywords(self):
        for keyword, color in self.keywords.items():
            self.text_editor.tag_config(keyword, foreground=color)
            start = '1.0'
            while True:
                pos = self.text_editor.search(keyword, start, stopindex=tk.END)
                if not pos: break
                end = f'{pos}+{len(keyword)}c'
                self.text_editor.tag_add(keyword, pos, end)
                start = end

    def text_editor_change(self, event):
        self.text_editor.edit_modified(False)  # 清除已修改标记
        self.highlight_keywords()  # 重新高亮显示关键词
        self.update_line_numbers()  # 更新行号

    def update_line_numbers(self):
        # Clear existing line numbers
        self.lineno.delete("all")

        # Get the total number of lines in the text editor
        line_count = int(self.text_editor.index('end-1c').split('.')[0])

        # Redraw the line numbers based on the actual position of each line in the text editor
        for i in range(1, line_count + 1):
            # Get the top-left and bottom-right coordinates of the line in the text editor
            bbox = self.text_editor.bbox(f"{i}.0")

            if bbox:
                # The third element of bbox represents the Y-coordinate of the top-left corner of the line
                y = bbox[1]

                # Draw the line number at the appropriate position in the canvas
                self.lineno.create_text(2, y, anchor="nw", text=str(i), fill="dark blue")

    def on_vsb_move(self, first, last):
        try:
            first_float = float(first)
            self.text_editor.yview_moveto(first_float)
        except ValueError:
            pass

    def nothing(self):
        pass

    def about(self):
        messagebox.showinfo("关于", "作者:林泓翰")

    def NASM(self):
        global keywords
        self.keywords = {
            'mov': '#00ffff',
            'add': '#00ffff',
            'sub': '#00ffff',
            'call': '#00ffff',
            'db': '#00ffff',
            ';': '#aaaaaa',
            '"': '#00ff00',
            'main': '#ff0000',
            'ret': '#ff0000',
            'extern': '#aa00ff',
            'global': '#aa00ff',
            'SECTION .test': '#aa00ff',
            '0': '#ffff00',
            '1': '#ffff00',
            '2': '#ffff00',
            '3': '#ffff00',
            '4': '#ffff00',
            '5': '#ffff00',
            '6': '#ffff00',
            '7': '#ffff00',
            '8': '#ffff00',
            '9': '#ffff00',
            '0x': '#ffff00',
            'rsp': '#848400',
            'rax': '#848400',
            'rbx': '#848400',
            'rcx': '#848400',
            'rdx': '#848400'
        }
    def CASM(self):
        global keywords
        self.keywords = {
            '赋值': '#00ffff',
            '加': '#00ffff',
            '减': '#00ffff',
            '调用': '#00ffff',
            '定义': '#00ffff',
            ';': '#aaaaaa',
            '“': '#00ff00',
            '”': '#00ff00',
            '主函数': '#ff0000',
            '返回': '#ff0000',
            '声明': '#aa00ff',
            '全局': '#aa00ff',
            '代码段': '#aa00ff',
            '0': '#ffff00',
            '1': '#ffff00',
            '2': '#ffff00',
            '3': '#ffff00',
            '4': '#ffff00',
            '5': '#ffff00',
            '6': '#ffff00',
            '7': '#ffff00',
            '8': '#ffff00',
            '9': '#ffff00',
            '0x': '#ffff00',
            '栈顶': '#848400',
            'rax': '#848400',
            'rbx': '#848400',
            'rcx': '#848400',
            'rdx': '#848400'
        }


if __name__ == '__main__':
    app = CodeEditor()
    app.mainloop()

看图标就知道是tkinter 

 总而言之,CASM还是很适合初学者的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值