首页 > 编程语言 >pythonasm库分析,看看你和自学编程小学生的差距

pythonasm库分析,看看你和自学编程小学生的差距

时间:2024-07-28 11:29:07浏览次数:16  
标签:int variables 编程 mov pythonasm ax 自学 def instructions

下面是pythonasm.asm库的源代码

from keystone import *
from capstone import *

assembly_instructions = []#储存汇编指令的列表

#汇编指令写入列表
def mov(reg1,reg2):
    assembly_instructions.append(f"mov {reg1},{reg2}")

def db(value):
    assembly_instructions.append(str(value))

def add(reg1, reg2):
    assembly_instructions.append(f"add {reg1}, {reg2}")

def inc(reg):
    assembly_instructions.append(f"inc {reg}")

def int_(vector):
    assembly_instructions.append(f"int {vector}")

def jmp(label):
    assembly_instructions.append(f"jmp {label}")

def jne(label):
    assembly_instructions.append(f"jne {label}")

def je(label):
    assembly_instructions.append(f"je {label}")

def label(label):
    assembly_instructions.append(f"{label}:")

# 创建汇编器和反汇编器引擎
ks = Ks(KS_ARCH_X86, KS_MODE_64)
engine = Cs(CS_ARCH_X86, CS_MODE_64)


def display():
    for instruction in assembly_instructions:#遍历列表
        try:
            # 汇编指令,获取机器码
            encoding, count = ks.asm(instruction)
            # 反汇编机器码
            for asm in engine.disasm(bytes(encoding), 0x1000):

                print(f"{instruction:20};0x{bytes(asm.bytes).hex().upper()}")

        except KsError:#处理db指令
            print(f"db {instruction:17};{hex(int(instruction))}")

这其实就是把python的函数转换成汇编指令再用第三方库汇编

下面是pythonasm.main内容

#pythonasm

"""
This is a module for ASM...
"""

import re
import os

variables = {'ax': 0, 'bx': 0, 'cx': 0, 'dx': 0}


def add(a, b): return a + b


def subtract(a, b): return a - b


def multiply(a, b): return a * b


def divide(a, b): return a / b if b != 0 else (print("Error:Divisor cannot be 0."), a)[1]


def operation(line):
    add_pattern = re.compile(r'add\s+(\w+),\s*(\w+)')
    sub_pattern = re.compile(r'sub\s+(\w+),\s*(\w+)')
    mul_pattern = re.compile(r'mul\s+(\w+),\s*(\w+)')
    div_pattern = re.compile(r'div\s+(\w+),\s*(\w+)')

    for pattern, operation in [(add_pattern, add), (sub_pattern, subtract), (mul_pattern, multiply), (div_pattern, divide)]:
        match = pattern.match(line)
        if match:
            operand1, operand2 = match.groups()
            if operand1 in variables:
                operand2_value = variables.get(operand2, None)
                if operand2_value is not None:
                    variables[operand1] = operation(variables[operand1], operand2_value)
                else:
                    try:
                        operand2_value = int(operand2)
                        variables[operand1] = operation(variables[operand1], operand2_value)
                    except ValueError:
                        print(f"Error:Operand {operand2} is not defined.")
            else:
                print(f"Error:Operand {operand1} is not defined.")
            return


def check():
    if (variables['ax'] == 4 and isinstance(variables['bx'], int) and variables['bx'] == 1
            and isinstance(variables['cx'], str) and variables['dx'] == len(variables['cx'])):
        print(variables['cx'])
    elif (variables['ax'] == 4 and isinstance(variables['bx'], int) and variables['bx'] == 1
          and isinstance(variables['cx'], str) and variables['dx'] != len(variables['cx'])):
        print("Error:Length does not match.")
    elif variables['ax'] == 3 and variables['bx'] == 0 and isinstance(variables['dx'], int):
        input_str = input()
        if len(input_str) <= variables['dx']:
            variables['cx'] = input_str
        else:
            print("Error:The input string length exceeds the reserved length.")


def asm(filename):
    if not os.path.exists(filename):
        print(f"Error:File {filename} does not exist.")
        return

    with open(filename, 'r') as file:
        lines = file.readlines()

    mov_reg_to_const_pattern = re.compile(r'mov\s+(\w+),\s*(\d+)')
    mov_reg_to_reg_pattern = re.compile(r'mov\s+(\w+),\s*\[?(\w+)\]?\s*')
    db_pattern = re.compile(r'(\w+)\s+db\s+"([^"]*)"')

    for line in lines:
        line = line.strip()

        match = mov_reg_to_const_pattern.match(line)
        if match:
            reg, value = match.groups()
            try:
                variables[reg] = int(value)
            except ValueError:
                print(f"Error:Cannot convert {value} to an integer.")
            continue

        match = mov_reg_to_reg_pattern.match(line)
        if match:
            dest, src = match.groups()
            if src in variables:
                variables[dest] = variables[src]
            else:
                print(f"Warning: Source register {src} is not defined.")
            continue

        match = db_pattern.match(line)
        if match:
            label, value = match.groups()
            variables[label] = value.strip('"')
            continue

        operation(line)
        if re.search(r"nt .*(?:80h|0x80)", line):
            check()




这是一个模拟汇编器,用re库的正则表达式编译文件,为寄存器赋值,int 80h系统中断调用时,就判断是否符合打印和输入的格式,部分代码还有错误处理

下面是官方描述(附翻译):

Project description

pythonasm Library

I. Overview

This is a Python library that contains a series of functions related to data processing and operations. It can simulate the input and output of an assembler. The author is Lin Honghan, a Chinese sixth-grade primary school student. The pypi account is linhhanpy, and the gitee account is linhhpy. It was made during the summer vacation when being bored. More functions will be updated in the future, adding an assembler virtual machine and using real assembler instructions.

II. Main Functions

  • Defined basic mathematical operation functions: add (addition), sub (subtraction), mul (multiplication), div (division, handling the case where the divisor is 0).
  • Handles instructions such as db, mov, etc.
  • operation function: Matches and performs corresponding operation operations according to specific instruction patterns.
  • check function: Used for checking specific conditions.
  • asm function: Can read the specified file, parse the instructions in it, and perform corresponding processing.

III. Usage Method

After importing the relevant modules, you can call the functions within for usage. IV. Dependent Libraries

  • re: Used for regular expression operations.
  • os: Used for file and directory-related operations.
  • keystone:用于编译
  • capstone:用于编译

V. Sample Code

import pythonasm.main
from pythonasm.asm import*

mov("ax", 1)
add("ax", 2)
inc("ax")
db(0x90)  # NOP
int_(0x80)
jmp(0x90)
display()
pythonasm.main.asm('pyasm.asm')
#pyasm.asm
msg db "abc"
mov ax,3
mov bx,0
mov cx,msg
mov dx,3
int 80h
mov ax,4
mov bx,1
mov dx,3
int 80h
#command_input
123
#command_out
mov ax,1            ;0x66B80100
add ax, 2           ;0x6683C002
inc ax              ;0x66FFC0
db 144              ;0x90
int 128             ;0xCD80
jmp 144             ;0xE98B000000
123

VI. Copyright Statement

This library is open source, but the author and source must be indicated. The final interpretation right belongs to Lin Honghan.

 下面是翻译:

Project description

pythonasm 库

一、概述 这是一个包含了一系列与数据处理和操作相关功能的 Python 库,能模拟汇编器的输入输出,转换机器码,作者为中国六年级小学生林泓翰pypi账号linhhanpy,gitee账号linhhpy,暑假无聊做的。 以后会更新更多功能,增加汇编虚拟机和使用真正的汇编指令。

二、主要功能(main)

  • 定义了基本的数学运算函数:add(加法)、sub(减法)、mul(乘法)、div(除法,处理除数为 0 的情况)。
  • 处理dbmov等指令。
  • operation 函数:根据特定的指令模式匹配并执行相应的运算操作。
  • check 函数:用于进行特定条件的检查。
  • asm 函数:能够读取指定文件,解析其中的指令并进行相应处理。
  • display函数:显示汇编和机器码

三、使用方法 导入相关模块后,即可调用其中的函数进行使用。

四、依赖库

  • re :用于正则表达式操作。
  • os :用于文件和目录相关操作。
  • keystone:用于编译
  • capstone:用于编译

五、示例代码

import pythonasm.main
from pythonasm.asm import*

mov("ax", 1)
add("ax", 2)
inc("ax")
db(0x90)  # NOP
int_(0x80)
jmp(0x90)
display()
pythonasm.main.asm('pyasm.asm')
#pyasm.asm
msg db "abc"
mov ax,3
mov bx,0
mov cx,msg
mov dx,3
int 80h
mov ax,4
mov bx,1
mov dx,3
int 80h
#command_input
123
#command_out
mov ax,1            ;0x66B80100
add ax, 2           ;0x6683C002
inc ax              ;0x66FFC0
db 144              ;0x90
int 128             ;0xCD80
jmp 144             ;0xE98B000000
123

六、版权声明 本库开源,但需标明作者和出处,最终解释权归林泓翰所有。

自学3个月,汇编都学会了!!!机器码还有点造诣

 具体请查看官方文档pypi的pythonasm官方文档

标签:int,variables,编程,mov,pythonasm,ax,自学,def,instructions
From: https://blog.csdn.net/linhhanpy/article/details/140748018

相关文章

  • Matlab编程资源库(10)离散傅立叶变换
    一、离散傅立叶变换算法简要给定一个N点的离散信号序列x(n),其中n表示时刻,n=0,1,2,...,N-1。定义离散傅立叶变换的频域序列X(k),其中k表示频率,k=0,1,2,...,N-1。通过以下公式计算每个频率对应的复数值: X(k)=Σx(n)*exp(-j*2π*kn/N),其中j表示虚......
  • Matlab编程资源库(11)多项式计算
    一、多项式的四则运算1.多项式的加减运算2.多项式乘法运算   函数conv(P1,P2)用于求多项式P1和P2的乘积。这里,P1、P2是两个多项式系数向量。3.多项式除法   函数[Q,r]=deconv(P1,P2)用于对多项式P1和P2作除法运算。其中Q返回多项式P1除以P2的商式,r返回P1除以......
  • Matlab编程资源库(9)数据插值与曲线拟合
    一、一维数据插值    在MATLAB中,实现这些插值的函数是interp1,其调用格式为:Y1=interp1(X,Y,X1,'method')    函数根据X,Y的值,计算函数在X1处的值。X,Y是两个等长的已知向量,分别描述采样点和样本值,X1是一个向量或标量,描述欲插值的点,Y1是一个与X1等长的插值结......
  • 编程语言之泛型困境
    困境泛型不可能三角泛型困境的本质是,关于泛型,你想要缓慢的程序员、缓慢的编译器和臃肿的二进制文件,还是缓慢的执行时间。简单来说就是:要么苦了程序员,要么苦了编绎器,要么降低运行时效率。不同语言对泛型的考量以C、C++和Java为例,它们在泛型的设计上有着不同考量:C语言:是系统......
  • Verilog编程学习之—呼吸灯
    Verilog编程-呼吸灯1.设计目标用FPGA产生占空比变化的PWM波,控制LED灯由暗变亮的变化。2.设计思路设置PWM波的步长为2us,周期为2ms,每个周期内LED亮的时间由0增加至999,再从999减少至0,依次循环,就可以看到LED灯由暗变亮再由亮变暗的循环过程。可以设置一个占空比寄存器duty_r和一个......
  • C++模板——泛型编程
    目录1.什么是泛型编程2.函数模板2.1定义格式2.2实例化及原理 2.3参数匹配原则3.类模板 3.1定义格式3.2实例化 4.非类型模板参数 5.模板的特化 5.1概念5.2函数模板和类模板特化6.模板的分离编译 1.什么是泛型编程 如何实现一个通用的加......
  • 暑假java自学进度总结03
    一.今日所学:1.标识符命名规则:必须:1>由数字,字母,下划线,美元符组成;2>不能以数字开头;3>不能是关键字;4>区分大小写;建议:1>命名方法,变量时用小驼峰命名法:*1.标识符是一个单词时,全部小写*2.标识符是多个单词组合时,第一个单词小写,其余单词首字母大写2>命名类名时用大驼峰命名法:......
  • 2024“钉耙编程”中国大学生算法设计超级联赛(3)复盘总结
    2024“钉耙编程”中国大学生算法设计超级联赛(3)本场我其实并没有给团队贡献是任何一个AC,连最简单的题都因为题目读错没有写出来。纯纯抱大佬大腿,然后赛后被嘲讽深度自同构-limie首先,先考虑对于一个有\(n\)个节点的树应该怎么做。设\(f_i\)表示\(i\)个节点的树中有多少个......
  • shell编程
    一、shell基础1.shell概念shell英文翻译过来是外壳的意思,作为计算机语言来理解可以认为它是操作系统的外壳。可以通过shell命令来操作和控制操作系统,比如Linux中的shell命令就包括ls、cd、pwd等等。shell在内核的基础上编写的一个应用程序,它连接了用户和Linux内核,......
  • FrameBuffer 应用编程-I.MX6U嵌入式Linux C应用编程学习笔记基于正点原子阿尔法开发板
    FrameBuffer应用编程什么是Framebuffer设备Framebuffer定义:Framebuffer是帧缓冲,指一块内存,用于保存一帧图像Linux系统中的Framebuffer:在Linux系统中,Framebuffer是一种显示驱动接口,抽象并屏蔽了不同显示设备的硬件细节,对应用层提供了一块显示内存(显存)Framebuf......