程序的自我修改

应用程序启动后修改自身EXE文件或自删除EXE文件 1.子进程等待父进程结束再处理事务(应用程序的自删除); 2.父进程将句柄等信息传递给子进程; 3.将EXE中加载的资源释放为本地文件。 见博客:http://blog.youkuaiyun.com/beanjoy/article/details/9228337 立即下载
本文目的在于向读者说明程序进行自我修改的基本方法,并希望可以起到抛砖引玉的作用。
如果读者有更好的方法或见解,欢迎来信交流E-mail: default_and_default@yahoo.cn

/*//////////////////////////////////////////////////////////////////////////////
This program will modify itself at the running time,
These  methods will be very useful in some situations,
Gook Luck!
//////////////////////////////////////////////////////////////////////////////*/
#include<stdio.h>
#include<windows.h>

void main()
{
  TCHAR Info001[MAX_PATH]="Welcome to Big Apple!";
  TCHAR Info002[MAX_PATH]="Welcome to Washington!";
  char temp=(char)0x90;
  WORD temp001=0x9090;
  DWORD temp002=0x90909090;

  PVOID BaseAddressOne=NULL;
  PVOID BaseAddressTwo=NULL;

  _asm
  {
    mov BaseAddressOne,offset LabelOne
    mov BaseAddressTwo,offset LabelTwo
  }

  MessageBox(NULL,Info001,"Information",MB_OK|MB_ICONINFORMATION);

//a kind of method to modify itself
  WriteProcessMemory(GetCurrentProcess(),BaseAddressTwo,&temp001,2,NULL);
  WriteProcessMemory(GetCurrentProcess(),BaseAddressOne,&temp001,2,NULL);


/*
//Another method to modify itself,this method needs to modify the code section's
//characteristics in PE file.

  _asm
  {
    mov ebx,BaseAddressOne
    mov ecx,BaseAddressTwo
    mov dx,temp001

    mov [ebx],dx
    mov [ecx],dx
  }
*/

LabelTwo:
  _asm
  {
    jmp LabelOne
  }
  _asm
  {
    nop
    nop
    nop
  }



  MessageBox(NULL,Info002,"Information",MB_OK|MB_ICONINFORMATION);
LabelOne:
  _asm
  {
    jmp Over
  }
  MessageBox(NULL,Info002,"Information",MB_OK|MB_ICONINFORMATION);
Over:
  return;
}



编译这个程序,我们发现WriteProcessMemory() 成功修改了程序自身代码,程序运行正常。
然后我们屏蔽程序中的WriteProcessMemory()调用,用/*  */之中的代码完成自我修改,
运行后会发现系统抛出异常 Access Violation.这是因为PE 中 代码节的属性默认为 0x60000020,
20 表示代码 20000000表示可执行,40000000表示可读,如果我们在此基础上加上 0x80000000(可写)
操作系统的loader在装载可执行文件时,便会将存放代码节数据的内存标记为可读,可写,可执行。
这样就不会有异常了。
读者可使用下面的程序来修改节属性:
/**************************************************************************************/
//The following code is used to modify characteristics of sections

#include<windows.h>
#include<stdio.h>
BOOL ModifyCharacteristicsOfSections (LPCTSTR FileName)
{
  DWORD i=0;
  HANDLE hDestinationFile=NULL;
  TCHAR  DestinationPEFile[MAX_PATH];
  DWORD NumberOfBytesRead=0;   //Number of bytes read
  DWORD NumberOfBytesWritten=0; //Number of bytes written

  DWORD ImageNtSignature=0;  //PE signature
  DWORD OffsetOfNewHeader=0;
  DWORD NumberOfSections=0;
  DWORD SizeOfSectionTable=0;           //size of section table
  
  HANDLE hGlobalAllocatedMemory=NULL;  //use GlobalAlloc();
  
  PIMAGE_SECTION_HEADER pImageSectionHeader=NULL; //a pointer to IMAGE_SECTION_TABLE

  IMAGE_DOS_HEADER ImageDosHeader;
  IMAGE_NT_HEADERS ImageNTHeaders;
  IMAGE_FILE_HEADER ImageFileHeader;
  
  IMAGE_OPTIONAL_HEADER ImageOptionalHeader;
  IMAGE_SECTION_HEADER ImageSectionHeader;
  DWORD dwFileSize=0;

  RtlZeroMemory(&ImageDosHeader,sizeof(IMAGE_DOS_HEADER));
  RtlZeroMemory(&ImageNTHeaders,sizeof(IMAGE_NT_HEADERS));
  RtlZeroMemory(&ImageFileHeader,sizeof(IMAGE_FILE_HEADER));
  
  RtlZeroMemory(&ImageOptionalHeader,sizeof(IMAGE_OPTIONAL_HEADER));
  RtlZeroMemory(&ImageSectionHeader,sizeof(IMAGE_SECTION_HEADER));
  
  strcpy(DestinationPEFile,FileName);

  hDestinationFile=CreateFile(DestinationPEFile,
    FILE_WRITE_DATA|FILE_READ_DATA,
    FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_ARCHIVE,NULL);
  
  if(hDestinationFile==INVALID_HANDLE_VALUE)
  {
//    printf("/nCreateFile() fails!Can't open file. Please try again!/n");
//    CloseHandle(hDestinationFile);
    return TRUE;
  }
  else
  {
    dwFileSize=GetFileSize(hDestinationFile,NULL);
  }

  SetFilePointer(hDestinationFile,0,NULL,FILE_BEGIN); //Revert the file pointer,this is very important.
  
  ReadFile(hDestinationFile,&ImageDosHeader,
    sizeof(IMAGE_DOS_HEADER),&NumberOfBytesRead,NULL);
  if(NumberOfBytesRead!=sizeof(IMAGE_DOS_HEADER))
  {
//    printf("/nReadFile() fails! Can't get IMAGE_DOS_HEADER./n");
    CloseHandle(hDestinationFile);
    return FALSE;
  }
  
  OffsetOfNewHeader=ImageDosHeader.e_lfanew; //File address of new exe header
  
  SetFilePointer(hDestinationFile,(LONG)OffsetOfNewHeader,NULL,FILE_BEGIN);
  
  ReadFile(hDestinationFile,&ImageNTHeaders,
    sizeof(IMAGE_NT_HEADERS),&NumberOfBytesRead,NULL); //Retrieve IMAGE_NT_HEADERS
  if(NumberOfBytesRead!=sizeof(IMAGE_NT_HEADERS))
  {
    CloseHandle(hDestinationFile);
    return FALSE;
  }

  if(ImageNTHeaders.Signature!=0x00004550)
  {
//    printf("Error./nPE signature is invalid!/n");
    CloseHandle(hDestinationFile);
    return FALSE;
  }
  
  
  SetFilePointer(hDestinationFile,OffsetOfNewHeader+4,NULL,FILE_BEGIN);  //Set the file pointer to point to IMAGE_FILE_HEADER
  ReadFile(hDestinationFile,&ImageFileHeader,
    sizeof(IMAGE_FILE_HEADER),&NumberOfBytesRead,NULL); //Retrieve IMAGE_FILE_HEADER
  if(NumberOfBytesRead!=sizeof(IMAGE_FILE_HEADER))
  {
//    printf("/nReadFile() fails! Can't get IMAGE_FILE_HEADER./n");
    CloseHandle(hDestinationFile);
    return FALSE;
  }


  if(ImageFileHeader.NumberOfSections<1)
  {
    CloseHandle(hDestinationFile);
    return FALSE;
  }
  
  if(dwFileSize<(sizeof(IMAGE_DOS_HEADER)+sizeof(IMAGE_NT_HEADERS)+sizeof(IMAGE_SECTION_HEADER)*ImageFileHeader.NumberOfSections))
  {
    CloseHandle(hDestinationFile);
    return FALSE;
  }



  ReadFile(hDestinationFile,&ImageOptionalHeader,
    sizeof(IMAGE_OPTIONAL_HEADER),&NumberOfBytesRead,NULL); //Retrieve IMAGE_OPTIONAL_HEADER

  if(NumberOfBytesRead!=sizeof(IMAGE_OPTIONAL_HEADER))
  {
//    printf("/nReadFile() fails! Can't get IMAGE_OPTIONAL_HEADER./n");
    CloseHandle(hDestinationFile);
    return FALSE;
  }
  if(ImageOptionalHeader.SectionAlignment<ImageOptionalHeader.FileAlignment)
  {
    CloseHandle(hDestinationFile);
    return FALSE;
  }


  NumberOfSections=ImageFileHeader.NumberOfSections; //Number of sections
  SizeOfSectionTable=sizeof(IMAGE_SECTION_HEADER)*NumberOfSections; //Get the size of Section Table
  
  hGlobalAllocatedMemory=GlobalAlloc(GPTR,SizeOfSectionTable);      //Allocate memory and initialize with zero
  if(hGlobalAllocatedMemory==NULL)
  {
//    printf("/nGlobalAlloc() failed! Please try again./n"); //if failed,return
    CloseHandle(hDestinationFile);
    return FALSE;
  }
  
  
    pImageSectionHeader=(PIMAGE_SECTION_HEADER)hGlobalAllocatedMemory; //Convert a handle to a pointer to IMAGE_SECTION_HEADER
  
  for(i=0;i<NumberOfSections;i++)  //Retrieve the Section Table
  {
    ReadFile(hDestinationFile,pImageSectionHeader+i,
      sizeof(IMAGE_SECTION_HEADER),&NumberOfBytesRead,NULL);
    if(NumberOfBytesRead!=sizeof(IMAGE_SECTION_HEADER))
    {
//      printf("Error.Can't get IMAGE_SECTION_HEADER./n");
      CloseHandle(hDestinationFile);
      return FALSE;
    }
  }

  for(i=0;i<NumberOfSections;i++)
  {
    DWORD dwTempCharacteristics=0;

    if((*(pImageSectionHeader+i)).PointerToRawData+(*(pImageSectionHeader+i)).SizeOfRawData>dwFileSize)
    {
      CloseHandle(hDestinationFile);
      return FALSE;
    }
    if((*(pImageSectionHeader+i)).PointerToRawData % ImageOptionalHeader.FileAlignment!=0)
    {
      CloseHandle(hDestinationFile);
      return FALSE;
    }
    printf("/nThe name of the section%d: ",i);
    printf("%s/n",(*(pImageSectionHeader+i)).Name);
    
    printf("Characteristics: %#x/n",(*(pImageSectionHeader+i)).Characteristics);
    printf("/nPlease input the new characteristics of the section./n");
    printf("If you enter 0,the characteristics of the section will not be modified./n");
    scanf("%x",&dwTempCharacteristics);

    if(dwTempCharacteristics!=0)
      (*(pImageSectionHeader+i)).Characteristics=dwTempCharacteristics;
      printf("------------------------------------------------------");
  }

  SetFilePointer(hDestinationFile,-((long)SizeOfSectionTable),NULL,FILE_CURRENT); //Set the file poiner

  WriteFile(hDestinationFile,pImageSectionHeader,SizeOfSectionTable,&NumberOfBytesWritten,NULL);
  if(NumberOfBytesWritten==SizeOfSectionTable)
  {
    printf("/nComplete successfully!/n");
  }
  else
  {
       printf("/nWriteFile() failed!/n");
  }
  GlobalFree(hGlobalAllocatedMemory); //Free memory

  CloseHandle(hDestinationFile);

  return TRUE;    
}

void main(int argc,char *argv[])
{
  if(argc!=2)
  {
    printf("Error/nUsage:ModifyCharacteristicsOfSections CompleteDestinationFileName/n");
    return;
  }
  if(!ModifyCharacteristicsOfSections(argv[1]))
  {
    printf("/nError.This usually means that this file is not a valid PE file or/n");
    printf("that this PE file has been modified by another program,for example,shell programm./n");
  }
}


/**********************************************************************************************/
以下是上面程序的输出信息:

The name of the section0: .text
Characteristics: 0x60000020

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
e0000020
------------------------------------------------------
The name of the section1: .rdata
Characteristics: 0x40000040

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
The name of the section2: .data
Characteristics: 0xc0000040

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
The name of the section3: .idata
Characteristics: 0xc0000040

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
The name of the section4: .reloc
Characteristics: 0x42000040

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
Complete successfully!

////////////////////////////////////////////////////////////////////////////

The name of the section0: .text
Characteristics: 0xe0000020

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
The name of the section1: .rdata
Characteristics: 0x40000040

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
The name of the section2: .data
Characteristics: 0xc0000040

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
The name of the section3: .idata
Characteristics: 0xc0000040

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
The name of the section4: .reloc
Characteristics: 0x42000040

Please input the new characteristics of the section.
If you enter 0,the characteristics of the section will not be modified.
0
------------------------------------------------------
Complete successfully!
嵌入式开发面试题全解析:指针、内存、数据类型关键问题总结 本文对嵌入式开发典型面试题进行深度解析,涵盖多方面关键知识。题目 19 揭示字符指针修改字符串常量的错误操作;题目 20 展现strcpy引发的缓冲区溢出风险;题目 21 体现未初始化数组与strlen结合的不可预测性;题目 22 通过位域与对齐规则计算结构体大小;题目 23 因unsigned char溢出导致循环异常。这些题目全面覆盖指针操作、内存管理、数据类型特性等核心内容,精准指出开发中易疏忽的陷阱,有助于理解编程规范,规避风险,提升代码质量与稳定性,是深入掌握嵌入式开发要点的实用指南。 阅读详情

相关推荐

2025小红书跳转卡片实战指南:从零搭建独立后台与自动化发卡系统

本文提供了一份2025年小红书跳转卡片的实战搭建指南,详细解析了独立后台系统的核心架构与自动化发卡流程。文章从零开始,手把手教你使用Node.js、Vue.js等技术栈构建包含后台管理、用户制卡中心与前端交互的完整系统,旨在帮助运营者实现合规引流,并掌握数据自主权与自动化运营能力。

weixin_29234423的博客 518

程序自修改(SMC)

理论:所谓SMC(Self Modifying Code)技术,就是一种将可执行文件中的代码或数据进行加密,防止别人使用逆向工程工具对程序进行静态分析的方法,只有程序运行时才对代码和数据进行解 密,从而正常运行程序和访问数据。本篇通过一个简单的实例来介绍这个技术。需要的运行环境vc6,程序编译为release版。由于本篇我们要在程序执行过程中,修改代码段中的一个函数内容,而默认情况下,我们编译生成

jia_xiaoxin的专栏 3647

MODIS 遥感数据批量下载(使用Cygwin)

MODIS 遥感数据批量下载(使用Cygwin)包含Cygwin的下载教程

weixin_45913084的博客 917

自修改代码浅析

相信大家都在程序调试或者分析中碰到过自修改代码的情况吧。所谓自修改代码,就是程序自我保护的一种机制。它使我们的反汇编调试器看起来相当地无助。因为我们看到的所谓的反汇编代码并非执行过程中的代码,它表面上看起来不合逻辑甚至一塌糊涂,但是运行起来却井井有条。因此,这项技术被广泛用在那些反破解的商业软件中,在试图bypass杀毒软件的黑客软件中也颇有涉及。在另一方面,cracker

憩园幽幽的专栏 3399

VSCode 1.85便携版安装与配置:解决远程服务器glibc版本过低报错的保姆级指南

本文详细介绍了如何通过VSCode 1.85便携版解决远程服务器glibc版本过低导致的兼容性问题。通过环境隔离和版本固化的方法,开发者可以在老旧服务器上稳定运行Remote-SSH插件,同时保留主力VSCode的配置。文章提供了从下载安装到深度配置的完整指南,帮助用户快速搭建稳定的开发环境。

weixin_30279315的博客 578

5G Multicast/Broadcast Services(MBS) (七) MBS广播DRX

当处于RRC_IDLE或RRC_INACTIVE或RRC_CONNECTED 状态时,如果为 G-RNTI 配置了broadcast DRX,则允许MAC entity使用broadcast DRX 操作不连续地监听此G-RNTI的PDCCH;此 G-RNTI 的 drx-onDurationTimerPTM 或 drx-InactivityTimerPTM 正在运行的时间,也就是。long DRX周期drx-LongCycle-PTM和drx-StartOffset-PTM定义DRX周期开始的子帧。

asd199086的博客 392

【计算机系统结构】Self-modifying code 自修改代码

Self-modifying code 在计算机科学中,自修改代码是一种代码,当代码执行时修改它自身的指令,通常用于减少指令路径长度以提高性能或简单地减少额外的,重复的,相似的代码,以此来简化维护。自修改是“标志设置”和程序的条件分支方法的代替方法,主要用于减少需要被测试的条件(分支条件)的次数。它通常只用于有意进行自修改的代码,而不适用于由于一个错误如缓冲区溢出而导致的意外修改其自身代码的情况。...

七爷OK 5959

别再只当调包侠了!YOLO检测头到损失函数全链路拆解,看完才算真懂

YOLO的精妙不在于某个单一创新,而在于各模块围绕“实时精准检测”这一目标的协同设计。Backbone追求高效特征压缩,Neck保障多尺度信息流通,Head解耦任务冲突,Loss动态引导优化方向。只有理解这套内在逻辑,才能跳出“调包-试错”的低效循环,在面对新场景、新问题时做出有理有据的改进决策。技术深度决定职业天花板。下次再调YOLO时,不妨先问自己:我改的这个参数,到底影响了系统中的哪一环?参考资料。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 186

自我修改(SelfModify): 探索代码自我更新的艺术

自我修改(SelfModify): 探索代码自我更新的艺术 项目简介 SelfModify 是一个创新的开源项目,由开发者 Leon Newton 创建,旨在实现程序的自我更新和维护。这个库允许你构建具备自动更新能力的应用程序,确保你的软件始终处于最新状态,无需用户手动干预。 技术分析 SelfModify的核心原理是利用动态加载和运行时代码替换的技术。在运行过程中,它能够检测到服务器上的新版本...

gitblog_00084的博客 829

无人机——电机篇(一)

1. 电机的定义 电机俗称“马达”,是无人机的动力来源,无人机通过改变电机的转速来改变无人机的飞行状态。即改变每个电机的速度,使得无人机能够盘旋空中,上升或下降,或向各个方向移动。2. 电机的分类 电机分为:“无刷电机”和“有刷电机” - 无刷电机:是采用半导体开关器件来实现电子换向,具有可靠性高、低干扰、低噪声低、寿命长等优点。一般应用在稍大型的飞行器,载重大,可以有更广泛的用途。 - 有刷电机:是内含电刷装置的将电能转换成机械能(电动机)或将机械能转换成电能(发电机)的旋转电机。有刷电机是所有电机的基

weixin_46066938的博客 1万+

深入剖析 Wenet 下 AISHELL-1 的 run.sh 脚本:从数据准备到模型训练

run.sh脚本用于处理 AISHELL-1 数据集的整个训练和测试流程。我们将逐步分析脚本中的每个部分,包括环境变量、参数设置、各个阶段的执行等。stage: 设置脚本的起始阶段(如数据准备)。stop_stage: 设置脚本的结束阶段。通过对 Wenet 下 AISHELL-1 的run.sh脚本的详细剖析,我们希望你能更好地理解每个步骤的功能及其背后的原理。此脚本不仅为模型训练提供了便利,也为用户自定义和扩展训练流程提供了基础。希望本教程能帮助你顺利完成语音识别项目!

帅小柏的博客 1634

CTF逆向学习之SMC自修改

SMC是指:一种将可执行文件中的代码或数据进行加密,防止别人使用逆向工程工具对程序进行静态分析的方法,只有程序运行时才对代码和数据进行解 密,从而正常运行程序和访问数据。是一种程序在运行时修改自身代码的技术。然而,SMC 也带来了复杂性和潜在的安全风险,因此需要谨慎使用。SMC 的核心思想是程序在运行时修改自身的指令。

2302_79797828的博客 2714

Ubuntu零基础教学-史上最详Ubuntu20.04安装教程,超级详细,强烈建议收藏!

官网地址:https://www.vmware.com/ 1、VMware Workstation Pro 15.5.1在Windows 10的安装不再介绍了,一路下一步即可。 2、下面详细介绍在VMware 虚拟机里安装Ubuntu 20.04 LTS的步骤

**My Coding Family** 2万+

程序的自我修改收藏

本文目的在于向读者说明程序进行自我修改的基本方法,并希望可以起到抛砖引玉的作用。如果读者有更好的方法或见解,欢迎来信交流E-mail: default_and_default@yahoo.cn/*//////////////////////////////////////////////////////////////////////////////This pro

大浪淘沙的专栏 941

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

程序员自我修改之读书学习

程序员的读书历程:x 语言入门 —> x 语言应用实践 —> x 语言高阶编程 —> x 语言的科学与艺术 —> 编程之美 —> 编程之道 —> 编程之禅

寒风的技术博客 2208

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

实现可自我修改的Go程序 | Gopher Daily (2022.01.31) ʕ◔ϖ◔ʔ

每日一谚:When Go eschewed the popular exception model of errors, it made a statement that error ha...

TonyBai 200

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

从自修改代码到递归自举:程序如何实现“自我认知”?

在计算机科学中,自指与递归是理解程序如何操作自身的关键概念。冯·诺依曼架构将代码与数据等同存储于内存,为程序自修改提供了物理基础。这种能力在底层编程中可实现代码的动态改写,例如通过汇编指令直接覆盖内存中的指令流,从而让程序具备影响自身与他者执行状态的能力。自修改代码虽在特定场景(如代码生成、软件保护)中有其技术价值,但在现代工程实践中往往因可调试性、安全性及性能优化等问题而被视为禁忌。递归则提供了更结构化的自指方式,函数通过调用自身来分解问题,体现了计算过程中的自我映射。更进一步,编译器的自举过程展示了系统

weixin_31528001的博客 288

程序的自我改写

曾经,程序的自动改写是每个黑客必备的知识,因为这样可以有效的节约内存,下面是在现代的GNU/Linux 操作系统上实现的程序自我改写。列一下环境:speller@SHELL-LAB:~/code/c$ egrep "model name" /proc/cpuinfo | uniq -c      2 model name      : Pentium(R) Dual-Core  CPU     

海阔天空的专栏 478

linux修改代码段,自修改代码总是在Linux上出现分段错误

我找到了一篇有关自我修改代码的文章,并尝试做一些示例,但是我总是遇到分段错误。据我所了解,fas违反了内存权限。代码段是(r)ead /e(x)ecute,因此尝试将结果写入此错误。是否可以通过在运行时或之前更改内存许可来测试程序?我使用的是linux,示例是用GAS汇编编写的。.extern memcpy.section .datastring:.asciz "whatever"string_...

weixin_29189987的博客 406

一种实现人工智能程序自进化的概念原理

一种实现人工智能程序自进化的概念原理

qq_44995144的博客 139

Python自修改程序

Python自修改程序 属实无聊之举 修改内容:第一行注释的数字,每次运行+1并输出 参数修改:name.py num直接修改数字 例如:cmd运行1.py 55 代码: # 1 import os import sys n = '' if len(sys.argv) == 2: n = sys.argv[1] with open(sys.argv[0],'r',encoding = 'utf-8') as fp: s = fp.readlines() a = s[0][2:-1]

浪速之星的博客 762

程序的自动改写

<br />曾经,程序的自动改写是每个黑客必备的知识,因为这样可以有效的节约内存,下面是在现代的GNU/Linux 操作系统上实现的程序自我改写。<br />列一下环境:<br />speller@SHELL-LAB:~/code/c$ egrep "model name" /proc/cpuinfo | uniq -c<br />      2 model name      : Pentium(R) Dual-Core  CPU      E6300  @ 2.80GHz<br />speller@SH

软件安全 678
上一篇: 一段感染引入表的vc代码
下一篇: 磁碟机病毒(VcingT)越来越变态——最新分析报告发布
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值