<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Computer, Electron and Technology &#187; windows</title>
	<atom:link href="http://www.donevii.com/post/tag/windows/feed" rel="self" type="application/rss+xml" />
	<link>http://www.donevii.com</link>
	<description>DoneVII CET &#38; CPPLITE</description>
	<lastBuildDate>Wed, 02 Jun 2010 10:45:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>snow leopard 下通过 py 脚本下载 google music</title>
		<link>http://www.donevii.com/post/922.html</link>
		<comments>http://www.donevii.com/post/922.html#comments</comments>
		<pubDate>Thu, 17 Sep 2009 02:49:26 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.donevii.com/?p=922</guid>
		<description><![CDATA[最近在国内没办法再用 spotify 听歌了，迫于无奈只好转向 google music 。 因为 firefox 尴尬的内存占用，并且考虑把歌同步到 iPhone 上来听，开始着手找下载 google music 的小工具，发现骨头做的 gmbox ... ]]></description>
			<content:encoded><![CDATA[<p>最近在国内没办法再用 spotify 听歌了，迫于无奈只好转向 google music 。</p>
<p>因为 firefox 尴尬的内存占用，并且考虑把歌同步到 iPhone 上来听，开始着手找下载 google music 的小工具，发现骨头做的 <a href="http://li2z.cn/2009/09/13/gmbox-0-2/">gmbox</a> 不错，可惜现在是只支持 windows 和 linux ，只好用 <a href="http://forum.ubuntu.com.cn/viewtopic.php?f=73&#038;p=1205852">gmusic.py</a> 这个脚本。</p>
<p>运行 gmusic.py 首先要安装 python3 环境，去 python 官方网站载下 python3.1 然后 configure &#8211;enable-shared &#038;&#038; make &#038;&#038; sudo make install &#038;&#038; ln -s /usr/local/bin/python3 /usr/bin/python3 既可</p>
<p>用 gmusic.py 下载速度在我的 istat 里显示大概是 800K 左右，非常不错。</p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/75.html" title="挣脱Windows的枷锁：Linux屏幕录像 (2006-10-10)">挣脱Windows的枷锁：Linux屏幕录像</a> (0)</li>
	<li><a href="http://www.donevii.com/post/78.html" title="[转]C/C++/Perl/汇编/Java效率比较 (2006-10-11)">[转]C/C++/Perl/汇编/Java效率比较</a> (0)</li>
	<li><a href="http://www.donevii.com/post/330.html" title="[超长篇] Inject Your Code to a Portable Executable File (2007-05-24)">[超长篇] Inject Your Code to a Portable Executable File</a> (0)</li>
	<li><a href="http://www.donevii.com/post/204.html" title="PHP &#038; memcached (2006-11-15)">PHP &#038; memcached</a> (0)</li>
	<li><a href="http://www.donevii.com/post/124.html" title="C++资源之不完全导引 (2006-10-26)">C++资源之不完全导引</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/922.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Intel® I/O Acceleration Technology (Intel® I/OAT)</title>
		<link>http://www.donevii.com/post/689.html</link>
		<comments>http://www.donevii.com/post/689.html#comments</comments>
		<pubDate>Tue, 16 Dec 2008 06:09:58 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/689.html</guid>
		<description><![CDATA[Intel® I/O Acceleration Technology (Intel® I/OAT), with Intel® QuickData Technology, moves data more efficiently through Intel® Xeon® processor-based servers for fast, scalable, and reliable network performance. Performance A primary benefit of Inte... ]]></description>
			<content:encoded><![CDATA[<p class="intro">Intel® I/O Acceleration Technology (Intel® I/OAT),<br />
with Intel® QuickData Technology, moves data more efficiently through<br />
Intel® Xeon® processor-based servers for fast, scalable, and reliable<br />
network performance.</p>
<p>		<!-- /product-overview-intro --></p>
<h2>Performance</h2>
<p>A<br />
primary benefit of Intel I/OAT is its ability to significantly reduce<br />
CPU overhead, freeing resources for more critical tasks. Intel I/OAT<br />
uses the <a href="http://www.donevii.com/post/tag/server" class="st_tag internal_tag" rel="tag" title="Posts tagged with server">server</a>&#8217;s processors more efficiently by leveraging<br />
architectural improvements within the CPU, chipset, network controller,<br />
and firmware to minimize performance-limiting bottlenecks. Intel I/OAT<br />
accelerates TCP/IP processing, delivers data-movement efficiencies<br />
across the entire <a href="http://www.donevii.com/post/tag/server" class="st_tag internal_tag" rel="tag" title="Posts tagged with server">server</a> platform, and minimizes system overhead.</p>
<h2>Scalability</h2>
<p>Intel<br />
I/OAT provides network acceleration that scales seamlessly across<br />
multiple Gigabit Ethernet (GbE) ports. It cost-effectively scales up to<br />
eight GbE ports and up to 10GbE, with power and thermal characteristics<br />
similar to those of a standard gigabit network adapter. TCP Offload<br />
Engine (TOE) solutions, in contrast, require a separate TOE card for<br />
each port, resulting in significant cost and thermal challenges for<br />
<a href="http://www.donevii.com/post/tag/server" class="st_tag internal_tag" rel="tag" title="Posts tagged with server">server</a> platforms.</p>
<h2>Reliability</h2>
<p>Intel I/OAT<br />
is a safe and flexible choice because it is tightly integrated into<br />
popular operating systems such as Microsoft Windows <a href="http://www.donevii.com/post/tag/server" class="st_tag internal_tag" rel="tag" title="Posts tagged with server">Server</a>* 2003 and<br />
Linux*, avoiding support risks associated with relying on third-party<br />
hardware vendors for network stack updates. Intel I/OAT also preserves<br />
critical network configurations such as teaming and failover, by<br />
maintaining control of the network stack processing within the<br />
CPU-where it belongs. This results in reduced support risks for IT<br />
departments.</p>
<p></p>
<p>via <a target="_blank" href="http://www.intel.com/technology/ioacceleration/">Intel</a></p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/78.html" title="[转]C/C++/Perl/汇编/Java效率比较 (2006-10-11)">[转]C/C++/Perl/汇编/Java效率比较</a> (0)</li>
	<li><a href="http://www.donevii.com/post/330.html" title="[超长篇] Inject Your Code to a Portable Executable File (2007-05-24)">[超长篇] Inject Your Code to a Portable Executable File</a> (0)</li>
	<li><a href="http://www.donevii.com/post/154.html" title="Linux 常用快捷键 (2006-10-31)">Linux 常用快捷键</a> (0)</li>
	<li><a href="http://www.donevii.com/post/75.html" title="挣脱Windows的枷锁：Linux屏幕录像 (2006-10-10)">挣脱Windows的枷锁：Linux屏幕录像</a> (0)</li>
	<li><a href="http://www.donevii.com/post/128.html" title="应用加速 (2006-10-26)">应用加速</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/689.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>评论:Web2.0用户之殇[转自cnbeta]</title>
		<link>http://www.donevii.com/post/586.html</link>
		<comments>http://www.donevii.com/post/586.html#comments</comments>
		<pubDate>Tue, 21 Oct 2008 09:45:46 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[生活]]></category>
		<category><![CDATA[类]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/586.html</guid>
		<description><![CDATA[一直认为现在 SNS 这类的东西不是太少，而是太多了，滥竽充数了。 以下内容转载。 越来越多的人拥有了越快来越多的Web2.0应用的帐户，一旦染上却如同瘟疫一样甩也甩不掉&#8230;经济下滑，很... ]]></description>
			<content:encoded><![CDATA[<p>一直认为现在 SNS 这类的东西不是太少，而是太多了，滥竽充数了。</p>
<p>以下内容转载。<br /><span class="Apple-style-span" style="border-collapse: separate; color: rgb(0, 0, 0); font-family: Verdana; font-size: 14px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: 21px; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px;">
<p style="margin: 0px 0px 1em; padding: 0px;">越来越多的人拥有了越快来越多的Web2.0应用的帐户，一旦染上却如同瘟疫一样甩也甩不掉&#8230;经济下滑，很多Web2.0网站开始吃紧，马云的寒冬论多多少少是正确的。经济吃紧，捂紧口袋成了不少人的最佳选择。但是我的ID数却没有随着经济的萧条而萧条。</p>
<p style="margin: 0px 0px 1em; padding: 0px;">从周五开始，我收到的邀请开始算，豆瓣&#8211;邀请我注册，Blogbus&#8212;我因为想换<a href="http://www.donevii.com/post/tag/blog" class="st_tag internal_tag" rel="tag" title="Posts tagged with blog">blog</a>，巴巴变&#8212;因为<a href="http://www.donevii.com/post/tag/blog" class="st_tag internal_tag" rel="tag" title="Posts tagged with blog">blog</a>我要放图片，开心网&#8212;好多人发邀请注册，Facebook上有人加我为好友，Hi5上有人想加我为好友，Hi5的一个插件应用跟我说有人想找我游戏，WAYN.com上有人给我发了信息。如果把时间扩大几周，Netlog的网友新鲜事，数次的开心网邀请，CaraO City的新功能，TripIt的AD，乃至TripAdvisor CEO拉选票&#8230;<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />不知道大家是不是一样，生活围绕这ID开始旋转，接受邀请，注册，交友，然后维持&#8230;.复杂的生活。豆瓣，Blogbus，歪酷博客，开心网，校内网，Myspace，Facebook，Hi5，WAYN.com，Netlog，巴巴变，Flickr，CaraO City，TripIt，TripAdvisor，Windows Live Spaces，QQ，QQ zone，Windows Live Messenger，大家多多少少都沾上过边。还有千千万万小心被拉入的小众型应用。越来越多的人拥有了越快来越多的Web2.0应用的帐户，一旦染上却如同瘟疫一样甩也甩不掉&#8230;<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />现在什么都是出于大战状态，大家机器上，同一类型的软件有好几种。浏览器大战，导致IE， Firefox， Opera，Chrome占据了机器，不过还好，他们只是使用习惯上的问题，没有太多粘性，所以要换还是很快的，也不影响。稍后来了邮箱大战，Gmail，Windows Live Hotmail，126，163&#8230;等等。，幸好逐渐开始废弃，逐渐统一到一起了（粘性虽然高，但在中国其实并不是最主要的联系手段），然后就又来了 IM软件大战，我用过Gtalk，Skype，QQ+TM，MSN（WLM），飞信，除了Gtalk（它靠着Gmail还可以随时实用）后四样依然健在而且还不能正式放弃，粘性太高了，Skype，老板，打电话要用，公司里也用它，QQ+TM不用说了，同学，朋友都在用，MSN，同学，同事，朋友也在用，它和QQ之间的人还有交叉&#8230;.表问我为什么&#8230;IM定位不清晰，飞信，忒重要了，免费发短信呢。好了，四款粘性极高的东西想狗皮膏药，号码也不互通，粘住了也下不来，如果说互联网满足了人们沟通的愿望，那IM就多少就是桥梁，当然不能过河拆桥啦。<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />现在正式出现了SNS大战，准确的活很早就有了，只是中国爆发的晚了那么一会。Facebook，同事，同学，朋友都在上面，人家邀请你注册，不能不给面子吧。校内网，同学，同事都在上面，人家也邀请你，也不能不去吧，开心网，人家都说开心网职场人士比较多，校内是给学生玩的，豆瓣大多都是90后，你总得跟同事、同学保持下吧，给我注册！！好了，然后Web2.0的一些特殊应用，比如WAYN.com、TripAdvisor的旅游，Hi5的交友，Myspace中国推广一般，多多少少让人头疼。SNS，Social Networking Services，既然是social的，你就得赴约吧&#8230;..生活就是这样复杂化了，同学和同事混在了一起，认识的和陌生的混在了一起，你说&#8230;<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />不能删，因为无数的同学，无数的同事，可能唯一遍布在这个SNS上那个SNS上&#8230;然后自己保存的ID越来越多，就跟<a href="http://www.donevii.com/post/tag/blog" class="st_tag internal_tag" rel="tag" title="Posts tagged with blog">Blog</a>一样，想要人留言，你得放在认识你的人知道的地方&#8230;..所以千万别乱换。<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />问题出在哪，大家都知道，但是都被迫忍受着。这样说吧，打个比方，我用电信上互联网，你用联通上网，我们虽然有时互相交流网速不快，但起码是能沟通的，不在乎对方是不是与自己一样用电信的网络还是用联通的网络&#8230;我们都能上网，都能互相聊天。但是SNS不是，聊天软件不是，粘性就是占茅坑，占资源，怎能共享，起码在中国是这样，最大的QQ不开放，WLM与Yahoo Messenger互连有什么用，Gtalk开放协议有什么用，没人用&#8230;.<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />SNS彻底是死的，顶多开放API让别人能在上面做应用，做插件，可是Facebook要是能和Myspace沟通，美国的SNS版图就要打乱了，中国也是，大家都在拼命的互抢用户，用户不得不同时存在多个账号，多次登陆，不可以通过一个SNS去跟另一个SNS上的好友沟通&#8230;但SNS们都有些用户，但没有一超的SNS，好处都不多，但都有好处&#8230;用户的粘性很大程度上是被迫，是不得不这样。用户也只想要一个SNS，SNS的目的是让支离破碎的关系网重新联系在一起，现在不仅关系网连在了一起，恐怕连 SNS们都靠用户连在了一起&#8230;..操作系统是为了屏蔽硬件不同更充分的利用硬件提供更友好的环境而产生，中间件是为了屏蔽操作系统及其他系统组件的不同而产生，促进应用软件之间的沟通的软件&#8230;.那多个的SNS之上呢&#8230;<br style="margin: 0px; padding: 0px;" /><br style="margin: 0px; padding: 0px;" />善哉善哉，真的希望产生SNS之上一层，屏蔽SNS之间的差异，提供给大家一个uni-interface..好让大家利用SNS真正的沟通而不是SNS们利用用户做到它们之间的沟通&#8230;.</p>
<p></span></p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/110.html" title="翻译：On having layout (2006-10-24)">翻译：On having layout</a> (0)</li>
	<li><a href="http://www.donevii.com/post/283.html" title="免费软件套装 (2007-01-08)">免费软件套装</a> (0)</li>
	<li><a href="http://www.donevii.com/post/118.html" title="Web2.0遭遇生死劫？ (2006-10-25)">Web2.0遭遇生死劫？</a> (0)</li>
	<li><a href="http://www.donevii.com/post/135.html" title=".NET资源站点汇总 (2006-10-27)">.NET资源站点汇总</a> (0)</li>
	<li><a href="http://www.donevii.com/post/61.html" title="有漏洞的Web 2.0 (2006-09-01)">有漏洞的Web 2.0</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/586.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DexposE2</title>
		<link>http://www.donevii.com/post/533.html</link>
		<comments>http://www.donevii.com/post/533.html#comments</comments>
		<pubDate>Wed, 01 Oct 2008 08:20:12 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/533.html</guid>
		<description><![CDATA[看到 mac 上的功能后，在网上搜的，windows 下模拟 DexposE2 的小软件，非常棒，资源占少用，可定制性还强。 我的电脑已经 almost mac-like 了。 :) 相关文章 這十八招Web2.0創業者千萬不要學 (0) 评论:W... ]]></description>
			<content:encoded><![CDATA[<p>看到 mac 上的功能后，在网上搜的，windows 下模拟 DexposE2 的小软件，非常棒，资源占少用，可定制性还强。</p>
<p>我的电脑已经 almost mac-like 了。 :)</p>
<p><a href="http://www.flickr.com/photos/28791486@N03/2722470909"><img src="http://farm4.static.flickr.com/3149/2722470909_43ae2e491f.jpg" /></a></p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/112.html" title="這十八招Web2.0創業者千萬不要學 (2006-10-24)">這十八招Web2.0創業者千萬不要學</a> (0)</li>
	<li><a href="http://www.donevii.com/post/586.html" title="评论:Web2.0用户之殇[转自cnbeta] (2008-10-21)">评论:Web2.0用户之殇[转自cnbeta]</a> (0)</li>
	<li><a href="http://www.donevii.com/post/229.html" title="设计模式之Life time controller模式 (2006-11-27)">设计模式之Life time controller模式</a> (0)</li>
	<li><a href="http://www.donevii.com/post/444.html" title="解决 loadrunner 8.1 拒绝服务问题 (2008-06-18)">解决 loadrunner 8.1 拒绝服务问题</a> (0)</li>
	<li><a href="http://www.donevii.com/post/110.html" title="翻译：On having layout (2006-10-24)">翻译：On having layout</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/533.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ScribeFire 试用</title>
		<link>http://www.donevii.com/post/524.html</link>
		<comments>http://www.donevii.com/post/524.html#comments</comments>
		<pubDate>Tue, 30 Sep 2008 16:22:35 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/524.html</guid>
		<description><![CDATA[这是在 ScribeFire 下的第一篇 BLOG，还是比较 easy 的，并且因为是集成在 FF 里，所以“感觉”比 Windows Live Writer 快不少。 自动检测使用的 BLOG 这个功能不错，不过不知道能不能同时 publish 到多个... ]]></description>
			<content:encoded><![CDATA[<p>这是在 ScribeFire 下的第一篇 <a href="http://www.donevii.com/post/tag/blog" class="st_tag internal_tag" rel="tag" title="Posts tagged with blog">BLOG</a>，还是比较 easy 的，并且因为是集成在 FF 里，所以“感觉”比 Windows Live Writer 快不少。</p>
<p>自动检测使用的 <a href="http://www.donevii.com/post/tag/blog" class="st_tag internal_tag" rel="tag" title="Posts tagged with blog">BLOG</a> 这个功能不错，不过不知道能不能同时 publish 到多个地方。</p>
<p>特别是左侧的 Ad, Promote 等这些功能，很有爱~！<br /><a href="http://www.flickr.com/photos/20881331@N00/2440640737"><img src="http://farm3.static.flickr.com/2376/2440640737_20c15c6268.jpg" /></a></p>
<p>ScribeFire 使用界面</p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/112.html" title="這十八招Web2.0創業者千萬不要學 (2006-10-24)">這十八招Web2.0創業者千萬不要學</a> (0)</li>
	<li><a href="http://www.donevii.com/post/586.html" title="评论:Web2.0用户之殇[转自cnbeta] (2008-10-21)">评论:Web2.0用户之殇[转自cnbeta]</a> (0)</li>
	<li><a href="http://www.donevii.com/post/110.html" title="翻译：On having layout (2006-10-24)">翻译：On having layout</a> (0)</li>
	<li><a href="http://www.donevii.com/post/272.html" title="深入Native应用程序 (2007-01-03)">深入Native应用程序</a> (0)</li>
	<li><a href="http://www.donevii.com/post/55.html" title="提供本站 ejeliot 风格模板下载 (2006-08-29)">提供本站 ejeliot 风格模板下载</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/524.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>解决 loadrunner 8.1 拒绝服务问题</title>
		<link>http://www.donevii.com/post/444.html</link>
		<comments>http://www.donevii.com/post/444.html#comments</comments>
		<pubDate>Wed, 18 Jun 2008 07:12:33 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[测试]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/444.html</guid>
		<description><![CDATA[因为要给朋友的一个XP上的项目做测试，要用 LR 跑一下，但是发现在设置 windows 资源监视时，对话框一直显示&#8220;拒绝访问&#8221;，所以上网搜了一下解决办法。 １、安全策略要调整； ２、服... ]]></description>
			<content:encoded><![CDATA[<p>因为要给朋友的一个XP上的项目做测试，要用 LR 跑一下，但是发现在设置 windows 资源监视时，对话框一直显示&#8220;拒绝访问&#8221;，所以上网搜了一下解决办法。</p>
<p>１、安全策略要调整；   <br />２、服务要开启；    </p>
<p>３、只留一个管理员账号，其它的账号在计算机管理里统统禁用；    <br />４、要用 net use 连接 ipc$；</p>
<p>以下为引用网上的详细内容：</p>
<p>安全策略在作怪（管理工具 -&gt; 本地安全策略 -&gt; 安全选项 -&gt; &quot;网络访问：本地帐户的共享和安全模式&quot;）。默认情况下，XP的访问方式是&quot;仅来宾&quot;的方式，那么你访问它，当然就固定为Guest来访问，而guest 账户没有监控的权限，所以要把访问方式改为&#8220;经典&#8221;模式，这样就可以以administrator的身份登陆了。   <br />备注：Remote Registry&#160;&#160;&#160; 这个服务要启动</p>
<p><strong>相关问题：<a href="http://www.51testing.com/"><u><strong>监视windows系统</strong></u></a>注意事项</strong></p>
<p>1 监视连接前的准备工作   <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; 首先保证被监视的windows系统开启以下二个服务Remote Procedure Call(RPC) 和Remote Registry Service (这里具体在那里开起服务就不说了)。    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; 被监视的WINDOWS机器:右击我的电脑,选择管理-&gt;共享文件夹-&gt;共享 在这里面要有C$这个共享文件夹,(要是没有自己手动加)。    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; 然后保证在安装LR的机器上使用运行.输入\\被监视机器IP\C$ 然后输入管理员帐号和密码,如果能看到被监视机器的C盘了,就说明你得到了那台机器的管理员权限,可以使用LR去连接了。    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; 说明: LR要连接WINDOWS机器进行监视貌似要有管理员帐号和密码才行。    <br />2 用LR监视windows的步骤    <br />(这里就不详细说明了,只要在窗口中右击鼠标选择Add Measurements就可以了)</p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/110.html" title="翻译：On having layout (2006-10-24)">翻译：On having layout</a> (0)</li>
	<li><a href="http://www.donevii.com/post/181.html" title="新方法爆出!!跟cnBeta一起来注册&#8217;@live.com&#8217;! (2006-11-10)">新方法爆出!!跟cnBeta一起来注册&#8217;@live.com&#8217;!</a> (0)</li>
	<li><a href="http://www.donevii.com/post/82.html" title="如何写一份好的工程师简历 (2006-10-16)">如何写一份好的工程师简历</a> (0)</li>
	<li><a href="http://www.donevii.com/post/221.html" title="什么是bootloader程序及其功能和特点 (2006-11-22)">什么是bootloader程序及其功能和特点</a> (0)</li>
	<li><a href="http://www.donevii.com/post/387.html" title="[转]嵌入式系统 Boot Loader 技术内幕 (2008-01-14)">[转]嵌入式系统 Boot Loader 技术内幕</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/444.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>回沈阳最想吃的几样东西</title>
		<link>http://www.donevii.com/post/441.html</link>
		<comments>http://www.donevii.com/post/441.html#comments</comments>
		<pubDate>Sun, 25 May 2008 11:46:32 +0000</pubDate>
		<dc:creator>gavinkwoe</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/441.html</guid>
		<description><![CDATA[Faint，发了四遍才搞定！Windows Live Writer真TM操蛋。 极品五笔与LiveWriter有冲突！千万别在插入图片之后打开软键盘，直接死掉。 平时工作也想不起来去吃，先看看图片流口水吧~ 第一道，老妈最... ]]></description>
			<content:encoded><![CDATA[<p>Faint，发了四遍才搞定！Windows Live Writer真TM操蛋。   <br />极品五笔与LiveWriter有冲突！千万别在插入图片之后打开软键盘，直接死掉。</p>
<blockquote><p>平时工作也想不起来去吃，先看看图片流口水吧~     <br />第一道，老妈最常做的就是我最喜欢吃的&#8220;土豆炖云豆&#8221;，超棒。回锅之后，味道无敌了，越炖越好吃！      <br />第二道，也是饭桌上常见的&#8220;红烧肉&#8221;，怎么吃都不腻，在成家之前先把这道菜学会喽，免得失传！      <br />第三道，最有营养的&#8220;地三鲜&#8221;，我感觉北京的&#8220;地三鲜&#8221;不是很地道，不管怎么样就是没老妈做的好吃吧。      <br />第四道，炎热的夏天，啥也不说了，吃一百遍也还想吃。</p>
</blockquote>
<p><a href="http://www.donevii.com/wp-content/uploads/2008/05/5174.jpg"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="484" alt="5174" src="http://www.donevii.com/wp-content/uploads/2008/05/5174-thumb.jpg" width="644" border="0" /></a> </p>
<p><a href="http://www.donevii.com/wp-content/uploads/2008/05/3447459920070615025606066-640.jpg"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="484" alt="3447459920070615025606066_640" src="http://www.donevii.com/wp-content/uploads/2008/05/3447459920070615025606066-640-thumb.jpg" width="644" border="0" /></a> </p>
<p><a href="http://www.donevii.com/wp-content/uploads/2008/05/gaoshu07021355.jpg"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="484" alt="gaoshu07021355" src="http://www.donevii.com/wp-content/uploads/2008/05/gaoshu07021355-thumb.jpg" width="644" border="0" /></a> </p>
<p><a href="http://www.donevii.com/wp-content/uploads/2008/05/1148583338920344-file.jpg"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="484" alt="1148583338920344_file" src="http://www.donevii.com/wp-content/uploads/2008/05/1148583338920344-file-thumb.jpg" width="644" border="0" /></a></p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/112.html" title="這十八招Web2.0創業者千萬不要學 (2006-10-24)">這十八招Web2.0創業者千萬不要學</a> (0)</li>
	<li><a href="http://www.donevii.com/post/586.html" title="评论:Web2.0用户之殇[转自cnbeta] (2008-10-21)">评论:Web2.0用户之殇[转自cnbeta]</a> (0)</li>
	<li><a href="http://www.donevii.com/post/229.html" title="设计模式之Life time controller模式 (2006-11-27)">设计模式之Life time controller模式</a> (0)</li>
	<li><a href="http://www.donevii.com/post/444.html" title="解决 loadrunner 8.1 拒绝服务问题 (2008-06-18)">解决 loadrunner 8.1 拒绝服务问题</a> (0)</li>
	<li><a href="http://www.donevii.com/post/110.html" title="翻译：On having layout (2006-10-24)">翻译：On having layout</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/441.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[转]嵌入式系统 Boot Loader 技术内幕</title>
		<link>http://www.donevii.com/post/387.html</link>
		<comments>http://www.donevii.com/post/387.html#comments</comments>
		<pubDate>Mon, 14 Jan 2008 05:24:32 +0000</pubDate>
		<dc:creator>gavinkwoe</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[mtk]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[boot]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[loader]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[Spreadtrum]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[串口]]></category>
		<category><![CDATA[内幕]]></category>
		<category><![CDATA[开发]]></category>
		<category><![CDATA[技术]]></category>
		<category><![CDATA[测试]]></category>
		<category><![CDATA[类]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/387.html</guid>
		<description><![CDATA[级别： 初级 詹荣开 (zhanrk@sohu.com), Linux爱好者 2003 年 12 月 01 日 本文详细地介绍了基于嵌入式系统中的 OS 启动加载程序 ―― Boot Loader 的概念、软件设计的主要任务以及结构框架等内容。 1. 引... ]]></description>
			<content:encoded><![CDATA[<p>级别： 初级</p>
<p><a href="http://www-128.ibm.com/developerworks/cn/linux/l-btloader/index.html#author"><font color="#996699">詹荣开</font></a> (<a href="mailto:zhanrk@sohu.com?subject=嵌入式系统 Boot Loader 技术内幕"><font color="#5c81a7">zhanrk@sohu.com</font></a>), Linux爱好者</p>
<p>2003 年 12 月 01 日</p>
<blockquote><p>本文详细地介绍了基于嵌入式系统中的 OS 启动加载程序 ―― Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的概念、软件设计的主要任务以及结构框架等内容。</p></blockquote>
<p><!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- include java script once we verify teams wants to use this and it will work on dbcs and cyrillic characters --><!--END RESERVED FOR FUTURE USE INCLUDE FILES--><a name="1" title="1"></a><span class="atitle">1. 引言</span></p>
<p>在专用的嵌入式板子运行 GNU/Linux 系统已经变得越来越流行。一个嵌入式 Linux 系统从软件的角度看通常可以分为四个层次：</p>
<p>1. <strong>引导加载程序。</strong>包括固化在固件(firmware)中的 boot 代码(可选)，和 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 两大部分。</p>
<p>2. <strong>Linux 内核。</strong>特定于嵌入式板子的定制内核以及内核的启动参数。</p>
<p>3. <strong>文件系统。</strong>包括根文件系统和建立于 Flash 内存设备之上文件系统。通常用 ram disk 来作为 root fs。</p>
<p>4. <strong>用户应用程序。</strong>特定于用户的应用程序。有时在用户应用程序和内核层之间可能还会包括一个嵌入式图形用户界面。常用的嵌入式 GUI 有：MicroWindows 和 MiniGUI 懂。</p>
<p>引导加载程序是系统加电后运行的第一段软件代码。回忆一下 PC 的体系结构我们可以知道，PC 机中的引导加载程序由 BIOS(其本质就是一段固件程序)和位于硬盘 MBR 中的 OS Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a>（比如，LILO 和 GRUB 等）一起组成。BIOS 在完成硬件检测和资源分配后，将硬盘 MBR 中的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 读到系统的 RAM 中，然后将控制权交给 OS Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a>。Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的主要运行任务就是将内核映象从硬盘上读到 RAM 中，然后跳转到内核的入口点去运行，也即开始启动操作系统。</p>
<p>而在嵌入式系统中，通常并没有像 BIOS 那样的固件程序（注，有的嵌入式 CPU 也会内嵌一段短小的启动程序），因此整个系统的加载启动任务就完全由 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 来完成。比如在一个基于 ARM7TDMI core 的嵌入式系统中，系统在上电或复位时通常都从地址 0&#215;00000000 处开始执行，而在这个地址处安排的通常就是系统的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 程序。</p>
<p>本文将从 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的概念、Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的主要任务、Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的框架结构以及 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的安装等四个方面来讨论嵌入式系统的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a>。</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td><img width="100%" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" height="1" /><br />
<img border="0" width="8" src="http://www.ibm.com/i/c.gif" height="6" /></td>
</tr>
</table>
<table align="right" cellPadding="0" cellSpacing="0" class="no-print">
<tr align="right">
<td><img width="100%" src="http://www.ibm.com/i/c.gif" height="4" /></p>
<table border="0" cellPadding="0" cellSpacing="0">
<tr>
<td vAlign="middle"><img border="0" width="16" src="http://www.ibm.com/i/v14/icons/u_bold.gif" height="16" /></td>
<td align="right" vAlign="top"><a href="http://www-128.ibm.com/developerworks/cn/linux/l-btloader/index.html#main" class="fbox"><strong><font color="#996699">回页首</font></strong></a></td>
</tr>
</table>
</td>
</tr>
</table>
<p><a name="2" title="2"></a><span class="atitle">2. Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的概念</span></p>
<p>简单地说，Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 就是在操作系统内核运行之前运行的一段小程序。通过这段小程序，我们可以初始化硬件设备、建立内存空间的映射图，从而将系统的软硬件环境带到一个合适的状态，以便为最终调用操作系统内核准备好正确的环境。</p>
<p>通常，Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 是严重地依赖于硬件而实现的，特别是在嵌入式世界。因此，在嵌入式世界里建立一个通用的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 几乎是不可能的。尽管如此，我们仍然可以对 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 归纳出一些通用的概念来，以指导用户特定的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 设计与实现。</p>
<p><a name="N10072" title="N10072"></a><span class="smalltitle"><strong><font face="Arial">1. Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 所支持的 CPU 和嵌入式板</font></strong></span></p>
<p>每种不同的 CPU 体系结构都有不同的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a>。有些 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 也支持多种体系结构的 CPU，比如 U-Boot 就同时支持 ARM 体系结构和MIPS 体系结构。除了依赖于 CPU 的体系结构外，Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 实际上也依赖于具体的嵌入式板级设备的配置。这也就是说，对于两块不同的嵌入式板而言，即使它们是基于同一种 CPU 而构建的，要想让运行在一块板子上的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 程序也能运行在另一块板子上，通常也都需要修改 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的源程序。</p>
<p><a name="N1007B" title="N1007B"></a><span class="smalltitle"><strong><font face="Arial">2. Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的安装媒介（Installation Medium）</font></strong></span></p>
<p>系统加电或复位后，所有的 CPU 通常都从某个由 CPU 制造商预先安排的地址上取指令。比如，基于 ARM7TDMI core 的 CPU 在复位时通常都从地址 0&#215;00000000 取它的第一条指令。而基于 CPU 构建的嵌入式系统通常都有某种类型的固态存储设备(比如：ROM、EEPROM 或 FLASH 等)被映射到这个预先安排的地址上。因此在系统加电后，CPU 将首先执行 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 程序。</p>
<p>下图1就是一个同时装有 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a>、内核的启动参数、内核映像和根文件系统映像的固态存储设备的典型空间分配结构图。<br />
<a name="N10089" title="N10089"></a><strong>图1 固态存储设备的典型空间分配结构</strong><br />
<img src="http://www-128.ibm.com/developerworks/cn/linux/l-btloader/images/image001.gif" /><br />
<a name="N10094" title="N10094"></a><span class="smalltitle"><strong><font face="Arial">3. 用来控制 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的设备或机制</font></strong></span></p>
<p>主机和目标机之间一般通过串口建立连接，Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 软件在执行时通常会通过串口来进行 I/O，比如：输出打印信息到串口，从串口读取用户控制字符等。</p>
<p><a name="N1009D" title="N1009D"></a><span class="smalltitle"><strong><font face="Arial">4. Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的启动过程是单阶段（Single Stage）还是多阶段（Multi-Stage）</font></strong></span></p>
<p>通常多阶段的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 能提供更为复杂的功能，以及更好的可移植性。从固态存储设备上启动的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 大多都是 2 阶段的启动过程，也即启动过程可以分为 stage 1 和 stage 2 两部分。而至于在 stage 1 和 stage 2 具体完成哪些任务将在下面讨论。</p>
<p><a name="N100A6" title="N100A6"></a><span class="smalltitle"><strong><font face="Arial">5. Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的操作模式 (Operation Mode)</font></strong></span></p>
<p>大多数 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 都包含两种不同的操作模式：&#8221;启动加载&#8221;模式和&#8221;下载&#8221;模式，这种区别仅对于开发人员才有意义。但从最终用户的角度看，Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的作用就是用来加载操作系统，而并不存在所谓的启动加载模式与下载工作模式的区别。</p>
<p><strong>启动加载（Boot loading）模式：</strong>这种模式也称为&#8221;自主&#8221;（Autonomous）模式。也即 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 从目标机上的某个固态存储设备上将操作系统加载到 RAM 中运行，整个过程并没有用户的介入。这种模式是 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的正常工作模式，因此在嵌入式产品发布的时侯，Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 显然必须工作在这种模式下。</p>
<p><strong>下载（Downloading）模式：</strong>在这种模式下，目标机上的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 将通过串口连接或网络连接等通信手段从主机（Host）下载文件，比如：下载内核映像和根文件系统映像等。从主机下载的文件通常首先被 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 保存到目标机的 RAM 中，然后再被 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 写到目标机上的FLASH 类固态存储设备中。Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的这种模式通常在第一次安装内核与根文件系统时被使用；此外，以后的系统更新也会使用 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的这种工作模式。工作于这种模式下的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 通常都会向它的终端用户提供一个简单的命令行接口。</p>
<p>像 Blob 或 U-Boot 等这样功能强大的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 通常同时支持这两种工作模式，而且允许用户在这两种工作模式之间进行切换。比如，Blob 在启动时处于正常的启动加载模式，但是它会延时 10 秒等待终端用户按下任意键而将 blob 切换到下载模式。如果在 10 秒内没有用户按键，则 blob 继续启动 Linux 内核。</p>
<p><a name="N100BE" title="N100BE"></a><span class="smalltitle"><strong><font face="Arial">6. BootLoader 与主机之间进行文件传输所用的通信设备及协议</font></strong></span></p>
<p>最常见的情况就是，目标机上的 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 通过串口与主机之间进行文件传输，传输协议通常是 xmodem／ymodem／zmodem 协议中的一种。但是，串口传输的速度是有限的，因此通过以太网连接并借助 TFTP 协议来下载文件是个更好的选择。</p>
<p>此外，在论及这个话题时，主机方所用的软件也要考虑。比如，在通过以太网连接和 TFTP 协议来下载文件时，主机方必须有一个软件用来的提供 TFTP 服务。</p>
<p>在讨论了 BootLoader 的上述概念后，下面我们来具体看看 BootLoader 的应该完成哪些任务。</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td><img width="100%" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" height="1" /><br />
<img border="0" width="8" src="http://www.ibm.com/i/c.gif" height="6" /></td>
</tr>
</table>
<table align="right" cellPadding="0" cellSpacing="0" class="no-print">
<tr align="right">
<td><img width="100%" src="http://www.ibm.com/i/c.gif" height="4" /></p>
<table border="0" cellPadding="0" cellSpacing="0">
<tr>
<td vAlign="middle"><img border="0" width="16" src="http://www.ibm.com/i/v14/icons/u_bold.gif" height="16" /></td>
<td align="right" vAlign="top"><a href="http://www-128.ibm.com/developerworks/cn/linux/l-btloader/index.html#main" class="fbox"><strong><font color="#996699">回页首</font></strong></a></td>
</tr>
</table>
</td>
</tr>
</table>
<p><a name="3" title="3"></a><span class="atitle">3. Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的主要任务与典型结构框架</span></p>
<p>在继续本节的讨论之前，首先我们做一个假定，那就是：假定内核映像与根文件系统映像都被加载到 RAM 中运行。之所以提出这样一个假设前提是因为，在嵌入式系统中内核映像与根文件系统映像也可以直接在 ROM 或 Flash 这样的固态存储设备中直接运行。但这种做法无疑是以运行速度的牺牲为代价的。</p>
<p>从操作系统的角度看，Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的总目标就是正确地调用内核来执行。</p>
<p>另外，由于 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的实现依赖于 CPU 的体系结构，因此大多数 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 都分为 stage1 和 stage2 两大部分。依赖于 CPU 体系结构的代码，比如设备初始化代码等，通常都放在 stage1 中，而且通常都用汇编语言来实现，以达到短小精悍的目的。而 stage2 则通常用C语言来实现，这样可以实现给复杂的功能，而且代码会具有更好的可读性和可移植性。</p>
<p>Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage1 通常包括以下步骤(以执行的先后顺序)：</p>
<ul>
<li>硬件设备初始化。</li>
<li>为加载 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage2 准备 RAM 空间。</li>
<li>拷贝 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage2 到 RAM 空间中。</li>
<li>设置好堆栈。</li>
<li>跳转到 stage2 的 C 入口点。</li>
</ul>
<p>Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage2 通常包括以下步骤(以执行的先后顺序)：</p>
<ul>
<li>初始化本阶段要使用到的硬件设备。</li>
<li>检测系统内存映射(memory map)。</li>
<li>将 kernel 映像和根文件系统映像从 flash 上读到 RAM 空间中。</li>
<li>为内核设置启动参数。</li>
<li>调用内核。</li>
</ul>
<p><a name="N1012A" title="N1012A"></a><span class="smalltitle"><strong><font face="Arial">3.1 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage1</font></strong></span></p>
<p><strong>3.1.1 基本的硬件初始化</strong></p>
<p>这是 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 一开始就执行的操作，其目的是为 stage2 的执行以及随后的 kernel 的执行准备好一些基本的硬件环境。它通常包括以下步骤（以执行的先后顺序）：</p>
<p>1． <strong>屏蔽所有的中断。</strong>为中断提供服务通常是 OS 设备驱动程序的责任，因此在 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的执行全过程中可以不必响应任何中断。中断屏蔽可以通过写 CPU 的中断屏蔽寄存器或状态寄存器（比如 ARM 的 CPSR 寄存器）来完成。</p>
<p>2． <strong>设置 CPU 的速度和时钟频率。</strong></p>
<p>3． <strong>RAM 初始化。</strong>包括正确地设置系统的内存控制器的功能寄存器以及各内存库控制寄存器等。</p>
<p>4． <strong>初始化 LED。</strong>典型地，通过 GPIO 来驱动 LED，其目的是表明系统的状态是 OK 还是 Error。如果板子上没有 LED，那么也可以通过初始化 UART 向串口打印 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 Logo 字符信息来完成这一点。</p>
<p>5． <strong>关闭 CPU 内部指令／数据 <a href="http://www.donevii.com/post/tag/cache" class="st_tag internal_tag" rel="tag" title="Posts tagged with cache">cache</a>。</strong></p>
<p><strong>3.1.2 为加载 stage2 准备 RAM 空间</strong></p>
<p>为了获得更快的执行速度，通常把 stage2 加载到 RAM 空间中来执行，因此必须为加载 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage2 准备好一段可用的 RAM 空间范围。</p>
<p>由于 stage2 通常是 C 语言执行代码，因此在考虑空间大小时，除了 stage2 可执行映象的大小外，还必须把堆栈空间也考虑进来。此外，空间大小最好是 memory page 大小(通常是 4KB)的倍数。一般而言，1M 的 RAM 空间已经足够了。具体的地址范围可以任意安排，比如 blob 就将它的 stage2 可执行映像安排到从系统 RAM 起始地址 0xc0200000 开始的 1M 空间内执行。但是，将 stage2 安排到整个 RAM 空间的最顶 1MB(也即(RamEnd-1MB) &#8211; RamEnd)是一种值得推荐的方法。</p>
<p>为了后面的叙述方便，这里把所安排的 RAM 空间范围的大小记为：stage2_size(字节)，把起始地址和终止地址分别记为：stage2_start 和 stage2_end(这两个地址均以 4 字节边界对齐)。因此：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">stage2_end＝stage2_start＋stage2_size</pre>
</td>
</tr>
</table>
<p>另外，还必须确保所安排的地址范围的的确确是可读写的 RAM 空间，因此，必须对你所安排的地址范围进行测试。具体的测试方法可以采用类似于 blob 的方法，也即：以 memory page 为被测试单位，测试每个 memory page 开始的两个字是否是可读写的。为了后面叙述的方便，我们记这个检测算法为：test_mempage，其具体步骤如下：</p>
<p>1． 先保存 memory page 一开始两个字的内容。</p>
<p>2． 向这两个字中写入任意的数字。比如：向第一个字写入 0&#215;55，第 2 个字写入 0xaa。</p>
<p>3． 然后，立即将这两个字的内容读回。显然，我们读到的内容应该分别是 0&#215;55 和 0xaa。如果不是，则说明这个 memory page 所占据的地址范围不是一段有效的 RAM 空间。</p>
<p>4． 再向这两个字中写入任意的数字。比如：向第一个字写入 0xaa，第 2 个字中写入 0&#215;55。</p>
<p>5． 然后，立即将这两个字的内容立即读回。显然，我们读到的内容应该分别是 0xaa 和 0&#215;55。如果不是，则说明这个 memory page 所占据的地址范围不是一段有效的 RAM 空间。</p>
<p>6． 恢复这两个字的原始内容。测试完毕。</p>
<p>为了得到一段干净的 RAM 空间范围，我们也可以将所安排的 RAM 空间范围进行清零操作。</p>
<p><strong>3.1.3 拷贝 stage2 到 RAM 中</strong></p>
<p>拷贝时要确定两点：(1) stage2 的可执行映象在固态存储设备的存放起始地址和终止地址；(2) RAM 空间的起始地址。</p>
<p><strong>3.1.4 设置堆栈指针 sp</strong></p>
<p>堆栈指针的设置是为了执行 C 语言代码作好准备。通常我们可以把 sp 的值设置为(stage2_end-4)，也即在 3.1.2 节所安排的那个 1MB 的 RAM 空间的最顶端(堆栈向下生长)。</p>
<p>此外，在设置堆栈指针 sp 之前，也可以关闭 led 灯，以提示用户我们准备跳转到 stage2。</p>
<p>经过上述这些执行步骤后，系统的物理内存布局应该如下图2所示。</p>
<p><strong>3.1.5 跳转到 stage2 的 C 入口点</strong></p>
<p>在上述一切都就绪后，就可以跳转到 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage2 去执行了。比如，在 ARM 系统中，这可以通过修改 PC 寄存器为合适的地址来实现。<br />
<a name="N101A5" title="N101A5"></a><strong>图2 bootloader 的 stage2 可执行映象刚被拷贝到 RAM 空间时的系统内存布局</strong><br />
<img src="http://www-128.ibm.com/developerworks/cn/linux/l-btloader/images/image002.gif" /><br />
<a name="N101B0" title="N101B0"></a><span class="smalltitle"><strong><font face="Arial">3.2 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage2 </font></strong></span></p>
<p>正如前面所说，stage2 的代码通常用 C 语言来实现，以便于实现更复杂的功能和取得更好的代码可读性和可移植性。但是与普通 C 语言应用程序不同的是，在编译和链接 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 这样的程序时，我们不能使用 glibc 库中的任何支持函数。其原因是显而易见的。这就给我们带来一个问题，那就是从那里跳转进 main() 函数呢？直接把 main() 函数的起始地址作为整个 stage2 执行映像的入口点或许是最直接的想法。但是这样做有两个缺点：1)无法通过main() 函数传递函数参数；2)无法处理 main() 函数返回的情况。一种更为巧妙的方法是利用 trampoline(弹簧床)的概念。也即，用汇编语言写一段trampoline 小程序，并将这段 trampoline 小程序来作为 stage2 可执行映象的执行入口点。然后我们可以在 trampoline 汇编小程序中用 CPU 跳转指令跳入 main() 函数中去执行；而当 main() 函数返回时，CPU 执行路径显然再次回到我们的 trampoline 程序。简而言之，这种方法的思想就是：用这段 trampoline 小程序来作为 main() 函数的外部包裹(external wrapper)。</p>
<p>下面给出一个简单的 trampoline 程序示例(来自blob)：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">.text .globl _trampoline _trampoline: 	bl	main 	/* if main ever returns we just call it again */ 	b	_trampoline</pre>
</td>
</tr>
</table>
<p>可以看出，当 main() 函数返回后，我们又用一条跳转指令重新执行 trampoline 程序――当然也就重新执行 main() 函数，这也就是 trampoline(弹簧床)一词的意思所在。</p>
<p><strong>3.2.1初始化本阶段要使用到的硬件设备</strong></p>
<p>这通常包括：（1）初始化至少一个串口，以便和终端用户进行 I/O 输出信息；（2）初始化计时器等。</p>
<p>在初始化这些设备之前，也可以重新把 LED 灯点亮，以表明我们已经进入 main() 函数执行。</p>
<p>设备初始化完成后，可以输出一些打印信息，程序名字字符串、版本号等。</p>
<p><strong>3.2.2 检测系统的内存映射（memory map）</strong></p>
<p>所谓内存映射就是指在整个 4GB 物理地址空间中有哪些地址范围被分配用来寻址系统的 RAM 单元。比如，在 SA-1100 CPU 中，从 0xC000,0000 开始的 512M 地址空间被用作系统的 RAM 地址空间，而在 Samsung S3C44B0X CPU 中，从 0x0c00,0000 到 0&#215;1000,0000 之间的 64M 地址空间被用作系统的 RAM 地址空间。虽然 CPU 通常预留出一大段足够的地址空间给系统 RAM，但是在搭建具体的嵌入式系统时却不一定会实现 CPU 预留的全部 RAM 地址空间。也就是说，具体的嵌入式系统往往只把 CPU 预留的全部 RAM 地址空间中的一部分映射到 RAM 单元上，而让剩下的那部分预留 RAM 地址空间处于未使用状态。 <strong>由于上述这个事实，因此 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的 stage2 必须在它想干点什么 (比如，将存储在 flash 上的内核映像读到 RAM 空间中) 之前检测整个系统的内存映射情况，也即它必须知道 CPU 预留的全部 RAM 地址空间中的哪些被真正映射到 RAM 地址单元，哪些是处于 &#8220;unused&#8221; 状态的。</strong></p>
<p><strong>(1) 内存映射的描述</strong></p>
<p>可以用如下数据结构来描述 RAM 地址空间中的一段连续(continuous)的地址范围：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">typedef struct memory_area_struct { 	u32 start; /* the base address of the memory region */ 	u32 size; /* the byte number of the memory region */ 	int used; } memory_area_t;</pre>
</td>
</tr>
</table>
<p>这段 RAM 地址空间中的连续地址范围可以处于两种状态之一：(1)used=1，则说明这段连续的地址范围已被实现，也即真正地被映射到 RAM 单元上。(2)used=0，则说明这段连续的地址范围并未被系统所实现，而是处于未使用状态。</p>
<p>基于上述 memory_area_t 数据结构，整个 CPU 预留的 RAM 地址空间可以用一个 memory_area_t 类型的数组来表示，如下所示：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">memory_area_t memory_map[NUM_MEM_AREAS] = { 	[0 ... (NUM_MEM_AREAS - 1)] = { 		.start = 0, 		.size = 0, 		.used = 0 	}, };</pre>
</td>
</tr>
</table>
<p>(2) 内存映射的检测</p>
<p>下面我们给出一个可用来检测整个 RAM 地址空间内存映射情况的简单而有效的算法：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">/* 数组初始化 */ for(i = 0; i &lt; NUM_MEM_AREAS; i++) 	memory_map[i].used = 0; /* first write a 0 to all memory locations */ for(addr = MEM_START; addr &lt; MEM_END; addr += PAGE_SIZE) 	* (u32 *)addr = 0; for(i = 0, addr = MEM_START; addr &lt; MEM_END; addr += PAGE_SIZE) {      /*       * 检测从基地址 MEM_START+i*PAGE_SIZE 开始,大小为 * PAGE_SIZE 的地址空间是否是有效的RAM地址空间。       */      调用3.1.2节中的算法test_mempage()；      if ( current memory page isnot a valid ram page) { 		/* no RAM here */ 		if(memory_map[i].used ) 			i++; 		continue; 	} 	 	/* 	 * 当前页已经是一个被映射到 RAM 的有效地址范围 	 * 但是还要看看当前页是否只是 4GB 地址空间中某个地址页的别名？ 	 */ 	if(* (u32 *)addr != 0) { /* alias? */ 		/* 这个内存页是 4GB 地址空间中某个地址页的别名 */ 		if ( memory_map[i].used ) 			i++; 		continue; 	} 	 	/* 	 * 当前页已经是一个被映射到 RAM 的有效地址范围 	 * 而且它也不是 4GB 地址空间中某个地址页的别名。 	 */ 	if (memory_map[i].used == 0) { 		memory_map[i].start = addr; 		memory_map[i].size = PAGE_SIZE; 		memory_map[i].used = 1; 	} else { 		memory_map[i].size += PAGE_SIZE; 	} } /* end of for (…) */</pre>
</td>
</tr>
</table>
<p>在用上述算法检测完系统的内存映射情况后，Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 也可以将内存映射的详细信息打印到串口。</p>
<p><strong>3.2.3 加载内核映像和根文件系统映像</strong></p>
<p><strong>(1) 规划内存占用的布局</strong></p>
<p>这里包括两个方面：(1)内核映像所占用的内存范围；（2）根文件系统所占用的内存范围。在规划内存占用的布局时，主要考虑基地址和映像的大小两个方面。</p>
<p>对于内核映像，一般将其拷贝到从(MEM_START＋0&#215;8000) 这个基地址开始的大约1MB大小的内存范围内(嵌入式 Linux 的内核一般都不操过 1MB)。为什么要把从 MEM_START 到 MEM_START＋0&#215;8000 这段 32KB 大小的内存空出来呢？这是因为 Linux 内核要在这段内存中放置一些全局数据结构，如：启动参数和内核页表等信息。</p>
<p>而对于根文件系统映像，则一般将其拷贝到 MEM_START+0&#215;0010,0000 开始的地方。如果用 Ramdisk 作为根文件系统映像，则其解压后的大小一般是1MB。</p>
<p><strong>（2）从 Flash 上拷贝</strong></p>
<p>由于像 ARM 这样的嵌入式 CPU 通常都是在统一的内存地址空间中寻址 Flash 等固态存储设备的，因此从 Flash 上读取数据与从 RAM 单元中读取数据并没有什么不同。用一个简单的循环就可以完成从 Flash 设备上拷贝映像的工作：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">  while(count) { 	*dest++ = *src++; /* they are all aligned with word boundary */ 	count -= 4; /* byte number */ };</pre>
</td>
</tr>
</table>
<p><strong>3.2.4 设置内核的启动参数</strong></p>
<p>应该说，在将内核映像和根文件系统映像拷贝到 RAM 空间中后，就可以准备启动 Linux 内核了。但是在调用内核之前，应该作一步准备工作，即：设置 Linux 内核的启动参数。</p>
<p>Linux 2.4.x 以后的内核都期望以标记列表(tagged list)的形式来传递启动参数。启动参数标记列表以标记 ATAG_CORE 开始，以标记 ATAG_NONE 结束。每个标记由标识被传递参数的 tag_header 结构以及随后的参数值数据结构来组成。数据结构 tag 和 tag_header 定义在 Linux 内核源码的include/asm/setup.h 头文件中：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">/* The list ends with an ATAG_NONE node. */ #define ATAG_NONE	0x00000000 struct tag_header { 	u32 size; /* 注意，这里size是字数为单位的 */ 	u32 tag; }; …… struct tag { 	struct tag_header hdr; 	union { 		struct tag_core		core; 		struct tag_mem32	mem; 		struct tag_videotext	videotext; 		struct tag_ramdisk	ramdisk; 		struct tag_initrd	initrd; 		struct tag_serialnr	serialnr; 		struct tag_revision	revision; 		struct tag_videolfb	videolfb; 		struct tag_cmdline	cmdline; 		/* 		 * Acorn specific 		 */ 		struct tag_acorn	acorn; 		/* 		 * DC21285 specific 		 */ 		struct tag_memclk	memclk; 	} u; };</pre>
</td>
</tr>
</table>
<p>在嵌入式 Linux 系统中，通常需要由 Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 设置的常见启动参数有：ATAG_CORE、ATAG_MEM、ATAG_CMDLINE、ATAG_RAMDISK、ATAG_INITRD等。</p>
<p>比如，设置 ATAG_CORE 的代码如下：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">params = (struct tag *)BOOT_PARAMS; 	params-&gt;hdr.tag = ATAG_CORE; 	params-&gt;hdr.size = tag_size(tag_core); 	params-&gt;u.core.flags = 0; 	params-&gt;u.core.pagesize = 0; 	params-&gt;u.core.rootdev = 0; 	params = tag_next(params);</pre>
</td>
</tr>
</table>
<p>其中，BOOT_PARAMS 表示内核启动参数在内存中的起始基地址，指针 params 是一个 struct tag 类型的指针。宏 tag_next() 将以指向当前标记的指针为参数，计算紧临当前标记的下一个标记的起始地址。注意，内核的根文件系统所在的设备ID就是在这里设置的。</p>
<p>下面是设置内存映射情况的示例代码：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">for(i = 0; i &lt; NUM_MEM_AREAS; i++) { 		if(memory_map[i].used) { 			params-&gt;hdr.tag = ATAG_MEM; 			params-&gt;hdr.size = tag_size(tag_mem32); 			params-&gt;u.mem.start = memory_map[i].start; 			params-&gt;u.mem.size = memory_map[i].size; 			 			params = tag_next(params); 		} }</pre>
</td>
</tr>
</table>
<p>可以看出，在 memory_map［］数组中，每一个有效的内存段都对应一个 ATAG_MEM 参数标记。</p>
<p>Linux 内核在启动时可以以命令行参数的形式来接收信息，利用这一点我们可以向内核提供那些内核不能自己检测的硬件参数信息，或者重载(override)内核自己检测到的信息。比如，我们用这样一个命令行参数字符串&#8221;console=ttyS0,115200n8&#8243;来通知内核以 ttyS0 作为控制台，且串口采用 &#8220;115200bps、无奇偶校验、8位数据位&#8221;这样的设置。下面是一段设置调用内核命令行参数字符串的示例代码：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">char *p; 	/* eat leading white space */ 	for(p = commandline; *p == ' '; p++) 		; 	/* skip non-existent command lines so the kernel will still     * use its default command line. 	 */ 	if(*p == '\0') 		return; 	params-&gt;hdr.tag = ATAG_CMDLINE; 	params-&gt;hdr.size = (sizeof(struct tag_header) + strlen(p) + 1 + 4) &gt;&gt; 2; 	strcpy(params-&gt;u.cmdline.cmdline, p); 	params = tag_next(params);</pre>
</td>
</tr>
</table>
<p>请注意在上述代码中，设置 tag_header 的大小时，必须包括字符串的终止符&#8217;\0&#8242;，此外还要将字节数向上圆整4个字节，因为 tag_header 结构中的size 成员表示的是字数。</p>
<p>下面是设置 ATAG_INITRD 的示例代码，它告诉内核在 RAM 中的什么地方可以找到 initrd 映象(压缩格式)以及它的大小：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">	params-&gt;hdr.tag = ATAG_INITRD2; 	params-&gt;hdr.size = tag_size(tag_initrd); 	 	params-&gt;u.initrd.start = RAMDISK_RAM_BASE; 	params-&gt;u.initrd.size = INITRD_LEN; 	 	params = tag_next(params);</pre>
</td>
</tr>
</table>
<p>下面是设置 ATAG_RAMDISK 的示例代码，它告诉内核解压后的 Ramdisk 有多大（单位是KB）：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">params-&gt;hdr.tag = ATAG_RAMDISK; params-&gt;hdr.size = tag_size(tag_ramdisk); 	 params-&gt;u.ramdisk.start = 0; params-&gt;u.ramdisk.size = RAMDISK_SIZE; /* 请注意，单位是KB */ params-&gt;u.ramdisk.flags = 1; /* automatically load ramdisk */ 	 params = tag_next(params);</pre>
</td>
</tr>
</table>
<p>最后，设置 ATAG_NONE 标记，结束整个启动参数列表：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">static void setup_end_tag(void) { 	params-&gt;hdr.tag = ATAG_NONE; 	params-&gt;hdr.size = 0; }</pre>
</td>
</tr>
</table>
<p><strong>3.2.5 调用内核</strong></p>
<p>Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 调用 Linux 内核的方法是直接跳转到内核的第一条指令处，也即直接跳转到 MEM_START＋0&#215;8000 地址处。在跳转时，下列条件要满足：</p>
<p>1． CPU 寄存器的设置：</p>
<ul>
<li>R0＝0；</li>
<li>R1＝机器类型 ID；关于 Machine Type Number，可以参见 <strong>linux/arch/arm/tools/mach-types。</strong></li>
<li>R2＝启动参数标记列表在 RAM 中起始基地址；</li>
</ul>
<p>2． CPU 模式：</p>
<ul>
<li>必须禁止中断（IRQs和FIQs）；</li>
<li>CPU 必须 SVC 模式；</li>
</ul>
<p>3． <a href="http://www.donevii.com/post/tag/cache" class="st_tag internal_tag" rel="tag" title="Posts tagged with cache">Cache</a> 和 MMU 的设置：</p>
<ul>
<li>MMU 必须关闭；</li>
<li>指令 <a href="http://www.donevii.com/post/tag/cache" class="st_tag internal_tag" rel="tag" title="Posts tagged with cache">Cache</a> 可以打开也可以关闭；</li>
<li>数据 <a href="http://www.donevii.com/post/tag/cache" class="st_tag internal_tag" rel="tag" title="Posts tagged with cache">Cache</a> 必须关闭；</li>
</ul>
<p>如果用 C 语言，可以像下列示例代码这样来调用内核：</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td class="code-outline">
<pre class="displaycode">void (*theKernel)(int zero, int arch, u32 params_addr) = (void (*)(int, int, u32))KERNEL_RAM_BASE; …… theKernel(0, ARCH_NUMBER, (u32) kernel_params_start);</pre>
</td>
</tr>
</table>
<p>注意，theKernel()函数调用应该永远不返回的。如果这个调用返回，则说明出错。</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td><img width="100%" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" height="1" /><br />
<img border="0" width="8" src="http://www.ibm.com/i/c.gif" height="6" /></td>
</tr>
</table>
<table align="right" cellPadding="0" cellSpacing="0" class="no-print">
<tr align="right">
<td><img width="100%" src="http://www.ibm.com/i/c.gif" height="4" /></p>
<table border="0" cellPadding="0" cellSpacing="0">
<tr>
<td vAlign="middle"><img border="0" width="16" src="http://www.ibm.com/i/v14/icons/u_bold.gif" height="16" /></td>
<td align="right" vAlign="top"><a href="http://www-128.ibm.com/developerworks/cn/linux/l-btloader/index.html#main" class="fbox"><strong><font color="#996699">回页首</font></strong></a></td>
</tr>
</table>
</td>
</tr>
</table>
<p><a name="4" title="4"></a><span class="atitle">4. 关于串口终端</span></p>
<p>在 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 程序的设计与实现中，没有什么能够比从串口终端正确地收到打印信息能更令人激动了。此外，向串口终端打印信息也是一个非常重要而又有效的调试手段。但是，我们经常会碰到串口终端显示乱码或根本没有显示的问题。造成这个问题主要有两种原因：(1) boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 对串口的初始化设置不正确。(2) 运行在 host 端的终端仿真程序对串口的设置不正确，这包括：波特率、奇偶校验、数据位和停止位等方面的设置。</p>
<p>此外，有时也会碰到这样的问题，那就是：在 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 的运行过程中我们可以正确地向串口终端输出信息，但当 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 启动内核后却无法看到内核的启动输出信息。对这一问题的原因可以从以下几个方面来考虑：</p>
<p>(1) 首先请确认你的内核在编译时配置了对串口终端的支持，并配置了正确的串口驱动程序。</p>
<p>(2) 你的 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 对串口的初始化设置可能会和内核对串口的初始化设置不一致。此外，对于诸如 s3c44b0x 这样的 CPU，CPU 时钟频率的设置也会影响串口，因此如果 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 和内核对其 CPU 时钟频率的设置不一致，也会使串口终端无法正确显示信息。</p>
<p>(3) 最后，还要确认 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 所用的内核基地址必须和内核映像在编译时所用的运行基地址一致，尤其是对于 uClinux 而言。假设你的内核映像在编译时用的基地址是 0xc0008000，但你的 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 却将它加载到 0xc0010000 处去执行，那么内核映像当然不能正确地执行了。</p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td><img width="100%" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" height="1" /><br />
<img border="0" width="8" src="http://www.ibm.com/i/c.gif" height="6" /></td>
</tr>
</table>
<table align="right" cellPadding="0" cellSpacing="0" class="no-print">
<tr align="right">
<td><img width="100%" src="http://www.ibm.com/i/c.gif" height="4" /></p>
<table border="0" cellPadding="0" cellSpacing="0">
<tr>
<td vAlign="middle"><img border="0" width="16" src="http://www.ibm.com/i/v14/icons/u_bold.gif" height="16" /></td>
<td align="right" vAlign="top"><a href="http://www-128.ibm.com/developerworks/cn/linux/l-btloader/index.html#main" class="fbox"><strong><font color="#996699">回页首</font></strong></a></td>
</tr>
</table>
</td>
</tr>
</table>
<p><a name="5" title="5"></a><span class="atitle">5. 结束语</span></p>
<p>Boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">Loader</a> 的设计与实现是一个非常复杂的过程。如果不能从串口收到那激动人心的&#8221;uncompressing linux&#8230;&#8230;&#8230;&#8230;&#8230;&#8230; done, booting the kernel……&#8221;内核启动信息，恐怕谁也不能说：&#8221;嗨，我的 boot <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> 已经成功地转起来了！&#8221;。</p>
<p><a name="author" title="author"></a><span class="atitle">关于作者</span></p>
<table border="0" width="100%" cellPadding="0" cellSpacing="0">
<tr>
<td colSpan="3"><img width="100%" src="http://www.ibm.com/i/c.gif" height="5" /></td>
</tr>
</table>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/78.html" title="[转]C/C++/Perl/汇编/Java效率比较 (2006-10-11)">[转]C/C++/Perl/汇编/Java效率比较</a> (0)</li>
	<li><a href="http://www.donevii.com/post/283.html" title="免费软件套装 (2007-01-08)">免费软件套装</a> (0)</li>
	<li><a href="http://www.donevii.com/post/221.html" title="什么是bootloader程序及其功能和特点 (2006-11-22)">什么是bootloader程序及其功能和特点</a> (0)</li>
	<li><a href="http://www.donevii.com/post/504.html" title="google背后的分布式架构 (2008-09-23)">google背后的分布式架构</a> (0)</li>
	<li><a href="http://www.donevii.com/post/124.html" title="C++资源之不完全导引 (2006-10-26)">C++资源之不完全导引</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/387.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[超长篇] Inject Your Code to a Portable Executable File</title>
		<link>http://www.donevii.com/post/330.html</link>
		<comments>http://www.donevii.com/post/330.html#comments</comments>
		<pubDate>Thu, 24 May 2007 07:50:01 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[doc]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.donevii.com/?p=330</guid>
		<description><![CDATA[转至: http://www.codeguru.com/cpp/w-p/system/misc/article.php/c11393 Downloads pemaker1.zip &#8211; pemaker2.zip &#8211; pemaker3.zip &#8211; pemaker4.zip &#8211; pemaker5.zip &#8211; peviewer.zip &#8211; test1.zip &#8211; Windows NT 3.51 (I mean, Win3... ]]></description>
			<content:encoded><![CDATA[<p>转至: <a href="http://www.codeguru.com/cpp/w-p/system/misc/article.php/c11393">http://www.codeguru.com/cpp/w-p/system/misc/article.php/c11393</a></p>
<p><strong>Downloads</strong></p>
<li><a href="http://www.codeguru.com/dbfiles/get_file/pemaker1.zip?id=11393&amp;lbl=PEMAKER1_ZIP&amp;ds=20060302">pemaker1.zip</a> &#8211; </li>
<li><a href="http://www.codeguru.com/dbfiles/get_file/pemaker2.zip?id=11393&amp;lbl=PEMAKER2_ZIP&amp;ds=20060302">pemaker2.zip</a> &#8211; </li>
<li><a href="http://www.codeguru.com/dbfiles/get_file/pemaker3.zip?id=11393&amp;lbl=PEMAKER3_ZIP&amp;ds=20060302">pemaker3.zip</a> &#8211; </li>
<li><a href="http://www.codeguru.com/dbfiles/get_file/pemaker4.zip?id=11393&amp;lbl=PEMAKER4_ZIP&amp;ds=20060302">pemaker4.zip</a> &#8211; </li>
<li><a href="http://www.codeguru.com/dbfiles/get_file/pemaker5.zip?id=11393&amp;lbl=PEMAKER5_ZIP&amp;ds=20060302">pemaker5.zip</a> &#8211; </li>
<li><a href="http://www.codeguru.com/dbfiles/get_file/peviewer.zip?id=11393&amp;lbl=PEVIEWER_ZIP&amp;ds=20060302">peviewer.zip</a> &#8211; </li>
<li><a href="http://www.codeguru.com/dbfiles/get_file/test1.zip?id=11393&amp;lbl=TEST1_ZIP&amp;ds=20060302">test1.zip</a> &#8211; </li>
<p><a name="more"><font color="#000000"></font></a><a href="http://en.wikipedia.org/wiki/Windows_NT_3.51" target="new">Windows NT 3.51</a> (I mean, <a href="http://en.wikipedia.org/wiki/Windows_3.1" target="new">Win3.1</a>, <a href="http://en.wikipedia.org/wiki/Windows_95" target="new">Win95</a>, <a href="http://en.wikipedia.org/wiki/Windows_98" target="new">Win98</a> were not perfect <a href="http://en.wikipedia.org/wiki/Operating_System" target="new">OS</a>s). The MS-DOS data causes that your executable file to have the performance inside MS-DOS and <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/HTML/_core_.2f.stub.asp" target="new">the MS-DOS Stub program</a> lets it display: <strong>&quot;This program can not be run in MS-DOS mode&quot;</strong> or <strong>&quot;This program can be run only in Windows mode&quot;</strong>, or some things like these comments when you try to run a Windows EXE file inside <a href="http://en.wikipedia.org/wiki/MS-DOS" target="new">MS-DOS 6.0</a>, where there is no footstep of Windows. Thus, this data is reserved for the code to indicate these comments in the <a href="http://en.wikipedia.org/wiki/MS-DOS" target="new">MS-DOS</a> <a href="http://en.wikipedia.org/wiki/Operating_System" target="new">operating system</a>. The most interesting part of the <a href="http://en.wikipedia.org/wiki/MS-DOS" target="new">MS-DOS</a> data is &quot;<strong>MZ</strong>&quot;! Can you believe, it refers to the name of &quot;<a href="http://en.wikipedia.org/wiki/Mark_Zbikowski" target="new">Mark Zbikowski</a>&quot;, one of the first Microsoft programmers?</p>
<p><font color="#000000"><img height="175" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=PEMAKER_GIF&amp;ds=20060302" width="452" alt="" /></font></p>
<h3>0 Preface</h3>
<p>You might demand to comprehend the ways a virus program injects its procedure into the interior of a portable executable file and corrupts it, or you are interested in implementing a packer or a protector to encrypt the data of your portable executable (PE) file. This article is committed to represent a brief discussion to realize the performance that is accomplished by EXE tools or some kinds of mal-ware.</p>
<p>You can employ this article&#8217;s source code to create your custom EXE builder. It could be used to make an EXE protector in the right way, or with the wrong intention, to spread a virus. However, my purpose of writing this article has been the first application, so I will not be responsible for the immoral usage of these methods.</p>
<h3>1 Prerequisites</h3>
<p>There are no specific mandatory prerequisites to follow the topics in this article. If you are familiar with a debugger and also the portable file format, I suggest you to drop to Sections 2 and 3; the whole of these sections has been made for people who don&#8217;t have any knowledge regarding the EXE file format or debuggers.</p>
<h3>2 Portable Executable File Format</h3>
<p>The Portable Executable file format was defined to provide the best way for the Windows Operating System to execute code and also to store the essential data that is needed to run a program&mdash;for example constant data, variable data, import library links, and resource data. It consists of MS-DOS file information, Windows NT file information, Section Headers, and Section images, as shown in Table 1.</p>
<h4>2.1 The MS-DOS data</h4>
<p>These data let you remember the first days of developing the Windows Operating System. You were at the beginning of a way to achieve a complete Operating System such as </p>
<p>To me, only the offset of the PE signature in the <a href="http://en.wikipedia.org/wiki/MS-DOS" target="new">MS-DOS</a> data is important, so I can use it to find the position of the <a href="http://en.wikipedia.org/wiki/Windows_NT" target="new">Windows NT</a> data. I just recommend that you take a look at Table 1, and then observe the structure of <tt>IMAGE_DOS_HEADER</tt> in the <em>&lt;winnt.h&gt;</em> header in the <em>&lt;Microsoft Visual Studio .net path&gt;\VC7\PlatformSDK\include\</em> folder or the <em>&lt;Microsoft Visual Studio 6.0 path&gt;\VC98\include\</em> folder. I do not know why the Microsoft team has forgotten to provide some comment about this structure in the <a href="http://msdn.microsoft.com/" target="new">MSDN</a> library!</p>
<pre><span class="codeKeyword">typedef</span> <span class="codeKeyword">struct</span> _IMAGE_DOS_HEADER { <span class="codeComment">// DOS .EXE header &quot;MZ&quot;</span>    WORD   e_magic;                <span class="codeComment">// Magic number</span>    WORD   e_cblp;                 <span class="codeComment">// Bytes on last page of file</span>    WORD   e_cp;                   <span class="codeComment">// Pages in file</span>    WORD   e_crlc;                 <span class="codeComment">// Relocations</span>    WORD   e_cparhdr;              <span class="codeComment">// Size of header in</span>                                   <span class="codeComment">// paragraphs</span>    WORD   e_minalloc;             <span class="codeComment">// Minimum extra paragraphs</span>                                   <span class="codeComment">// needed</span>    WORD   e_maxalloc;             <span class="codeComment">// Maximum extra paragraphs</span>                                   <span class="codeComment">// needed</span>    WORD   e_ss;                   <span class="codeComment">// Initial (relative) SS</span>                                   <span class="codeComment">// value</span>    WORD   e_sp;                   <span class="codeComment">// Initial SP value</span>    WORD   e_csum;                 <span class="codeComment">// Checksum</span>    WORD   e_ip;                   <span class="codeComment">// Initial IP value</span>    WORD   e_cs;                   <span class="codeComment">// Initial (relative) CS</span>                                   <span class="codeComment">// value</span>    WORD   e_lfarlc;               <span class="codeComment">// File address of relocation</span>                                   <span class="codeComment">// table</span>    WORD   e_ovno;                 <span class="codeComment">// Overlay number</span>    WORD   e_res[4];               <span class="codeComment">// Reserved words</span>    WORD   e_oemid;                <span class="codeComment">// OEM identifier</span>                                   <span class="codeComment">// (for e_oeminfo)</span>    WORD   e_oeminfo;              <span class="codeComment">// OEM information;</span>                                   <span class="codeComment">// e_oemid specific</span>    WORD   e_res2[10];             <span class="codeComment">// Reserved words</span>    LONG   <font color="#ff0000">e_lfanew</font>;               <span class="codeComment">// File address of the new</span>                                   <span class="codeComment">// exe header</span>  } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;</pre>
<p><tt>e_lfanew</tt> is the offset that refers to the position of the Windows NT data. I have provided a program to obtain the header information from an EXE file and to display it to you. To use the program, just try:</p>
<h4>PE Viewer</h4>
<p><img height="314" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=PEVIEWER1_GIF&amp;ds=20060302" width="491" alt="" /></p>
<p><img height="363" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=PEVIEWER2_GIF&amp;ds=20060302" width="500" alt="" /><br />(<a href="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=PEVIEWER2_GIF&amp;ds=20060302" target="_blank">Full Size Image</a>)</p>
<p><img height="313" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=PEVIEWER3_GIF&amp;ds=20060302" width="500" alt="" /><br />(<a href="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=PEVIEWER3_GIF&amp;ds=20060302" target="_blank">Full Size Image</a>)</p>
<p>This sample is useful for the whole of this article.</p>
<p><strong>Table 1:</strong> Portable Executable file format structure</p>
<p>
<table cellspacing="2" cellpadding="2" border="2">
<tbody>
<tr valign="top">
<td rowspan="17">MS-DOS <br />            information</td>
<td rowspan="16"><tt>IMAGE_DOS_<br />            HEADER</tt></td>
<td>DOS EXE Signature</td>
<td rowspan="16">
<pre lang="text">00000000  ASCII <font color="#008000">&quot;MZ&quot;</font>00000002  DW 009000000004  DW 000300000006  DW 000000000008  DW 00040000000A  DW 00000000000C  DW FFFF0000000E  DW 000000000010  DW 00B800000012  DW 000000000014  DW 000000000016  DW 000000000018  DW 00400000001A  DW 00000000001C  DB 00b&amp;b&amp;0000003B  DB 000000003C  DD <font color="#ff0000">000000F0</font></pre>
</td>
</tr>
<tr valign="top">
<td><tt>DOS_PartPag</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_PageCnt</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_ReloCnt</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_HdrSize</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_MinMem</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_MaxMem</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_ReloSS</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_ExeSP</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_ChkSum</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_ExeIPP</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_ReloCS</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_TablOff</tt></td>
</tr>
<tr valign="top">
<td><tt>DOS_Overlay</tt></td>
</tr>
<tr valign="top">
<td><tt>b&amp;<br />            </tt>Reserved words<tt><br />            b&amp;</tt></td>
</tr>
<tr valign="top">
<td>Offset to PE signature</td>
</tr>
<tr valign="top">
<td>MS-DOS Stub <br />            Program</td>
<td colspan="2">
<pre lang="text">00000040  ..B:..B4.C!B8\LC!<font color="#008000">This program canno</font>00000060  <font color="#008000">t be run in DOS mode.</font>...$.......</pre>
</td>
</tr>
<tr valign="top">
<td rowspan="54">Windows NT <br />            information
<p><tt>IMAGE_<br />            NT_HEADERS</tt></p>
</td>
<td>Signature</td>
<td>PE signature (PE)</td>
<td>
<pre lang="text"><font color="#ff0000">000000F0</font>  ASCII <font color="#008000">&quot;PE&quot;</font></pre>
</td>
</tr>
<tr valign="top">
<td rowspan="7"><tt>IMAGE_<br />            FILE_HEADER</tt></td>
<td><tt>Machine</tt></td>
<td rowspan="7">
<pre lang="text">000000F4  DW 014C000000F6  DW 0003000000F8  DD 3B7D8410000000FC  DD 0000000000000100  DD 0000000000000104  DW 00E000000106  DW 010F</pre>
</td>
</tr>
<tr valign="top">
<td><tt>NumberOfSections</tt></td>
</tr>
<tr valign="top">
<td><tt>TimeDateStamp</tt></td>
</tr>
<tr valign="top">
<td><tt>PointerToSymbolTable</tt></td>
</tr>
<tr valign="top">
<td><tt>NumberOfSymbols</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfOptionalHeader</tt></td>
</tr>
<tr valign="top">
<td><tt>Characteristics</tt></td>
</tr>
<tr valign="top">
<td rowspan="46"><tt>IMAGE_<br />            OPTIONAL_<br />            HEADER32</tt></td>
<td><tt>MagicNumber</tt></td>
<td rowspan="30">
<pre lang="text">00000108  DW 010B0000010A  DB 070000010B  DB 000000010C  DD 0001280000000110  DD 00009C0000000114  DD 0000000000000118  DD 000124750000011C  DD 0000100000000120  DD 0001400000000124  DD 0100000000000128  DD 000010000000012C  DD 0000020000000130  DW 000500000132  DW 000100000134  DW 000500000136  DW 000100000138  DW 00040000013A  DW 00000000013C  DD 0000000000000140  DD 0001F00000000144  DD 0000040000000148  DD 0001D7FC0000014C  DW 00020000014E  DW 800000000150  DD 0004000000000154  DD 0000100000000158  DD 001000000000015C  DD 0000100000000160  DD 0000000000000164  DD 00000010</pre>
</td>
</tr>
<tr valign="top">
<td><tt>MajorLinkerVersion</tt></td>
</tr>
<tr valign="top">
<td><tt>MinorLinkerVersion</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfCode</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfInitializedData</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfUninitializedData</tt></td>
</tr>
<tr valign="top">
<td><tt>AddressOfEntryPoint</tt></td>
</tr>
<tr valign="top">
<td><tt>BaseOfCode</tt></td>
</tr>
<tr valign="top">
<td><tt>BaseOfData</tt></td>
</tr>
<tr valign="top">
<td><tt>ImageBase</tt></td>
</tr>
<tr valign="top">
<td><tt>SectionAlignment</tt></td>
</tr>
<tr valign="top">
<td><tt>FileAlignment</tt></td>
</tr>
<tr valign="top">
<td><tt>MajorOSVersion</tt></td>
</tr>
<tr valign="top">
<td><tt>MinorOSVersion</tt></td>
</tr>
<tr valign="top">
<td><tt>MajorImageVersion</tt></td>
</tr>
<tr valign="top">
<td><tt>MinorImageVersion</tt></td>
</tr>
<tr valign="top">
<td><tt>MajorSubsystemVersion</tt></td>
</tr>
<tr valign="top">
<td><tt>MinorSubsystemVersion</tt></td>
</tr>
<tr valign="top">
<td><tt>Reserved</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfImage</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfHeaders</tt></td>
</tr>
<tr valign="top">
<td><tt>CheckSum</tt></td>
</tr>
<tr valign="top">
<td><tt>Subsystem</tt></td>
</tr>
<tr valign="top">
<td><tt>DLLCharacteristics</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfStackReserve</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfStackCommit</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfHeapReserve</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfHeapCommit</tt></td>
</tr>
<tr valign="top">
<td><tt>LoaderFlags</tt></td>
</tr>
<tr valign="top">
<td><tt>NumberOfRvaAndSizes</tt></td>
</tr>
<tr valign="top">
<td rowspan="16"><tt>IMAGE_<br />            DATA_DIRECTORY[16]</tt></td>
<td>Export Table</td>
</tr>
<tr valign="top">
<td>Import Table</td>
</tr>
<tr valign="top">
<td>Resource Table</td>
</tr>
<tr valign="top">
<td>Exception Table</td>
</tr>
<tr valign="top">
<td>Certificate File</td>
</tr>
<tr valign="top">
<td>Relocation Table</td>
</tr>
<tr valign="top">
<td><a href="http://www.donevii.com/post/tag/debug" class="st_tag internal_tag" rel="tag" title="Posts tagged with debug">Debug</a> Data</td>
</tr>
<tr valign="top">
<td>Architecture Data</td>
</tr>
<tr valign="top">
<td>Global Ptr</td>
</tr>
<tr valign="top">
<td>TLS Table</td>
</tr>
<tr valign="top">
<td>Load Config Table</td>
</tr>
<tr valign="top">
<td>Bound Import Table</td>
</tr>
<tr valign="top">
<td>Import Address Table</td>
</tr>
<tr valign="top">
<td>Delay Import Descriptor</td>
</tr>
<tr valign="top">
<td>COM+ Runtime Header</td>
</tr>
<tr valign="top">
<td>Reserved</td>
</tr>
<tr valign="top">
<td rowspan="13">Sections <br />            information</td>
<td rowspan="10"><tt>IMAGE_<br />            SECTION_<br />            HEADER[0]</tt></td>
<td><tt>Name[8]</tt></td>
<td rowspan="10">
<pre lang="text">000001E8  ASCII<font color="#008000">&quot;.text&quot;</font>000001F0  DD 000126B0000001F4  DD 00001000000001F8  DD 00012800000001FC  DD 0000040000000200  DD 0000000000000204  DD 0000000000000208  DW 00000000020A  DW 00000000020C  DD 60000020    CODE|EXECUTE|READ</pre>
</td>
</tr>
<tr valign="top">
<td><tt>VirtualSize</tt></td>
</tr>
<tr valign="top">
<td><tt>VirtualAddress</tt></td>
</tr>
<tr valign="top">
<td><tt>SizeOfRawData</tt></td>
</tr>
<tr valign="top">
<td><tt>PointerToRawData</tt></td>
</tr>
<tr valign="top">
<td><tt>PointerToRelocations</tt></td>
</tr>
<tr valign="top">
<td><tt>PointerToLineNumbers</tt></td>
</tr>
<tr valign="top">
<td><tt>NumberOfRelocations</tt></td>
</tr>
<tr valign="top">
<td><tt>NumberOfLineNumbers</tt></td>
</tr>
<tr valign="top">
<td><tt>Characteristics</tt></td>
</tr>
<tr valign="top">
<td><tt>b&amp;<br />            b&amp;<br />            b&amp;<br />            IMAGE_<br />            SECTION_<br />            HEADER[n]</tt></td>
<td colspan="2">
<pre lang="text">00000210  ASCII<font color="#008000">&quot;.data&quot;</font>; SECTION00000218  DD 0000101C ; VirtualSize = 0x101C0000021C  DD 00014000 ; VirtualAddress = 0x1400000000220  DD 00000A00 ; SizeOfRawData = 0xA0000000224  DD 00012C00 ; PointerToRawData = 0x12C0000000228  DD 00000000 ; PointerToRelocations = 0x00000022C  DD 00000000 ; PointerToLineNumbers = 0x000000230  DW 0000     ; NumberOfRelocations = 0x000000232  DW 0000     ; NumberOfLineNumbers = 0x000000234  DD C0000040 ; Characteristics =                        INITIALIZED_DATA|READ|WRITE00000238  ASCII<font color="#008000">&quot;.rsrc&quot;</font>; SECTION00000240  DD 00008960 ; VirtualSize = 0x896000000244  DD 00016000 ; VirtualAddress = 0x1600000000248  DD 00008A00 ; SizeOfRawData = 0x8A000000024C  DD 00013600 ; PointerToRawData = 0x1360000000250  DD 00000000 ; PointerToRelocations = 0x000000254  DD 00000000 ; PointerToLineNumbers = 0x000000258  DW 0000     ; NumberOfRelocations = 0x00000025A  DW 0000     ; NumberOfLineNumbers = 0x00000025C  DD 40000040 ; Characteristics =                        INITIALIZED_DATA|READ</pre>
</td>
</tr>
<tr valign="top">
<td><tt>SECTION[0]</tt></td>
<td colspan="2">
<pre lang="text">00000400  EA 22 DD 77 D7 23 DD 77  C*&quot;C.wC.#C.w00000408  9A 18 DD 77 00 00 00 00  E!.C.w....00000410  2E 1E C7 77 83 1D C7 77  ..C.wF..C.w00000418  FF 1E C7 77 00 00 00 00  C?.C.w....00000420  93 9F E7 77 D8 05 E8 77  b.E8C'wC..C(w00000428  FD A5 E7 77 AD A9 E9 77  C=B%C'w&amp;shy;B)C)w00000430  A3 36 E7 77 03 38 E7 77  B#6C'w.8C'w00000438  41 E3 E6 77 60 8D E7 77  AC#C&amp;w`BC'w00000440  E6 1B E6 77 2B 2A E7 77  C&amp;.C&amp;w+*C'w00000448  7A 17 E6 77 79 C8 E6 77  z.C&amp;wyC.C&amp;w00000450  14 1B E7 77 C1 30 E7 77  ..C'wC.0C'wb&amp;</pre>
</td>
</tr>
<tr valign="top">
<td><tt>b&amp;<br />            b&amp;<br />            b&amp;<br />            SECTION[n]</tt></td>
<td colspan="2">
<pre lang="text">b&amp;0001BF00  63 00 2E 00 63 00 68 00  c...c.h.0001BF08  6D 00 0A 00 43 00 61 00  m...C.a.0001BF10  6C 00 63 00 75 00 6C 00  l.c.u.l.0001BF18  61 00 74 00 6F 00 72 00  a.t.o.r.0001BF20  11 00 4E 00 6F 00 74 00  ..N.o.t.0001BF28  20 00 45 00 6E 00 6F 00   .E.n.o.0001BF30  75 00 67 00 68 00 20 00  u.g.h. .0001BF38  4D 00 65 00 6D 00 6F 00  M.e.m.o.0001BF40  72 00 79 00 00 00 00 00  r.y.....0001BF48  00 00 00 00 00 00 00 00  ........0001BF50  00 00 00 00 00 00 00 00  ........0001BF58  00 00 00 00 00 00 00 00  ........0001BF60  00 00 00 00 00 00 00 00  ........0001BF68  00 00 00 00 00 00 00 00  ........0001BF70  00 00 00 00 00 00 00 00  ........0001BF78  00 00 00 00 00 00 00 00  ........</pre>
</td>
</tr>
</tbody>
</table>
<h4>2.2 The Windows NT data</h4>
<p>As mentioned in the preceding section, <tt>e_lfanew</tt> storage in the MS-DOS data structure refers to the location of the Windows NT information. Hence, if you assume that the <tt>pMem</tt> pointer relates the start point of the memory space for a selected portable executable file, you can retrieve the MS-DOS header and also the Windows NT headers by the following lines, which you also can perceive in the PE viewer sample (<em>pelib.cpp</em>, <tt>PEStructure::OpenFileName()</tt>):</p>
<pre>IMAGE_DOS_HEADER        image_dos_header;IMAGE_NT_HEADERS        image_nt_headers;PCHAR pMem;b&amp;memcpy(&amp;image_dos_header, pMem,       <span class="codeKeyword">sizeof</span>(IMAGE_DOS_HEADER));memcpy(&amp;image_nt_headers,       pMem+image_dos_header.e_lfanew,       <span class="codeKeyword">sizeof</span>(IMAGE_NT_HEADERS));</pre>
<p><a name="more"><font color="#000000"></font></a><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_nt_headers_str.asp" target="new"><tt>IMAGE_NT_HEADERS</tt></a> structure definition. It makes it possible to grasp what the image NT header maintains to execute a code inside the Windows NT OS. Now, you are conversant with the Windows NT structure; it consists of the <font color="#008000">&quot;PE&quot;</font> Signature, the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_file_header_str.asp" target="new">File Header</a>, and the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_optional_header_str.asp" target="new">Optional Header</a>. Do not forget to take a glimpse at their comments in the <a href="http://msdn.microsoft.com/" target="new">MSDN</a> Library and in Table 1.</p>
<p>It seems to be very simple, the retrieval of the headers information. I recommend inspecting the MSDN library regarding the </p>
<p>One the whole, I consider merely, in most circumstances, the following cells of the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_nt_headers_str.asp" target="new"><tt>IMAGE_NT_HEADERS</tt></a> structure:</p>
<pre>FileHeader-&gt;NumberOfSectionsOptionalHeader-&gt;AddressOfEntryPointOptionalHeader-&gt;ImageBaseOptionalHeader-&gt;SectionAlignmentOptionalHeader-&gt;FileAlignmentOptionalHeader-&gt;SizeOfImageOptionalHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]              -&gt;VirtualAddressOptionalHeader-&gt;DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]              -&gt;Size</pre>
<p>You can observe the main purpose of these values clearly, and their role when the internal virtual memory space allocated for an EXE file by the Windows task manager if you pay attention to their explanations in <a href="http://msdn.microsoft.com/" target="new">MSDN</a> library, so I am not going to repeat the MSDN annotations here.</p>
<p>I should make a brief comment regarding the PE data directories, or <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_optional_header_str.asp" target="new"><tt>OptionalHeader</tt></a>-&gt; <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_data_directory_str.asp" target="new"><tt>DataDirectory[]</tt></a>, because I think there are a few aspects of interest concerning them. When you come to survey the Optional header through the Windows NT information, you will find that there are <em>16</em> directories at the end of the Optional Header, where you can find the consecutive directories, including their Relative Virtual Address and Size. I just mention here the notes from <em>&lt;winnt.h&gt;</em> to clarify these information:</p>
<pre><span class="codeComment">// Export Directory</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_EXPORT          0<span class="codeComment">// Import Directory</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_IMPORT          1<span class="codeComment">// Resource Directory</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_RESOURCE        2<span class="codeComment">// Exception Directory</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_EXCEPTION       3<span class="codeComment">// Security Directory</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_SECURITY        4<span class="codeComment">// Base Relocation Table</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_BASERELOC       5<span class="codeComment">// <a href="http://www.donevii.com/post/tag/debug" class="st_tag internal_tag" rel="tag" title="Posts tagged with debug">Debug</a> Directory</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_DEBUG           6<span class="codeComment">// Architecture Specific Data</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_ARCHITECTURE    7<span class="codeComment">// RVA of GP</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_GLOBALPTR       8<span class="codeComment">// TLS Directory</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_TLS             9<span class="codeComment">// Load Configuration Directory</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    10<span class="codeComment">// Bound Import Directory in headers</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   11<span class="codeComment">// Import Address Table</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_IAT            12<span class="codeComment">// Delay Load Import Descriptors</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   13<span class="codeComment">// COM Runtime descriptor</span><span class="codeKeyword">#define</span> IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14</pre>
<p>The last one (15) was reserved for use in the future; I have not yet seen any purpose for it, even in PE64.</p>
<p>For instance, if you want to perceive the relative virtual address (RVA) and the size of the resource data, it is enough to retrieve them by:</p>
<pre>DWORD dwRVA  = image_nt_headers.OptionalHeader-&gt;   DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE]-&gt;VirtualAddress;DWORD dwSize = image_nt_headers.OptionalHeader-&gt;   DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE]-&gt;Size;</pre>
<p>To comprehend more regarding the significance of data directories, I forward you to Section 3.4.3 of the <a href="http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx" target="new">Microsoft Portable Executable and the Common Object File Format Specification</a> document by Microsoft, and furthermore Section 6 of this document, where you discern the various types of sections and their applications. You will see the section&#8217;s advantage subsequently.</p>
<h4>2.3 The Section Headers and Sections</h4>
<p>You currently observe how the portable executable files declare the location and the size of a section on a disk storage file and inside the virtual memory space allocated for the program with <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_nt_headers_str.asp" target="new"><tt>IMAGE_NT_HEADERS</tt></a>-&gt; <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_optional_header_str.asp" target="new"><tt>OptionalHeader</tt></a>-&gt;<tt>SizeOfImage</tt> by the Windows task manager, as well the characteristics to demonstrate the type of the section. To better understand the Section header as my previous declaration, I suggest having a brief look at the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_section_header_str.asp" target="new"><tt>IMAGE_SECTION_HEADER</tt></a> structure definition in the MSDN library. For an EXE packer developer, <tt>VirtualSize</tt>, <tt>VirtualAddress</tt>, <tt>SizeOfRawData</tt>, <tt>PointerToRawData</tt>, and <tt>Characteristics</tt> cells have significant rules. When developing an EXE packer, you should be clever enough to play with them. There are somet hings to note when you modify them; you should take care to align the <tt>VirtualSize</tt> and <tt>VirtualAddress</tt> according to <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_optional_header_str.asp" target="new"><tt>OptionalHeader</tt></a>-&gt;<tt>SectionAlignment</tt>, as well as <tt>SizeOfRawData</tt> and <tt>PointerToRawData</tt> in line with <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_optional_header_str.asp" target="new"><tt>OptionalHeader</tt></a>-&gt;<tt>FileAlignment</tt>. Otherwise, you will corrupt your target EXE file and it will never run. Regarding <tt>Characteristics</tt>, I pay attention mostly to establish a section by <tt>IMAGE_SCN_MEM_READ</tt> | <tt>IMAGE_SCN_MEM_WRITE</tt> | <tt>IMAGE_SCN_CNT_INITIALIZED_DATA</tt>, I prefer that my new section has the ability to initialize such data during the running process, such as import table; besides, I need it to be able to modify itself by the <a href="http://www.donevii.com/post/tag/loader" class="st_tag internal_tag" rel="tag" title="Posts tagged with loader">loader</a> with my settings in the section characteristics to read- and writeable.</p>
<p>Moreover, you should pay attention to the section names; you can know the purpose of each section by its name. I will just forward you to Section 6 of the <a href="http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx" target="new">Microsoft Portable Executable and the Common Object File Format Specification</a> documents. I believe it represents the totality of sections by their names; this is also included in Table 2.</p>
<p><strong>Table 2:</strong> Section names</p>
<p>
<table cellspacing="2" cellpadding="2" border="2">
<tbody>
<tr>
<td><font color="#008000">&quot;.text&quot;</font></td>
<td>Code Section</td>
</tr>
<tr>
<td><font color="#008000">&quot;CODE&quot;</font></td>
<td>Code Section of file linked by Borland Delphi or Borland Pascal</td>
</tr>
<tr>
<td><font color="#008000">&quot;.data&quot;</font></td>
<td>Data Section</td>
</tr>
<tr>
<td><font color="#008000">&quot;DATA&quot;</font></td>
<td>Data Section of file linked by Borland Delphi or Borland Pascal</td>
</tr>
<tr>
<td><font color="#008000">&quot;.rdata&quot;</font></td>
<td>Section for Constant Data </td>
</tr>
<tr>
<td><font color="#008000">&quot;.idata&quot;</font></td>
<td>Import Table</td>
</tr>
<tr>
<td><font color="#008000">&quot;.edata&quot; </font></td>
<td>Export Table</td>
</tr>
<tr>
<td><font color="#008000">&quot;.tls&quot;</font></td>
<td>TLS Table</td>
</tr>
<tr>
<td><font color="#008000">&quot;.reloc&quot;</font></td>
<td>Relocation Information</td>
</tr>
<tr>
<td><font color="#008000">&quot;.rsrc&quot;</font></td>
<td>Resource Information</td>
</tr>
</tbody>
</table>
<p>To comprehend the section headers and also the sections, you can run the sample PE viewer. With this PE viewer, you can realize only the application of the section headers in a file image, so to observe the main significance in the Virtual Memory, you should try to load a PE file by a debugger. The next section represents the main idea of using the virtual address and size in the virtual memory by using a debugger. The last note is about <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_nt_headers_str.asp" target="new"><tt>IMAGE_NT_HEADERS</tt></a>-&gt; <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/image_file_header_str.asp" target="new"><tt>FileHeader</tt></a>-&gt;<tt>NumberOfSections</tt>, that provides a number of sections in a PE file. Do not forget to adjust it whenever you remove or add some sections to a PE file. I am talking about section injection!</p>
<h3>3 Debugger, Disassembler and some Useful Tools</h3>
<p>In this part, you will become familiar with the necessary and essential equipment to develop your PE tools.</p>
<h4>3.1 Debuggers</h4>
<p>The first essential prerequisite to become a PE tools developer is to have enough experience with bug tracer tools. Furthermore, you should know most of the assembly instructions. To me, the Intel documents are the best references. You can obtain them from the Intel site for IA-32, and on top of that IA-64; the future belongs to IA-64 CPUs, Windows XP 64-bit, and also PE64!</p>
<ul>
<li><a href="http://www.intel.com/design/pentium4/manuals/index_new.htm#1" target="new">IA-32 Intel Architecture Software Developer&#8217;s Manuals</a> </li>
<li><a href="http://www.intel.com/software/products/compilers/docs/linux/ref/asm_lan_lx.htm#cover.htm" target="new">Intel Itanium Architecture Assembly Language Reference Guide</a> </li>
<li><a href="http://www.intel.com/cd/ids/developer/asmo-na/eng/19415.htm" target="new">The Intel Itanium Processor Developer Resource Guide</a> </li>
</ul>
<p>To trace a PE file, <a href="http://en.wikipedia.org/wiki/SoftICE" target="new">SoftICE</a> by <a href="http://www.compuware.com/" target="new">Compuware Corporation</a>, I knew it also as named <a href="http://en.wikipedia.org/wiki/Numega" target="new">NuMega</a> when I was at high school, is the best <a href="http://en.wikipedia.org/wiki/Debugger" target="new">debugger</a> in the world. It implements process tracing by using the <a href="http://en.wikipedia.org/wiki/Kernel_mode" target="new">kernel mode</a> method debugging without applying Windows debugging <a href="http://en.wikipedia.org/wiki/Application_programming_interface" target="new">application programming interface</a> (API) functions. In addition, I will introduce one perfect debugger in <a href="http://en.wikipedia.org/wiki/User_mode" target="new">user mode</a> level. It utilizes the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/debugging_reference.asp" target="new">Windows debugging API</a> to trace a PE file and also attaches itself to an active <a href="http://en.wikipedia.org/wiki/Computer_process" target="new">process</a>. These <a href="http://en.wikipedia.org/wiki/Application_programming_interface" target="new">API</a> functions have been provided by Microsoft teams, inside the Windows Kernel32 library, to trace a specific process, by using Microsoft tools, or perhaps, to make your own debugger! Some of those <a href="http://en.wikipedia.org/wiki/Application_programming_interface" target="new">API</a> functions inlude:</p>
<ul><tt>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/createthread.asp" target="new">CreateThread()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/createprocess.asp" target="new">CreateProcess()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/openprocess.asp" target="new">OpenProcess()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/debugactiveprocess.asp" target="new">DebugActiveProcess()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/getthreadcontext.asp" target="new">GetThreadContext()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/setthreadcontext.asp" target="new">SetThreadContext()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/continuedebugevent.asp" target="new">ContinueDebugEvent()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/debugbreak.asp" target="new">DebugBreak()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/readprocessmemory.asp" target="new">ReadProcessMemory()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/writeprocessmemory.asp" target="new">WriteProcessMemory()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/suspendthread.asp" target="new">SuspendThread()</a> </li>
<li><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/resumethread.asp" target="new">ResumeThread()</a> </li>
<p>    </tt></ul>
<h5>3.1.1 SoftICE</h5>
<p>It was in 1987; Frank Grossman and Jim Moskun decided to establish a company called <a href="http://en.wikipedia.org/wiki/Numega" target="new">NuMega Technologies</a> in Nashua, NH, to develop some equipment to trace and test the reliability of Microsoft Windows software programs. Now, it is a part of <a href="http://en.wikipedia.org/wiki/Compuware" target="new">Compuware Corporation</a> and its product has participated to accelerate the reliability in Windows software, and additionally in Windows driver developments. Currently, everyone knows the Compuware DriverStudio that is used to establish an environment for implementing the elaboration of a kernel driver or a system file by aiding the <a href="http://www.microsoft.com/whdc/ddk/winddk.mspx" target="new">Windows Driver Development Kit (DDK)</a>. It bypasses the involvement of DDK to implement a portable executable file of kernel level for a Windows system software developer. For us, only one instrument of DriverStudio is important, <a href="http://en.wikipedia.org/wiki/SoftICE" target="new">SoftICE</a>; this debugger can be used to trace every portable executable file, a PE file for user mode level or a PE file for kernel mode level.</p>
<p><strong>Figure 1:</strong> SoftICE Window</p>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody bgcolor="#000000" color="gray">
<tr>
<td><font color="#808080"><font color="#00ccff">EAX=00000000</font>EBX=7FFDD000<font color="#00ccff"> ECX=0007FFB0 EDX=7C90EB94</font> ESI=FFFFFFFF EDI=7C919738 <font color="#00ccff">EBP=0007FFF0 ESP=0007FFC4 EIP=010119E0</font> o d i s <font color="#00ccff">z </font>a <font color="#00ccff">p</font> c<br />                CS=0008 DS=0023 SS=0010 ES=0023 FS=0030 GS=0000</font> <font color="#00ccff">SS:0007FFC4=87C816D4F</font></td>
</tr>
<tr>
<td><font color="#808080">0023:01013000 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 &#8230;&#8230;&#8230;&#8230;&#8230;. 0023:01013010 01 00 00 00 20 00 00 00-0A 00 00 00 0A 00 00 00 &#8230;&#8230;&#8230;&#8230;&#8230;. 0023:01013020 20 00 00 00 00 00 00 00-53 63 69 43 61 6C 63 00 &#8230;&#8230;..SciCalc. 0023:01013030 00 00 00 00 00 00 00 00-62 61 63 6B 67 72 6F 75 &#8230;&#8230;..backgrou 0023:01013040 6E 64 00 00 00 00 00 00-2E 00 00 00 00 00 00 00 nd&#8230;&#8230;&#8230;&#8230;..</font></td>
</tr>
<tr>
<td><font color="#808080">0010:0007FFC4 4F 6D 81 7C 38 07 91 7C-FF FF FF FF 00 90 FD 7F Om |8 b.| . 0010:0007FFD4 ED A6 54 80 C8 FF 07 00-E8 B4 F5 81 FF FF FF FF T . 0010:0007FFE4 F3 99 83 7C 58 6D 81 7C-00 00 00 00 00 00 00 00 Xm |&#8230;&#8230;.. 0010:0007FFF4 00 00 00 00 E0 19 01 01-00 00 00 00 00 00 00 00 &#8230;. &#8230;.</font></td>
</tr>
<tr>
<td><font color="#808080"><font color="#00ccff">010119E0 PUSH EBP</font> 010119E1 MOV EBP,ESP 010119E3 PUSH -1 010119E5 PUSH 01001570 010119EA PUSH 01011D60 010119EF MOV EAX,DWORD PTR FS:[0] 010119F5 PUSH EAX 010119F6 MOV DWORD PTR FS:[0],ESP 010119FD ADD ESP,-68 01011A00 PUSH EBX 01011A01 PUSH ESI 01011A02 PUSH EDI 01011A03 MOV DWORD PTR SS:[EBP-18],ESP 01011A06 MOV DWORD PTR SS:[EBP-4],0</font></td>
</tr>
<tr>
<td><font color="#808080">:_</font><font color="#808080"></p>
<p>                </font></td>
</tr>
</tbody>
</table>
<h5>3.1.2 OllyDbg</h5>
<p>It was about four years ago that I first saw this debugger by chance. For me, it was the best choice; I was not wealthy enough to purchase SoftICE, and at that time, SoftICE only had good functions for <a href="http://en.wikipedia.org/wiki/DOS" target="new">DOS</a>, <a href="http://en.wikipedia.org/wiki/Windows_98" target="new">Windows 98</a>, and <a href="http://en.wikipedia.org/wiki/Windows_2000" target="new">Windows 2000</a>. I found that this debugger supported all kinds of Windows versions. Therefore, I started to learn it very fast, and now it is my favorite debugger for the Windows OS. It is a debugger that can be used to trace all kinds of portable executable files except a <a href="http://en.wikipedia.org/wiki/Common_Language_Infrastructure" target="new">Common Language Infrastructure (CLI)</a> file format in user mode level, by using the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/debugging_reference.asp" target="new">Windows debugging API</a>. <strong>Oleh Yuschuk</strong>, the author, is one of worthiest software developers I have seen in my life. He is a Ukrainian who now lives in Germany. I should mention here that his debugger is the best choice for hacker and cracker parties around the world! It is freeware! You can try it from the <a href="http://www.ollydbg.de/" target="new">OllyDbg Homepage</a>.</p>
<p>    <a name="more"><font color="#000000">&nbsp;</font>
<p><strong>Figure 2:</strong> OllyDbg CPU Window</p>
<p><img height="452" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=SCREENSHOT_JPG&amp;ds=20060302" width="500" alt="" /><br />    (</p>
<h5>3.1.3 Which parts are important in a debugger interface?</h5>
<p>I have introduced two debuggers without talking about how you can employ them, and also which parts you should pay attention to. Regarding using debuggers, I refer you to their instructions in help documents. However, I want to explain briefly the important parts of a debugger; of course, I am talking about low-level debuggers, or in other words, machine-language debuggers of the x86 CPU families.</p>
<p>All of low-level debuggers consist of the following subdivisions:</p>
<ol>
<li>Registers viewer.<br />
<table cellspacing="2" cellpadding="2" border="2">
<tbody>
<tr>
<td align="center"><font color="#808080">EAX</font></td>
</tr>
<tr>
<td align="center"><font color="#808080">ECX</font></td>
</tr>
<tr>
<td align="center"><font color="#808080">EDX</font></td>
</tr>
<tr>
<td align="center"><font color="#808080">EBX</font></td>
</tr>
<tr>
<td align="center"><font color="#808080">ESP</font></td>
</tr>
<tr>
<td align="center"><font color="#808080">EBP</font></td>
</tr>
<tr>
<td align="center"><font color="#808080">ESI</font></td>
</tr>
<tr>
<td align="center"><font color="#808080">EDI</font></td>
</tr>
<tr>
<td align="center"><font color="#808080">EIP</font></td>
</tr>
<tr>
<td>
<p align="center"><font color="#808080">o</font><font color="#808080"> d t s z a p c</font></p>
</td>
</tr>
</tbody>
</table>
</li>
<li>Disassembler or Code viewer.<br />
<table cellspacing="2" cellpadding="2" border="2">
<tbody>
<tr>
<td>
<pre>010119E0 PUSH EBP010119E1 MOV EBP,ESP010119E3 PUSH -1010119E5 PUSH 01001570010119EA PUSH 01011D60010119EF MOV EAX,DWORD PTR FS:[0]010119F5 PUSH EAX010119F6 MOV DWORD PTR FS:[0],ESP010119FD ADD ESP,-6801011A00 PUSH EBX01011A01 PUSH ESI01011A02 PUSH EDI01011A03 MOV DWORD PTR SS:[EBP-18],ESP01011A06 MOV DWORD PTR SS:[EBP-4],0</pre>
</td>
</tr>
</tbody>
</table>
</li>
<li>Memory watcher.<br />
<table cellspacing="0" cellpadding="0" width="560" border="1">
<tbody>
<tr>
<td><font color="#808080">0023:01013000 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 &#8230;&#8230;&#8230;&#8230;&#8230;. 0023:01013010 01 00 00 00 20 00 00 00-0A 00 00 00 0A 00 00 00 &#8230;&#8230;&#8230;&#8230;&#8230;. 0023:01013020 20 00 00 00 00 00 00 00-53 63 69 43 61 6C 63 00 &#8230;&#8230;..SciCalc. 0023:01013030 00 00 00 00 00 00 00 00-62 61 63 6B 67 72 6F 75 &#8230;&#8230;..backgrou 0023:01013040 6E 64 00 00 00 00 00 00-2E 00 00 00 00 00 00 00 nd&#8230;&#8230;&#8230;&#8230;..</font></td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
</li>
<li>Stack viewer.<br />
<table cellspacing="0" cellpadding="0" width="560" border="1">
<tbody>
<tr>
<td><font color="#808080">0010:0007FFC4 4F 6D 81 7C 38 07 91 7C-FF FF FF FF 00 90 FD 7F Om |8 b.| . 0010:0007FFD4 ED A6 54 80 C8 FF 07 00-E8 B4 F5 81 FF FF FF FF T . 0010:0007FFE4 F3 99 83 7C 58 6D 81 7C-00 00 00 00 00 00 00 00 Xm |&#8230;&#8230;.. 0010:0007FFF4 00 00 00 00 E0 19 01 01-00 00 00 00 00 00 00 00 &#8230;. &#8230;.</font></td>
</tr>
</tbody>
</table>
</li>
<li>Command line, command buttons, or shortcut keys to follow the debugging process.<br />
<table cellspacing="0" cellpadding="0" width="560" border="1">
<tbody>
<tr>
<td align="center">Command</td>
<td align="center">SoftICE</td>
<td align="center">OllyDbg</td>
</tr>
<tr>
<td align="center">Run</td>
<td align="center">F5</td>
<td align="center">F9</td>
</tr>
<tr>
<td align="center">Step Into</td>
<td align="center">F11</td>
<td align="center">F7</td>
</tr>
<tr>
<td align="center">Step Over</td>
<td align="center">F10</td>
<td align="center">F8</td>
</tr>
<tr>
<td align="center">Set Break Point</td>
<td align="center">F8</td>
<td align="center">F2</td>
</tr>
</tbody>
</table>
</li>
</ol>
<p>You can compare Figures 1 and 2 to distinguish the difference between SoftICE and OllyDbg. When you want to trace a PE file, you should mostly consider these five subdivisions. Furthermore, every debugger comprises of some other useful parts; you should discover them by yourself.</p>
<h4>3.2 Disassembler</h4>
<p>You can consider OllyDbg and SoftICE to be excellent disassemblers, but I also want to introduce another disassembler tool that is famous in the reverse engineering world.</p>
<h5>3.2.1 Proview disassembler</h5>
<p><a href="http://community.reverse-engineering.net/viewforum.php?f=50&amp;sid=a77c210bc1030dd395452bb7e1f67439" target="new">Proview</a> or <a href="http://pvdasm.reverse-engineering.net/" target="new">PVDasm</a> is an admirable disassembler by the <a href="http://community.reverse-engineering.net/" target="new">Reverse-Engineering-Community</a>; it is still under development and bug fixing. You can find its disassmbler source engine and employ it to create your own disassembler.</p>
<h5>3.2.2 W32Dasm</h5>
<p><a href="http://www.softpedia.com/get/Programming/Debuggers-Decompilers-Dissasemblers/WDASM.shtml" target="new">W32DASM</a> can disassemble both 16- and 32-bit executable file formats. In addition to its disassembling ability, you can employ it to analyze import, export, and resource data directories data.</p>
<h5>3.2.3 IDA Pro</h5>
<p>All reverse-engineering experts know that <a href="http://www.datarescue.com/idabase/idaproc.htm" target="new">IDA Pro</a> can be used to investigate, not only x86 instructions, but that of various kinds of CPU types like AVR, PIC, and so forth. It can illustrate the assembly source of a portable executable file by using colored graphics and tables, and is very useful for any newbie in this area. Furthermore, it has the capability to trace an executable file inside the user mode level in the same way as OllyDbg.</p>
<h4>3.3 Some Useful Tools</h4>
<p>A good PE tools developer is conversant with the tools that save his time, so I recommend that you select some appropriate instruments to investigate the base information under a portable executable file.</p>
<h5>3.3.1 LordPE</h5>
<p><a href="http://www.softpedia.com/get/Programming/File-Editors/LordPE.shtml" target="new">LordPE</a> by <a href="http://scifi.pages.at/yoda9k/aboutme.htm" target="new">y0da</a> is still the first choice to retrieve PE file information with the possibility to modify them.</p>
<p><img height="206" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=LORDPE_GIF&amp;ds=20060302" width="441" alt="" /></p>
<h5>3.3.2 PEiD</h5>
<p><a href="http://peid.has.it/" target="new">PE iDentifier</a> is valuable to identify the type of compilers, packers, and cryptors of PE files. As of now, it can detect more than 500 different signature types of PE files.</p>
<p><img height="166" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=PEID_GIF&amp;ds=20060302" width="296" alt="" /></p>
<h5>3.3.3 Resource Hacker</h5>
<p><a href="http://www.angusj.com/resourcehacker/" target="new">Resource Hacker </a>can be employed to modify resource directory information; icon, menu, version info, string table, and so on.</p>
<p><img height="141" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=RESOURCEHACKER_GIF&amp;ds=20060302" width="191" alt="" /></p>
<h5>3.3.4 WinHex</h5>
<p><a href="http://www.winhex.com/winhex/index-m.html" target="new">WinHex</a>, it is clear what you can do with this tool.</p>
<p><img height="230" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=WINHEX_GIF&amp;ds=20060302" width="329" alt="" /></p>
<h5>3.3.5 CFF Explorer</h5>
<p>Eventually, <a href="http://www.pmode.net/CFF.php" target="new">CFF Explorer </a>by <a href="http://www.pmode.net/USERS/116/UserInfo.xml" target="new">Ntoskrnl </a>is what you want to have as a PE Utility tool in your arsenal; it supports PE32/64, PE rebuild included <a href="http://en.wikipedia.org/wiki/Common_Language_Infrastructure" target="new">Common Language Infrastructure (CLI)</a> file. In other words, the <a href="http://en.wikipedia.org/wiki/Microsoft_.NET" target="new">.NET file</a>, a resource modifier, and much more facilities which can not be found in others. Just try to discover every unimaginable option by hand.</p>
<p><img height="217" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=CFFEXPLORER_GIF&amp;ds=20060302" width="301" alt="" /></p>
<h3>4 Add a New Section and Change the OEP</h3>
<p>You are ready to do the first step of making your project. I have provided a library to add a new section and rebuild the portable executable file. Before starting, I wnat you to get familiar with the headers of a PE file, by using <a href="http://www.ollydbg.de/" target="new">OllyDbg</a>. You should first open a PE file; that pops up a menu, <strong>View-&gt;Executable file</strong>. Again, you get a popup menu: <strong>Special-&gt;PE header</strong>. You will observe a scene similar to Figure 3. Now, come to the Main Menu <strong>View-&gt;Memory</strong>, and try to distinguish the sections inside the <strong>Memory map</strong> window.</p>
<h4>Figure 3</h4>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td><font color="#808080">
<pre>00000000000000020000000400000006000000080000000A0000000C0000000E00000010000000120000001400000016000000180000001A0000001C0000001D0000001E0000001F000000200000002100000022000000230000002400000025000000260000002700000028000000290000002A0000002B0000002C0000002D0000002E0000002F000000300000003100000032000000330000003400000035000000360000003700000038000000390000003A0000003B0000003C</pre>
<p>                </font></td>
<td>
<pre> 4D 5A 9000 0300 0000 0400 0000 FFFF 0000 B800 0000 0000 0000 4000 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F0000000</pre>
</td>
<td>
<pre> ASCII <font color="#008000">&quot;MZ&quot;</font> DW 0090 DW 0003 DW 0000 DW 0004 DW 0000 DW FFFF DW 0000 DW 00B8 DW 0000 DW 0000 DW 0000 DW 0040 DW 0000 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DD <font color="#ff0000">000000F0</font></pre>
</td>
<td>
<pre> DOS EXE Signature DOS_PartPag = 90 (144.) DOS_PageCnt = 3 DOS_ReloCnt = 0 DOS_HdrSize = 4 DOS_MinMem = 0 DOS_MaxMem = FFFF (65535.) DOS_ReloSS = 0 DOS_ExeSP = B8 DOS_ChkSum = 0 DOS_ExeIP = 0 DOS_ReloCS = 0 DOS_TablOff = 40 DOS_Overlay = 0 Offset to PE signature</pre>
</td>
</tr>
</tbody>
</table>
<p>    <a name="more"><font color="#000000">&nbsp;</font>
<p>I want to explain how you can plainly change the Offset of Entry Point (OEP) in your sample file, <em>CALC.EXE</em> of Windows XP. First, by using a PE Tool, and also using your PE Viewer, you find OEP, <tt>0x00012475</tt>, and Image Base, <tt>0x01000000</tt>. This value of OEP is the Relative Virtual Address, so the Image Base value is used to convert it to the Virtual Address.</p>
<table cellspacing="0" cellpadding="0" width="450" border="1">
<tbody>
<tr>
<td>
<p><strong>Virtual_Address = Image_Base + Relative_Virtual_Address</strong></p>
</td>
</tr>
</tbody>
</table>
<pre>DWORD OEP_RVA = image_nt_headers-&gt;   OptionalHeader.AddressOfEntryPoint ;<span class="codeComment">// OEP_RVA = 0x00012475</span>DWORD OEP_VA = image_nt_headers-&gt;   OptionalHeader.ImageBase + OEP_RVA ;<span class="codeComment">// OEP_VA = 0x01000000 + 0x00012475 = 0x01012475</span></pre>
<h4>PE Maker: Step 1</h4>
<p>Download pemaker1.zip and test1.zip from the files at the end of this article.</p>
<p><tt>DynLoader()</tt>, in <em>loader.cpp</em>, is reserved for the data of the new section&mdash;in other words, the <strong>Loader</strong>.</p>
<h4>DynLoader Step 1</h4>
<pre><span class="codeKeyword">__stdcall</span> <span class="codeKeyword">void</span> DynLoader(){_asm{<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_MAGIC)<span class="codeComment">//----------------------------------</span>    MOV EAX,01012475h <span class="codeComment">// &lt;&lt; Original OEP</span>    JMP EAX<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_END_MAGIC)<span class="codeComment">//----------------------------------</span>}}</pre>
<p>Unfortunately, this source can only be applied for the sample test file. You should complete it by saving the value of the original OEP in the new section, and use it to reach the real OEP. I have accomplished it in Step 2 (Section 5).</p>
<h4>4.1 Retrieve and Rebuild PE file</h4>
<p>I have made a simple class library to recover PE information and to use it in a new PE file.</p>
<h4>CPELibrary Class Step 1</h4>
<pre><span class="codeComment">//----------------------------------------------------------------</span><span class="codeKeyword">class</span> CPELibrary{<span class="codeKeyword">private</span>:    <span class="codeComment">//-----------------------------------------</span>    PCHAR                   pMem;    DWORD                   dwFileSize;    <span class="codeComment">//-----------------------------------------</span><span class="codeKeyword">protected</span>:    <span class="codeComment">//-----------------------------------------</span>    PIMAGE_DOS_HEADER       image_dos_header;    PCHAR                   pDosStub;    DWORD                   dwDosStubSize, dwDosStubOffset;    PIMAGE_NT_HEADERS       image_nt_headers;    PIMAGE_SECTION_HEADER   image_section_header[MAX_SECTION_NUM];    PCHAR                   image_section[MAX_SECTION_NUM];    <span class="codeComment">//-----------------------------------------</span><span class="codeKeyword">protected</span>:    <span class="codeComment">//-----------------------------------------</span>    DWORD PEAlign(DWORD dwTarNum,DWORD dwAlignTo);    <span class="codeKeyword">void</span> AlignmentSections();    <span class="codeComment">//-----------------------------------------</span>    DWORD Offset2RVA(DWORD dwRO);    DWORD RVA2Offset(DWORD dwRVA);    <span class="codeComment">//-----------------------------------------</span>    PIMAGE_SECTION_HEADER ImageRVA2Section(DWORD dwRVA);    PIMAGE_SECTION_HEADER ImageOffset2Section(DWORD dwRO);    <span class="codeComment">//-----------------------------------------</span>    DWORD ImageOffset2SectionNum(DWORD dwRVA);    PIMAGE_SECTION_HEADER AddNewSection(<span class="codeKeyword">char</span>* szName,DWORD dwSize);    <span class="codeComment">//-----------------------------------------</span><span class="codeKeyword">public</span>:    <span class="codeComment">//-----------------------------------------</span>    CPELibrary();    ~CPELibrary();    <span class="codeComment">//-----------------------------------------</span>    <span class="codeKeyword">void</span> OpenFile(<span class="codeKeyword">char</span>* FileName);    <span class="codeKeyword">void</span> SaveFile(<span class="codeKeyword">char</span>* FileName);    <span class="codeComment">//-----------------------------------------</span>};</pre>
<p>In Table 1, the usage of <tt>image_dos_header</tt>, <tt>pDosStub</tt>, <tt>image_nt_headers</tt>, <tt>image_section_header</tt> [<tt>MAX_SECTION_NUM</tt>], and <tt>image_section</tt>[<tt>MAX_SECTION_NUM</tt>] is clear. You use <tt>OpenFile()</tt> and <tt>SaveFile()</tt> to retrieve and rebuild a PE file. Furthermore, <tt>AddNewSection()</tt> is employed to create the new section, the important step.</p>
<p>    </a><br />
<h4>4.2 Create data for the new section</h4>
<p><a name="more"><font color="#000000"> </font></a><a href="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=LINKTIP1_GIF&amp;ds=20060302" target="_blank">Full Size Image</a>)
<p>You can comprehend the difference between incremental link and no-incremental link by looking at the following picture:</p>
<p>    <img height="130" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=INCREMENTAL_LINK_GIF&amp;ds=20060302" width="415" alt="" />
<p>To acquire the virtual address of <tt>DynLoader()</tt>, you obtain the virtual address of <tt>JMP pemaker.DynLoader</tt> in the incremental link, but by no-incremental link, the real virtual address is gained by the following code:</p>
<pre>DWORD dwVA= (DWORD) DynLoader;</pre>
<p>This setting is more critical in the incremental link when you try to find the beginning and ending of the <strong>Loader</strong>, <tt>DynLoader()</tt>, by <tt>CPECryptor::ReturnToBytePtr()</tt>:</p>
<pre><span class="codeKeyword">void</span>* CPECryptor::ReturnToBytePtr(<span class="codeKeyword">void</span>* FuncName, DWORD findstr){    <span class="codeKeyword">void</span>* tmpd;    __asm   {        mov eax, FuncName        jmp dfhjg:    inc eaxdf:     mov ebx, [eax]        cmp ebx, findstr        jnz hjg        mov tmpd, eax    }    <span class="codeKeyword">return</span> tmpd;}</pre>
</p>
<p>In <em>pecrypt.cpp</em>, I have represented another class, <tt>CPECryptor</tt>, to comprise the data of the new section. Nevertheless, the data of the new section is created by <tt>DynLoader()</tt> in <em>loader.cpp</em>, DynLoader Step 1. You use the <tt>CPECryptor</tt> class to enter this data in to the new section, and also some other stuff.</p>
<h4>CPECryptor Class Step 1</h4>
<pre><span class="codeComment">//----------------------------------------------------------------</span><span class="codeKeyword">class</span> CPECryptor: <span class="codeKeyword">public</span> CPELibrary{<span class="codeKeyword">private</span>:    <span class="codeComment">//----------------------------------------</span>    PCHAR pNewSection;    <span class="codeComment">//----------------------------------------</span>    DWORD GetFunctionVA(<span class="codeKeyword">void</span>* FuncName);    <span class="codeKeyword">void</span>* ReturnToBytePtr(<span class="codeKeyword">void</span>* FuncName, DWORD findstr);    <span class="codeComment">//----------------------------------------</span><span class="codeKeyword">protected</span>:    <span class="codeComment">//----------------------------------------</span><span class="codeKeyword">public</span>:    <span class="codeComment">//----------------------------------------</span>    <span class="codeKeyword">void</span> CryptFile(<span class="codeKeyword">int</span>(__cdecl *callback) (<span class="codeKeyword">unsigned</span> <span class="codeKeyword">int</span>,                                           <span class="codeKeyword">unsigned</span> <span class="codeKeyword">int</span>));    <span class="codeComment">//----------------------------------------</span>};<span class="codeComment">//----------------------------------------------------------------</span></pre>
<h4>4.3 Some notes regarding creating a new PE file</h4>
<ul>
<li>Align the <tt>VirtualAddress</tt> and the <tt>VirtualSize</tt> of each section by <tt>SectionAlignment</tt>:
<pre>image_section_header[i]-&gt;VirtualAddress=    PEAlign(image_section_header[i]-&gt;VirtualAddress,    image_nt_headers-&gt;OptionalHeader.SectionAlignment);image_section_header[i]-&gt;Misc.VirtualSize=    PEAlign(image_section_header[i]-&gt;Misc.VirtualSize,    image_nt_headers-&gt;OptionalHeader.SectionAlignment);</pre>
</li>
<li>Align the <tt>PointerToRawData</tt> and the <tt>SizeOfRawData</tt> of each section by <tt>FileAlignment</tt>:
<pre>image_section_header[i]-&gt;PointerToRawData =    PEAlign(image_section_header[i]-&gt;PointerToRawData,            image_nt_headers-&gt;OptionalHeader.FileAlignment);image_section_header[i]-&gt;SizeOfRawData =    PEAlign(image_section_header[i]-&gt;SizeOfRawData,            image_nt_headers-&gt;OptionalHeader.FileAlignment);</pre>
</li>
<li>Correct the <tt>SizeofImage</tt> by the virtual size and the virtual address of the last section:
<pre>image_nt_headers-&gt;OptionalHeader.SizeOfImage =   image_section_header[LastSection]-&gt;VirtualAddress +   image_section_header[LastSection]-&gt;Misc.VirtualSize;</pre>
</li>
<li>Set the Bound Import Directory header to zero because this directory is not very important to execute a PE file:
<pre>image_nt_headers-&gt;   OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].  VirtualAddress = 0;image_nt_headers-&gt;   OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_                                IMPORT].Size = 0;</pre>
</li>
</ul>
<h4>4.4 Some notes regarding linking this VC Project</h4>
<ul>
<li>Set <em>Linker-&gt;General-&gt;Enable Incremental Linking</em> to <strong>No (/INCREMENTAL:NO)</strong>.</p>
<p>        <img height="125" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=LINKTIP1_GIF&amp;ds=20060302" width="500" alt="" /><br />        (</li>
</ul>
<h3>5 Store Important Data and Reach the Original OEP</h3>
<p>Right now, we save the Original OEP and also the Image Base in order to reach to the virtual address of OEP. I have reserved a free space at the end of <tt>DynLoader()</tt> to store them, DynLoader Step 2.</p>
<h4>PE Maker &#8211; Step 2</h4>
<p>Download the pemaker2.zip source files from the end of the article.</p>
<h4>DynLoader Step 2</h4>
<pre><span class="codeKeyword">__stdcall</span> <span class="codeKeyword">void</span> DynLoader(){_asm{<span class="codeComment">//------------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_MAGIC)<span class="codeComment">//------------------------------------</span>Main_0:    PUSHAD    <span class="codeComment">// get base ebp</span>    CALL Main_1Main_1:    POP EBP    SUB EBP,OFFSET Main_1    MOV EAX,DWORD PTR [EBP+_RO_dwImageBase]    ADD EAX,DWORD PTR [EBP+_RO_dwOrgEntryPoint]    PUSH EAX    RETN <span class="codeComment">// &gt;&gt; JMP to Original OEP</span><span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_DATA1)<span class="codeComment">//----------------------------------<font color="#ff0000"></font><span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_END_MAGIC)<span class="codeComment">//----------------------------------</span>}}</span>_RO_dwImageBase:                DWORD_TYPE(0xCCCCCCCC)_RO_dwOrgEntryPoint:            DWORD_TYPE(0xCCCCCCCC)</pre>
<p>The new function, <tt>CPECryptor::CopyData1()</tt>, will implement the copy of the Image Base value and the Offset of Entry Point value into 8 bytes of free space in the loader.</p>
<h4>5.1 Restore the first register&#8217;s context</h4>
<p>It is important to recover the Original Context of the thread. You have not yet done it in the DynLoader Step 2 source code. You can modify the source of <tt>DynLoader()</tt> to repossess the first Context.</p>
<pre><span class="codeKeyword">__stdcall</span> <span class="codeKeyword">void</span> DynLoader(){_asm{<span class="codeComment">//------------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_MAGIC)<span class="codeComment">//------------------------------------</span>Main_0:    <font color="#ff0000">PUSHAD<span class="codeComment">// Save the registers context in stack</span>    CALL Main_1Main_1:    POP EBP<span class="codeComment">// Get Base EBP</span>    SUB EBP,OFFSET Main_1    MOV EAX,DWORD PTR [EBP+_RO_dwImageBase]    ADD EAX,DWORD PTR [EBP+_RO_dwOrgEntryPoint]    MOV DWORD PTR [ESP+1Ch],EAX <span class="codeComment">// pStack.Eax &lt;- EAX</span>    <font color="#ff0000">POPAD <span class="codeComment">// Restore the first registers context from stack</span>    PUSH EAX    XOR  EAX, EAX    RETN <span class="codeComment">// &gt;&gt; JMP to Original OEP</span><span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_DATA1)<span class="codeComment">//----------------------------------</span>_RO_dwImageBase:                DWORD_TYPE(0xCCCCCCCC)_RO_dwOrgEntryPoint:            DWORD_TYPE(0xCCCCCCCC)<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_END_MAGIC)<span class="codeComment">//----------------------------------</span>}}</font></font></pre>
<h4>5.2 Restore the original stack</h4>
<p>You also can recover the original stack by setting the value of the beginning stack + <tt>0x34</tt> to the Original OEP, but it is not very important. Nevertheless, in the following code, I have accomplished the loader code by a simple trick to reach the OEP in addition to redecorating the stack. You can observe the implementation by tracing using <a href="http://www.ollydbg.de/" target="new">OllyDbg</a> or SoftICE.</p>
<pre><span class="codeKeyword">__stdcall</span> <span class="codeKeyword">void</span> DynLoader(){_asm{<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_MAGIC)<span class="codeComment">//----------------------------------</span>Main_0:    PUSHAD    <span class="codeComment">// Save the registers context in stack</span>    CALL Main_1Main_1:    POP EBP    SUB EBP,OFFSET Main_1    MOV EAX,DWORD PTR [EBP+_RO_dwImageBase]    ADD EAX,DWORD PTR [EBP+_RO_dwOrgEntryPoint]    MOV DWORD PTR [ESP+54h],EAX    <span class="codeComment">// pStack.Eip &lt;- EAX</span>    POPAD    <span class="codeComment">// Restore the first registers context from stack</span>    CALL _OEP_Jump    DWORD_TYPE(0xCCCCCCCC)_OEP_Jump:    PUSH EBP    MOV EBP,ESP    MOV EAX,DWORD PTR [ESP+3Ch]    <span class="codeComment">// EAX &lt;- pStack.Eip</span>    MOV DWORD PTR [ESP+4h],EAX     <span class="codeComment">// _OEP_Jump RETURN pointer &lt;- EAX</span>    XOR EAX,EAX    LEAVE    RETN<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_DATA1)<span class="codeComment">//----------------------------------</span>_RO_dwImageBase:                DWORD_TYPE(0xCCCCCCCC)_RO_dwOrgEntryPoint:            DWORD_TYPE(0xCCCCCCCC)<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_END_MAGIC)<span class="codeComment">//----------------------------------</span>}}</pre>
<h4>5.3 Approach OEP by structured exception handling</h4>
<p><a name="more"><font color="#000000"> </font></a><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/key_s-z_4.asp" target="new"><tt>try-except</tt> statement</a> in C++ clarifies the operation of <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/about_structured_exception_handling.asp" target="new">structured exception handling</a>. Besides the assembly code of this code, it elucidates the structured exception handler installation, the raise of an exception, and the exception handler function.</p>
<p>An exception is generated when a program falls into a fault code execution and an error happens, so in such a special condition, the program immediately jumps to a function called the exception handler from exception handler list of the Thread Information Block.</p>
<p>The next example of a </p>
<pre><span class="codeKeyword">#include</span> &quot;stdafx.h&quot;<span class="codeKeyword">#include</span> &quot;windows.h&quot;<span class="codeKeyword">void</span> RAISE_AN_EXCEPTION(){_asm{    INT 3    INT 3    INT 3    INT 3}}<span class="codeKeyword">int</span> _tmain(<span class="codeKeyword">int</span> argc, _TCHAR* argv[]){    <span class="codeKeyword">__try</span>    {        <span class="codeKeyword">__try</span>{            printf(&quot;1: Raise an Exception\n&quot;);            RAISE_AN_EXCEPTION();        }        <span class="codeKeyword">__finally</span>        {            printf(&quot;2: In Finally\n&quot;);        }    }    <span class="codeKeyword">__except</span>( printf(&quot;3: In Filter\n&quot;), EXCEPTION_EXECUTE_HANDLER )    {        printf(&quot;4: In Exception Handler\n&quot;);    }    <span class="codeKeyword">return</span> 0;}</pre>
<pre><font color="#000000"><strong>; main()</strong></font><font color="#808080">00401000: PUSH EBP00401001: MOV EBP,ESP00401003: PUSH -100401005: PUSH 00407160<font color="#000000"><strong>; <span class="codeKeyword">__try</span> {</strong></font><font color="#008000">; the structured exception handler (SEH) installation </font><font color="#0000ff">0040100A: PUSH _except_handler30040100F: MOV EAX,DWORD PTR FS:[0]00401015: PUSH EAX00401016: MOV DWORD PTR FS:[0],ESP</font>0040101D: SUB ESP,800401020: PUSH EBX00401021: PUSH ESI00401022: PUSH EDI00401023: MOV DWORD PTR SS:[EBP-18],ESP<font color="#000000"><strong>;     <span class="codeKeyword">__try</span> {</strong></font>00401026: XOR ESI,ESI00401028: MOV DWORD PTR SS:[EBP-4],ESI0040102B: MOV DWORD PTR SS:[EBP-4],100401032: PUSH OFFSET <font color="#a52a2a">&quot;1: Raise an Exception&quot;</font>00401037: CALL printf0040103C: ADD ESP,4<font color="#008000">; the raise a exception, INT 3 exception</font>; RAISE_AN_EXCEPTION()<font color="#0000ff">0040103F: INT300401040: INT300401041: INT300401042: INT3</font><font color="#000000"><strong>;     } <span class="codeKeyword">__finally</span> {</strong></font>00401043: MOV DWORD PTR SS:[EBP-4],ESI00401046: CALL 0040104D0040104B: JMP 004010800040104D: PUSH OFFSET <font color="#a52a2a">&quot;2: In Finally&quot;</font>00401052: CALL printf00401057: ADD ESP,40040105A: RETN<font color="#000000"><strong>;     }</strong></font><font color="#000000"><strong>; }</strong></font><font color="#000000"><strong>; <span class="codeKeyword">__except</span>( </strong></font>0040105B: JMP 004010800040105D: PUSH OFFSET <font color="#a52a2a">&quot;3: In Filter&quot;</font>00401062: CALL printf00401067: ADD ESP,40040106A: MOV EAX,1 ; EXCEPTION_EXECUTE_HANDLER = 10040106F: RETN<font color="#000000"><strong>;     , EXCEPTION_EXECUTE_HANDLER )</strong></font><font color="#000000"><strong>; {</strong></font><font color="#008000">; the exception handler funtion</font><font color="#0000ff">00401070: MOV ESP,DWORD PTR SS:[EBP-18]00401073: PUSH OFFSET <font color="#a52a2a">&quot;4: In Exception Handler&quot;</font>00401078: CALL printf0040107D: ADD ESP,4</font><font color="#000000"><strong>; }</strong></font>00401080: MOV DWORD PTR SS:[EBP-4],-10040108C: XOR EAX,EAX<font color="#008000">; restore previous SEH</font><font color="#0000ff">0040108E: MOV ECX,DWORD PTR SS:[EBP-10]00401091: MOV DWORD PTR FS:[0],ECX</font>00401098: POP EDI00401099: POP ESI0040109A: POP EBX0040109B: MOV ESP,EBP0040109D: POP EBP0040109E: RETN</font></pre>
<p>Make a Win32 console project, and link and run the preceding C++ code, to perceive the result:</p>
<p>
<table cellspacing="0" cellpadding="0" width="400" border="1">
<tbody bgcolor="#000000" color="gray">
<tr>
<td><font color="#ffffff"><strong>1: Raise an Exception<br />                3: In Filter<br />                2: In Finally<br />                4: In Exception Handler<br />                _</p>
<p>                </strong></font></td>
</tr>
</tbody>
</table>
<p>This program runs the exception expression, <tt>printf(&quot;3: In Filter\n&quot;);</tt>, when an exception happens&mdash;in this example, the <tt>INT 3</tt> exception. You can employ other kinds of exception too. In <a href="http://www.ollydbg.de/" target="new">OllyDbg</a>, <strong>Debugging options-&gt;Exceptions</strong>, you can see a short list of different types of exceptions.</p>
<p><img height="200" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=OLLYDBG_EXCEPTIONS_GIF&amp;ds=20060302" width="280" alt="" /></p>
<h5>5.3.1 Implement Exception Handler</h5>
<p>You want to construct a structured exception handler to reach OEP. Now, I think you have distinguished the SEH installation, the exception raise, and the exception expression filter, by foregoing the assembly code. To establish your exception handler approach, you need to comprise the following codes:</p>
<ul>
<li><strong>SEH installation</strong>:
<pre><font color="#808080">LEA EAX,[EBP+_except_handler1_OEP_Jump]PUSH EAXPUSH DWORD PTR FS:[0]MOV DWORD PTR FS:[0],ESP</font></pre>
</li>
<li><strong>An Exception Raise</strong>:
<pre><font color="#808080">INT 3</font></pre>
</li>
<li><strong>Exception handler expression filter</strong>:
<pre><font color="#808080">_except_handler1_OEP_Jump:   PUSH EBP   MOV EBP,ESP   ...   <span class="codeComment">// EXCEPTION_CONTINUE_SEARCH = 0</span>   MOV EAX, EXCEPTION_CONTINUE_SEARCH   LEAVE   RETN</font></pre>
</li>
</ul>
<p>So, you yearn to make the ensuing C++ code in assembly language to inaugurate your engine to approach the Offset of the Entry Point by SEH.</p>
<pre><span class="codeKeyword">__try</span>    <span class="codeComment">// SEH installation</span>{    __asm    {        INT 3    <span class="codeComment">// An Exception Raise</span>    }}<span class="codeKeyword">__except</span>( ..., EXCEPTION_CONTINUE_SEARCH ){}<span class="codeComment">// Exception handler expression filter</span></pre>
<p>In assembly code&#8230;</p>
<pre><font color="#808080">    <font color="#008000">; ----------------------------------------------------    ; the structured exception handler (SEH) installation    <font color="#000000"><strong>; <span class="codeKeyword">__try</span> {</strong></font></font>    LEA EAX,[EBP+_except_handler1_OEP_Jump]    PUSH EAX    PUSH DWORD PTR FS:[0]    MOV DWORD PTR FS:[0],ESP    <font color="#008000">; ----------------------------------------------------    ; the raise a INT 3 exception</font>    INT 3    INT 3    INT 3    INT 3    <font color="#000000"><strong>; }    ; <span class="codeKeyword">__except</span>( ... </strong></font>    <font color="#008000">; ----------------------------------------------------    ; exception handler expression filter</font>_except_handler1_OEP_Jump:    PUSH EBP    MOV EBP,ESP    ...    MOV EAX, EXCEPTION_CONTINUE_SEARCH ; EXCEPTION_CONTINUE_SEARCH = 0    LEAVE    RETN    <font color="#000000"><strong>; , EXCEPTION_CONTINUE_SEARCH ) { }</strong></font></font></pre>
<p>The exception value, <tt>__except(..., Value)</tt>, determines how the exception is handled. It can have three values: 1, 0, -1. To understand them, refer to the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/key_s-z_4.asp" target="new"><tt>try-except</tt> statement</a> description in the MSDN library. You set it to <tt>EXCEPTION_CONTINUE_SEARCH (0)</tt>, not to run the exception handler function; therefore, by this value, the exception is not recognized. It is simply ignored, and the thread continues its code execution.</p>
<h4>How the SEH installation is implemented</h4>
<p>As you perceived from the illustrated code, the SEH installation is done by the FS segment register. Microsoft Windows 32 bit uses the FS segment register as a pointer to the data block of the main thread. The first <font color="#0000ff">0x1C</font> bytes comprise the information of the Thread Information Block (TIB). Therefore, <tt>FS:[00h]</tt> refers to <tt>ExceptionList</tt> of the main thread, Table 3. In your code, you have pushed the pointer to <tt>_except_handler1_OEP_Jump</tt> in the stack and changed the value of <tt>ExceptionList</tt>, <tt>FS:[00h]</tt>, to the beginning of the stack, <tt>ESP</tt>.</p>
<h4>Thread Information Block (TIB)</h4>
<pre><span class="codeKeyword">typedef</span> <span class="codeKeyword">struct</span> _NT_TIB32 {   DWORD ExceptionList;   DWORD StackBase;   DWORD StackLimit;   DWORD SubSystemTib;   <span class="codeKeyword">union</span> {      DWORD FiberData;      DWORD Version;   };   DWORD ArbitraryUserPointer;   DWORD Self;} NT_TIB32, *PNT_TIB32;</pre>
<h4>Table 3: FS segment register and Thread Information Block</h4>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td align="center"><font color="#0000ff">DWORD PTR FS:[00h]</font></td>
<td align="center">ExceptionList</td>
</tr>
<tr>
<td align="center"><font color="#0000ff">DWORD PTR FS:[04h]</font></td>
<td align="center">StackBase</td>
</tr>
<tr>
<td align="center"><font color="#0000ff">DWORD PTR FS:[08h]</font></td>
<td align="center">StackLimit</td>
</tr>
<tr>
<td align="center"><font color="#0000ff">DWORD PTR FS:[0Ch]</font></td>
<td align="center">SubSystemTib</td>
</tr>
<tr>
<td align="center"><font color="#0000ff">DWORD PTR FS:[10h]</font></td>
<td align="center">FiberData / Version</td>
</tr>
<tr>
<td align="center"><font color="#0000ff">DWORD PTR FS:[14h]</font></td>
<td align="center">ArbitraryUserPointer</td>
</tr>
<tr>
<td align="center"><font color="#0000ff">DWORD PTR FS:[18h]</font></td>
<td align="center">Self</td>
</tr>
</tbody>
</table>
<h5>5.3.2 Attain OEP by adjusting the Thread Context</h5>
<p>In this part, you effectuate your performance by accomplishing the OEP approach. You change the Context of the thread and ignore every simple exception handling, and let the thread continue the execution, but in the original OEP!</p>
<p>    <a name="more"><font color="#000000">&nbsp;</font>
<p>When an exception happens, the context of the processor during the time of the exception is saved in the stack. Through </p>
<pre>MOV EAX, ContextRecordMOV EDI, dwOEP                   ; EAX &lt;- dwOEPMOV DWORD PTR DS:[EAX+0B8h], EDI ; pContext.Eip &lt;- EAX</pre>
<h4>Win32 Thread Context structure</h4>
<pre><span class="codeKeyword">#define</span> MAXIMUM_SUPPORTED_EXTENSION     512<span class="codeKeyword">typedef</span> <span class="codeKeyword">struct</span> _CONTEXT {    <span class="codeComment">//-----------------------------------------</span>    DWORD ContextFlags;    <span class="codeComment">//-----------------------------------------</span>    DWORD   Dr0;    DWORD   Dr1;    DWORD   Dr2;    DWORD   Dr3;    DWORD   Dr6;    DWORD   Dr7;    <span class="codeComment">//-----------------------------------------</span>    FLOATING_SAVE_AREA FloatSave;    <span class="codeComment">//-----------------------------------------</span>    DWORD   SegGs;    DWORD   SegFs;    DWORD   SegEs;    DWORD   SegDs;    <span class="codeComment">//-----------------------------------------</span>    DWORD   Edi;    DWORD   Esi;    DWORD   Ebx;    DWORD   Edx;    DWORD   Ecx;    DWORD   Eax;    <span class="codeComment">//-----------------------------------------</span>    DWORD   Ebp;    DWORD   Eip;    DWORD   SegCs;    DWORD   EFlags;    DWORD   Esp;    DWORD   SegSs;    <span class="codeComment">//-----------------------------------------</span>    BYTE    ExtendedRegisters[MAXIMUM_SUPPORTED_EXTENSION];    <span class="codeComment">//----------------------------------------</span>} CONTEXT,*LPCONTEXT;</pre>
<h4>Table 4: CONTEXT</h4>
<table cellspacing="0" cellpadding="0" width="200" border="1">
<tbody>
<tr>
<td align="center" height="35">Context Flags</td>
<td align="center" height="35"><font color="#0000ff">0&#215;00000000</font></td>
<td align="center" colspan="2" height="35"><tt>ContextFlags</tt></td>
</tr>
<tr>
<td align="center" rowspan="6">
<p>Context Debug Registers</p>
</td>
<td align="center"><font color="#0000ff">0&#215;00000004</font></td>
<td align="center" colspan="2"><tt>Dr0</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000008</font></td>
<td align="center" colspan="2"><tt>Dr1</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x0000000C</font></td>
<td align="center" colspan="2"><tt>Dr2</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000010</font></td>
<td align="center" colspan="2"><tt>Dr3</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000014</font></td>
<td align="center" colspan="2"><tt>Dr6</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000018</font></td>
<td align="center" colspan="2"><tt>Dr7</tt></td>
</tr>
<tr>
<td align="center" rowspan="9">
<p>Context Floating Point</p>
</td>
<td align="center"><font color="#0000ff">0x0000001C</font></td>
<td align="center" rowspan="9"><tt>FloatSave</tt></td>
<td align="center"><tt>StatusWord</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000020</font></td>
<td align="center"><tt>StatusWord</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000024</font></td>
<td align="center"><tt>TagWord</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000028</font></td>
<td align="center"><tt>ErrorOffset</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x0000002C</font></td>
<td align="center"><tt>ErrorSelector</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000030</font></td>
<td align="center"><tt>DataOffset</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000034</font></td>
<td align="center"><tt>DataSelector</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000038<br />                &#8230;<br />                0&#215;00000087</font></td>
<td align="center"><tt>RegisterArea</tt> [<font color="#0000ff">0x50</font>]</td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000088</font></td>
<td align="center"><tt>Cr0NpxState</tt></td>
</tr>
<tr>
<td align="center" rowspan="4">Context Segments</td>
<td align="center"><font color="#0000ff">0x0000008C</font></td>
<td align="center" colspan="2"><tt>SegGs</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000090</font></td>
<td align="center" colspan="2"><tt>SegFs</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000094</font></td>
<td align="center" colspan="2"><tt>SegEs</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0&#215;00000098</font></td>
<td align="center" colspan="2"><tt>SegDs</tt></td>
</tr>
<tr>
<td align="center" rowspan="6">Context Integer</td>
<td align="center"><font color="#0000ff">0x0000009C</font></td>
<td align="center" colspan="2"><tt>Edi</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000A0</font></td>
<td align="center" colspan="2"><tt>Esi</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000A4</font></td>
<td align="center" colspan="2"><tt>Ebx</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000A8</font></td>
<td align="center" colspan="2"><tt>Edx</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000AC</font></td>
<td align="center" colspan="2"><tt>Ecx</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000B0</font></td>
<td align="center" colspan="2"><tt>Eax</tt></td>
</tr>
<tr>
<td align="center" rowspan="6">Context Control</td>
<td align="center"><font color="#0000ff">0x000000B4</font></td>
<td align="center" colspan="2"><tt>Ebp</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000B8</font></td>
<td align="center" colspan="2"><tt>Eip</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000BC</font></td>
<td align="center" colspan="2"><tt>SegCs</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000C0</font></td>
<td align="center" colspan="2"><tt>EFlags</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000C4</font></td>
<td align="center" colspan="2"><tt>Esp</tt></td>
</tr>
<tr>
<td align="center"><font color="#0000ff">0x000000C8</font></td>
<td align="center" colspan="2"><tt>SegSs</tt></td>
</tr>
<tr>
<td align="center">Context Extended Registers</td>
<td align="center">
<p align="center"><font color="#0000ff">0x000000CC<br />                &#8230;<br />                0x000002CB</font></p>
</td>
<td align="center" colspan="2"><tt>ExtendedRegisters</tt>[<font color="#0000ff">0x200</font>]</td>
</tr>
</tbody>
</table>
<p>By the following code, you have accomplished the main purpose of coming to OEP by the structured exception handler:</p>
<pre><span class="codeKeyword">__stdcall</span> <span class="codeKeyword">void</span> DynLoader(){_asm{<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_MAGIC)<span class="codeComment">//----------------------------------</span>Main_0:    PUSHAD  <span class="codeComment">// Save the registers context in stack</span>    CALL Main_1Main_1:    POP EBP    SUB EBP,OFFSET Main_1 <span class="codeComment">// Get Base EBP</span>    MOV EAX,DWORD PTR [EBP+_RO_dwImageBase]    ADD EAX,DWORD PTR [EBP+_RO_dwOrgEntryPoint]    MOV DWORD PTR [ESP+10h],EAX    <span class="codeComment">// pStack.Ebx &lt;- EAX</span>    LEA EAX,[EBP+_except_handler1_OEP_Jump]    MOV DWORD PTR [ESP+1Ch],EAX    <span class="codeComment">// pStack.Eax &lt;- EAX</span>    POPAD  <span class="codeComment">// Restore the first registers context from stack</span>    <span class="codeComment">//----------------------------------------------------</span>    <span class="codeComment">// the structured exception handler (SEH) installation</span>    PUSH EAX    XOR  EAX, EAX    PUSH DWORD PTR FS:[0]       <span class="codeComment">// NT_TIB32.ExceptionList</span>    MOV DWORD PTR FS:[0],ESP    <span class="codeComment">// NT_TIB32.ExceptionList &lt;-ESP</span>    <span class="codeComment">//----------------------------------------------------</span>    <span class="codeComment">// the raise a INT 3 exception</span>    DWORD_TYPE(0xCCCCCCCC)    <span class="codeComment">//--------------------------------------------------------</span><span class="codeComment">// -------- exception handler expression filter ----------</span>_except_handler1_OEP_Jump:    PUSH EBP    MOV EBP,ESP    <span class="codeComment">//------------------------------</span>    MOV EAX,DWORD PTR SS:[EBP+010h]   <span class="codeComment">// PCONTEXT: pContext &lt;- EAX</span>    <span class="codeComment">//==============================</span>    PUSH EDI    <span class="codeComment">// restore original SEH</span>    MOV EDI,DWORD PTR DS:[EAX+0C4h]    <span class="codeComment">// pContext.Esp</span>    PUSH DWORD PTR DS:[EDI]    POP DWORD PTR FS:[0]    ADD DWORD PTR DS:[EAX+0C4h],8    <span class="codeComment">// pContext.Esp</span>    <span class="codeComment">//------------------------------</span>    <span class="codeComment">// set the Eip to the OEP</span>    MOV EDI,DWORD PTR DS:[EAX+0A4h] <span class="codeComment">// EAX &lt;- pContext.Ebx</span>    MOV DWORD PTR DS:[EAX+0B8h],EDI <span class="codeComment">// pContext.Eip &lt;- EAX</span>    <span class="codeComment">//------------------------------</span>    POP EDI    <span class="codeComment">//==============================</span>    MOV EAX, EXCEPTION_CONTINUE_SEARCH    LEAVE    RETN<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_START_DATA1)<span class="codeComment">//----------------------------------</span>_RO_dwImageBase:                DWORD_TYPE(0xCCCCCCCC)_RO_dwOrgEntryPoint:            DWORD_TYPE(0xCCCCCCCC)<span class="codeComment">//----------------------------------</span>    DWORD_TYPE(DYN_LOADER_END_MAGIC)<span class="codeComment">//----------------------------------</span>}}</pre>
<h3>6 Build an Import Table and Reconstruct the Original Import Table</h3>
<p>There are two ways to use the Windows <a href="http://en.wikipedia.org/wiki/Microsoft_Dynamic_Link_Library" target="new">dynamic link library (DLL)</a> in Windows application programming:</p>
<ul>
<li><strong>Using Windows libraries by additional dependencies</strong>:&nbsp;<br />        <a name="more"><font color="#000000"> </font>
<p><font color="#000000"><img height="145" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=DEPENDENCIES_GIF&amp;ds=20060302" width="500" alt="" /><br />        </font>(</p>
<p>        </a><a href="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=DEPENDENCIES_GIF&amp;ds=20060302" target="_blank">Full Size Image</a>)</li>
<li><strong>Using Windows dynamic link libraries in run-time</strong>:
<pre><span class="codeComment">// DLL function signature</span><span class="codeKeyword">typedef</span> HGLOBAL (*importFunction_GlobalAlloc)(UINT, SIZE_T);...importFunction_GlobalAlloc __GlobalAlloc;<span class="codeComment">// Load DLL file</span>HINSTANCE hinstLib = LoadLibrary(&quot;Kernel32.dll&quot;);<span class="codeKeyword">if</span> (hinstLib == <span class="codeKeyword">NULL</span>){   <span class="codeComment">// Error - unable to load DLL</span>}<span class="codeComment">// Get function pointer</span>__GlobalAlloc =   (importFunction_GlobalAlloc)GetProcAddress(hinstLib,                                              &quot;GlobalAlloc&quot;);<span class="codeKeyword">if</span> (addNumbers == <span class="codeKeyword">NULL</span>){    <span class="codeComment">// Error - unable to find DLL function</span>}FreeLibrary(hinstLib);</pre>
</li>
</ul>
<p>When you make a Windows application project, the linker includes at least <em>kernel32.dll</em> in the base dependencies of your project. Without <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/loadlibrary.asp" target="new"><tt>LoadLibrary()</tt></a> and <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getprocaddress.asp" target="new"><tt>GetProcAddress()</tt></a> of <em>Kernel32.dll</em>, you cannot load a DLL at run time. The dependencies information is stored in the import table section. By using <a href="http://www.microsoft.com/resources/documentation/Windows/XP/all/reskit/en-us/Default.asp?url=/resources/documentation/Windows/XP/all/reskit/en-us/prmb_tol_kewf.asp" target="new">Dependency Walker</a>, it is not so difficult to observe the DLL module and the functions that are imported into a PE file.</p>
<p><img height="352" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=DEPENDENCY_WALKER_GIF&amp;ds=20060302" width="480" alt="" /></p>
<p>You attempt to establish your custom import table to conduct your project. Furthermore, you have to fix up the original import table at the end to run the real code of the program.</p>
<h4>PE Maker: Step 3</h4>
<p>Download the pemaker3.zip source files from the end of the article.</p>
<h4>6.1 Construct the Client Import Table</h4>
<p>I strongly advise that you to read Section 6.4 of the <a href="http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx" target="new">Microsoft Portable Executable and the Common Object File Format Specification</a> document. This section contains the principal information to comprehend the import table performance. The import table data is accessible by a second data directory of the optional header from PE headers, so you can access it by using the following code:</p>
<pre>DWORD dwVirtualAddress = image_nt_headers-&gt;   OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].      VirtualAddress;DWORD dwSize = image_nt_headers-&gt;   OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].      Size;</pre>
<p>The <tt>VirtualAddress</tt> refers to structures by <tt>IMAGE_IMPORT_DESCRIPTOR</tt>. This structure contains the pointer to the imported DLL name and the relative virtual address of the first thunk.</p>
<pre><span class="codeKeyword">typedef</span> <span class="codeKeyword">struct</span> _IMAGE_IMPORT_DESCRIPTOR {    <span class="codeKeyword">union</span> {        DWORD   Characteristics;        DWORD   OriginalFirstThunk;    };    DWORD   TimeDateStamp;    DWORD   ForwarderChain;    DWORD   <font color="#ff0000">Name</font>;         <span class="codeComment">// the imported DLL name</span>    DWORD   <font color="#ff0000">FirstThunk</font>;   <span class="codeComment">// the relative virtual address of the</span>                          <span class="codeComment">// first thunk</span>} IMAGE_IMPORT_DESCRIPTOR, *PIMAGE_IMPORT_DESCRIPTOR;</pre>
<p>When a program is running, the Windows Task Manager sets the thunks by the virtual address of the function. The virtual address is found by the name of the function. At first, the thunks hold the relative virtual address of the function name, as shown in Table 5; during execution, they are fixed up by the virtual address of the functions (see Table 6).</p>
<h4>Table 5: The Import Table in a file image</h4>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td rowspan="8"><tt>IMAGE_IMPORT_<br />                DESCRIPTOR[0]</tt></td>
<td><tt>OriginalFirstThunk</tt></td>
<td colspan="2" rowspan="3">&nbsp;</td>
<td colspan="2" rowspan="4">&nbsp;</td>
</tr>
<tr>
<td><tt>TimeDateStamp</tt></td>
</tr>
<tr>
<td><tt>ForwarderChain</tt></td>
</tr>
<tr>
<td><tt>Name_RVA</tt></td>
<td>&#8212;&#8212;&gt;</td>
<td><font color="#a52a2a">&quot;kernel32.dll&quot;<font color="#0000ff">,0</font></font></td>
</tr>
<tr>
<td><tt>FirstThunk_RVA</tt></td>
<td>&#8212;&#8212;&gt;</td>
<td><tt>proc_1_name_RVA</tt></td>
<td>&#8212;&#8212;&gt;</td>
<td><font color="#0000ff">0,0,</font><font color="#a52a2a">&quot;LoadLibraryA&quot;</font><font color="#0000ff">,0</font></td>
</tr>
<tr>
<td colspan="2" rowspan="3">&nbsp;</td>
<td><tt>proc_2_name_RVA</tt></td>
<td>&#8212;&#8212;&gt;</td>
<td><font color="#0000ff">0,0,</font><font color="#a52a2a">&quot;GetProcAddress&quot;</font><font color="#0000ff">,0</font></td>
</tr>
<tr>
<td><tt>proc_3_name_RVA</tt></td>
<td>&#8212;&#8212;&gt;</td>
<td><font color="#0000ff">0,0,</font><font color="#a52a2a">&quot;GetModuleHandleA&quot;</font><font color="#0000ff">,0</font></td>
</tr>
<tr>
<td>&#8230;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><tt>IMAGE_IMPORT_<br />                DESCRIPTOR[1]</tt></td>
<td colspan="5">&nbsp;</td>
</tr>
<tr>
<td><tt>...</tt></td>
<td colspan="5">&nbsp;</td>
</tr>
<tr>
<td><tt>IMAGE_IMPORT_<br />                DESCRIPTOR[n]</tt></td>
<td colspan="5">&nbsp;</td>
</tr>
</tbody>
</table>
<h4>Table 6: The Import Table in virtual memory</h4>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td rowspan="8"><tt>IMAGE_IMPORT_DESCRIPTOR[0]</tt></td>
<td><tt>OriginalFirstThunk</tt></td>
<td colspan="2" rowspan="3">&nbsp;</td>
</tr>
<tr>
<td><tt>TimeDateStamp</tt></td>
</tr>
<tr>
<td><tt>ForwarderChain</tt></td>
</tr>
<tr>
<td><tt>Name_RVA</tt></td>
<td><tt>------&gt;</tt></td>
<td><font color="#a52a2a">&quot;kernel32.dll&quot;<font color="#0000ff">,0</font></font></td>
</tr>
<tr>
<td><tt>FirstThunk_RVA</tt></td>
<td><tt>------&gt;</tt></td>
<td><tt>proc_1_VA</tt></td>
</tr>
<tr>
<td colspan="2" rowspan="3">&nbsp;</td>
<td><tt>proc_2_VA</tt></td>
</tr>
<tr>
<td><tt>proc_3_VA</tt></td>
</tr>
<tr>
<td><tt>...</tt></td>
</tr>
<tr>
<td><tt>IMAGE_IMPORT_DESCRIPTOR[1]</tt></td>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td><tt>...</tt></td>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td><tt>IMAGE_IMPORT_DESCRIPTOR[n]</tt></td>
<td colspan="3">&nbsp;</td>
</tr>
</tbody>
</table>
<p>You want to make a simple import table to import <tt>LoadLibrary()</tt>, and <tt>GetProcAddress()</tt> from <em>Kernel32.dll</em>. You need these two essential API functions to cover other API functions in run-time. The following assembly code shows how easily you can reach your solution:</p>
<pre><font color="#808080">0101F000: <font color="#0000ff">00000000</font> ; OriginalFirstThunk0101F004: <font color="#0000ff">00000000</font> ; TimeDateStamp0101F008: <font color="#0000ff">00000000</font> ; ForwarderChain0101F00C: <font color="#0000ff">0001F034</font> ; Name;       ImageBase + 0001F034                                 -&gt; 0101F034 -&gt; &quot;Kernel32.dll&quot;,00101F010: <font color="#0000ff">0001F028</font> ; FirstThunk; ImageBase + 0001F028 -&gt; 0101F0280101F014: <font color="#0000ff">00000000</font>0101F018: <font color="#0000ff">00000000</font>0101F01C: <font color="#0000ff">00000000</font>0101F020: <font color="#0000ff">00000000</font>0101F024: <font color="#0000ff">00000000</font>0101F028: <font color="#0000ff">0001F041</font> ; ImageBase + 0001F041 -&gt; 0101F041                     -&gt; 0,0,&quot;LoadLibraryA&quot;,00101F02C: <font color="#0000ff">0001F050</font> ; ImageBase + 0001F050 -&gt; 0101F050                     -&gt; 0,0,&quot;GetProcAddress&quot;,00101F030: <font color="#0000ff">00000000</font>0101F034: <font color="#a52a2a"><span class="codeComment">'K' 'e' 'r' 'n' 'e' 'l' '3' '2' '.' 'd' 'l' 'l' </span>0001F041: <font color="#0000ff">00 00</font> <font color="#a52a2a"><span class="codeComment">'L' 'o' 'a' 'd' 'L' 'i' 'b' 'r' 'a' 'r' 'y' 'A'</span>0001F050: <font color="#0000ff">00 00</font> <font color="#a52a2a"><span class="codeComment">'G' 'e' 't' 'P' 'r' 'o' 'c' 'A' 'd' 'd' 'r' 'e' 's'</span>          <span class="codeComment">'s'</span></font> <font color="#0000ff">00</font></font> <font color="#0000ff">00</font></font><font color="#0000ff">00</font></font></pre>
<p>After running&#8230;</p>
<pre><font color="#808080">0101F000: <font color="#0000ff">00000000</font> ; OriginalFirstThunk0101F004: <font color="#0000ff">00000000</font> ; TimeDateStamp0101F008: <font color="#0000ff">00000000</font> ; ForwarderChain0101F00C: <font color="#0000ff">0001F034</font> ; Name;       ImageBase + 0001F034                                 -&gt; 0101F034 -&gt; &quot;Kernel32.dll&quot;,00101F010: <font color="#0000ff">0001F028</font> ; FirstThunk; ImageBase + 0001F028 -&gt; 0101F0280101F014: <font color="#0000ff">00000000</font>0101F018: <font color="#0000ff">00000000</font>0101F01C: <font color="#0000ff">00000000</font>0101F020: <font color="#0000ff">00000000</font>0101F024: <font color="#0000ff">00000000</font>0101F028: <font color="#ff0000">7C801D77</font> ; -&gt; Kernel32.LoadLibrary()0101F02C: <font color="#ff0000">7C80AC28</font> ; -&gt; Kernel32.GetProcAddress()0101F030: <font color="#0000ff">00000000</font>0101F034: <font color="#a52a2a"><span class="codeComment">'K' 'e' 'r' 'n' 'e' 'l' '3' '2' '.' 'd' 'l' 'l' </span>0001F041: <font color="#0000ff">00 00</font> <font color="#a52a2a"><span class="codeComment">'L' 'o' 'a' 'd' 'L' 'i' 'b' 'r' 'a' 'r' 'y' 'A'</span>0001F050: <font color="#0000ff">00 00</font> <font color="#a52a2a"><span class="codeComment">'G' 'e' 't' 'P' 'r' 'o' 'c' 'A' 'd' 'd' 'r' 'e' 's'</span>          <span class="codeComment">'s'</span></font> <font color="#0000ff">00</font></font> <font color="#0000ff">00</font></font><font color="#0000ff">00</font></font></pre>
<p>I have prepared a class library to make every import table by using a client string table. The <tt>CITMaker</tt> class library in <em>itmaker.h</em>; it will build an import table by <tt>sz_IT_EXE_strings</tt> and also the relative virtual address of the import table.</p>
<pre><span class="codeKeyword">static</span> <span class="codeKeyword">const</span> <span class="codeKeyword">char</span> *sz_IT_EXE_strings[]={    &quot;Kernel32.dll&quot;,    &quot;LoadLibraryA&quot;,    &quot;GetProcAddress&quot;,    0,,    0,};</pre>
<p>You subsequently employ this class library to establish an import table to support DLLs and OCXs, so this is a general library to present all possible import tables easily. The next step is clarified in the following code.</p>
<pre>CITMaker *<font color="#ff0000">ImportTableMaker</font> = <span class="codeKeyword">new</span> CITMaker( IMPORT_TABLE_EXE );...pimage_section_header=AddNewSection( &quot;.xxx&quot;, dwNewSectionSize );<span class="codeComment">// build import table by the current virtual address</span><font color="#ff0000">ImportTableMaker</font>-&gt;<font color="#008000">Build</font>( <font color="#0000ff">pimage_section_header-&gt;VirtualAddress</font> );memcpy( pNewSection, <font color="#ff0000">ImportTableMaker</font>-&gt;<font color="#008000">pMem</font>,<font color="#ff0000">ImportTableMaker</font>-&gt;<font color="#008000">dwSize</font> );...memcpy( image_section[image_nt_headers-&gt;FileHeader.NumberOfSections-1],        pNewSection,        dwNewSectionSize );...image_nt_headers-&gt;OptionalHeader.  DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress  = <font color="#0000ff">pimage_section_header-&gt;VirtualAddress</font>;image_nt_headers-&gt;OptionalHeader.  DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size  = <font color="#ff0000">ImportTableMaker</font>-&gt;<font color="#008000">dwSize</font>;...<span class="codeKeyword">delete</span> <font color="#ff0000">ImportTableMaker</font>;</pre>
<p>The import table is copied at the beginning of the new section, and the relevant data directory is adjusted to the relative virtual address of the new section and the size of the new import table.</p>
<h4>6.2 Using other API functions at run time</h4>
<p>At this time, you can load other DLLs and find the process address of other functions by using <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/loadlibrary.asp" target="new"><tt>LoadLibrary()</tt></a> and <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getprocaddress.asp" target="new"><tt>GetProcAddress()</tt></a>:</p>
<pre><font color="#808080">lea edi, <font color="#ff0000">@</font><font color="#a52a2a">&quot;Kernel32.dll&quot;</font><span class="codeComment">//-------------------</span><font color="#0000ff">push edimov eax,offset _p_LoadLibrarycall [ebp+eax] <span class="codeComment">//LoadLibrary(lpLibFileName);</span><span class="codeComment">//-------------------</span>mov esi,eax    <span class="codeComment">// esi -&gt; hModule</span>lea edi, <font color="#ff0000">@</font><font color="#a52a2a">&quot;GetModuleHandleA&quot;</font><span class="codeComment">//-------------------</span><font color="#0000ff">push edipush esimov eax,offset _p_GetProcAddresscall [ebp+eax] <span class="codeComment">//GetModuleHandle=GetProcAddress(hModule, lpProcName);</span><span class="codeComment">//--------------------</span></font></font></font></pre>
<p>    <a name="more"><font color="#000000">&nbsp;</font></a><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/loadlibrary.asp" target="new"><tt>LoadLibrary()</tt></a> and <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getprocaddress.asp" target="new"><tt>GetProcAddress()</tt></a> aid you in your effort to reach your intention.</p>
<p>I want to have a complete imported function table similar in performance done in a real EXE file. If you look inside a PE file, you will discover that an API call is done by an indirection jump through the virtual address of the API function:</p>
<h4>JMP DWORD PTR [XXXXXXXX]</h4>
<pre><font color="#808080">...0101F028: <font color="#ff0000">7C801D77</font>      ; Virtual Address of kernel32.LoadLibrary()...0101F120: JMP DWORD PTR [<font color="#ff0000">0101F028</font>]...0101F230: CALL <font color="#ff0000">0101F120</font> ;  JMP to kernel32.LoadLibrary...</font></pre>
<p>It makes it easy to expand the other part of your project by this performance, so you construct two data tables: the first for API virtual addresses, and the second for the <tt>JMP [XXXXXXXX]</tt>.</p>
<pre><span class="codeKeyword">#define</span> __jmp_api               byte_type(0xFF) byte_type(0x25)__asm{...<span class="codeComment">//----------------------------------------------------------------</span>_p_GetModuleHandle:             dword_type(0xCCCCCCCC)_p_VirtualProtect:              dword_type(0xCCCCCCCC)_p_GetModuleFileName:           dword_type(0xCCCCCCCC)_p_CreateFile:                  dword_type(0xCCCCCCCC)_p_GlobalAlloc:                 dword_type(0xCCCCCCCC)<span class="codeComment">//----------------------------------------------------------------</span>_jmp_GetModuleHandle:           __jmp_api   dword_type(0xCCCCCCCC)_jmp_VirtualProtect:            __jmp_api   dword_type(0xCCCCCCCC)_jmp_GetModuleFileName:         __jmp_api   dword_type(0xCCCCCCCC)_jmp_CreateFile:                __jmp_api   dword_type(0xCCCCCCCC)_jmp_GlobalAlloc:               __jmp_api   dword_type(0xCCCCCCCC)<span class="codeComment">//----------------------------------------------------------------</span>...}</pre>
<p>In the succeeding code, you have concluded your ambition to install a custom internal import table! (You cannot call it import table.)</p>
<pre><font color="#808080">    ...    lea edi,[ebp+_p_szKernel32]    lea ebx,[ebp+_p_GetModuleHandle]    lea ecx,[ebp+_jmp_GetModuleHandle]    add ecx,02h_api_get_lib_address_loop:        push ecx        <font color="#0000ff">push edi        mov eax,offset _p_LoadLibrary        call [ebp+eax]    <span class="codeComment">//LoadLibrary(lpLibFileName);</span>        pop ecx        mov esi,eax       <span class="codeComment">// esi -&gt; hModule</span>        push edi        call __strlen        add esp,04h        add edi,eax_api_get_proc_address_loop:            push ecx            <font color="#0000ff">push edi            push esi            mov eax,offset _p_GetProcAddress            <span class="codeComment">//GetModuleHandle=GetProcAddress(hModule, lpProcName);</span>            call [ebp+eax]            pop ecx</font>            <font color="#008000">mov [ebx],eax            mov [ecx],ebx    <span class="codeComment">// JMP DWORD PTR [XXXXXXXX]</span>            add ebx,04h            add ecx,06h            push edi            call __strlen            add esp,04h            add edi,eax            mov al,<span class="codeKeyword">byte</span> ptr [edi]        test al,al        jnz _api_get_proc_address_loop        inc edi        mov al,<span class="codeKeyword">byte</span> ptr [edi]    test al,al    jnz _api_get_lib_address_loop    ...</font></font></font></pre>
<h4>6.3 Fix up the Original Import Table</h4>
<p>To run the program again, you should fix up the thunks of the actual import table; otherwise, you have a corrupted target PE file. Your code must correct all of the thunks the same as Table 5 to Table 6. Once more, </p>
<pre><font color="#808080">    ...    mov ebx,[ebp+<font color="#ff0000">_p_dwImportVirtualAddress</font>]    test ebx,ebx    jz _it_fixup_end    mov esi,[ebp+<font color="#ff0000">_p_dwImageBase</font>]    add ebx,esi             <span class="codeComment">// dwImageBase + dwImportVirtualAddress</span>_it_fixup_get_lib_address_loop:        mov eax,[ebx+00Ch]  <span class="codeComment">// image_import_descriptor.Name</span>        test eax,eax        jz _it_fixup_end        mov ecx,[ebx+010h]  <span class="codeComment">// image_import_descriptor.FirstThunk</span>        add ecx,esi        mov [ebp+<font color="#ff0000">_p_dwThunk</font>],ecx    <span class="codeComment">// dwThunk</span>        mov ecx,[ebx]       <span class="codeComment">// image_import_descriptor.Characteristics</span>        test ecx,ecx        jnz _it_fixup_table            mov ecx,[ebx+010h]_it_fixup_table:        add ecx,esi        mov [ebp+<font color="#ff0000">_p_dwHintName</font>],ecx    <span class="codeComment">// dwHintName</span>        add eax,esi  <span class="codeComment">// image_import_descriptor.Name + dwImageBase = ModuleName</span>        <font color="#0000ff">push eax     <span class="codeComment">// lpLibFileName</span>        mov eax,offset _p_LoadLibrary        call [ebp+eax]               <span class="codeComment">// LoadLibrary(lpLibFileName);</span>        test eax,eax        jz _it_fixup_end        mov edi,eax_it_fixup_get_proc_address_loop:            mov ecx,[ebp+<font color="#ff0000">_p_dwHintName</font>]    <span class="codeComment">// dwHintName</span>            mov edx,[ecx]            <span class="codeComment">// image_thunk_data.Ordinal</span>            test edx,edx            jz _it_fixup_next_module            test edx,080000000h      <span class="codeComment">// .IF( import by ordinal )</span>            jz _it_fixup_by_name                and edx,07FFFFFFFh    <span class="codeComment">// get ordinal</span>                jmp _it_fixup_get_addr_it_fixup_by_name:            add edx,esi  <span class="codeComment">// image_thunk_data.Ordinal</span>                         <span class="codeComment">// + dwImageBase = OrdinalName</span>            inc edx            inc edx                  <span class="codeComment">// OrdinalName.Name</span>_it_fixup_get_addr:            <font color="#0000ff">push edx <span class="codeComment">//lpProcName</span>            push edi                 <span class="codeComment">// hModule</span>            mov eax,offset _p_GetProcAddress            call [ebp+eax]    <span class="codeComment">// GetProcAddress(hModule, lpProcName);</span>            <font color="#008000">mov ecx,[ebp+<font color="#ff0000">_p_dwThunk</font>]    <span class="codeComment">// dwThunk</span>            mov [ecx],eax  <span class="codeComment">// correction the thunk</span>            <span class="codeComment">// dwThunk =&gt; next dwThunk</span>            add dword ptr [ebp+<font color="#ff0000">_p_dwThunk</font>], <font color="#0000ff">004h</font>            <span class="codeComment">// dwHintName =&gt; next dwHintName</span>            add dword ptr [ebp+<font color="#ff0000">_p_dwHintName</font>],<font color="#0000ff">004h</font>        jmp _it_fixup_get_proc_address_loop_it_fixup_next_module:        add ebx,014h      <span class="codeComment">// sizeof(IMAGE_IMPORT_DESCRIPTOR)</span>    jmp _it_fixup_get_lib_address_loop_it_fixup_end:    ...</font></font></font></font></pre>
<pre>
<h3>7 Support DLL and OCX</h3>

Now, you intend to include the <a href="http://en.wikipedia.org/wiki/Microsoft_Dynamic_Link_Library" target="new">dynamic link library (DLL)</a> and <a href="http://en.wikipedia.org/wiki/OCX" target="new">OLE-ActiveX Control</a> in your PE builder project. Supporting them is very easy if you pay attention to the two-time arrival into the Offset of Entry Point, the relocation table implementation, and the client import table.
<h4>PE Maker: Step 4</h4>

&nbsp;

<a name="more"><font color="#000000"> </font></a><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/loadlibrary.asp" target="new"><tt>LoadLibrary()</tt></a>, or an OCX is registered by using <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/loadlibrary.asp" target="new"><tt>LoadLibrary()</tt></a> and <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getprocaddress.asp" target="new"><tt>GetProcAddress()</tt></a> through calling <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/com/html/4442206b-b2ad-47d7-8add-18002c44c5a2.asp" target="new"><tt>DllRegisterServer()</tt></a>, the first of the OEP arrival is done.

&nbsp;
<pre>hinstDLL = LoadLibrary( &quot;test1.dll&quot; );hinstOCX = LoadLibrary( &quot;test1.ocx&quot; );_DllRegisterServer = GetProcAddress( hinstOCX,                                     &quot;DllRegisterServer&quot; );_DllRegisterServer();    <span class="codeComment">// ocx register</span></pre>
</p>
<p>Download the pemaker4.zip source files from the end of the article.</p>
<h4>7.1 Twice OEP approach</h4>
<p>The Offset of Entry Point of a DLL file or an OCX file is touched by the main program atleast twice:</p>
<ul>
<li><strong>Constructor</strong>: When a DLL is loaded by </li>
<li><strong>Destructor</strong>: When the main program frees the library usage by <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/freelibrary.asp" target="new"><tt>FreeLibrary()</tt></a>, the second OEP arrival happens.
<p>&nbsp;</p>
<pre>FreeLibrary( hinstDLL );FreeLibrary( hinstOCX );</pre>
</li>
</ul>
<p>To perform this, I have employed a trick that causes in the second time again, the instruction pointer (EIP) traveling towards the original OEP by the structured exception handler.</p>
<pre><font color="#808080"><font color="#000000">_main_0:    pushad    <span class="codeComment">// save the registers context in stack</span>    call _main_1_main_1:    pop ebp    sub ebp,offset _main_1    <span class="codeComment">// get base ebp</span>    <span class="codeComment">//---------------- support dll, ocx  -----------------</span>_support_dll_0:</font>    jmp _support_dll_1        <span class="codeComment">// <font color="#ff0000">nop; nop;    // &lt;&lt; trick</font></span>                              <span class="codeComment">// in the second time OEP</span>    <font color="#000000">jmp _support_dll_2</font>_support_dll_1:    <span class="codeComment">//----------------------------------------------------</span>    ...    <span class="codeComment">//---------------- support dll, ocx  1 ---------------</span>    mov edi,[ebp+_p_dwImageBase]    add edi,[edi+03Ch]            <span class="codeComment">// edi -&gt; IMAGE_NT_HEADERS</span>    mov ax,word ptr [edi+016h]    <span class="codeComment">// edi -&gt; image_nt_headers-&gt;</span>                                  <span class="codeComment">// FileHeader.Characteristics</span>    test ax,<font color="#008000">IMAGE_FILE_DLL</font>    jz _support_dll_2        mov ax, <font color="#ff0000">9090h <span class="codeComment">// &lt;&lt; trick</span>        mov word ptr [ebp+_support_dll_0],ax</font></font><font color="#000000">_support_dll_2:    <span class="codeComment">//----------------------------------------------------</span>    ...    into OEP by SEH ...</font></pre>
<p>I hope you caught the trick in the preceding code, but this is not all of it. You have a problem in <tt>ImageBase</tt>, when the library has been loaded in different image bases by the main program. You should write some code to find the real image base and store it to use forward.</p>
<pre><font color="#808080">    mov eax,<font color="#008000">[esp+24h]</font>    <span class="codeComment">// the real imagebase</span>    mov ebx,<font color="#008000">[esp+30h]</font>    <span class="codeComment">// oep</span>    cmp eax,ebx    ja _no_dll_pe_file_0        cmp word ptr [eax],IMAGE_DOS_SIGNATURE        jne _no_dll_pe_file_0            mov [ebp+_p_dwImageBase],eax_no_dll_pe_file_0:</font></pre>
<p>This code finds the real image base by investigating the stack information. By using the real image base and the formal image base, you should correct all memory calls inside the image program!! Don't be afraid; it will be done simply by the relocating the table information.</p>
<h4>7.2 Implement relocation table</h4>
<p>To understand the relocation table better, you can take a look at Section 6.6 of the <a href="http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx" target="new">Microsoft Portable Executable and Common Object File Format Specification</a> document. The relocation table contains many packages to relocate the information related to the virtual address inside the virtual memory image. Each package is comprised of an 8-byte header to exhibit the base virtual address and the number of data, demonstrated by the <tt>IMAGE_BASE_RELOCATION</tt> data structure.</p>
<pre><span class="codeKeyword">typedef</span> <span class="codeKeyword">struct</span> _IMAGE_BASE_RELOCATION {   DWORD   VirtualAddress;   DWORD   SizeOfBlock;} IMAGE_BASE_RELOCATION, *PIMAGE_BASE_RELOCATION;</pre>
<h4>Table 7 - The Relocation Table</h4>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td align="center" rowspan="7">Block[1]</td>
<td align="center" colspan="4">VirtualAddress</td>
</tr>
<tr>
<td align="center" colspan="4">SizeOfBlock</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">...</td>
<td align="center">...</td>
<td align="center">...</td>
<td align="center">...</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">00</td>
<td align="center">00</td>
</tr>
<tr>
<td align="center" rowspan="7">Block[2]</td>
<td align="center" colspan="4">VirtualAddress</td>
</tr>
<tr>
<td align="center" colspan="4">SizeOfBlock</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">...</td>
<td align="center">...</td>
<td align="center">...</td>
<td align="center">...</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">00</td>
<td align="center">00</td>
</tr>
<tr>
<td align="center">...</td>
<td align="center" colspan="4">
<p>&nbsp;</p>
<p>... </p>
<p>&nbsp;</p>
</td>
</tr>
<tr>
<td align="center" rowspan="7">Block[n]</td>
<td align="center" colspan="4">VirtualAddress</td>
</tr>
<tr>
<td align="center" colspan="4">SizeOfBlock</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">type:4</td>
<td align="center">offset:12</td>
</tr>
<tr>
<td align="center">...</td>
<td align="center">...</td>
<td align="center">...</td>
<td align="center">...</td>
</tr>
<tr>
<td align="center">type:4</td>
<td align="center">offset:12</td>
<td align="center">00</td>
<td align="center">00</td>
</tr>
</tbody>
</table>
<p>Table 7 illustrates the main idea of the relocation table. Furthermore, you can upload a DLL or an OCX file in <a href="http://www.ollydbg.de/" target="new">OllyDbg</a> to observe the relocation table, the <em>&quot;.reloc&quot;</em> section through <em>Memory map window</em>. By the way, you find the position of the relocation table by using the following code in your project:</p>
<pre>DWORD dwVirtualAddress = image_nt_headers-&gt;  OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].  VirtualAddress;DWORD dwSize = image_nt_headers-&gt;  OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;</pre>
<p>By OllyDbg, you have the same as the following for the <em>&quot;.reloc&quot;</em> section, by using the Long Hex viewer mode. In this example, the base virtual address is <strong>0x1000</strong> and the size of the block is <strong>0x184</strong>.</p>
<pre>008E1000 : 00001000  00000184  30163000  30403028008E1010 : 30683054  308C3080  30AC309C  30D830CC008E1020 : 30E030DC  30E830E4  30F030EC  310030F4008E1030 : 3120310D  315F3150  31A431A0  31C031A8008E1040 : 31D031CC  31F431EC  31FC31F8  32043200008E1050 : 320C3208  32143210  324C322C  32583254008E1060 : 3260325C  32683264  3270326C  32B03274</pre>
<p>It relocates the data in the subsequent virtual addresses:</p>
<pre>0x1000 + 0x0000 = 0x10000x1000 + 0x0016 = 0x10160x1000 + 0x0028 = 0x10280x1000 + 0x0040 = 0x10400x1000 + 0x0054 = 0x1054...</pre>
<p>Each package performs the relocation by using consecutive 4 bytes form its internal information. The first byte refers to the type of relocation and the next three bytes are the offset that must be used with the base virtual address and the image base to correct the image information.</p>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td align="center" width="30">type</td>
<td align="center" colspan="3">offset</td>
</tr>
<tr>
<td align="center"><font color="#0000ff">03</font></td>
<td align="center"><font color="#0000ff">00</font></td>
<td align="center"><font color="#0000ff">00</font></td>
<td align="center"><font color="#0000ff">00</font></td>
</tr>
</tbody>
</table>
<h4>What is the type?</h4>
<p>The type can be one of the following values:</p>
<ul>
<li><tt>IMAGE_REL_BASED_ABSOLUTE (0)</tt>: No effect </li>
<li><tt>IMAGE_REL_BASED_HIGH (1)</tt>: Relocate by the high 16 bytes of the base virtual address and the offset </li>
<li><tt>IMAGE_REL_BASED_LOW (2)</tt>: Relocate by the low 16 bytes of the base virtual address and the offset </li>
<li><tt>IMAGE_REL_BASED_HIGHLOW (3)</tt>: Relocate by the base virtual address and the offset </li>
</ul>
<h4>What is done in the relocation?</h4>
<p>By relocation, some values inside the virtual memory are corrected according to the current image base by the <em>&quot;.reloc&quot;</em> section packages.</p>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td align="center"><strong>delta_ImageBase = current_ImageBase - image_nt_headers-&gt;OptionalHeader.ImageBase</strong></td>
</tr>
</tbody>
</table>
<pre>mem[ current_ImageBase + 0x1000 ] =   mem[ current_ImageBase + 0x1000 ] + delta_ImageBase ;mem[ current_ImageBase + 0x1016 ] =   mem[ current_ImageBase + 0x1016 ] + delta_ImageBase ;mem[ current_ImageBase + 0x1028 ] =   mem[ current_ImageBase + 0x1028 ] + delta_ImageBase ;mem[ current_ImageBase + 0x1040 ] =   mem[ current_ImageBase + 0x1040 ] + delta_ImageBase ;mem[ current_ImageBase + 0x1054 ] =  mem[ current_ImageBase + 0x1054 ] + delta_ImageBase ;...</pre>
<p>I have employed the following code from Morphine packer to implement the relocation.</p>
<pre><font color="#808080">    ..._reloc_fixup:    mov eax,[ebp+_p_dwImageBase]    mov edx,eax    mov ebx,eax    add ebx,[ebx+3Ch]    <span class="codeComment">// edi -&gt; IMAGE_NT_HEADERS</span>    <span class="codeComment">// edx -&gt;image_nt_headers-&gt;OptionalHeader.ImageBase</span>    mov ebx,[ebx+034h]    <font color="#ff0000">sub edx,ebx <span class="codeComment">// edx -&gt; reloc_correction    // delta_ImageBase</span>    je _reloc_fixup_end    mov ebx,[ebp+_p_dwRelocationVirtualAddress]    test ebx,ebx    jz _reloc_fixup_end    add ebx,eax_reloc_fixup_block:    mov eax,[ebx+004h]          <span class="codeComment">//ImageBaseRelocation.SizeOfBlock</span>    test eax,eax    jz _reloc_fixup_end    lea ecx,[eax-008h]    shr ecx,001h    lea edi,[ebx+008h]_reloc_fixup_do_entry:        movzx eax,word ptr [edi]<span class="codeComment">//Entry</span>        push edx        mov edx,eax        shr eax,00Ch            <span class="codeComment">//Type = Entry &gt;&gt; 12</span>        mov esi,[ebp+_p_dwImageBase]<span class="codeComment">//ImageBase</span>        and dx,00FFFh        add esi,[ebx]        add esi,edx        pop edx_reloc_fixup_HIGH:              <span class="codeComment">// IMAGE_REL_BASED_HIGH</span>        dec eax        jnz _reloc_fixup_LOW            mov eax,edx            shr eax,010h        <span class="codeComment">//HIWORD(Delta)</span>            jmp _reloc_fixup_LOW_fixup_reloc_fixup_LOW:               <span class="codeComment">// IMAGE_REL_BASED_LOW</span>            dec eax        jnz _reloc_fixup_HIGHLOW        movzx eax,dx            <span class="codeComment">//LOWORD(Delta)</span>_reloc_fixup_LOW_fixup:            <font color="#ff0000">add word ptr [esi],ax<span class="codeComment">// mem[x] = mem[x] + delta_ImageBase</span>        jmp _reloc_fixup_next_entry_reloc_fixup_HIGHLOW:           <span class="codeComment">// IMAGE_REL_BASED_HIGHLOW</span>            dec eax        jnz _reloc_fixup_next_entry        <font color="#ff0000">add [esi],edx           <span class="codeComment">// mem[x] = mem[x] + delta_ImageBase</span>_reloc_fixup_next_entry:        inc edi        inc edi                 <span class="codeComment">//Entry++</span>        loop _reloc_fixup_do_entry_reloc_fixup_next_base:    add ebx,[ebx+004h]    jmp _reloc_fixup_block_reloc_fixup_end:    ...</font></font></font></font></pre>
<h4>7.3 Build a special import table</h4>
<p>To support the <a href="http://en.wikipedia.org/wiki/OCX" target="new">OLE-ActiveX Control</a> registration, you should present an appropriate import table to your target OCX and DLL file. Therefore, I have established an import table by the following string:</p>
<pre><span class="codeKeyword">const</span> <span class="codeKeyword">char</span> *sz_IT_OCX_strings[]={   &quot;Kernel32.dll&quot;,   &quot;LoadLibraryA&quot;,   &quot;GetProcAddress&quot;,   &quot;GetModuleHandleA&quot;,   0,   &quot;User32.dll&quot;,   &quot;GetKeyboardType&quot;,   &quot;WindowFromPoint&quot;,   0,   &quot;AdvApi32.dll&quot;,   &quot;RegQueryValueExA&quot;,   &quot;RegSetValueExA&quot;,   &quot;StartServiceA&quot;,   0,   &quot;Oleaut32.dll&quot;,   &quot;SysFreeString&quot;,   &quot;CreateErrorInfo&quot;,   &quot;SafeArrayPtrOfIndex&quot;,   0,   &quot;Gdi32.dll&quot;,   &quot;UnrealizeObject&quot;,   0,   &quot;Ole32.dll&quot;,   &quot;CreateStreamOnHGlobal&quot;,   &quot;IsEqualGUID&quot;,   0,   &quot;ComCtl32.dll&quot;,   &quot;ImageList_SetIconSize&quot;,   0,   0,};</pre>
<p>Without these API functions, the library can not be loaded, and moreover the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/com/html/4442206b-b2ad-47d7-8add-18002c44c5a2.asp" target="new"><tt>DllregisterServer()</tt></a> and <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/com/html/b71137a7-284e-4521-a3b2-9dad9c9d3c54.asp" target="new"><tt>DllUregisterServer()</tt></a> will not operate. In <tt>CPECryptor::CryptFile</tt>, I have distinguished between EXE files and DLL files in the initialization of the new import table object during creation:</p>
<pre><span class="codeKeyword">if</span>(( image_nt_headers-&gt;FileHeader.Characteristics             &amp; IMAGE_FILE_DLL ) == IMAGE_FILE_DLL ){    ImportTableMaker = <span class="codeKeyword">new</span> CITMaker( IMPORT_TABLE_OCX );}<span class="codeKeyword">else</span>{    ImportTableMaker = <span class="codeKeyword">new</span> CITMaker( IMPORT_TABLE_EXE );}</pre>
<p>&nbsp;</p>
<h3>8 Preserve the Thread Local Storage</h3>
<p>By using Thread Local Storage (TLS), a program is able to execute a multithreaded process, This performance mostly is used by <a href="http://www.borland.com/" target="new">Borland</a> linkers: <a href="http://www.borland.com/us/products/delphi/index.html" target="new">Delphi</a> and <a href="http://www.borland.com/us/products/cbuilder/index.html" target="new">C++ Builder</a>. When you pack a PE file, you should take care to keep the TLS clean; otherwise, your packer will not support Borland Delphi and C++ Builder linked EXE files. To comprehend TLS, I refer you to Section 6.7 of the <a href="http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx" target="new">Microsoft Portable Executable and Common Object File Format Specification</a> document. You can observe the TLS structure by <tt>IMAGE_TLS_DIRECTORY32</tt> in <em>winnt.h</em>.</p>
<pre><span class="codeKeyword">typedef</span> <span class="codeKeyword">struct</span> _IMAGE_TLS_DIRECTORY32 {   DWORD   StartAddressOfRawData;   DWORD   EndAddressOfRawData;   DWORD   AddressOfIndex;   DWORD   AddressOfCallBacks;   DWORD   SizeOfZeroFill;   DWORD   Characteristics;} IMAGE_TLS_DIRECTORY32, * PIMAGE_TLS_DIRECTORY32;</pre>
<p>    <a name="more"><font color="#000000"> </font></a><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/dialogboxes/dialogboxreference/dialogboxfunctions/messagebox.asp" target="new"><tt>MessageBox()</tt></a> from <em>user32.dll</em>.</p>
<p>To keep the TLS directory safe, I have copied it in a special place inside the loader:</p>
<pre><font color="#808080">..._tls_dwStartAddressOfRawData:   dword_type(0xCCCCCCCC)_tls_dwEndAddressOfRawData:     dword_type(0xCCCCCCCC)_tls_dwAddressOfIndex:          dword_type(0xCCCCCCCC)_tls_dwAddressOfCallBacks:      dword_type(0xCCCCCCCC)_tls_dwSizeOfZeroFill:          dword_type(0xCCCCCCCC)_tls_dwCharacteristics:         dword_type(0xCCCCCCCC)...</font></pre>
<p>It is necessary to correct the TLS directory entry in the Optional Header:</p>
<pre><span class="codeKeyword">if</span>(image_nt_headers-&gt;   OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].   VirtualAddress!=0){   memcpy(&amp;pDataTable-&gt;image_tls_directory,          image_tls_directory,          <span class="codeKeyword">sizeof</span>(IMAGE_TLS_DIRECTORY32));   dwOffset=DWORD(pData1)-DWORD(pNewSection);   dwOffset+=<span class="codeKeyword">sizeof</span>(t_DATA_1)-<span class="codeKeyword">sizeof</span>(IMAGE_TLS_DIRECTORY32);   image_nt_headers-&gt;      OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].      VirtualAddress=dwVirtualAddress + dwOffset;}</pre>
<h3>9 Inject Your Code</h3>
<p>You are ready to place your code inside the new section. Your code is a &quot;Hello World!&quot; message by </p>
<pre><font color="#808080">...push MB_OK | MB_ICONINFORMATIONlea eax,[ebp+_p_szCaption]push eaxlea eax,[ebp+_p_szText]push eaxpush <span class="codeKeyword">NULL</span>call _jmp_MessageBox<span class="codeComment">// MessageBox(NULL, szText, szCaption, MB_OK | MB_ICONINFORMATION) ;</span>...</font></pre>
<h4>PE Maker: Step 5</h4>
<p>Download the pemaker5.zip source files from the end of the article.</p>
<p><img height="119" src="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=HELLOWORLD_GIF&amp;ds=20060302" width="146" alt="" /></p>
<h3>10 Conclusion</h3>
<p>By reading this article, you have perceived how easily you can inject code to a portable executable file. You can complete the code by using the source of other packers, create a packer in the same way as <a href="http://yodap.sourceforge.net/" target="new">Yoda's Protector</a>, and make your packer undetectable by mixing up with <a href="http://www.hxdef.org/download.php" target="new">Morphine</a> source code. I hope that you have enjoyed this brief discussion of one part of the reverse engineering field. See you again in the next discussion!</p>
<p>&nbsp;</p>
</pre>
<p>    </a><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/exception_pointers_str.asp" target="new"><tt>EXCEPTION_POINTERS</tt></a>, you have access to the pointer of <tt>ContextRecord</tt>. The <tt>ContextRecord</tt> has the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/context_str.asp" target="new"><tt>CONTEXT</tt></a> data structure, as seen in Table 4. This is the thread context during the exception time. When you ignore the exception by <tt>EXCEPTION_CONTINUE_SEARCH (0)</tt>, the instruction pointer, as well as the context, will be set to <tt>ContextRecord</tt> to return to the previous condition. Therefore, if you change the <tt>Eip</tt> of the Win32 Thread Context to the Original Offset of Entry Point, it will come clearly into OEP.</a><a href="http://www.codeguru.com/dbfiles/get_image.php?id=11393&amp;lbl=SCREENSHOT_JPG&amp;ds=20060302" target="_blank">Full Size Image</a>)</p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/283.html" title="免费软件套装 (2007-01-08)">免费软件套装</a> (0)</li>
	<li><a href="http://www.donevii.com/post/75.html" title="挣脱Windows的枷锁：Linux屏幕录像 (2006-10-10)">挣脱Windows的枷锁：Linux屏幕录像</a> (0)</li>
	<li><a href="http://www.donevii.com/post/203.html" title="使用memcached进行内存缓存 (2006-11-15)">使用memcached进行内存缓存</a> (0)</li>
	<li><a href="http://www.donevii.com/post/78.html" title="[转]C/C++/Perl/汇编/Java效率比较 (2006-10-11)">[转]C/C++/Perl/汇编/Java效率比较</a> (0)</li>
	<li><a href="http://www.donevii.com/post/204.html" title="PHP &#038; memcached (2006-11-15)">PHP &#038; memcached</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/330.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Armadillo标准壳完全扫盲</title>
		<link>http://www.donevii.com/post/329.html</link>
		<comments>http://www.donevii.com/post/329.html#comments</comments>
		<pubDate>Thu, 24 May 2007 01:31:31 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[doc]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.donevii.com/?p=329</guid>
		<description><![CDATA[转至: http://hi.baidu.com/%CC%EC%CD%E2%C3%AB%B3%E6/blog 【前言】本人初学脱壳，以前只会用自动脱壳器，手动只脱过upx的壳，实在是菜鸟一个。日前有幸拿到一个共享软件，用peid一查，Armadillo 1.xx &#8211; 2... ]]></description>
			<content:encoded><![CDATA[<p>转至: <a href="http://hi.baidu.com/%CC%EC%CD%E2%C3%AB%B3%E6/blog">http://hi.baidu.com/%CC%EC%CD%E2%C3%AB%B3%E6/blog</a></p>
<p>【前言】<br />本人初学脱壳，以前只会用自动脱壳器，手动只脱过upx的壳，实在是菜鸟一个。日前有幸拿到一个共享软件，用peid一查，Armadillo 1.xx &#8211; 2.xx -&gt; Silicon Realms Toolworks [Overlay]，俺出生牛犊不怕虎，见壳就有脱的冲动，用od载入一看，傻了眼，这壳和upx的完全不同，入口点和一般程序差不多嘛。遂知道自己水平不济，驱猫上看雪拜读各位前辈的文章。无奈本人水平实在有限，看了大半天还是没理清楚过程。想起马gg曾经说过，实践是检验真理的唯一标准，于是操起工具对该软件大卸七块。经过2天的仔细研习，终于悟得精要，成功把壳干掉了。鉴于感觉入门门槛确实有点高，因此特写此文以帮助菜鸟们迈过刀山火海，飞向光明之巅:D</p>
<p>【术语解释】<br />为什么我要写这一段呢？因为我发现看高手们的脱文，最难逾越的一关是术语。高手们脱文中的各种说法，并不能马上就明白过来究竟是什么东西。因此，希望在这里把Armadillo脱文经常遇到的几个术语稍作解释。本人水平有限，如果解释有误请指出。</p>
<p>[OEP] 这个是Original Entry Point的缩写，中文字面意思就是程序的原入口地址。为什么叫&ldquo;原&rdquo;呢？通常加壳软件会把原来的程序编码存放，以防止静态反汇编分析，并在执行前先运行一段解码的程序。所以，加壳后的程序，其入口地址是直接指向解码部分的代码，而非原来的程序入口。我们脱壳所要做的工作，就是还原出原来的程序，并且每次执行时直接从原入口地址开始执行（而不需要再运行用于解码的&ldquo;壳&rdquo;），因此需要得知原入口地址是什么，即OEP。</p>
<p>[Armadillo] 传说中的猛壳，因为拼写太长，也有人缩写为arm壳。它使用多种加密手段以防止脱壳，比如检测debugger、修改IAT、还有高级版本的stolen byte和双线程解码。</p>
<p>[IAT] Import Address Table的缩写，也有叫输入表，引入表。它用来保存程序用到的API函数的入口地址。</p>
<p>[RVA] Relative Virtual Address，相对虚拟地址。win32系统会把进程读入到内存中执行，所以存在着内存地址和文件偏移的转换关系。PE文件头里面会有一个内存基址base，原来在文件中偏移为x的内容，在内存里面的偏移就变成base+x。为了区分这两种地址偏移，通常叫文件中的偏移为RVA</p>
<p>[magic jump]（一般破文是按10多次或者20多次F9，就来到magicjump。我根本不知道怎么去判断一个新软件的magicjump在哪里，也不知道那个次数是怎么得来的，不怕，下面我会教一种我认为比较好的方法）其实所谓magic jump，是指跳过改写IAT的代码段。Armadillo的解壳过程有一个特点，就是会改写IAT。（这里我用的是&ldquo;改写&rdquo;而不是某些文章中的&ldquo;破坏&rdquo;是有原因的。曾经我在这里也困惑过，破坏带有不可恢复的意思，事实上IAT对应的地址并没有完全破坏，只是被改写成更难辨认的形式。这里举一个具体例子）</p>
<p>00E6E0E1&nbsp;&nbsp;&nbsp;&nbsp; mov edx,[EA01B8]&nbsp;&nbsp;&nbsp;&nbsp; // ~= kernel32.dll/00D4/FindNextFileA<br />00E6E0E7&nbsp;&nbsp;&nbsp;&nbsp; add edx,64<br />00E6E0EA&nbsp;&nbsp;&nbsp;&nbsp; call edx<br />00E6E0EC&nbsp;&nbsp;&nbsp;&nbsp; mov edx,[EA0144]&nbsp;&nbsp;&nbsp;&nbsp; // ~= kernel32.dll/016F/GetModuleFileNameW<br />00E6E0F2&nbsp;&nbsp;&nbsp;&nbsp; add edx,64<br />00E6E0F5&nbsp;&nbsp;&nbsp;&nbsp; mov ecx,5</p>
<p>这个是被改写后的IAT指向的一端程序段。里面实际工作是作还原工作。先取出edx(这里对应一个假API)，然后加上64偏移才得到真正的API，再进行函数调用。FindNextFileA后面的偏移64是GetTickCount，GetModuleFileNameW后面是GetModuleHandleA，所以上面的代码相当于<br />call kernel32.GetTickCount<br />nop<br />&hellip;<br />call kernel32.GetModuleHandleA</p>
<p>这样可以使得手动脱壳过程中把IAT表弄坏（因为无法识别出正确的API），但是加壳程序却可以正常运行。是不是很狡猾？解决办法也简单，在脱壳的过程中避开执行改写IAT表的代码段，只需要修改一条指令，这条指令，正是magic jump！</p>
<p>能够坚持看到这里是否已经有点烦闷了？基本理论就这么多了。准备好工具了吗？让我们马上开始。</p>
<p>【工具】OD、LordPE、ImportREC<br />【过程】<br />【Action 1】 明察暗访OEP<br />OD载入程序，用插件隐藏OD，忽略所有异常，alt_m查看内存映射，在00401000处下内存读取断点，F9<br />程序停下来了，看到没有，熟悉的开头。没有看到？肯定你遇到异常了，shift_F9试试？<br />005E14E4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 55&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; push ebp<br />005E14E5&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8BEC&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mov ebp,esp<br />005E14E7&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 83C4 E4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; add esp,-1C</p>
<p>我们找到OEP了，马上记下吧。Action 1目标完成：OEP=001E14E4<br />等等，是不是打错字了？不是005E14E4吗？还记得RVA吗？通常来说，windows会把程序读到从00400000开始的连续内存空间（当然也不是一成不变，只是通常碰到的情况都是这样），也就是说你看到的OEP 005E14E4是内存的地址，它的RVA是001E14E4。明白了吗？</p>
<p>【Action 2】攻下桥头堡<br />运行到OEP预示着解码阶段的完成了。所以理论上现在内存中的是已解码的程序。先不要动OD，保持在OEP入口。运行LordPE，选刚刚运行的程序的线程，full dump，Action 2完成！</p>
<p>先别对着dump出来的exe笑啊，如果现在那个是最终的脱壳结果，Armadillo就不叫猛壳了，我刚刚写的一堆理论也就白费劲。喝口水再继续吧。下面才到重点。</p>
<p>【Action 3】扫清地雷阵<br />OD没有关掉吧？恩，别动它，继续保持。运行ImportREC，选择程序进程，在下面的IAT Infos needed填入刚才拿到的OEP。AutoSearch，看到RVA框变了，那个就是IAT的地址和大小了。我这里找到的数值是001ED240<br />回到OD，d 5ed240（还记得刚刚说过的内存偏移的换算关系吗？），看到什么了？那个就是IAT呀。记下它的样子。然后分别在第一个项目和最后一个项目下硬件写入断点。（为什么用硬件捏？因为它不影响速度，而且重新运行的时候不会没掉，呵呵）<br />下面重新运行吧。F9，碰到硬件断点了。还记得IAT的样子吗？继续F9，直到第一个条目和你刚刚记下的一样。现在按page up，一直向上找GetModuleHandleA</p>
<p>00E86AB1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6A 00&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; push 0<br />00E86AB3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FF15 D400E900&nbsp;&nbsp;&nbsp; call dword ptr ds:[E900D4]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ; kernel32.GetModuleHandleA<br />00E86AB9&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3985 90C4FFFF&nbsp;&nbsp;&nbsp; cmp dword ptr ss:[ebp-3B70],eax<br />00E86ABF&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 75 0F&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; jnz short 00E86AD0<br />00E86AC1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; C785 8CC4FFFF 8&gt;mov dword ptr ss:[ebp-3B74],0E95180<br />00E86ACB&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; E9 C4000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; jmp 00E86B94<br />00E86AD0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 83A5 68C2FFFF 0&gt;and dword ptr ss:[ebp-3D98],0<br />00E86AD7&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; C785 64C2FFFF C&gt;mov dword ptr ss:[ebp-3D9C],0E957C0<br />00E86AE1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; EB 1C&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; jmp short 00E86AFF<br />00E86AE3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B85 64C2FFFF&nbsp;&nbsp;&nbsp; mov eax,dword ptr ss:[ebp-3D9C]<br />00E86AE9&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 83C0 0C&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; add eax,0C<br />00E86AEC&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8985 64C2FFFF&nbsp;&nbsp;&nbsp; mov dword ptr ss:[ebp-3D9C],eax<br />00E86AF2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B85 68C2FFFF&nbsp;&nbsp;&nbsp; mov eax,dword ptr ss:[ebp-3D98]<br />00E86AF8&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 40&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; inc eax<br />00E86AF9&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8985 68C2FFFF&nbsp;&nbsp;&nbsp; mov dword ptr ss:[ebp-3D98],eax<br />00E86AFF&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B85 64C2FFFF&nbsp;&nbsp;&nbsp; mov eax,dword ptr ss:[ebp-3D9C]<br />00E86B05&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8338 00&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cmp dword ptr ds:[eax],0<br />00E86B08&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0F84 86000000&nbsp;&nbsp;&nbsp; je 00E86B94<br />00E86B0E&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B85 64C2FFFF&nbsp;&nbsp;&nbsp; mov eax,dword ptr ss:[ebp-3D9C]<br />00E86B14&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B40 08&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mov eax,dword ptr ds:[eax+8]<br />00E86B17&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 83E0 01&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; and eax,1<br />00E86B1A&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 85C0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; test eax,eax<br />00E86B1C&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 74 25&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; je short 00E86B43<br />00E86B1E&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; A1 2800EA00&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mov eax,dword ptr ds:[EA0028]<br />00E86B23&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B0D 2800EA00&nbsp;&nbsp;&nbsp; mov ecx,dword ptr ds:[EA0028]<br />00E86B29&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B40 20&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mov eax,dword ptr ds:[eax+20]<br />00E86B2C&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3341 40&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xor eax,dword ptr ds:[ecx+40]<br />00E86B2F&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B0D 2800EA00&nbsp;&nbsp;&nbsp; mov ecx,dword ptr ds:[EA0028]<br />00E86B35&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3341 28&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xor eax,dword ptr ds:[ecx+28]<br />00E86B38&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 25 80000000&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; and eax,80<br />00E86B3D&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 85C0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; test eax,eax<br />00E86B3F&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 74 02&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; je short 00E86B43<br />00E86B41&nbsp;&nbsp;&nbsp; ^ EB A0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; jmp short 00E86AE3<br />00E86B43&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B85 68C2FFFF&nbsp;&nbsp;&nbsp; mov eax,dword ptr ss:[ebp-3D98]<br />00E86B49&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B0D 74B7E900&nbsp;&nbsp;&nbsp; mov ecx,dword ptr ds:[E9B774]<br />00E86B4F&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B15 2800EA00&nbsp;&nbsp;&nbsp; mov edx,dword ptr ds:[EA0028]<br />00E86B55&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B0481&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mov eax,dword ptr ds:[ecx+eax*4]<br />00E86B58&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3342 24&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xor eax,dword ptr ds:[edx+24]<br />00E86B5B&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B0D 2800EA00&nbsp;&nbsp;&nbsp; mov ecx,dword ptr ds:[EA0028]<br />00E86B61&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3341 28&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xor eax,dword ptr ds:[ecx+28]<br />00E86B64&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B0D 2800EA00&nbsp;&nbsp;&nbsp; mov ecx,dword ptr ds:[EA0028]<br />00E86B6A&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3341 44&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xor eax,dword ptr ds:[ecx+44]<br />00E86B6D&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 8B0D 2800EA00&nbsp;&nbsp;&nbsp; mov ecx,dword ptr ds:[EA0028]<br />00E86B73&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3341 6C&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xor eax,dword ptr ds:[ecx+6C]<br />00E86B76&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3985 90C4FFFF&nbsp;&nbsp;&nbsp; cmp dword ptr ss:[ebp-3B70],eax</p>
<p>你看到的这段可能会跟我给出的有点差异，不过很好认，会有一段mov和xor交错出现的地方，并且mov语句是完全相同的。这里是00E86B1E-00E86B76</p>
<p>向上找可以跳过这段代码的转跳语句，这里是<br />00E86B08&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0F84 86000000&nbsp;&nbsp;&nbsp; je 00E86B94&nbsp;&nbsp;&nbsp;&nbsp; ;magic jump!!!!!!!!</p>
<p>我看到其他教程，这句是je short的，所以可能是Armadillo版本不同。不过道理都是一样，避开对IAT表的改写。<br />把这句改成jmp，再按F9，遇到第二个硬件断点，这时IAT转换完成。这个可是没有被做过手脚的完整IAT啊～<br />哦，这里别忘了，回到刚刚修改的jmp那里，改回je啊。不然后面的解码会出错导致程序异常终止了。（至少我脱的这个壳会这样。好像只有很少的脱文提到要恢复指令，反正恢复也没坏，多做一步吧，不然异常了可能还要重新来过）<br />再bp 005e14e4，在OEP处下断，F9，运行到OEP</p>
<p>【Action 4】长驱直入，胜利会师<br />拿出ImportREC出来吧，重新选一下进程，autosearch，步骤应该都熟悉了。这次可以点Get Imports了。如果还有unresolved pointer，就点Show Invalid，Trace Level1试试，剩下的用Cut thunk全部干掉。然后fix dump，选择Action 2 dump出来的exe，应该就多出来一个文件名后面多带一个_的exe文件。这个是脱壳后独立运行的exe啊。试试能不能运行，不行的话，调整一下ImportREC的参数再试试，有些软件不能用Add new section的。把auto search的结果填到New Import Infos，去掉Add new section再试一遍。</p>
<p>【Action 5】清除残余势力<br />脱壳出来的程序很大，因为里面包含了很多已经没用的解码程序段。为了做到完美脱壳，我们可以把没用的代码清理掉。主要过程可以参考《脱壳后软件减肥大法》http://www.pediy.com/bbshtml/BBS6/pediy6313.htm，这里就不赘述了。不过调整.idata保证VA连续的那一步我不是按它的，不需要手动调整，直接用LordPE的rebuild PE就可以了，有现成工具干吗还要造轮子了？</p>
<p>【后记】<br />当我看到脱壳出来的程序正常运行时，有一种兴奋的感觉。也许我是脱壳菜鸟，这些对高手们确实不值得一提。可是正如fly斑竹所说，我知道自己进阶了。把过程和大家共享，希望大家可以跨过入门的门槛，共同进步。</p>

	<h4>相关文章</h4>
	<ul class="st-related-posts">
	<li><a href="http://www.donevii.com/post/75.html" title="挣脱Windows的枷锁：Linux屏幕录像 (2006-10-10)">挣脱Windows的枷锁：Linux屏幕录像</a> (0)</li>
	<li><a href="http://www.donevii.com/post/283.html" title="免费软件套装 (2007-01-08)">免费软件套装</a> (0)</li>
	<li><a href="http://www.donevii.com/post/112.html" title="這十八招Web2.0創業者千萬不要學 (2006-10-24)">這十八招Web2.0創業者千萬不要學</a> (0)</li>
	<li><a href="http://www.donevii.com/post/110.html" title="翻译：On having layout (2006-10-24)">翻译：On having layout</a> (0)</li>
	<li><a href="http://www.donevii.com/post/740.html" title="管理者，请你远离产品开发/设计部门[转] (2009-01-12)">管理者，请你远离产品开发/设计部门[转]</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/329.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
