<?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; ror</title>
	<atom:link href="http://www.donevii.com/post/tag/ror/feed" rel="self" type="application/rss+xml" />
	<link>http://www.donevii.com</link>
	<description>关注技术、移动互联网以及一切 GEEK &#38; NERD 的事情</description>
	<lastBuildDate>Wed, 21 Dec 2011 10:49:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>slideshare 服务中断</title>
		<link>http://www.donevii.com/post/635.html</link>
		<comments>http://www.donevii.com/post/635.html#comments</comments>
		<pubDate>Wed, 26 Nov 2008 10:05:54 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[ror]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/635.html</guid>
		<description><![CDATA[在北京，此网站无法访问。 Something went wrong! This is probably a temporary error. - Try refreshing the page or - Go back and try again 504 Erro... ]]></description>
			<content:encoded><![CDATA[<p>在北京，此网站无法访问。</p>
<div id="container">
<h1>Something went wrong!</h1>
<p>This is probably a temporary <a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">error</a>.
  </p>
<ul>
<li>- Try <a href="javascript:location.reload(true)">refreshing</a> the page or</li>
<li>- <a href="javascript:history.go(-1);">Go back</a> and try again</li>
</ul>
</div>
<p><span class="errorCode">504 Error</p>
<p></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/635.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ffmpeg-php make error</title>
		<link>http://www.donevii.com/post/540.html</link>
		<comments>http://www.donevii.com/post/540.html#comments</comments>
		<pubDate>Sat, 04 Oct 2008 07:09:18 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[ror]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/540.html</guid>
		<description><![CDATA[make 时一直报 &#8216;ImgReSampleContext&#8217; undeclared 这个错误，看了一下 log 好像是谁改了 avcodec.h 文件，只好用 ffmpeg r15261 来编译了，sigh。ffmpeg svn 的稳定性一直很愁... ]]></description>
			<content:encoded><![CDATA[<p>make 时一直报 &#8216;ImgReSampleContext&#8217; undeclared 这个错误，看了一下 log 好像是谁改了 avcodec.h 文件，只好用 ffmpeg r15261 来编译了，sigh。ffmpeg svn 的稳定性一直很愁人<a href="http://www.flickr.com/photos/27801040@N03/2835558500"><img src="http://farm4.static.flickr.com/3179/2835558500_5cef17c0ae.jpg" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/540.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>一个有关用户体验的文章</title>
		<link>http://www.donevii.com/post/539.html</link>
		<comments>http://www.donevii.com/post/539.html#comments</comments>
		<pubDate>Thu, 02 Oct 2008 09:47:38 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[测试]]></category>
		<category><![CDATA[生活]]></category>
		<category><![CDATA[类]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/539.html</guid>
		<description><![CDATA[一直坚信细节决定成败，在 BLUEIDEA 碰巧看到这篇有关用户体验的文章，讲述的内容都是很简单的，但是实际在工作中，有些东西我也总遗忘，转载过来和大家共享吧。 以下是我做美工的两年生... ]]></description>
			<content:encoded><![CDATA[<p>一直坚信细节决定成败，在 BLUEIDEA 碰巧看到这篇有关用户体验的文章，讲述的内容都是很简单的，但是实际在工作中，有些东西我也总遗忘，转载过来和大家共享吧。</p>
<p><span id="more-539"></span></p>
<blockquote><p>
以下是我做美工的两年生活中一条条总结出来的经验，每一点都是我常用的，虽然不是什么大学问，但我觉得要互相学习才能提高，所以现在拿出来和大家一起分享，如果你觉得实用就拿去试试，然后留个评论，我就很高兴了，不喜欢的可以路过。费话少说，下面正式开始。</p>
<p>1.加载大图片时，显示loading小图片。</p>
<p>这招是我最常用的。当我们要加载一张比较大的图片时，如果能加载图片的同时，显示loading的小图片，那样看起来就人性化很多。当加载完成时，图片会盖住loading小图片，这是一个很有用的小技巧，我的每个网站都加上了这个功能，不信你可以到这个页面看，http：//www.82xuexi.cn/<a href="http://www.donevii.com/post/tag/html" class="st_tag internal_tag" rel="tag" title="Posts tagged with html">html</a>/2008-09/245.htm这个页面是我专门做来演示这个示例的，上面我放了一张很大的图片，应该可以看清加载过程。要实现这个小功能，只要在网站的公共样式表上添加下面这个样式 ，就可以实现了。</p>
<p>img {</p>
<p>background-image：url（loading.gif）;</p>
<p>background-position：center;</p>
<p>background-repeat：no-repeat;</p>
<p>}</p>
<p>解释一下上面的代码，懂CSS的站长可以略去这段。第一行“img”指向页面的全体图片元素（看到样式表的优势了吧，只要一句，就能作用于网站的全体同类元素，不是DIV+CSS的网站站长是不是有想法了？呵呵）。第二行“background-image：url（loading.gif）;”是指为图片添加一个以图片为背景的背景（读起来有点拗口）。这个loading.gif是你要你自己上传的加载小图片。不过有些网站的images文件夹里已经有这个图片了，直接用就行，如果你确实不想到处找的话，我这里有一堆，选一个你喜欢的玩玩吧：http：//www.82xuexi.cn/html /2008-09/333.htm。第三行：background-position：center;把背景图片居中，这样看起来比较顺眼。第四行：background-repeat：no-repeat;就是让loading.gif小图片只显示一个，如果没有这句，就用出现很多排列起来的 loading.gif小图片，这要注意一下。</p>
<p>2.选填表单右边显示“可不填”。</p>
<p>这是我最初在QQ网站的留言本上看到的，当时看到个人信息的一些表单旁边写着“可不埴”的时候，真的是感觉非常舒服，你想想，人家好不容易有空给你留言，你还想人家慢慢看你的留言说明吗？给你留言，当然想简要完事啦。你却动不动跳出个“表单内容不能有空”这不把人家吓跑才怪。这个小技巧可以应用于各大论坛的用户注册，留言本等地方，不要只在必填框旁边加个红*就算了，这样对于熟悉网站的人来说当然没问题，但你要考虑到各种各样的网民。“可不填”三个字，就能大大提高用户体验，为什么不试试呢。</p>
<p>3.保证每个页面都有回首页的连接。</p>
<p>为什么要主这个呢？因为我看到很多网站都没注意到这个小细节，有一次我在一个论坛上登陆，成功后，他跳转到另一个页面提示登陆成功，等了十几秒它都不自动返回，但我又已经顺手把多的页面关掉了，所以，只剩下一个页面了，我又不能返回，他又没有返回首页的链接，一气之下，我就关掉浏览器走人了。所以，建议站长朋友们有空多检查一下自己的网站，看是不是有些页面是孤独的。</p>
<p>4.在执行AJAX操作时，如果响应时间过长，应提示用户加载超时。</p>
<p>这个在AJAX中，可以使你的程序更人性化的小技巧，不多说了，你看下面的代码就明白。如果你看不明白的话，就不要乱改网站，会出错的。这是一个用户验证的程序片段，注意红色部分。</p>
<p>var timeLast;</p>
<p>//发送信息</p>
<p>function submitSelectItem（）</p>
<p>{</p>
<p>var postStr=“uid=”+document.getElementById（“userName”）.value+“&amp;pwd=”+hex_md5</p>
<p>（document.getElementById（“passWord”）.value）;</p>
<p>timeLast=window.setTimeout（“show_timeout（）”，15000 ）;//超过15000毫秒后显示超时</p>
<p>show_waitting（）;</p>
<p>createXMLHTTP（）;//创建XMLHttpRequest对象</p>
<p>var url=“ajax/chcekUser.aspx？time=”+TimeDemo（）;</p>
<p>xmlHttp.open（“POST”，url，true）;</p>
<p>xmlHttp.setRequestHeader（“Content-Type”，“application/x-www-form-urlencoded：charset=UTF-8”）;</p>
<p>xmlHttp.onreadystatechange=getResponseRusult;</p>
<p>xmlHttp.send（postStr）;</p>
<p>}</p>
<p>//回调函数</p>
<p>function getResponseRusult（）</p>
<p>{</p>
<p>if（xmlHttp.readyState==4）//判断对象状态</p>
<p>{</p>
<p>if（xmlHttp.status==200）//信息成功返回，开始处理信息</p>
<p>{</p>
<p>clearTimeout（window.timeLast）;</p>
<p>var reint=xmlHttp.responseText;</p>
<p>switch （reint） {</p>
<p>case “1”：</p>
<p>show_success（）;break ;</p>
<p>case “2” ：</p>
<p>show_tryCountOut（）;break ;</p>
<p>default ：</p>
<p>show_<a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">error</a>（）;break ;</p>
<p>}</p>
<p>}</p>
<p>}</p>
<p>}</p>
<p>5.可能的不良后果提前提醒用户。</p>
<p>如果你的页面很大，特别是要用到很多表格时，加载时间可能会很长，这时候要提前告诉用户。“页面可能加载时间比较长，请耐心等待。..。”之类的。</p>
<p>6.拿到美工做给你的页面，一定要测试不同的浏览器。</p>
<p>这主要是有些美工不太负责，你不要求他就不测试。所以要自己测试一下，发现在其它浏览器显示不正常时，要求美工修改。我做的页面都经过火孤，IE6，IE7，OPERA等测试才交给客户的。我觉得交给客户不成熟的东西会对自己形像不好。</p>
<p>7.文章标题采用缩略时，要在“title“有完整描述。</p>
<p>这点在很多SEO教程中都说过的，我就不分析了。</p>
<p>8.用户人性关怀。</p>
<p>如果网站使用了注册制度，主页应该为新用户和老用户登录提供链接。并且要有某种方式让我知道自己已经登录了，友好方法（“欢迎回到不爱学习网，lanmeng”）。</p>
<p>9.让我看到自己正在寻找东西。</p>
<p>主页应该让我想要任何东西显而易见——如果它在站内某个地方话。。.. 。.. 还有我没有寻找。同时，主页也应该让我看到一些很精彩，我也许感兴趣内容——就算我并没有寻找它们。</p>
<p>10.告诉我从哪里开始。</p>
<p>在一个新网站里，无从下手感觉糟糕透了。这点对新用户比较有效。可以这样判断下：</p>
<p>if（session.isNewSession）{</p>
<p>//新用户向导。</p>
<p>}
</p></blockquote>
<p><a href="http://bbs.blueidea.com/viewthread.php?tid=2888813" target="_blank">原文链接</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/539.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>(日本AV扫盲贴)如何选AV片</title>
		<link>http://www.donevii.com/post/448.html</link>
		<comments>http://www.donevii.com/post/448.html#comments</comments>
		<pubDate>Wed, 25 Jun 2008 03:01:37 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[life]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[女生]]></category>
		<category><![CDATA[类]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/448.html</guid>
		<description><![CDATA[日本的马赛克制度 现在很多朋友都在求一些知名女优的无码片,但相信看多下面的A片制作流程,你就会发现,这几乎是不可能发生的事情。现在一些狼友们能够认识的,基本都是2 线以上的明星,能... ]]></description>
			<content:encoded><![CDATA[<p>日本的马赛克制度   <br />现在很多朋友都在求一些知名女优的无码片,但相信看多下面的A片制作流程,你就会发现,这几乎是不可能发生的事情。现在一些狼友们能够认识的,基本都是2 线以上的明星,能拿的出手的,那更是多为一线,比如像爱田由, 松岛枫, 苍井空, 神谷姬, mihiro&#8230;等等,都是各个厂商的台柱女星.这些人基本是不可能有无码片的.WHY?原因就在于她们都和有码的一线大厂签订了合约, 像kmp, alice japan, max-a, s1. moodyz. kuki&#8230;.等大厂.为什么都是有码的厂商呢?这是因为在日本无码片是非法的, 所以一线女优有合约时都不可能拍, 而退役后如果一年內沒有无码流出版出现的話, 基本上是不会有无码流出片了,所以,朋友们,看到标题为无码流出版的片子,多多收集吧,可遇不可求啊.    <br />那你可能会问:不对啊,我看过很多无码的日系A片啊,有些女优也是相当有名啊.这点的确不错,下面就来介绍一下日本无码片中女优的情况.    <br />第一种是退休后的女优因为种种原因复出之后拍无码片,比如像鈴木麻奈美, 吉野莎莉, NANA&#8230;&#8230;&#8230;.等等.不过这些主要都是些二流女优. 而像古都光,高樹瑪利亞, 伊東玲, 美竹涼子&#8230;等一线女优基本上不会复出拍无码.    <br />第二种就是没有合同的女优.比如大家所熟悉的潮吹女王红音.她是沒有合同在身的女优, 在日本俗称流浪女优(好凄凉的名字&#8230;&#8230;),.由于沒有合同在身,所以只要价钱合理,就可以拍.    <br />第三种就是素人时拍的无码片,现在被厂商拿出来贩卖,比如立花里子,现在她的无码片就属于这一种.    <br />最后一种就比较多了,就是从有码界引退后,再投身无码界,比如纹舞等等.    <br />总结一点,无码片中的女优在日本基本上都不是一流的,原因很简单,无码片的档次比有码的要低的多.    <br />无码片由于是非法的, 所以成本會很低.因此无码片时间就是金钱, 不会有太多內容和道具, 服装, 化妆, 灯光, 画面, 后期加工都会很粗糙,而且有时看到一些女优的阴部又黑又烂, 就像两片烂肉, 看到都沒有性趣, 所以除了有名女优拍的,我个人基本不看无码.    <br />总的来说,无码片是看人,有码片是看片.两者重点不同.有码片就像是電影,像《魔戒》, 《星球大战》等.无码片就像是小品剧, 纯粹个人表演, 两者沒有什么好比的.    <br />最后提个传言,坊间一直流传, 在酒井法子出道前, 曾拍摄一部三级片.但不知是露两点的R片, 还是打真军的A片, 這个消息一直被资深狼友们奉为神之传说.    <br />小弟我福缘浅薄, 一直未能得看酒井法子的片片,希望上天眷顾,一遂我得心愿.<img src="http://static.footbig.com/babel-static/img/icons/silk/emoticon_happy.png" align="absMiddle" border="0" />    <br />AV，日本最流行。可以说,AV已经是日本的重要产业之一.    <br />既然有心看AV，要挑嘛，第一个当然就是要看人。从BT上下片然后一部部看,从中认识女优固然也不错,不过眼界就会窄很多,所以搜索才是王道.至于怎么搜,看下面.    <br />首先参考的资料是是VIDEOBOY的杂志排名。虽然是日本杂志的排行，和国人的口味不太一样，不过还是有一定的公信力，可以拿来当作参考，能够排到前十名的都可以算是实力派的AV女优(这个自己上YAHOO.JP搜索)。不过这东西一般人根本没机会买到,我也是偶然的机会从我出国的表哥那里看到的,不过除了排名其他就完全看不懂了,<img src="http://static.footbig.com/babel-static/img/icons/silk/emoticon_happy.png" align="absMiddle" border="0" />.所以一般还是要从网上下手.    <br />如果要纯粹网站的排名的话，V.SHOCK，XCITY和avgirls.net的排名可以拿来参考。此外一些贩售AV的网站也有排名可以当成拍片的依据，要看专门的AV讨论志的话，VIDEOBOY，BESTVIDEO和DVDPERFECT是专门的AV讨论志，BEJEAN的话算是比较综合性质的写真杂志，而URECCO和BEPPIN SCHOOL算是专门的写真杂志。如果只想看排名,直接在网上搜上面提到的关键字,也会有所收获.    <br />至于国内的AV论坛，介于狼网的制度,为避免广告之嫌,不多做介绍.    <br />下面是个人的心得了,其实也都是一些选片的基本技巧,看看封面就可以知道大半了,所以下面的东西大家要仔细看了,对你选片绝对有帮助的.    <br />一、首先是女优类型(这是每部片子中都会有介绍的,选定了这个,就选对了一大半了)    <br />1、巨乳系:VIDEOBOY排名前十名的有一半以上都是属于F-CUP级的，以巨乳著名的AV女星有大浦安娜，熏樱子，白鸟さくら，樱朱音，舞冈结希，星川光等等&#8230;&#8230;    <br />2、清纯派:首要推荐就是高树玛莉亚，2003年日本票选唯一五颗星AV女优；接着下来能推的就是古都ひかる，苍井そら，美竹凉子，小沢菜穂和萩原舞等等&#8230;&#8230;    <br />3、罗莉向(LOLI，指看上去像小姑娘的女优,当然实际年龄都是合法的,不然厂商就要倒霉了<img src="http://static.footbig.com/babel-static/img/icons/silk/emoticon_happy.png" align="absMiddle" border="0" />):第一名大概就是堤莎也佳，另外小仓杏，小仓ありす(小仓艾利丝)，月野しずく，秋月杏奈等也都可以看。    <br />4、痴女系(与痴汉相对,这个比较难解释,大体就是很主动的女性的意思,自己体会吧)：三上翔子(目前改行当AV监督去了,哈哈,比较厉害)和朝河兰是最佳选择，而他们的后辈像立花里子，宫下杏菜，姬川丽和芹泽直美也都是蛮有名的痴女系,还有个人比较喜欢的原千尋也属其中.    <br />5、熟女系：紫彩乃，赤坂ルナ和麻布レオナ熟女三大天后是入门(不过都超过30了说)，其它像是友田真希，小池绘美子，友崎亚希，MAYUKA等也值得一看。    <br />此外，要高挑美腿的话，绫乃梓，鸟越乃亚(现名NOA)和矢崎茜就拿下来吧，立花里子也不赖；    <br />想找大姐姐的话，松岛枫是不二人选；其它像泷泽优奈,水元ゆうな,穗花,nana,中川瞳能收就收；    <br />纯粹想要搞菊花的话，目前是AV女优后庭次数第一的南波杏是不二选择；    <br />要想听叫声的话，小泽圆，白石瞳，萩原舞会让人听到麻苏苏&#8230;&#8230;    <br />要看明星脸的话(这个纯属YY,个人反正没多大兴趣)，唯川纯(长得很象台湾红星林志玲)，松嶋菜菜(有点松岛菜菜子的味道)，今野由爱(象极滨崎步)，坂下麻衣(很象侯佩岑哦),还有那个井泽芽衣(像范冰冰)均可以拿来玩超级比一比；    <br />只要纯无码的话，及川奈央，白石ひより，樱田さくら和葵实这几位的产量都很多。    <br />如果阁下的水准已经超出常人,想纯粹看AV男优的话，加藤鹰，南佳也，巧克力向井(现役摔角手，特技是火车便当固)和MICKY柳井(外号THE HELICOPTER MAN，特技就是直升机)一定要认识!!这条MM们可能游泳<img src="http://static.footbig.com/babel-static/img/icons/silk/emoticon_happy.png" align="absMiddle" border="0" />    <br />二、看完了人,下面是选片的一些技巧    <br />第一 看系列    <br />1.较长卖的系列，    <br />例如MAX COFE，Tokyo Hot,女教师狩猎，不法侵乳，超高级泰国浴女郎，ANGEL系列 ，猥亵系列，制服人形，DIGITAL MOSAIC系列等等都是票房保证.    <br />另外比较重口味的像是:极乱/极本番系列，志摩紫光SM调教系列，死夜恶系列，痴汉系列，人间废业系列，四时间系列对于口味比较重的来说可以拿来选择 .    <br />2.一些比较常见的系列 :    <br />新人第一作的话:强力推荐&#8221;处女宫&#8221;系列    <br />素人的话就是: AURORA PROJECT    <br />角色扮演的话就以: ANGEL系列，MAX COFE系列和制服人形系列较出名    <br />比较淫乱的话:催眠系列，极乱系列，极本番系列都是值得一看的系列作    <br />要SM调教的话:志摩紫光SM调教系列和龙缚爱玩调教系列算是出名的作品系列    <br />3、话题性的东西也常是票房保证    <br />例如全裸系列(全裸和太鼓，全裸芭蕾，全裸体育选手权，全裸中国杂技团等等)，因为人难找，做出来都是高成本高回收；另一种就是AV女优竞技系列(像是全裸马拉松，全裸相扑，全裸水中舞蹈、全裸美女运动会等等)，这个成本较上面那种少，话题性也够，要找人也不难，一堆小牌AV女优排队等着选但是缺点就是品质参差不齐，偶而还会看到哥斯拉级的恐龙妹(以前看过的全裸足球,那个恶心的我)&#8230;&#8230;    <br />4、电影改编的色情版本也常是题材(这个大家估计就很少看到了,FFX应该是比较多人看过的)：    <br />电影方面的，像《杀死比尔》、《霹雳娇娃》、《极道之女》等等&#8230;&#8230;    <br />电视剧方面，像《白色巨塔》，《魔女的条件》，《鬼之栖家》等&#8230;&#8230;    <br />电脑游戏方面，像零红蝶，FFX&#8230;&#8230;    <br />漫画方面，《像玛莉亚的凝望》、《银河铁道999》、《网球甜心》等&#8230;&#8230;    <br />音乐方面，像女子十二乐坊&#8230;.    <br />AV特摄的，像《爆乳战队》、《超光辉士》等&#8230;&#8230;    <br />上述这类型的当然都是以搭原作的市场话题顺风车为导向，只要话题炒热了，就不怕没钱赚。    <br />5、当然有些特殊类型的片子也是焦点，例如交互式AV和VR FUCK系列，因为制作DVD片子的成本高(拍起来的成本倒是比一般片子低)，在日本很难看到。这个就是和欧美DP公司出品的MY PLAYING THINGS相类似的一种片子,可以通过遥控器和片子中的女优互动,有很强的投入感,不过介于上面提到的原因,很难看到.    <br />第二 看公司    <br />大手公司像是MOODYZ，SOFT OF DEMAND，ATTACKERS，I ENERGY这些大手出片量多，也敢出话题性的作品(象《金丝雀》系列)；比较小一点的像&#8220;忠实堂&#8221;，&#8220;桃太郎映像&#8221;，&#8220;マルクス兄弟&#8221;，&#8220;ACTIVE 1&#8221;，&#8220;MAX A&#8221;等等，要不就是靠重口味(像最近刚出的樱田SAKURA母子号泣乱交)，要不就是靠看板娘(像夏目NANA)来在这市场分一杯羹。    <br />专门作出租片的像芳友社(h.m.p)则就纯粹靠口碑了，所以这家的片子品质不错；另外近期出来的新公S1REALWORKS，这两家标榜超薄码，而且挖了一堆知名的av女优当看板娘，像苍井、樱朱音、nao、小泽菜穗&#8230;.等等，所以也相当值得注目。    <br />第三 看监督    <br />现在的一般狼友几乎不可能会注意监督,但是监督确实是片子好坏的一个重要因素:好监督可以把一个看起来不怎么样的AV女优拍到红，不好的监督就常常沦为封面杀手。这个业界中比较棒的就属长崎南(少数女性监督)、二村ヒトシ、溜池通口三人；话题性的话则属志摩紫光、川崎军二、甲斐正明为首。    <br />第四 看封面    <br />除非你对这个女优或者是这个系列有相当程度的认知 ,不然封面封底拍的越漂亮(尤其是拍到像艺术沙龙照那种)，踩到地雷的可能性越大 .    <br />讲个例子，古都光的片子封面封底都打光或修到脸上的三颗痣都看不到&#8230;..    <br />如果你实在都不知道该怎么选，没关系 .大手公司一段时间都会出精选集 .    <br />像: DEEPS和h.m.p的精选集，四个小时让你看半年份的片子精华.而且价格又便宜(不到1000日圆)，可以作为类型的挑选标准 .    <br />日本的片子以DVD为大宗 ,所以入手收藏的话当然以DVD为主 .但是日本的片子有分成出租版和贩卖版 .当然出租版的片长较短 .贩卖版则绝大多数有附DVD特点映像 .    <br />下面是推荐的DVD-A片收藏手册 :    <br />紅頭馬系列 彩色豬系列 老虎系列 私校女生系列    <br />AV女王系列 金獅珍藏系列    <br />無尾熊系列女優大賞10部強片    <br />小水蛙系列 女校生援助交際系列 同人誌系列    <br />名星女優全集 小澤圓全集 近親相姦    <br />閃電系列 亞熱系列    <br />JAPANAVGIRL系列 神工系列    <br />JAPAN TEEGIRL系列 超激烈-SM系列    <br />AV鳳梨系列 糖果女孩系列    <br />粉紅蝸系列    <br />老虎系列 海外武士系列    <br />日本羊系列 女優牛奶系列    <br />日本黑馬系列 真豬無碼系列    <br />漂亮寶貝系列 清純可愛系列 日本黃冠系列 東瀛美少女系列無碼影片    <br />新春賀歲系列 特別服務系列無碼影片    <br />日本飛龍系列 香菇大賞系列 野花系列無碼影片    <br />白鷹系列 黑熊系列    <br />學生系列 快樂龜系列 宇宙企画系列 一本道系列    <br />这些是市面上可能见到的日本A片系列的DVD，多为不知名版本，多为2次转录，有少量的黑封面不知名版本套装为直灌碟，画质良好，带花絮。其中著名的为亚热系列，老虎系列，武士系列，宇宙企画系列，一本道系列。    <br />最后，如果你实在都不知道该怎么选，没关系，大手公司一段时间都会出精选集，像DEEPS和h.m.p的精选集，四个小时让你看半年份的片子精华，前些时候狼网的精英们就发过这样的片子,这中片子可以作为类型的挑选标准。    <br />最后也是最重要的，就是看片子的人是你而不是别人，自己的眼光才是最重要的，所以片子看的越多对自己的鉴赏能力帮助越大。    <br />总结来说,下面就是个人的一些看AV心得    <br />1、知名系列品质有保证    <br />2、别相信报章杂志的报导    <br />3、旧的AV女优别管马赛克了，因为不是无码就是超厚码(哈哈,是超厚)    <br />4、要看超薄码请认定&quot;デジタルモザイク&quot;和&quot;デジ消&quot;这两个名词(看DVD封面,防止发片的人恶意误导)    <br />5、口碑是相当重要的一个参考,但如果看的片不多就不用管太多    <br />6、再次纠正狼友们的一种错误观念:无码才是美.适度的遮掩才能更衬托出AV女优的优点    <br />7、别管真假，自己看的有感觉才是重点    <br />8、素人还是看看就好    <br />9、口味多元化不见得好    <br />10、封面是最后选片的依据    <br />日本AV大公司介绍    <br />1. XCITY.JP     <br />这是日本最大的成人录像带信息站,负责多家出版商的信息,如ATLAS21,宇宙企 Japan, Max-A, Sexia及VIP等.     <br />2. 桃太郎映像出版     <br />这是日本的老牌子,另外他们也经营美国最大的A片出版商     <br />VCA的片子在日本的发行.     <br />3. Attackers Net     <br />鬼畜轮奸系列就是他们死夜恶品牌下的作品,另外他们似乎也以绳缚系列作品著称.     <br />4. Athena     <br />日本成人录像带大师代代木忠开的公司,原本他们是委托Xcity代管网站,后来自己独立经营.     <br />5. h.m.p.     <br />这也是老牌子,老字号的芳友舍,处女官及官能姬都是他们的名招牌.     <br />6. Audazweb     <br />这家公司有Face, Plus, Cherry, Live及Soul等系列品牌.Face是以知名女优为主,拍摄过程中会对女优施以催眠,让观众看看她们的真正面目.     <br />Plus品牌则有三种系列――羞耻,雌女及激射.Cherry是以美少女造型为主, Live则以街头搭讪的女性作为女主角.     <br />7. Moodyz     <br />这是一家由女社长经营的成人录像带出版公司,他们时常有不错的创意,例如推出与日本著名的偶像团体――早安少女组对抗的&quot;уみЫュみИ娘。&quot;(简称为уみ娘。与早安少女组完全一样),她们也采取每次出辑就更换团员的方式来维持新鲜感.还有让一名女优在片中承受115发(射精),远远超过Waap的 Dream Shower及Audazweb的激射系列.另外还有一个令人佩服的企画――东海道53站逆搭讪接力,原本东海道53站是日本著名浮世绘画家――歌川广重传世的作品,没想到他们竟以此为起点,由Moodyz的女优沿途向当地的男子搭讪,向他们取得精液,方法不限.     <br />8. Japan Soft on Demand(SOD)     <br />这家成立才刚要满七周年的公司,也在成立之初吸引不少死忠的观众,因为他们成立的宗旨就是要提供满足客户需求的内容.森下ゑペノ?加护やゆベ(以早安少女组的加护为范本)?川旁Qコノ都在这里拍摄不少作品.他们甚至还花下巨资改装一辆货运车,名为Magic Mirror号21,由他们公司旗下的女优陪同到日本全国各地去出差服务他们的影迷,影迷可以在这辆车内与女优共赴巫山,拥有绝佳的&quot;隐密性&quot;――当时外面的人看不到,等到影片上市,全日本都看得到.他们最近还有一个了不起的企画,就是裸体交响乐团,要求这些女演奏者及指挥都要全裸上阵,演奏完自然免不了一阵肉枪林精液雨.     <br />9. 一本道    <br />一本道是日本的有名的AV电影公司，公司的影片以大屏幕，码率高为基点，拥有官方网站地址是http://www.1photo.com/ 拥有的AV女优多为漂亮名角.. 本人对一本道的评价是：一本道的女优漂亮的很漂亮，而且口技很好，丑的太丑，可能是他走极端的一个表现方法吧！    <br />一本道的片子在这里就不多介绍了，在亚洲一本道还是非常有名气的，一本道的女优都很漂亮，其中不乏众多的极品美女（真想不通，为什么那么漂亮去拍A片呢？！郁闷ing），由于本人整理的片子数量太多，在此就不一一附上图片了，其中很多女优是一本道的著名女优，早已闻名遐尔了，大家看着名字就能想到她们的音容笑貌了。。。    <br />一本道女优：    <br />持月真由 桜木ルイ 观月丽华 立花杏子 上原留华 冴岛奈绪 結城杏奈 山田いずみ 长濑爱 東さおり 森原由纪 星崎 木田彩美 矢吹麻里奈真木里美 岩崎まりあ 憂木瞳 藤崎可菜子 长濑爱 乃木真利子 椎名みずき 櫻井涼子 真鹜里美子 日野かおり 持田凉子 坂巻リオナ 風間ゆみ中山ひなの 常盤かおり 松浦ゆい 相川みき    <br />河合さくら 篠原まこ 倉沢もえ 司崎与三上 すらり さおり りんか まい 篠原ゆかり つかさ 野原なつみ 木村めぐみ 渡部時子 神林はなこ萩本志乃 .三浦奈緒 櫻沢えりす 倉本麻衣 高橋みちよ 小川美樹 笠木忍 小野寺めぐみ 星野あい 和田チエユ 赤坂美保 岡田純奈 新由惠理子村上明子 坂口楓 岡田純菜 中田由眞 桃井望 堤さやか 広末奈绪 水樹ゆり 松下純香 早濑理纱 深田涼子 春日部まり 岡部真理子 长瀬哀子星野ひかり 雨宮沙紀 三月あん 上原理香 上原絵里香 朝河蘭 小林宽子 泉ゆうか 神谷詩織 杉原美里 竹中ようこ 池野瞳（=海野なぎさ）仲本みなみ 戸内あすか 高原奈美 倉本麻衣 相馬あけみ 上原絵里香 天城友紀 深田涼子 萩原さやか 夢野まりあ 中田由真 萩原さやか 及川奈央雪乃小春 仲本みなみ ゆう香 麻生葉子 池野瞳 片桐ゆう 浅見薫 中根ゆか 沙里奈ユイ 遊佐七海 小野寺沙希 雪乃小春 內藤 若林 小泉 恭香白鳥ゆうか 麻生葉子 水城ゆり..    <br />&#8212;&#8212;摘自(日本AV年鉴)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/448.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[转]AT指令集及S寄存器</title>
		<link>http://www.donevii.com/post/389.html</link>
		<comments>http://www.donevii.com/post/389.html#comments</comments>
		<pubDate>Wed, 16 Jan 2008 03:46:35 +0000</pubDate>
		<dc:creator>gavinkwoe</dc:creator>
				<category><![CDATA[mobile]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[command]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mtk]]></category>
		<category><![CDATA[register]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[测试]]></category>
		<category><![CDATA[类]]></category>
		<category><![CDATA[缓存]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/389.html</guid>
		<description><![CDATA[AT命令使计算机或终端与调制解调器通讯,所有命令行必须由ASCII字符“AT”开始并由 &#60;Enter&#62; 结束。除了A/指令和推出(缺省为+++)。这些将在后面讨论。字母&#8221;AT&#8221;用以提醒调制解调器注... ]]></description>
			<content:encoded><![CDATA[<p id="textboxContent" class="p_entry2">AT命令使计算机或终端与调制解调器通讯,所有命令行必须由ASCII字符“AT”开始并由 &lt;Enter&gt; 结束。除了A/指令和推出(缺省为+++)。这些将在后面讨论。字母&#8221;AT&#8221;用以提醒调制解调器注意，其后将有一条或多条命令出现, &#8220;AT&#8221;及其后的字母可以是大写或小写。</p>
<h5>
<p align="center"><font color="#ff0000">AT必须同为大写或小写。如&#8221;At&#8221;或&#8221;aT&#8221;是不允许的。</font></p>
</h5>
<blockquote><p>    一串命令可以写在一行里。为了便于阅读可以加或不加空格。命令中或命令间的空格会被忽略，命令行的最多字符数为39(包括&#8221;AT&#8221;)。在输入一条命令期间，可以用退格键(backspace)改正除&#8221;AT&#8221;以外的错误。若命令行中任一处出现语法错误，本行其后的内容将被忽略，并返回ERROR。大数带有超出正常范围的参数的命令将不被接收并返回 <a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">ERROR</a>.本章列出所有设置调制解调器的命令。包括控制ACTIVE调制解调器的贺氏标准AT命令集。贺氏V系列命令集和扩展命令集</p>
<p><strong>AT命令集的描述</strong></p>
<p>  <strong>    符号 * 表明该命令的设置可用AT&amp;Wn命令存于两个用户方案中的一个</strong></p>
<p><strong>A/        重执行命令</strong></p>
<blockquote>
<blockquote><p>重执行前一AT命令行，主要用于连接时占线，无应答或号码错误。这一命令必须单独构成一命令行并由&#8221;/&#8221;字符结束,(&lt;Enter&gt; 不能用于结束命令)。</p></blockquote>
</blockquote>
<p><strong>+++       退出字符 缺省:+</strong></p>
<blockquote>
<blockquote><p>切换调制解调器从在线状态到命令状态，而不会中断数据连接。可以通过改变S寄存器S2的值来改变这一字符。</p></blockquote>
</blockquote>
<p><strong>AT=x      写入被选的S寄存器</strong></p>
<blockquote>
<blockquote><p>这一命令将数值x写入当前被选的S寄存器，一个S寄存器可由ATSn命令选择，若 x 是一个数字,所有S 寄存器将返回 OK 响应。</p></blockquote>
</blockquote>
<p><strong>AT?       读被选的S寄存器</strong></p>
<blockquote><p>  这一命令读并且显示被选的S寄存器的内容。一个S寄存器可由ATSn命令选择。</p></blockquote>
<p><strong>ATA       应答</strong></p>
<blockquote>
<blockquote><p>它必须是命令行中的最后一条指令。调制解调器在应答方式下继续执行连接程序。在与远端调制解调器交换载波后进入连接状态,如果在由寄存器S7规定的时间内(缺省值=50秒)没有检测到载波, 调制解调器将挂机。在连接过程中，通过DTE输入的任何一个字母都将中断这一命令。</p></blockquote>
</blockquote>
<p><strong>ATBn*     选择ITU-T或Bell模式 缺省=0</strong></p>
<blockquote>
<blockquote><p> ATB0 选择在1200和300bps速率下通讯的ITU-T V.22和V.21协议<br />
 ATB1 选择在1200和300bps速率下通讯的Bell 212A和103协议</p></blockquote>
</blockquote>
<p><strong>ATCn      载波控制缺省=1</strong></p>
<blockquote>
<blockquote><p>包含这一命令只是为了保证兼容性，执行号只是返回一结果码而没有其它作用。<br />
ATC1 正常传输载波切换</p></blockquote>
</blockquote>
<p><strong>ATDn      拨号</strong></p>
<blockquote>
<blockquote><p>它必须是命令行中的最后一条指令, ATD命令使调制解调器摘机后, 根据输入的参数拨号,以建立连接。如果不带参数，调制解调器摘机后，不拨号进入发起方式。</p>
<p>使用标点可使命令更易读懂。圆括号,连字符和空格符会被忽略。拔号命令行中如果出现了非法字符，则该字符及其后的内容将被忽略。调制解调器允许的拨号命令长度为36个字符。</p>
<p>参数：0-9 A B C D * # L P T R ! @ W , ; ^ S=n<br />
0-9     DTMF 符号0到9<br />
A-D     DTMF 符号A,B,C和D。在一些国家中不使用这些符号<br />
*       &#8220;星&#8221;号(仅用于音频拨号)<br />
#       &#8220;#&#8221;号(仅用于音频拨号)<br />
J       为本次呼叫执行在可提供的最高速率下的MNP10链路协商(可选)<br />
K       使本次呼叫MNP10链路协商期间电源电平可调(可选)<br />
L       重拨上一次拨过的号码<br />
P       脉冲拨号<br />
T       双音频拨号<br />
R       逆叫方式。允许调制解调器使用应答方式呼叫只能作为发起使用的调制解调        器, 必须作为命令行中的最后一个字符输入。<br />
!       使调制解调器按照S29中规定的值挂机一段时间再摘机。<br />
@       使调制解调器等待5秒钟的无声回答<br />
w       按照寄存器S7中规定的时间，在拨号前等待拨号音。<br />
,       在拨号过程中，按照寄存器S8中规定的时间,暂停<br />
;       拨号后返回命令状态<br />
^       打开呼叫音<br />
()      被忽视，用于格式化号码串<br />
-       被忽视，用于格式化号码串<br />
&lt;space&gt; 被忽视,用于格式化号码串<br />
S=n     用AT&amp;Zn 命令存在地址n处的号码拨号</p></blockquote>
</blockquote>
<p><strong>ATE*     命令回应           缺省:1</strong></p>
<blockquote>
<blockquote><p>ATE0 关闭命令回应<br />
ATE1 打开 命令回应</p></blockquote>
</blockquote>
<p><strong>ATHn     摘挂机控制       缺省:0</strong></p>
<blockquote>
<blockquote><p>ATH0 使调制解调器挂机<br />
ATH1 当调制解调器处于挂机状态，使调制解调器摘机，返回响 OK，等待进一步的命令。</p></blockquote>
</blockquote>
<p><strong>ATIn     识别</strong></p>
<blockquote>
<blockquote><p>I0 报告产品代码<br />
I1 报告ROM中预先计算的校验和<br />
I2 计算校验和并与ROM中的校验和比较,返回&#8221;OK&#8221;或&#8221;ERROR&#8221;结果码<br />
I3 报告固件修正<br />
I4 报告OEM定义的识别串<br />
I5 报告国家代码参数<br />
I6 报告固件修正<br />
I7 报告调制解调器数据泵类型</p></blockquote>
</blockquote>
<p><strong>ATLn*    扬声器音量       缺省:2</strong></p>
<blockquote>
<blockquote><p>ATL0 扬声器低音量<br />
ATL1 扬声器低音量<br />
ATL2 扬声器中音量<br />
ATL3 扬声器高音量</p></blockquote>
</blockquote>
<p><strong>ATMn*    扬声器控制       缺省:1</strong></p>
<blockquote>
<blockquote><p>ATM0 关闭扬声器<br />
ATM1 扬声器在呼叫建立握手阶段打开至检测到来自于远端调制解调器的载波后关闭<br />
ATM2 扬声器持续开<br />
ATM3 扬声器在应答期间打开。当检测到来自于远端的调制解调器的载波和拨号时关闭</p></blockquote>
</blockquote>
<p><strong>ATNn*     调制握手       缺省:1</strong></p>
<blockquote>
<blockquote><p><strong> </strong>ATN0 要求调制解调器S37选择连接速率,若S37＝0,则连接速率必须与发出的上一条AT命令的速率相匹配。如果所选择的速率可用不止一个通讯标准实现(如Bell212A或ITU-T V.22 速率在 1200bps)调制解调器同时参考ATB 命令选择。ATN1 允许时使用双方调制解调器都支持的任一速率握手，使能够自动检测。在这一方式下，ATB命令被忽视，调制解调器只用ITU-T方式连接。</p></blockquote>
</blockquote>
<p><strong>ATOn     进入数据在现状态 缺省:0</strong></p>
<blockquote>
<blockquote><p>ATO0 使调制解调器从命令在现状态直接返回数据在线状态,不经过自动均衡。<br />
ATO1 使调制解调器从命令在现状态返回数据在状态,经过自动均衡。</p></blockquote>
</blockquote>
<p><strong>ATP*     设脉冲拨号为缺省</strong><br />
 </p>
<p><strong>ATQn*    结果码显示        缺省:0</strong></p>
<blockquote>
<blockquote><p>ATQ0 调制解调器向DTE发送结果码<br />
ATQ1 禁止调制解调器向DTE发送结果码</p></blockquote>
</blockquote>
</blockquote>
<p align="center"><a target="_blank" href="http://www.lsllhd.com/gksmpale/sspek.htm"><font color="#ff0000">点击查看S寄存器详解！</font></a></p>
<blockquote><p><strong>ATSn     设S寄存器n为缺省寄存器</strong><br />
 <strong>ATSn?    读S寄存器</strong></p>
<blockquote>
<blockquote><p>读S寄存器中的内容，所有的S寄存器都可以读</p></blockquote>
</blockquote>
<p><strong>ATSn=x   写入S寄存器</strong></p>
<blockquote>
<blockquote><p>将 x值写入指定的S寄存器n</p></blockquote>
</blockquote>
<p><strong>ATT*     设音频拔号为缺省</strong><br />
 </p>
<p><strong>ATVn*    结束码类型 (消息控制)        缺省</strong>:1</p>
<blockquote>
<blockquote><p>ATV0 发送短型 (数字型) 结果码<br />
ATV1 发送长型 (字符型) 结果码</p></blockquote>
</blockquote>
<p><strong>ATWn*    协商进程报告                缺省:0</strong></p>
<blockquote>
<blockquote><p>ATW0 不报告纠错呼叫进程<br />
ATW1 报告纠错呼叫进程<br />
ATW2 不报告纠错呼叫进程，CONNECT xxxx指示DCE速率。</p></blockquote>
</blockquote>
<p><strong>ATXn*     扩展结果码            缺省:4</strong></p>
<blockquote>
<blockquote><p>ATX0<strong> </strong>调制解调器忽视拨号音和忙音。当由盲拨建立连接时，发送CONNECT信息。ATX1 调制解调器忽视拨号音和忙音。当由盲拨建立连接时，CONNECT XXXX 反映的是比特速率</p>
<p>ATX2 调制解调器忽视忙音，但在拨号前等待拨号音，如果5秒钟内检测不到拨号音，则发送NO DIAL TONE 信息，连接建立后 发送 CONNECT xxxx反映比特速率。</p>
<p>ATX3 调制解调器忽视拨号音,若检测到忙音,发送BUSY信息,当由盲拨建立起连接时, CONNECT XXXX 反映的是比特速率。</p>
<p>ATX4 如果5秒钟内检测不到拨号音，发送NO DIAL TONE 讯息,检测到忙音, 发送BUSY信息。连接建立后发送CONNECT XXXX 反映比特速率。</p></blockquote>
</blockquote>
<p><strong>ATYn*     控制长间隔拆接         缺省:0</strong></p>
<blockquote>
<blockquote><p>ATY0 不允许长间隔拆接<br />
ATY1 允许长间隔拆接</p></blockquote>
</blockquote>
<p><strong>ATZn      复位                缺省:0</strong></p>
<blockquote>
<blockquote><p>重新调出由用户方案规定的动态配置<br />
ATZ0 软复位并重新调出用户方案0<br />
ATZ1 软复位并重新调出用户方案1</p></blockquote>
</blockquote>
<p><strong>AT&amp;An*    握手异常终止(备选)    缺省:1</strong></p>
<blockquote>
<blockquote><p><strong> </strong>AT&amp;A0 在握手时禁止用户进行异常终止。当拨号或应答时，握手不能异常终止,只有DTR 信号下降。AT&amp;A1 用户可以在握手时进行异常终止.在接收到DTE的字符后,发起和应答可以在握手期间随时进行异常终止.</p></blockquote>
</blockquote>
<p><strong>AT&amp;Cn*     RS232-C DCD          设置缺省:1</strong></p>
<blockquote>
<blockquote><p>AT&amp;C0 DCD为ON，不论来自远端的调制解调器的数据载波的状态为何。<br />
AT&amp;C1 DCD 跟随来自于远端调制解调器的数据载波的状态</p></blockquote>
</blockquote>
<p><strong>AT&amp;Dn*    RS232-C DTR          设置缺省:2</strong></p>
<blockquote>
<blockquote><p>决定了调制解调器与来自串口的DTR信号相关的操作。由于跟踪DTR的下降引起的操作在下表列出:</p></blockquote>
</blockquote>
</blockquote>
<table border="1" width="72%" height="201">
<tr>
<td width="20%"> </td>
<td width="21%"><center>&amp;D0 </center></td>
<td width="20%"><center>&amp;D1 </center></td>
<td width="20%"><center>&amp;D2 </center></td>
<td width="19%"><center>&amp;D3 </center></td>
</tr>
<tr>
<td width="20%"><center>&amp;Q0 </center></td>
<td width="21%"><center>NONE </center></td>
<td width="20%"><center>2 </center></td>
<td width="20%"><center>3 </center></td>
<td width="19%"><center>4 </center></td>
</tr>
<tr>
<td height="22" width="20%"><center>&amp;Q1 </center></td>
<td height="22" width="21%"><center>1 </center></td>
<td height="22" width="20%"><center>2 </center></td>
<td height="22" width="20%"><center>3 </center></td>
<td height="22" width="19%"><center>4 </center></td>
</tr>
<tr>
<td width="20%"><center>&amp;Q2 </center></td>
<td width="21%"><center>3 </center></td>
<td width="20%"><center>3 </center></td>
<td width="20%"><center>3 </center></td>
<td width="19%"><center>3 </center></td>
</tr>
<tr>
<td width="20%"><center>&amp;Q3 </center></td>
<td width="21%"><center>3 </center></td>
<td width="20%"><center>3 </center></td>
<td width="20%"><center>3 </center></td>
<td width="19%"><center>3 </center></td>
</tr>
<tr>
<td width="20%"><center>&amp;Q4 </center></td>
<td width="21%"><center>1 </center></td>
<td width="20%"><center>2 </center></td>
<td width="20%"><center>3 </center></td>
<td width="19%"><center>4 </center></td>
</tr>
<tr>
<td width="20%"><center>&amp;Q5 </center></td>
<td width="21%"><center>NONE </center></td>
<td width="20%"><center>2 </center></td>
<td width="20%"><center>3 </center></td>
<td width="19%"><center>4 </center></td>
</tr>
<tr>
<td width="20%"><center>&amp;Q6 </center></td>
<td width="21%"><center>NONE </center></td>
<td width="20%"><center>2 </center></td>
<td width="20%"><center>3 </center></td>
<td width="19%"><center>4 </center></td>
</tr>
</table>
<p><dir><dir></p>
<blockquote><p>1 调制解调器断开连接并发送结果码OK<br />
2 若在数据状态下,则进入命令状态,并发送结果码OK<br />
3 调制解调器断开连接并发送结果码OK, DTR 为 OFF时不能自动应答<br />
4 调制解调器执行热启动(即与ATZ命令相同)</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Fn     重新调用工厂            设置缺省:0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>&amp;F0 重新调用作为V.42bis自动可靠方式的出厂缺省设置<br />
&amp;F1 重新调用作为MNP5自动可靠方式的出厂缺省设置<br />
&amp;F2 重新调用作为DIRECT方式的出厂缺省设置<br />
&amp;F3 重新调用作为MNP10方式自动可靠方式的出厂缺省设置(可选)</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Gn*    设置保护音            缺省:0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT&amp;G0 无保护音<br />
AT&amp;G1 无保护音<br />
AT&amp;G2 1800HZ保护音</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Jn*    电话插头选择          缺省:0</strong><br />
 </p>
<blockquote>
<blockquote><p>包含这一命令只是基于兼容性的考虑，没有任何功能<br />
AT&amp;J0 不操作任何功能<br />
AT&amp;J1 不操作任何功能</p></blockquote>
</blockquote>
</blockquote>
<blockquote><p><strong>AT&amp;Kn*    DTE/调制解调器流    控制缺省:3</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT&amp;K0 关闭流控制<br />
AT&amp;K3 使用RTS/CTS流控<br />
AT&amp;K4 使用XON/XOFF流控<br />
AT&amp;K5 使用透明XON/XOFF流控<br />
AT&amp;K6 使用RTS/CTS和XON/XOFF流控(作为传真方式下的缺省)</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Ln*    传输线类型            缺省:0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT&amp;L0 拨号线<br />
AT&amp;L1 二线专线 （备选）<br />
AT&amp;L2 四线专线 （备选）</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Mn*    通讯方式</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>与AT&amp;Q0-3相同</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Pn*    拨号脉冲占空比        缺省:0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT&amp;P0 39％61％占空比@10PPS<br />
AT&amp;P1 33％67％占空比@10PPS<br />
AT&amp;P2 39％61％占空比@20PPS<br />
AT&amp;P3 33％67％占空比@20PPS</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Qn*    通讯方式             缺省:5</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT&amp;Q0 选择直接异步操作<br />
AT&amp;Q1 选择同步模式一操作<br />
AT&amp;Q2 选择同步模式二操作<br />
AT&amp;Q3 选择同步模式三操作<br />
AT&amp;Q4 选择自动同步模式操作<br />
AT&amp;Q5 选择纠错模式操作<br />
AT&amp;Q6 选择标准模式下的异步操作</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Rn*    RS232-C RTS/CTS   设置缺省:0</strong></p>
<blockquote>
<blockquote><p>AT&amp;R0 CTS跟踪RTS, 本地DTE发送的RTS由OFF变为ON经过由寄存器S26所规定的以10微秒为增量的延迟后,CTS变为ONAT&amp;R1 调制解调器忽视RTS,除非使用了AT&amp;K3命令,CTS保持为ON</p></blockquote>
</blockquote>
<p><strong>AT&amp;Sn*    RS232-C DSR       设置缺省:0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT&amp;S0 DSR始终为ON<br />
AT&amp;S1 DSR根据EIA-232-C的规定操作</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Tn*    测试和诊断            缺省:4</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>测试只能在非纠错方式下(标准或直接模式)下的异步操作中进行，除参数7和8以外，要中止正在进行中的测试必须首先敲入退出符。若S18非零，则测试经由S18规定的时间后自动中止并显示OK。AT&amp;T0 终止进行中的测试<br />
AT&amp;T1 启动本地模拟回环<br />
AT&amp;T3 在本地启动远端数字回环·,若连接未建通,返回ERROR<br />
AT&amp;T4 允许调制解调器响应来自远端的进行远程数字环回测试的请求<br />
AT&amp;T5 拒绝调制解调器响应来自远端的进行远程数字环回测试的求<br />
AT&amp;T6 启动远端数字环回测试,若连接未通,返回ERROR<br />
T&amp;T7 启动远端数字环回自测试,若连接未建通,返回ERROR<br />
AT&amp;T8 启动本地模拟环回自测试<br />
 </p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;V     看当今配置及用户参数</strong></p>
<blockquote>
<blockquote><p>AT&amp;V0 查看当前配置、用户方案和存储的电话号码<br />
AT&amp;V1 显示最后一次数据连接的详细情况</p></blockquote>
</blockquote>
</blockquote>
<blockquote><p><strong>AT&amp;Wn    储存用户参数              缺省：0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT&amp;W0 作为用户0存贮<br />
AT&amp;W1 作为用户1存贮</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Xn*</strong>   <strong> 选择同步时钟源             缺省：0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT&amp;X0 调制解调器提供传输时钟，内部时钟。 AT&amp;X1 DTE提供传输时钟，外部时钟。<br />
AT&amp;X2 由调制解调器从接外载波信号中提供传输时钟，从属接收时钟</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT&amp;Yn*    指示缺省用户参数            缺省：0</strong></p>
<blockquote>
<blockquote><p>在硬复位后可选择将使用的用户方案。<br />
AT&amp;Y0 选择用户方案0<br />
AT&amp;Y1 选择用户方案1</p></blockquote>
</blockquote>
</blockquote>
<blockquote><p><strong>AT&amp;Zn=x   储存电话号码(n=0-3)         缺省：0</strong></p>
<blockquote>
<blockquote><p>将一36位数字电话号码(x)存放在一指定电话号码表中(n), 作以后拨号用(参见命令ATDS=n)</p></blockquote>
</blockquote>
</blockquote>
<p><dir><dir></p>
<blockquote><p>AT\An 最大MNP块的大小缺省:2<br />
AT\A0 设最大块为64个字符<br />
AT\A1 设最大块为128个字符<br />
AT\A2 设最大块为192个字符<br />
AT\A3 设最大块为256个字符</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT\Bn     发送中断信号(n=1-9)        缺省:3</strong></p>
<blockquote>
<blockquote><p>当在非MNP连接期间输入此命令,调制解调器向远端调制解器发送一中断信号,中断信号长度参数为n值的100倍（以毫秒            为单位）,在MNP模式下,输入此命令,调制解调器向远端调制解调器发送一链路注意码PDU</p></blockquote>
</blockquote>
</blockquote>
<blockquote><p><strong>AT\Gn     调制解调器到调制解调器的流控制    缺省:0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT\G0 关闭流控(XON/XOFF)<br />
AT\G1 打开流控(XON/XOFF)<br />
 </p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT\Jn     DTE速率自动调整控制            缺省:0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT\J0 关闭匹配线路速率的DTE速率调整功能<br />
AT\J1 打开匹配线路速率的DTE速率调整功能<br />
 </p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT\Kn     中断控制                     缺省:5</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>在数据传输期间收到来自DTE的中断信号时,调制解调器作出如下响应AT\K0,2,4 调制解调器进入连机命令状态,而不向远端发送中断信号<br />
AT\K1 调制解调器清空终端的缓冲器并向远端调制解调器发送中断信号<br />
AT\K3 调制解调器不清空终端的缓冲器,但向远端调制解调器发送中断信号<br />
AT\K5 调制解调器随发送的数据发送中断信号. 调制解调器在连机命令状态时数据传输过程中，做如下操作<br />
AT\K0,1 调制解调器清空终端的缓冲器，并向远端调制解调器发送中断信号<br />
AT\K2,3 调制解调器不清空缓冲器，但向远端调制解调器发送中断信号<br />
AT\K4,5 调制解调器随传输的数据按顺序发送中断信号 在非纠错模式下收到来自DTE的中断信号时,调制解调器做如下操作<br />
AT\K0,1 调制解调器清除终端的缓冲器,并向本地DTE发送中断信号<br />
AT\K2,3 调制解调器不清除缓冲器,但向本地DTE发送中断信号<br />
AT\K4,5 调制解调器随接收的数据按顺序发送中断信号<br />
 <br />
 </p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT\Ln     MNP块传输控制                 缺省:0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT\L0 对于MNP链路连接使用流模式<br />
AT\L1 对于MNP链路连接使用块模式<br />
 </p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT\Nn     操作模式控制                 缺省:3</strong></p>
<blockquote>
<blockquote><p>AT\N0 选择标准速度缓存模式(无纠错)<br />
AT\N1 选择直接模式(等效于&amp;M0,&amp;Q0)<br />
AT\N2 选择可靠模式,可靠连接失败会使调制解调器挂机<br />
AT\N3 选择自动可靠模式<br />
AT\N4 选择LAPM纠错模式,LAPM纠错连接失败会使调制解调器挂机<br />
AT\N5 选择MNP纠错模式,MNP纠错连接失败会使调制解调器挂机</p></blockquote>
</blockquote>
</blockquote>
<blockquote><p><strong>AT\Vn     单线连接信息                 缺省：0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT\V0 关闭单线连接信息。<br />
AT\V1 打开单线连接信息。</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT％C*    压缩控制                    缺省: 3</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT%C0 关闭数据压缩 AT%C1 打开MNP5数据压缩<br />
AT%C2 打开V.42bis数据压缩<br />
AT%C3 打开MNP5和V.42bis数据压缩</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT％En    开/关自动均衡                缺省：2</strong><br />
 </p>
<blockquote>
<blockquote><p>控制是使调制解调器自动监听线路质量并请求均衡(％E1)还是当线路质量不好时降速，线路质量好时升速。</p></blockquote>
</blockquote>
</blockquote>
<p><dir><dir></p>
<blockquote><p>AT%E0 关闭线路质量监听和自动均衡。<br />
AT%E1 打开线路质量监听和自动均衡。<br />
AT%E2 打开线路质量监听和速率自动调整上升或下降。<br />
AT%E3 打开线路质量监听和采用快速挂机的自动均衡。</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT％L     报告接收灵敏度</strong></p>
<blockquote>
<blockquote><p>返回接收信号的电平值,提供以下数值</p></blockquote>
</blockquote>
</blockquote>
<p><dir><dir></p>
<blockquote><p>001=-1dBm接收电平<br />
002=-2dBm接收电平<br />
: :<br />
043=-43dBm接收电平</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT%On     选择应答或呼叫模式             缺省：1</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT%O0 选择应答式模<br />
AT%O1 选择发起式模</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT%Rn     选择接收灵敏度 (</strong>适用於专线型号)<strong> 缺省：0</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>AT%R0 -43dBm<br />
AT%R1 -33dBm<br />
<strong>备选：</strong>适用於拔号线型号,JP2跳线：-33dBM 连接1-2 针；-43 连接2-3针</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT％Q     显示线路信号质量</strong></p></blockquote>
<p><dir><dir></p>
<blockquote><p>返回眼图指标(EQM)值的高字节,该字节的表示范围为0到127,当这一数值为70DC±10(依赖于线路速率)或更大时,若已使用了AT％E1命令则调制解调器将自动均衡,标准连接时这一数在0到15之间。到60时则为较差连接。</p></blockquote>
<p></dir></dir></p>
<blockquote><p><strong>AT#CIDn   呼叫者身份鉴定                 缺省：0</strong></p>
<blockquote>
<blockquote><p>AT#CID=0关闭呼叫者身份鉴定<br />
AT#CID=1打开DTE格式化形式的呼叫者身份鉴定<br />
AT#CID=2打开DTE非格式化形式的呼叫者身份鉴定<br />
AT#CID? 从调制解调器中恢复当前呼叫者身份鉴定方式<br />
AT#CID=? 返回调制解调器允许模式的列表,表中各部分间用逗号隔开</p></blockquote>
</blockquote>
<p><strong>AT-SDR=n  鉴别性振铃                    缺省：0</strong></p>
<blockquote>
<blockquote><p>AT-SDR=0 允许任何振铃、并报告&#8221;RING&#8221;<br />
AT-SDR=1 允许一类型振铃<br />
AT-SDR=2 允许二类型振铃<br />
AT-SDR=3 允许一及二类型振铃<br />
AT-SDR=4 允许三类型振铃<br />
AT-SDR=5 允许一及三类型振铃<br />
AT-SDR=6 允许二及三类型振铃<br />
AT-SDR=7 允许一、二及三类型振铃</p></blockquote>
</blockquote>
</blockquote>
<table border="1" width="556" cellPadding="9">
<tr>
<td width="22%" vAlign="top"><center>振铃类型 </center></td>
<td width="78%" vAlign="top"><center>振铃时段模式 </center></td>
</tr>
<tr>
<td width="22%" vAlign="top"><center>1 </center></td>
<td width="78%" vAlign="top">响2秒、停4秒</td>
</tr>
<tr>
<td height="21" width="22%" vAlign="top"><center>2 </center></td>
<td height="21" width="78%" vAlign="top">响0.8秒、停0.4秒、响0.8秒、停4秒</td>
</tr>
<tr>
<td height="20" width="22%" vAlign="top"><center>3 </center></td>
<td height="20" width="78%" vAlign="top">响0.4秒、停0.2秒、响0.4秒、停0.2秒、响0.8秒、停4秒</td>
</tr>
</table>
<blockquote><p><strong>AT+MS*     选择线路调制方式</strong></p>
<blockquote>
<blockquote><p>命令格式为（336型号）:<br />
AT+MS=&lt;模式&gt;,&lt;自动模式&gt;,&lt;最小速率&gt;,&lt;最大速率&gt;<br />
缺省值为 AT+MS=11,1,300,33600 （336型号）命令格式为（560型号）:<br />
AT+MS=&lt;模式&gt;,&lt;自动模式&gt;,&lt;最小速率&gt;,&lt;最大速率&gt;,<br />
&lt;x_law&gt;,&lt;rb_signal&gt;,&lt;maxup_rate&gt;<br />
缺省值为 AT+MS=12,1,300,56000,33600 （560型号）</p>
<p><strong>AT+MS?  </strong>向包含所选选项的DTE发送一信息流</p>
<p><strong>AT+MS=?</strong> 向包含所提供选项的DTE发送一信息流<br />
 <br />
 </p></blockquote>
</blockquote>
</blockquote>
<table border="1" width="100%" cellPadding="9">
<tr>
<td width="22%" vAlign="top"><center>自动模式 </center></td>
<td width="78%" vAlign="top"><center>选 项 </center></td>
</tr>
<tr>
<td width="22%" vAlign="top"><center>0 </center></td>
<td width="78%" vAlign="top"><center>关闭自动模式 </center></td>
</tr>
<tr>
<td height="21" width="22%" vAlign="top"><center>1 </center></td>
<td height="21" width="78%" vAlign="top"><center>打开自动模式 </center></td>
</tr>
</table>
<blockquote>
<blockquote>
<blockquote></blockquote>
</blockquote>
</blockquote>
<table border="1" width="100%" cellPadding="9">
<tr>
<td height="42" width="7%" vAlign="top"><center>模式 </center></td>
<td height="42" width="16%" vAlign="top">  调制方式选择</td>
<td height="42" width="77%" vAlign="top"><center>可能 波特率(bps) &lt;最小 波特率&gt; &lt;最大 波特率&gt; </center></td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>0 </center></td>
<td width="16%" vAlign="top">V.21</td>
<td width="77%" vAlign="top">300</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>1 </center></td>
<td width="16%" vAlign="top">V.22</td>
<td width="77%" vAlign="top">1200</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>2 </center></td>
<td width="16%" vAlign="top">V.22bis</td>
<td width="77%" vAlign="top">2400或1200</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>3 </center></td>
<td width="16%" vAlign="top">V.23</td>
<td width="77%" vAlign="top">1200</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>9 </center></td>
<td width="16%" vAlign="top">V.32</td>
<td width="77%" vAlign="top">9600或4800</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>10 </center></td>
<td width="16%" vAlign="top">V.32bis</td>
<td width="77%" vAlign="top">14400,12000,9600,7200 或4800</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>11 </center></td>
<td width="16%" vAlign="top">V.34</td>
<td width="77%" vAlign="top">33600,31200,28800,26400,24000,21600,19200, 16800,14400,12000, <br />
9600,7200,4800或2400</td>
</tr>
<tr>
<td height="83" width="7%" vAlign="top"><center>12 </center></td>
<td height="83" width="16%" vAlign="top">V.90</td>
<td height="83" width="77%" vAlign="top">56000,54667,53333,52000,50667,49333,48000,46667,45333,42667, <br />
41333,40000,38667,37333,36000,34667,33333,32000,30667,29333, <br />
28000 (560型号适用)</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>56 </center></td>
<td width="16%" vAlign="top">K56flex</td>
<td width="77%" vAlign="top">56000,54000,52000,50000,48000,46000,44000,42000,40000,38000, <br />
36000,34000,32000 (560型号适用)</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>64 </center></td>
<td width="16%" vAlign="top">Bell 103</td>
<td width="77%" vAlign="top">300</td>
</tr>
<tr>
<td width="7%" vAlign="top"><center>69 </center></td>
<td width="16%" vAlign="top">Bell 212</td>
<td width="77%" vAlign="top">1200</td>
</tr>
</table>
<blockquote>
<blockquote><p>&lt;x_law&gt; 是一个可选的数字，用来确定码类型，选择是：</p>
<blockquote><p>0 = u-Law 1 = A-Law注意：ATZ命令将复位&lt;x_law&gt;值为0 (u-Law)。<br />
 </p>
<p>&lt;rb_signaling&gt; 是一个可选的数字，用于配置一个发送数据的调制解调器产生“丢失位”信号或不产生“丢               失位”信号；或配置一台接收数据的调制解调器检测“丢失位”信号或不检测“丢失位”信               号。选择是：</p></blockquote>
</blockquote>
</blockquote>
<p><dir></p>
<blockquote>
<blockquote><p>0 = 发送数据的调制解调器产生丢失位信号。接收数据的调制解调器检测丢失位信号。1= 发送数据的调制解调器不产生丢失位信号。接收数据的调制解调器不检测丢失位信号。</p>
<p>注意：ATZ命令将复位&lt;rb_signaling&gt;值为0。<br />
 </p></blockquote>
</blockquote>
<p></dir></p>
<blockquote>
<blockquote><p>Maxup_rate : 连接速率的最大值。</p></blockquote>
</blockquote>
<p id="TBPingURL">Trackback: http://tb.<a href="http://www.donevii.com/post/tag/blog" class="st_tag internal_tag" rel="tag" title="Posts tagged with blog">blog</a>.csdn.net/TrackBack.aspx?PostId=1535176</p>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/389.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 启动加载程序 ―― <a href="http://www.donevii.com/post/tag/boot" class="st_tag internal_tag" rel="tag" title="Posts tagged with boot">Boot</a> Loader 的概念、软件设计的主要任务以及结构框架等内容。</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/<a href="http://www.donevii.com/post/tag/linux" class="st_tag internal_tag" rel="tag" title="Posts tagged with linux">Linux</a> 系统已经变得越来越流行。一个嵌入式 <a href="http://www.donevii.com/post/tag/linux" class="st_tag internal_tag" rel="tag" title="Posts tagged with linux">Linux</a> 系统从软件的角度看通常可以分为四个层次：</p>
<p>1. <strong>引导加载程序。</strong>包括固化在固件(firmware)中的 boot 代码(可选)，和 Boot Loader 两大部分。</p>
<p>2. <strong>Linux 内核。</strong>特定于嵌入式板子的定制内核以及内核的启动参数。</p>
<p>3. <strong>文件系统。</strong>包括根文件系统和建立于 <a href="http://www.donevii.com/post/tag/flash" class="st_tag internal_tag" rel="tag" title="Posts tagged with flash">Flash</a> 内存设备之上文件系统。通常用 ram disk 来作为 root fs。</p>
<p>4. <strong>用户应用程序。</strong>特定于用户的应用程序。有时在用户应用程序和内核层之间可能还会包括一个嵌入式图形用户界面。常用的嵌入式 GUI 有：MicroWindows 和 MiniGUI 懂。</p>
<p>引导加载程序是系统加电后运行的第一段软件代码。回忆一下 PC 的体系结构我们可以知道，PC 机中的引导加载程序由 BIOS(其本质就是一段固件程序)和位于硬盘 MBR 中的 OS Boot Loader（比如，LILO 和 GRUB 等）一起组成。BIOS 在完成硬件检测和资源分配后，将硬盘 MBR 中的 Boot Loader 读到系统的 RAM 中，然后将控制权交给 OS Boot Loader。Boot Loader 的主要运行任务就是将内核映象从硬盘上读到 RAM 中，然后跳转到内核的入口点去运行，也即开始启动操作系统。</p>
<p>而在嵌入式系统中，通常并没有像 BIOS 那样的固件程序（注，有的嵌入式 CPU 也会内嵌一段短小的启动程序），因此整个系统的加载启动任务就完全由 Boot Loader 来完成。比如在一个基于 ARM7TDMI core 的嵌入式系统中，系统在上电或复位时通常都从地址 0&#215;00000000 处开始执行，而在这个地址处安排的通常就是系统的 Boot Loader 程序。</p>
<p>本文将从 Boot Loader 的概念、Boot Loader 的主要任务、Boot Loader 的框架结构以及 Boot Loader 的安装等四个方面来讨论嵌入式系统的 Boot Loader。</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 Loader 的概念</span></p>
<p>简单地说，Boot Loader 就是在操作系统内核运行之前运行的一段小程序。通过这段小程序，我们可以初始化硬件设备、建立内存空间的映射图，从而将系统的软硬件环境带到一个合适的状态，以便为最终调用操作系统内核准备好正确的环境。</p>
<p>通常，Boot Loader 是严重地依赖于硬件而实现的，特别是在嵌入式世界。因此，在嵌入式世界里建立一个通用的 Boot Loader 几乎是不可能的。尽管如此，我们仍然可以对 Boot Loader 归纳出一些通用的概念来，以指导用户特定的 Boot Loader 设计与实现。</p>
<p><a name="N10072" title="N10072"></a><span class="smalltitle"><strong><font face="Arial">1. Boot Loader 所支持的 CPU 和嵌入式板</font></strong></span></p>
<p>每种不同的 CPU 体系结构都有不同的 Boot Loader。有些 Boot Loader 也支持多种体系结构的 CPU，比如 U-Boot 就同时支持 ARM 体系结构和MIPS 体系结构。除了依赖于 CPU 的体系结构外，Boot Loader 实际上也依赖于具体的嵌入式板级设备的配置。这也就是说，对于两块不同的嵌入式板而言，即使它们是基于同一种 CPU 而构建的，要想让运行在一块板子上的 Boot Loader 程序也能运行在另一块板子上，通常也都需要修改 Boot Loader 的源程序。</p>
<p><a name="N1007B" title="N1007B"></a><span class="smalltitle"><strong><font face="Arial">2. Boot Loader 的安装媒介（Installation Medium）</font></strong></span></p>
<p>系统加电或复位后，所有的 CPU 通常都从某个由 CPU 制造商预先安排的地址上取指令。比如，基于 ARM7TDMI core 的 CPU 在复位时通常都从地址 0&#215;00000000 取它的第一条指令。而基于 CPU 构建的嵌入式系统通常都有某种类型的固态存储设备(比如：ROM、EEPROM 或 FLASH 等)被映射到这个预先安排的地址上。因此在系统加电后，CPU 将首先执行 Boot Loader 程序。</p>
<p>下图1就是一个同时装有 Boot Loader、内核的启动参数、内核映像和根文件系统映像的固态存储设备的典型空间分配结构图。<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 Loader 的设备或机制</font></strong></span></p>
<p>主机和目标机之间一般通过串口建立连接，Boot Loader 软件在执行时通常会通过串口来进行 I/O，比如：输出打印信息到串口，从串口读取用户控制字符等。</p>
<p><a name="N1009D" title="N1009D"></a><span class="smalltitle"><strong><font face="Arial">4. Boot Loader 的启动过程是单阶段（Single Stage）还是多阶段（Multi-Stage）</font></strong></span></p>
<p>通常多阶段的 Boot Loader 能提供更为复杂的功能，以及更好的可移植性。从固态存储设备上启动的 Boot Loader 大多都是 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 Loader 的操作模式 (Operation Mode)</font></strong></span></p>
<p>大多数 Boot Loader 都包含两种不同的操作模式：&#8221;启动加载&#8221;模式和&#8221;下载&#8221;模式，这种区别仅对于开发人员才有意义。但从最终用户的角度看，Boot Loader 的作用就是用来加载操作系统，而并不存在所谓的启动加载模式与下载工作模式的区别。</p>
<p><strong>启动加载（Boot loading）模式：</strong>这种模式也称为&#8221;自主&#8221;（Autonomous）模式。也即 Boot Loader 从目标机上的某个固态存储设备上将操作系统加载到 RAM 中运行，整个过程并没有用户的介入。这种模式是 Boot Loader 的正常工作模式，因此在嵌入式产品发布的时侯，Boot Loader 显然必须工作在这种模式下。</p>
<p><strong>下载（Downloading）模式：</strong>在这种模式下，目标机上的 Boot Loader 将通过串口连接或网络连接等通信手段从主机（Host）下载文件，比如：下载内核映像和根文件系统映像等。从主机下载的文件通常首先被 Boot Loader 保存到目标机的 RAM 中，然后再被 Boot Loader 写到目标机上的FLASH 类固态存储设备中。Boot Loader 的这种模式通常在第一次安装内核与根文件系统时被使用；此外，以后的系统更新也会使用 Boot Loader 的这种工作模式。工作于这种模式下的 Boot Loader 通常都会向它的终端用户提供一个简单的命令行接口。</p>
<p>像 Blob 或 U-Boot 等这样功能强大的 Boot Loader 通常同时支持这两种工作模式，而且允许用户在这两种工作模式之间进行切换。比如，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 Loader 通过串口与主机之间进行文件传输，传输协议通常是 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 Loader 的主要任务与典型结构框架</span></p>
<p>在继续本节的讨论之前，首先我们做一个假定，那就是：假定内核映像与根文件系统映像都被加载到 RAM 中运行。之所以提出这样一个假设前提是因为，在嵌入式系统中内核映像与根文件系统映像也可以直接在 ROM 或 Flash 这样的固态存储设备中直接运行。但这种做法无疑是以运行速度的牺牲为代价的。</p>
<p>从操作系统的角度看，Boot Loader 的总目标就是正确地调用内核来执行。</p>
<p>另外，由于 Boot Loader 的实现依赖于 CPU 的体系结构，因此大多数 Boot Loader 都分为 stage1 和 stage2 两大部分。依赖于 CPU 体系结构的代码，比如设备初始化代码等，通常都放在 stage1 中，而且通常都用汇编语言来实现，以达到短小精悍的目的。而 stage2 则通常用C语言来实现，这样可以实现给复杂的功能，而且代码会具有更好的可读性和可移植性。</p>
<p>Boot Loader 的 stage1 通常包括以下步骤(以执行的先后顺序)：</p>
<ul>
<li>硬件设备初始化。</li>
<li>为加载 Boot Loader 的 stage2 准备 RAM 空间。</li>
<li>拷贝 Boot Loader 的 stage2 到 RAM 空间中。</li>
<li>设置好堆栈。</li>
<li>跳转到 stage2 的 C 入口点。</li>
</ul>
<p>Boot Loader 的 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 Loader 的 stage1</font></strong></span></p>
<p><strong>3.1.1 基本的硬件初始化</strong></p>
<p>这是 Boot Loader 一开始就执行的操作，其目的是为 stage2 的执行以及随后的 kernel 的执行准备好一些基本的硬件环境。它通常包括以下步骤（以执行的先后顺序）：</p>
<p>1． <strong>屏蔽所有的中断。</strong>为中断提供服务通常是 OS 设备驱动程序的责任，因此在 Boot Loader 的执行全过程中可以不必响应任何中断。中断屏蔽可以通过写 CPU 的中断屏蔽寄存器或状态寄存器（比如 ARM 的 CPSR 寄存器）来完成。</p>
<p>2． <strong>设置 CPU 的速度和时钟频率。</strong></p>
<p>3． <strong>RAM 初始化。</strong>包括正确地设置系统的内存控制器的功能寄存器以及各内存库控制寄存器等。</p>
<p>4． <strong>初始化 LED。</strong>典型地，通过 GPIO 来驱动 LED，其目的是表明系统的状态是 OK 还是 <a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">Error</a>。如果板子上没有 LED，那么也可以通过初始化 UART 向串口打印 Boot Loader 的 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 Loader 的 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 Loader 的 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 Loader 的 stage2 </font></strong></span></p>
<p>正如前面所说，stage2 的代码通常用 C 语言来实现，以便于实现更复杂的功能和取得更好的代码可读性和可移植性。但是与普通 C 语言应用程序不同的是，在编译和链接 boot loader 这样的程序时，我们不能使用 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 Loader 的 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 Loader 也可以将内存映射的详细信息打印到串口。</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 Loader 设置的常见启动参数有：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 <a href="http://www.donevii.com/post/tag/command" class="st_tag internal_tag" rel="tag" title="Posts tagged with command">command</a> lines so the kernel will still     * use its default <a href="http://www.donevii.com/post/tag/command" class="st_tag internal_tag" rel="tag" title="Posts tagged with command">command</a> 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 Loader 调用 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． Cache 和 MMU 的设置：</p>
<ul>
<li>MMU 必须关闭；</li>
<li>指令 Cache 可以打开也可以关闭；</li>
<li>数据 Cache 必须关闭；</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 loader 程序的设计与实现中，没有什么能够比从串口终端正确地收到打印信息能更令人激动了。此外，向串口终端打印信息也是一个非常重要而又有效的调试手段。但是，我们经常会碰到串口终端显示乱码或根本没有显示的问题。造成这个问题主要有两种原因：(1) boot loader 对串口的初始化设置不正确。(2) 运行在 host 端的终端仿真程序对串口的设置不正确，这包括：波特率、奇偶校验、数据位和停止位等方面的设置。</p>
<p>此外，有时也会碰到这样的问题，那就是：在 boot loader 的运行过程中我们可以正确地向串口终端输出信息，但当 boot loader 启动内核后却无法看到内核的启动输出信息。对这一问题的原因可以从以下几个方面来考虑：</p>
<p>(1) 首先请确认你的内核在编译时配置了对串口终端的支持，并配置了正确的串口驱动程序。</p>
<p>(2) 你的 boot loader 对串口的初始化设置可能会和内核对串口的初始化设置不一致。此外，对于诸如 s3c44b0x 这样的 CPU，CPU 时钟频率的设置也会影响串口，因此如果 boot loader 和内核对其 CPU 时钟频率的设置不一致，也会使串口终端无法正确显示信息。</p>
<p>(3) 最后，还要确认 boot loader 所用的内核基地址必须和内核映像在编译时所用的运行基地址一致，尤其是对于 uClinux 而言。假设你的内核映像在编译时用的基地址是 0xc0008000，但你的 boot loader 却将它加载到 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 Loader 的设计与实现是一个非常复杂的过程。如果不能从串口收到那激动人心的&#8221;uncompressing linux&#8230;&#8230;&#8230;&#8230;&#8230;&#8230; done, booting the kernel……&#8221;内核启动信息，恐怕谁也不能说：&#8221;嗨，我的 boot loader 已经成功地转起来了！&#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>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/387.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[分享] 某知名手机平台的XML Parser源代码</title>
		<link>http://www.donevii.com/post/353.html</link>
		<comments>http://www.donevii.com/post/353.html#comments</comments>
		<pubDate>Sun, 25 Nov 2007 06:21:27 +0000</pubDate>
		<dc:creator>gavinkwoe</dc:creator>
				<category><![CDATA[c/c++/c#]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[平台]]></category>
		<category><![CDATA[手机]]></category>
		<category><![CDATA[源代码]]></category>

		<guid isPermaLink="false">http://www.donevii.com/post/353.html</guid>
		<description><![CDATA[    今天心情不错~ 分享一下小弟06年在某手机公司写的XML parser. 虽然当时脑子里还没有FSM的概念, 但代码逻辑还算清晰, 颇有成就感! 结构比较简单, 按DOM方式把指定文件解析成节点树, 另外提... ]]></description>
			<content:encoded><![CDATA[<p>    今天心情不错~ 分享一下小弟06年在某手机公司写的XML <a href="http://www.donevii.com/post/tag/parser" class="st_tag internal_tag" rel="tag" title="Posts tagged with parser">parser</a>.<br />
虽然当时脑子里还没有FSM的概念, 但代码逻辑还算清晰, 颇有成就感!<br />
结构比较简单, 按DOM方式把指定文件解析成节点树, 另外提供几个简单的查找函数.<br />
部分功能等完善, 过段时间再发一份功能比较完善的C++版本.</p>
<h3><strong>PLX_XMLParser.h</strong></h3>
<p>#if _MSC_VER &gt; 1000<br />
#pragma once<br />
#endif</p>
<p>#ifndef __XMLPARSE_H<br />
#define __XMLPARSE_H</p>
<p>#include</p>
<p>//////////////////////////////<br />
// Configure</p>
<p>#define USE_INLINE_FUNCTION<br />
#define USE_FILEBUFFER</p>
<p>//////////////////////////////<br />
// Constants</p>
<p>typedef enum {<br />
XMLERR_OK       = 0&#215;0,<br />
XMLERR_EFILE,       // failed to open file<br />
XMLERR_ALRDOPEN,    // already opened<br />
XMLERR_EDOC,<br />
XMLERR_EPARSE,<br />
} XMLERR;</p>
<p>typedef enum {<br />
NODETYPE_UNKN    = 0&#215;0,<br />
NODETYPE_ELEM   = 0&#215;1,<br />
NODETYPE_TEXT   = 0&#215;2,<br />
NODETYPE_COMM   = 0&#215;4,<br />
NODETYPE_INST   = 0&#215;8, // Not support<br />
//NODETYPE_USEFUL = NODETYPE_ELEM|NODETYPE_TEXT,<br />
//NODETYPE_ALL    = NODETYPE_ELEM|NODETYPE_TEXT|NODETYPE_COMM|NODETYPE_INST,<br />
} NODETYPE;</p>
<p>typedef enum {<br />
DSTAT_UNOPEN    = 0&#215;0,<br />
DSTAT_OPENED    = 0&#215;1,<br />
} DOCSTAT;</p>
<p>typedef enum {<br />
ISTAT_STOP      = 0&#215;0,<br />
ISTAT_CONTINUE  = 0&#215;1,<br />
ISTAT_PASS      = 0&#215;2,<br />
} ITERSTAT;</p>
<p>enum {    MAXLEN_BSTR    = 256 };</p>
<p>//////////////////////////////<br />
// Structures</p>
<p>struct tagBString<br />
{<br />
LONG    m_lLength;<br />
union   {<br />
CHAR    m_paStr[1];<br />
LPCSTR  m_pszStr;<br />
};<br />
};</p>
<p>typedef struct tagBString       BSTRING;<br />
typedef struct tagBString       *LPBSTRING;<br />
typedef struct tagBString const *LPCBSTRING;</p>
<p>struct tagXMLAttrib;<br />
typedef struct tagXMLAttrib            XMLATTRIB;<br />
typedef struct tagXMLAttrib            *LPXMLATTRIB;<br />
typedef struct tagXMLAttrib    const    *LPCXMLATTRIB;</p>
<p>struct tagXMLAttrib<br />
{<br />
LPBSTRING   m_pbstrName;<br />
LPBSTRING   m_pbstrValue;<br />
LPXMLATTRIB    m_pNext;<br />
};</p>
<p>struct tagXMLNode;<br />
typedef struct tagXMLNode       XMLNODE;<br />
typedef struct tagXMLNode       *LPXMLNODE;<br />
typedef struct tagXMLNode const *LPCXMLNODE;</p>
<p>struct tagXMLNode<br />
{<br />
NODETYPE    m_eNodeType;<br />
LONG        m_lDepth;</p>
<p>LPBSTRING   m_pbstrTag;</p>
<p>LONG        m_lChildNum;<br />
LONG        m_lChildNum_Elem;</p>
<p>LPXMLNODE    m_pRoot;<br />
LPXMLNODE   m_pParent;<br />
LPXMLNODE   m_pFirstChild;<br />
LPXMLNODE   m_pLastChild;<br />
LPXMLNODE   m_pPrevSibling;<br />
LPXMLNODE   m_pNextSibling;</p>
<p>LONG        m_lAttribNum;<br />
LPXMLATTRIB m_pFirstAttrib;<br />
};</p>
<p>struct tagXMLDocument<br />
{<br />
DOCSTAT     m_eDocStat;<br />
LPXMLNODE   m_lpRootNode;<br />
};</p>
<p>typedef struct tagXMLDocument       XMLDOCUMENT;<br />
typedef struct tagXMLDocument       *LPXMLDOCUMENT;<br />
typedef struct tagXMLDocument const *LPCXMLDOCUMENT;</p>
<p>//////////////////////////////<br />
// Types</p>
<p>typedef ITERSTAT    (CALLBACK *LPFNNODEPROC)( LPCXMLNODE pNode, LPVOID pvParam );</p>
<p>//////////////////////////////<br />
// Macros</p>
<p>#if    defined(USE_INLINE_FUNCTION)</p>
<p>#define BSTR_C( pBStr )                     (&amp;((pBStr)-&gt;m_paStr[0]))<br />
#define BSTR_CAST( pvAnyType )              ((LPBSTRING)pvAnyType)<br />
#define    BSTR_LEN( pBStr )                   ((pBStr)-&gt;m_lLength)<br />
#define BSTR_ALLOC( pszStr )                AllocBString( pszStr, (NULL != (pszStr) ? ((LONG)strlen(pszStr)) : (0L)) )<br />
#define BSTR_ALLOCEX( pszStr, nLen )        AllocBString( pszStr, (LONG)nLen )<br />
#define BSTR_FREE( pBStr )                  free( pBStr )<br />
#define BSTR_SAFEFREE( pBStr )              if ( NULL != pBStr ) { free( pBStr ); pBStr = NULL; }<br />
#define BSTR_EQUAL( pBStrL, pBStrR ) \<br />
( (BSTR_LEN(pBStrL) == BSTR_LEN(pBStrR) &amp;&amp; 0 == strcmp(BSTR_C(pBStrL), BSTR_C(pBStrL))) ? \<br />
TRUE : FALSE )<br />
#define BSTR_EQUAL_STATIC( pBStr, szStatic ) \<br />
( (BSTR_LEN(pBStr) == (LONG)(sizeof(szStatic) &#8211; 1) &amp;&amp; 0 == strcmp(BSTR_C(pBStr), szStatic)) ? \<br />
TRUE : FALSE )<br />
#define BSTR_EQUAL_CSTR( pBStr, pszStr ) \<br />
( (BSTR_LEN(pBStr) == (LONG)strlen(pszStr) &amp;&amp; 0 == strcmp(BSTR_C(pBStr), pszStr)) ? \<br />
TRUE : FALSE )</p>
<p>#define    <a href="http://www.donevii.com/post/tag/xml" class="st_tag internal_tag" rel="tag" title="Posts tagged with xml">XML</a>_GetRootNode( pDoc )             ((NULL == (pDoc) || (pDoc)-&gt;m_eDocStat != DSTAT_OPENED) ? NULL : (pDoc)-&gt;m_lpRootNode)<br />
#define    XML_GetNodeType( pNode )             (NULL != (pNode) ? (pNode)-&gt;m_eNodeType : NODETYPE_UNKN)<br />
#define    XML_GetNodeDepth( pNode )            (NULL != (pNode) ? (pNode)-&gt;m_lDepth : (-1L))<br />
#define    XML_GetNodeParent( pNode )             (NULL != (pNode) ? (pNode)-&gt;m_pParent : NULL)<br />
#define    XML_GetNodeFirstChild( pNode )         (NULL != (pNode) ? (pNode)-&gt;m_pFirstChild : NULL)<br />
#define    XML_GetNodeLastChild( pNode )         (NULL != (pNode) ? (pNode)-&gt;m_pLastChild : NULL)<br />
#define    XML_GetNodeChildNum( pNode )         (NULL != (pNode) ? (pNode)-&gt;m_lChildNum : (0L))<br />
#define    XML_GetNodeChildNum_Elem( pNode )     (NULL != (pNode) ? (pNode)-&gt;m_lChildNum_Elem : (0L))<br />
#define    XML_GetNodePrevSibling( pNode )     (NULL != (pNode) ? (pNode)-&gt;m_pPrevSibling : NULL)<br />
#define    XML_GetNodeNextSibling( pNode )     (NULL != (pNode) ? (pNode)-&gt;m_pNextSibling : NULL)<br />
#define    XML_GetNodeTagName( pNode )         (NULL != (pNode) ? (pNode)-&gt;m_pbstrTag : NULL)<br />
#define    XML_GetNodeAttribNum( pNode )         (NULL != (pNode) ? (pNode)-&gt;m_lAttribNum : (0L))<br />
#define    XML_GetNodeFirstAttrib( pNode )     (NULL != (pNode) ? (pNode)-&gt;m_pFirstAttrib : NULL)<br />
#define    XML_GetNodeNextAttrib( pAttr )         (NULL != (pAttr) ? (pAttr)-&gt;m_pNext : NULL)<br />
#define XML_GetAttribValueBString( pAttr )  (NULL != (pAttr) ? (pAttr)-&gt;m_pbstrValue) : NULL)<br />
#define XML_GetAttribValueCString( pAttr )  (NULL != (pAttr) ? BSTR_C((pAttr)-&gt;m_pbstrValue) : NULL)<br />
#define XML_GetAttribValueLong( pAttr )     (NULL != (pAttr) ? (LONG)strtol(BSTR_C((pAttr)-&gt;m_pbstrValue), NULL, 0) : (0L))<br />
#define XML_GetAttribValueInt( pAttr )      (NULL != (pAttr) ? (int)strtol(BSTR_C((pAttr)-&gt;m_pbstrValue), NULL, 0) : (0))</p>
<p>#endif</p>
<p>//////////////////////////////<br />
// Function prototypes</p>
<p>#if defined(__cplusplus)<br />
extern &#8220;C&#8221; {<br />
#endif</p>
<p>size_t      strlen_when( LPCSTR lpszStr, CHAR ch );<br />
size_t        strlen_notin( LPCSTR lpszStr, LPCSTR lpszSet );<br />
LPCSTR        strchr_notin( LPCSTR lpszStr, LPCSTR lpszSet );<br />
LPCSTR        strchr_skipws( LPCSTR lpszStr );</p>
<p>LPBSTRING   AllocBString( LPCSTR lpszStr, LONG lLen );</p>
<p>XMLERR      XML_OpenDocument( LPXMLDOCUMENT pDoc, LPCSTR lpszFileName, DWORD dwReserve );<br />
XMLERR      XML_CloseDocument( LPXMLDOCUMENT pDoc );<br />
LPXMLNODE    XML_GetNode( LPXMLDOCUMENT pDoc, LPXMLNODE pStartPoint, LPCSTR lpszTag, LONG lLen );<br />
LPXMLATTRIB    XML_GetNodeAttrib( LPXMLNODE pNode, LPCSTR lpszAttr, LONG lLen );<br />
LPXMLNODE    XML_GetNodeSibling( LPXMLNODE pNode, LPCSTR lpszTag, LONG lLen, BOOL IncludeThis );<br />
LONG         XML_ForEachNode( LPXMLDOCUMENT pDoc, LPXMLNODE pStartPoint, LPFNNODEPROC pfnNodeProc, LPVOID pvParam );</p>
<p>#if defined(__cplusplus)<br />
}   // extern &#8220;C&#8221; {<br />
#endif</p>
<p>#endif // #ifndef __XMLPARSE_H</p>
<h3>PLX_XMLParser.c</h3>
<p>#include &lt;assert.h&gt;<br />
#include &lt;fcntl.h&gt;<br />
#include &lt;io.h&gt;<br />
#if defined(<a href="http://www.donevii.com/post/tag/debug" class="st_tag internal_tag" rel="tag" title="Posts tagged with debug">DEBUG</a>) || defined(_<a href="http://www.donevii.com/post/tag/debug" class="st_tag internal_tag" rel="tag" title="Posts tagged with debug">DEBUG</a>)<br />
#include &lt;stdio.h&gt;<br />
#endif</p>
<p>#include &#8220;XMLParse.h&#8221;</p>
<p>//#pragma warning(disable:4305)</p>
<p>//////////////////////////////<br />
// Configure</p>
<p>//#define  USE_MEMORY_HEAP</p>
<p>#ifdef  USE_FILEBUFFER  // Whether use file system with os-layer buffer</p>
<p>#define INVALID_FILE_HANDLE         ((int)-1)<br />
#define FILE_HANDLE                 int</p>
<p>#define MODE_RDONLY                 (O_RDONLY)<br />
#define FILE_OPEN(pszFile,mode)     open( pszFile, mode )<br />
#define FILE_READ(hFile,pbuf,size)  read(hFile, (LPVOID)pbuf, size)<br />
#define FILE_SEEK(hFile,off,pos)    lseek( hFile, off, pos )<br />
#define FILE_CLOSE(hFile)           close( hFile )</p>
<p>#else</p>
<p>#define INVALID_FILE_HANDLE         ((FILE *)NULL)<br />
#define FILE_HANDLE                 FILE *</p>
<p>#define MODE_RDONLY                 (&#8220;r&#8221;)<br />
#define FILE_OPEN(pszFile,mode)     fopen( pszFile, mode )<br />
#define FILE_READ(hFile,pbuf,size)  fread((LPVOID)pbuf, size, 1, hFile)<br />
#define FILE_SEEK(hFile,off,pos)    fseek( hFile, off, pos )<br />
#define FILE_CLOSE(hFile)           fclose( hFile )</p>
<p>#endif</p>
<p>//////////////////////////////<br />
// Constants</p>
<p>enum {    MAXLEN_READBUF    = 1024 };</p>
<p>typedef enum {<br />
PSTAT_STOP      = 0&#215;0,<br />
PSTAT_INITIAL,<br />
PSTAT_FINAL,<br />
PSTAT_DECL_BEG,<br />
PSTAT_DECL_END,<br />
PSTAT_ELEM_BEG,<br />
PSTAT_ELEM_END,<br />
PSTAT_TEXT_BEG,<br />
PSTAT_TEXT_END,<br />
PSTAT_CDATA_BEG,<br />
PSTAT_CDATA_END,<br />
PSTAT_COMM_BEG,<br />
PSTAT_COMM_END,<br />
PSTAT_<a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">ERROR</a>,<br />
} PARSESTAT;</p>
<p>//////////////////////////////<br />
// Macros</p>
<p>#define ZERO_MEMORY(p, size) \<br />
( memset((LPVOID)(p), 0&#215;0, (size_t)size) )</p>
<p>#define is_WhiteSpace(ch)   (((ch) == &#8216; &#8216;  || (ch) == &#8216;\t&#8217;) ? TRUE : FALSE)<br />
#define is_LineBreak(ch)    (((ch) == &#8216;\r&#8217; || (ch) == &#8216;\n&#8217;) ? TRUE : FALSE)<br />
#define is_LeftBracket(ch)    ((ch) == &#8216;&lt;&#8217; ? TRUE : FALSE)<br />
#define is_RightBracket(ch)    ((ch) == &#8216;&gt;&#8217; ? TRUE : FALSE)</p>
<p>#define is_BufferEmpty(ps)  ((ps)-&gt;m_lReadCursor &gt;= (ps)-&gt;m_lReadSize ? TRUE : FALSE)<br />
#define get_BufferChar(ps)  ((CHAR)((ps)-&gt;m_aReadBuf[(ps)-&gt;m_lReadCursor]))</p>
<p>#define is_FirstChild(pn)    ((pn)-&gt;m_pPrevSibling == NULL ? TRUE : FALSE)<br />
#define is_LastChild(pn)    ((pn)-&gt;m_pNextSibling == NULL ? TRUE : FALSE)</p>
<p>//////////////////////////////<br />
// Structures</p>
<p>struct tagXMLParseStat<br />
{<br />
PARSESTAT   m_eParseStat;<br />
LONG        m_lDepth;<br />
LPXMLNODE    m_pRootNode;<br />
LPXMLNODE    m_pLastNode;</p>
<p>FILE_HANDLE    m_hOpenFile;<br />
LONG        m_lFileCursor;<br />
LONG        m_lFileLength;</p>
<p>LONG        m_lLineNo;<br />
LONG        m_lReadCursor;<br />
LONG        m_lReadSize;<br />
BYTE        m_aReadBuf[MAXLEN_READBUF];<br />
};<br />
typedef struct tagXMLParseStat            XMLPARSESTAT;<br />
typedef struct tagXMLParseStat            *LPXMLPARSESTAT;<br />
typedef struct tagXMLParseStat    const    *LPCXMLPARSESTAT;</p>
<p>struct tagXMLIterator<br />
{<br />
LONG            m_lCount;<br />
LPFNNODEPROC    m_pfnProc;<br />
LPVOID          m_pvParam;<br />
LPXMLNODE       m_pStation;<br />
};<br />
typedef struct tagXMLIterator       XMLITERFATOR;<br />
typedef struct tagXMLIterator       *LPXMLITERFATOR;<br />
typedef struct tagXMLIterator const *LPCXMLITERFATOR;</p>
<p>/*struct tagMemoryPage<br />
{<br />
LONG    lGranu ;<br />
LONG    lSize;<br />
LPVOID  pvPage;<br />
BYTE    bUseFlags[1];<br />
};<br />
typedef struct tagMemoryPage        MEMORYPAGE;<br />
typedef struct tagMemoryPage        *LPMEMORYPAGE;<br />
typedef struct tagMemoryPage const  *LPCMEMORYPAGE;*/</p>
<p>//////////////////////////////<br />
// Function prototypes</p>
<p>#if defined(__cplusplus)<br />
extern &#8220;C&#8221; {<br />
#endif</p>
<p>static void        XML_FreeNodeTree( LPXMLNODE pNode );<br />
static void        XML_FreeAttribList( LPXMLATTRIB pAttrib );<br />
static void     XML_IterateTree( LPXMLNODE pTree, LPXMLITERFATOR pIterator );<br />
static BOOL     XMLCmpNode_EqualTag( LPCXMLNODE pNode, LPVOID pvParam );</p>
<p>static BOOL        Parser_RoutineStart( LPXMLPARSESTAT pParseStat, LPXMLDOCUMENT pResult );<br />
static int        Parser_GetTagString( LPXMLPARSESTAT pParseStat, LPSTR lpszBuf );<br />
static BOOL        Parser_ReadStream( LPXMLPARSESTAT pParseStat );<br />
static void        Parser_OnInitial( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnElemBegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnElemEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnTextBegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnTextEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnCDATABegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnCDATAEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnCommBegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnCommEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnDeclBegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static void        Parser_OnDeclEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag );<br />
static BOOL        Parser_OnFinal( LPXMLPARSESTAT pParseStat );<br />
static BOOL        Parser_OnError( LPXMLPARSESTAT pParseStat );</p>
<p>//#if defined(USE_MEMORY_HEAP)<br />
//static LPVOID   MemoryHeap_Create( LONG lInitialGranu, LONG lInitialSize );<br />
//static BOOL     MemoryHeap_Destroy( LPVOID );<br />
//static LPVOID   MemoryHeap_Alloc( void );<br />
//static void     MemoryHeap_Free( LPVOID pvBlock );<br />
//#endif</p>
<p>#if defined(__cplusplus)<br />
}   // extern &#8220;C&#8221; {<br />
#endif</p>
<p>//////////////////////////////<br />
// Function implementations</p>
<p>#if defined(__cplusplus)<br />
extern &#8220;C&#8221; {<br />
#endif</p>
<p>/*********************************************************************\<br />
* Function: strlen_when<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
size_t strlen_when( LPCSTR lpszStr, CHAR ch )<br />
{<br />
<a href="http://www.donevii.com/post/tag/register" class="st_tag internal_tag" rel="tag" title="Posts tagged with register">register</a> size_t nLen;<br />
assert( NULL != lpszStr );<br />
for ( nLen = 0; *lpszStr != ch &amp;&amp; *lpszStr != &#8216;\0&#8242;;    lpszStr++, nLen++ )<br />
;<br />
return nLen;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: strlen_notin<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
size_t strlen_notin( LPCSTR lpszStr, LPCSTR lpszSet )<br />
{<br />
register size_t nLen;<br />
assert( NULL != lpszStr );<br />
for ( nLen = 0; *lpszStr != &#8216;\0&#8242; &amp;&amp; NULL == strchr(lpszSet, *lpszStr); lpszStr++, nLen++ )<br />
;<br />
return nLen;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: strchr_notin<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
LPCSTR strchr_notin( LPCSTR lpszStr, LPCSTR lpszSet )<br />
{<br />
assert( NULL != lpszStr );<br />
for ( ; *lpszStr != &#8216;\0&#8242; &amp;&amp; NULL == strchr(lpszSet, *lpszStr); lpszStr++ )<br />
;<br />
return lpszStr;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: strchr_skipws<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
LPCSTR strchr_skipws( LPCSTR lpszStr )<br />
{<br />
assert( NULL != lpszStr );<br />
for ( ; *lpszStr != &#8216;\0&#8242; &amp;&amp; is_WhiteSpace(*lpszStr); lpszStr++ )<br />
;<br />
return lpszStr;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: AllocBString<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
LPBSTRING AllocBString( LPCSTR lpszStr, LONG lLen )<br />
{<br />
LPBSTRING pBStr = (LPBSTRING)malloc( sizeof(LONG) + lLen + 1 );<br />
assert( NULL != pBStr );</p>
<p>pBStr-&gt;m_lLength = lLen;<br />
strncpy( &amp;pBStr-&gt;m_paStr[0], lpszStr, lLen );<br />
pBStr-&gt;m_paStr[lLen] = &#8216;\0&#8242;;</p>
<p>return pBStr;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_OpenDocument<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
XMLERR XML_OpenDocument( LPXMLDOCUMENT pDoc, LPCSTR lpszFileName, DWORD dwReserve )<br />
{<br />
BOOL            bRet;<br />
FILE_HANDLE        hFile;<br />
XMLPARSESTAT    xmlParseStat;</p>
<p>assert( NULL != pDoc );<br />
assert( NULL != lpszFileName );</p>
<p>if ( pDoc-&gt;m_eDocStat == DSTAT_OPENED )<br />
return XMLERR_ALRDOPEN;</p>
<p>ZERO_MEMORY( &amp;xmlParseStat, sizeof(XMLPARSESTAT) );</p>
<p>hFile = FILE_OPEN( lpszFileName, MODE_RDONLY );<br />
if ( INVALID_FILE_HANDLE == hFile )<br />
return XMLERR_EFILE;</p>
<p>xmlParseStat.m_hOpenFile    = hFile;<br />
xmlParseStat.m_lFileCursor    = 0;<br />
xmlParseStat.m_lFileLength    = FILE_SEEK( hFile, 0, SEEK_END );<br />
FILE_SEEK( hFile, 0, SEEK_SET );</p>
<p>xmlParseStat.m_lDepth = 0;<br />
xmlParseStat.m_lLineNo = 1;<br />
bRet = Parser_RoutineStart( &amp;xmlParseStat, pDoc );<br />
if ( FALSE == bRet )<br />
{<br />
FILE_CLOSE( hFile );<br />
return XMLERR_EPARSE;<br />
}</p>
<p>pDoc-&gt;m_eDocStat    = DSTAT_OPENED;<br />
pDoc-&gt;m_lpRootNode    = xmlParseStat.m_pRootNode;<br />
FILE_CLOSE( hFile );<br />
return XMLERR_OK;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_CloseDocument<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
XMLERR XML_CloseDocument( LPXMLDOCUMENT pDoc )<br />
{<br />
if ( NULL != pDoc &amp;&amp; pDoc-&gt;m_eDocStat == DSTAT_OPENED )<br />
{<br />
XML_FreeNodeTree( pDoc-&gt;m_lpRootNode );<br />
pDoc-&gt;m_lpRootNode = NULL;<br />
pDoc-&gt;m_eDocStat = DSTAT_UNOPEN;<br />
}<br />
return XMLERR_OK;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_GetTagString<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
int Parser_GetTagString( LPXMLPARSESTAT pParseStat, LPSTR lpszBuf )<br />
{<br />
int        nLen;<br />
CHAR    ch;<br />
CHAR    chTerm;<br />
BOOL    bInclude;</p>
<p>// Should to ensure barket match Here!</p>
<p>nLen = 0;<br />
for ( ;; )<br />
{<br />
if ( is_BufferEmpty(pParseStat) &amp;&amp; FALSE == Parser_ReadStream(pParseStat) )<br />
goto __RET;</p>
<p>ch = get_BufferChar(pParseStat);<br />
if ( ch == &#8216;\n&#8217; )<br />
pParseStat-&gt;m_lLineNo++;</p>
<p>if ( !is_WhiteSpace(ch) &amp;&amp; !is_LineBreak(ch) )<br />
break;</p>
<p>pParseStat-&gt;m_lReadCursor++;<br />
}</p>
<p>if ( is_LeftBracket(ch) )<br />
{<br />
chTerm = &#8216;&gt;&#8217;;<br />
bInclude = TRUE;<br />
}<br />
else<br />
{<br />
chTerm = &#8216;&lt;&#8217;;<br />
bInclude = FALSE;<br />
}</p>
<p>for ( ;; )<br />
{<br />
if ( is_BufferEmpty(pParseStat) &amp;&amp; FALSE == Parser_ReadStream(pParseStat) )<br />
break;</p>
<p>ch = get_BufferChar(pParseStat);<br />
if ( ch == &#8216;\n&#8217; )<br />
pParseStat-&gt;m_lLineNo++;</p>
<p>if ( ch == chTerm )<br />
{<br />
if ( FALSE != bInclude )<br />
{<br />
lpszBuf[nLen++] = chTerm;<br />
pParseStat-&gt;m_lReadCursor++;<br />
}<br />
break;<br />
}</p>
<p>lpszBuf[nLen++] = ch;<br />
pParseStat-&gt;m_lReadCursor++;<br />
}</p>
<p>__RET:<br />
lpszBuf[nLen] = &#8216;\0&#8242;;<br />
return nLen;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_ReadStream<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
BOOL Parser_ReadStream( LPXMLPARSESTAT pParseStat )<br />
{<br />
size_t    nSize;</p>
<p>pParseStat-&gt;m_lReadCursor    = 0;<br />
pParseStat-&gt;m_lReadSize    = 0;<br />
nSize = FILE_READ( pParseStat-&gt;m_hOpenFile, (LPVOID)&amp;pParseStat-&gt;m_aReadBuf[0], MAXLEN_READBUF );<br />
if ( nSize &lt;= 0 )<br />
return FALSE;</p>
<p>pParseStat-&gt;m_lReadSize        = (LONG)nSize;<br />
pParseStat-&gt;m_lFileCursor  += (LONG)nSize;<br />
return TRUE;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_RoutineStart<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
BOOL Parser_RoutineStart( LPXMLPARSESTAT pParseStat, LPXMLDOCUMENT pResult )<br />
{<br />
BOOL    bRet;<br />
CHAR    szTag[256];</p>
<p>assert( NULL != pParseStat );</p>
<p>pParseStat-&gt;m_eParseStat = PSTAT_INITIAL;<br />
while ( pParseStat-&gt;m_eParseStat != PSTAT_STOP )<br />
{<br />
switch ( pParseStat-&gt;m_eParseStat )<br />
{<br />
case PSTAT_INITIAL:     Parser_OnInitial( pParseStat, &amp;szTag[0] );        break;</p>
<p>case PSTAT_DECL_BEG:    Parser_OnDeclBegin( pParseStat, &amp;szTag[0] );    break;<br />
case PSTAT_DECL_END:    Parser_OnDeclEnd( pParseStat, &amp;szTag[0] );        break;</p>
<p>case PSTAT_ELEM_BEG:    Parser_OnElemBegin( pParseStat, &amp;szTag[0] );    break;<br />
case PSTAT_ELEM_END:    Parser_OnElemEnd( pParseStat, &amp;szTag[0] );      break;</p>
<p>case PSTAT_TEXT_BEG:    Parser_OnTextBegin( pParseStat, &amp;szTag[0] );    break;<br />
case PSTAT_TEXT_END:    Parser_OnTextEnd( pParseStat, &amp;szTag[0] );        break;</p>
<p>case PSTAT_CDATA_BEG:    Parser_OnCDATABegin( pParseStat, &amp;szTag[0] );    break;<br />
case PSTAT_CDATA_END:    Parser_OnCDATAEnd( pParseStat, &amp;szTag[0] );        break;</p>
<p>case PSTAT_COMM_BEG:    Parser_OnCommBegin( pParseStat, &amp;szTag[0] );    break;<br />
case PSTAT_COMM_END:    Parser_OnCommEnd( pParseStat, &amp;szTag[0] );        break;</p>
<p>case PSTAT_FINAL:        bRet = Parser_OnFinal( pParseStat );            break;<br />
case PSTAT_ERROR:        bRet = Parser_OnError( pParseStat );            break;</p>
<p>default:<br />
assert( !&#8221;Unknown parsing status!&#8221; );<br />
break;<br />
}<br />
}<br />
return bRet;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnInitial<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnInitial( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
int     nLen;<br />
assert( NULL != lpszTag );</p>
<p>lpszTag[0] = &#8216;\0&#8242;;</p>
<p>nLen = Parser_GetTagString( pParseStat, lpszTag );<br />
if ( nLen &lt;= 0 )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_STOP;<br />
return;<br />
}</p>
<p>if ( lpszTag[0] == &#8216;&lt;&#8217;  )<br />
{<br />
if ( lpszTag[1] == &#8216;?&#8217;)<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_DECL_BEG;<br />
}<br />
else if ( !strncmp(&amp;lpszTag[1], &#8220;!&#8211;&#8221;, 3) )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_COMM_BEG;<br />
}<br />
else if ( lpszTag[1] == &#8216;/&#8217; )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_ELEM_END;<br />
}<br />
else if ( isalpha(lpszTag[1]) )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_ELEM_BEG;<br />
}<br />
else if ( !strncmp(&amp;lpszTag[1], &#8220;![CDATA[", 8) )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_CDATA_BEG;<br />
}<br />
else<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_ERROR;<br />
}<br />
}<br />
else if ( NULL != pParseStat-&gt;m_pLastNode )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_TEXT_BEG;<br />
}<br />
else<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_ERROR;<br />
}<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnFinal<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
BOOL Parser_OnFinal( LPXMLPARSESTAT pParseStat )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_STOP;<br />
return TRUE;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnError<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
BOOL Parser_OnError( LPXMLPARSESTAT pParseStat )<br />
{<br />
XML_FreeNodeTree( pParseStat-&gt;m_pRootNode );<br />
pParseStat-&gt;m_pRootNode     = NULL;<br />
pParseStat-&gt;m_eParseStat = PSTAT_STOP;<br />
TRACE( "[Xml Parser]: Syntax error @ %s #%ld.\n&#8221;, &#8220;&#8221;, pParseStat-&gt;m_lLineNo);<br />
return FALSE;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnDeclBegin<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnDeclBegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
int nLenTag;</p>
<p>if ( NULL != pParseStat-&gt;m_pRootNode )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_ERROR;<br />
return;<br />
}</p>
<p>lpszTag = (LPSTR)strchr_skipws( (LPCSTR)(lpszTag + 2) );<br />
if ( lpszTag == &#8216;\0&#8242; )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_ERROR;<br />
return;<br />
}</p>
<p>nLenTag = (int)strlen_notin(lpszTag, &#8221; \t\r\n&gt;&#8221;);<br />
if ( nLenTag == 3 &amp;&amp; !strncmp(lpszTag, &#8220;xml&#8221;, 3) )<br />
{<br />
// Here, dispose version and coding infomation in XML document header<br />
}<br />
else if ( nLenTag == 14 &amp;&amp; !strncmp(lpszTag, &#8220;xml-stylesheet&#8221;, 3) )<br />
{<br />
// Unsupport<br />
}<br />
else<br />
{<br />
// Unknown declaretion<br />
}</p>
<p>pParseStat-&gt;m_eParseStat = PSTAT_INITIAL;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnDeclEnd<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnDeclEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
// Do noting<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnElemBegin<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnElemBegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
int         nLenTag;<br />
int         nLenValue;<br />
LPSTR       lpszValue;<br />
LPXMLNODE   pNode;<br />
LPXMLATTRIB    pAttrib;<br />
LPXMLATTRIB pPrevAttr;</p>
<p>assert( is_LeftBracket(lpszTag[0]) );</p>
<p>// Multi-root node is not supproted<br />
if ( 0 == pParseStat-&gt;m_lDepth &amp;&amp; NULL != pParseStat-&gt;m_pRootNode )<br />
goto __ERROR;</p>
<p>pNode = (LPXMLNODE)malloc(sizeof(XMLNODE));<br />
if ( NULL == pNode )<br />
goto __ERROR;</p>
<p>ZERO_MEMORY( pNode, sizeof(XMLNODE) );<br />
pNode-&gt;m_eNodeType    = NODETYPE_ELEM;<br />
pNode-&gt;m_lDepth        = pParseStat-&gt;m_lDepth;<br />
if ( NULL != pParseStat-&gt;m_pLastNode )<br />
{<br />
assert( pNode-&gt;m_lDepth &gt;= pParseStat-&gt;m_pLastNode-&gt;m_lDepth );<br />
if ( pNode-&gt;m_lDepth &gt; pParseStat-&gt;m_pLastNode-&gt;m_lDepth ) // new child<br />
{<br />
pNode-&gt;m_pParent = pParseStat-&gt;m_pLastNode;<br />
pParseStat-&gt;m_pLastNode-&gt;m_pFirstChild = pNode;<br />
}<br />
else if ( pNode-&gt;m_lDepth == pParseStat-&gt;m_pLastNode-&gt;m_lDepth ) // new sibling<br />
{<br />
pNode-&gt;m_pParent = pParseStat-&gt;m_pLastNode-&gt;m_pParent;<br />
pParseStat-&gt;m_pLastNode-&gt;m_pNextSibling = pNode;<br />
pNode-&gt;m_pPrevSibling = pParseStat-&gt;m_pLastNode;<br />
}</p>
<p>if ( NULL != pNode-&gt;m_pParent )<br />
{<br />
pNode-&gt;m_pParent-&gt;m_lChildNum++;<br />
pNode-&gt;m_pParent-&gt;m_lChildNum_Elem++;<br />
}<br />
}</p>
<p>if ( NULL == pParseStat-&gt;m_pRootNode )<br />
{<br />
pParseStat-&gt;m_pRootNode = pNode;<br />
}<br />
pNode-&gt;m_pRoot = pParseStat-&gt;m_pRootNode;</p>
<p>pParseStat-&gt;m_pLastNode    = pNode;</p>
<p>lpszTag++;<br />
nLenTag = (int)strlen_notin(lpszTag, &#8221; \t\r\n&gt;&#8221;);<br />
if ( nLenTag &lt;= 0 )<br />
goto __ERROR;</p>
<p>pNode-&gt;m_pbstrTag = BSTR_ALLOCEX(lpszTag, nLenTag);<br />
if ( NULL == pNode-&gt;m_pbstrTag )<br />
goto __ERROR;</p>
<p>lpszTag = (LPSTR)(lpszTag + nLenTag);</p>
<p>for ( pPrevAttr = NULL;; )<br />
{<br />
lpszTag = (LPSTR)strchr_skipws( lpszTag );</p>
<p>if ( is_RightBracket(*lpszTag) )<br />
{<br />
pParseStat-&gt;m_lDepth++; // Move down one layer<br />
pParseStat-&gt;m_eParseStat = PSTAT_INITIAL;<br />
break;<br />
}<br />
else if ( !strncmp(lpszTag, &#8220;/&gt;&#8221;, 2) )<br />
{<br />
//pParseStat-&gt;m_lDepth&#8211;; //<br />
pParseStat-&gt;m_eParseStat = PSTAT_INITIAL;<br />
break;<br />
}</p>
<p>nLenTag = (int)strlen_when( lpszTag, &#8216;=&#8217; );<br />
if ( nLenTag &lt;= 0 )<br />
goto __ERROR;</p>
<p>lpszValue = strchr( (LPCSTR)(lpszTag + nLenTag), &#8216;\&#8221;&#8216; );<br />
if ( NULL == lpszValue )<br />
goto __ERROR;</p>
<p>lpszValue++;<br />
nLenValue = (int)strlen_when( lpszValue, &#8216;\&#8221;&#8216; );</p>
<p>//if ( nLenValue &lt;= 0 )<br />
//    goto __ERROR;</p>
<p>pAttrib = (LPXMLATTRIB)malloc(sizeof(XMLATTRIB));<br />
if ( NULL == pAttrib )<br />
goto __ERROR;<br />
ZERO_MEMORY( pAttrib, sizeof(XMLATTRIB) );</p>
<p>pAttrib-&gt;m_pbstrName    = BSTR_ALLOCEX( lpszTag, nLenTag );<br />
pAttrib-&gt;m_pbstrValue    = BSTR_ALLOCEX( lpszValue, nLenValue );<br />
if ( NULL == pAttrib-&gt;m_pbstrName || NULL == pAttrib-&gt;m_pbstrValue )<br />
goto __ERROR;</p>
<p>if ( NULL == pNode-&gt;m_pFirstAttrib )<br />
pNode-&gt;m_pFirstAttrib = pAttrib;</p>
<p>if ( NULL != pPrevAttr )<br />
pPrevAttr-&gt;m_pNext = pAttrib;<br />
pPrevAttr = pAttrib;</p>
<p>pNode-&gt;m_lAttribNum++;<br />
lpszTag = lpszValue + nLenValue + 1;<br />
}</p>
<p>return;</p>
<p>__ERROR:<br />
XML_FreeNodeTree( pNode );<br />
pParseStat-&gt;m_eParseStat = PSTAT_ERROR;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnElemEnd<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnElemEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
pParseStat-&gt;m_lDepth&#8211;;</p>
<p>if ( NULL != pParseStat-&gt;m_pLastNode )<br />
{<br />
if ( NULL != pParseStat-&gt;m_pLastNode-&gt;m_pParent )<br />
pParseStat-&gt;m_pLastNode-&gt;m_pParent-&gt;m_pLastChild = pParseStat-&gt;m_pLastNode;</p>
<p>if ( pParseStat-&gt;m_pLastNode-&gt;m_lDepth &gt; pParseStat-&gt;m_lDepth )<br />
pParseStat-&gt;m_pLastNode = pParseStat-&gt;m_pLastNode-&gt;m_pParent;<br />
}</p>
<p>if ( 0 == pParseStat-&gt;m_lDepth )<br />
pParseStat-&gt;m_eParseStat = PSTAT_FINAL;<br />
else<br />
pParseStat-&gt;m_eParseStat = PSTAT_INITIAL;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnTextBegin<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnTextBegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
LPXMLNODE pNode;</p>
<p>pNode = (LPXMLNODE)malloc(sizeof(XMLNODE));<br />
if ( NULL == pParseStat-&gt;m_pLastNode )<br />
goto __ERROR;</p>
<p>ZERO_MEMORY( pNode, sizeof(XMLNODE) );<br />
pNode-&gt;m_eNodeType    = NODETYPE_TEXT;<br />
pNode-&gt;m_lDepth        = pParseStat-&gt;m_lDepth;</p>
<p>if ( NULL != pParseStat-&gt;m_pLastNode )<br />
{<br />
assert( pNode-&gt;m_lDepth &gt;= pParseStat-&gt;m_pLastNode-&gt;m_lDepth );<br />
if ( pNode-&gt;m_lDepth &gt; pParseStat-&gt;m_pLastNode-&gt;m_lDepth )<br />
{<br />
pNode-&gt;m_pParent = pParseStat-&gt;m_pLastNode;<br />
pParseStat-&gt;m_pLastNode-&gt;m_pFirstChild = pNode;<br />
}<br />
else if ( pNode-&gt;m_lDepth == pParseStat-&gt;m_pLastNode-&gt;m_lDepth )<br />
{<br />
pNode-&gt;m_pParent = pParseStat-&gt;m_pLastNode-&gt;m_pParent;<br />
pParseStat-&gt;m_pLastNode-&gt;m_pNextSibling = pNode;<br />
pNode-&gt;m_pPrevSibling = pParseStat-&gt;m_pLastNode;<br />
}</p>
<p>if ( NULL != pNode-&gt;m_pParent )<br />
pNode-&gt;m_pParent-&gt;m_lChildNum++;</p>
<p>pNode-&gt;m_pRoot = pParseStat-&gt;m_pLastNode-&gt;m_pRoot;<br />
}</p>
<p>pParseStat-&gt;m_pLastNode    = pNode;</p>
<p>pNode-&gt;m_pbstrTag = BSTR_ALLOC(lpszTag);<br />
if ( NULL == pNode-&gt;m_pbstrTag )<br />
goto __ERROR;</p>
<p>pParseStat-&gt;m_lDepth++; // Move down one layer<br />
pParseStat-&gt;m_eParseStat = PSTAT_TEXT_END;<br />
return;</p>
<p>__ERROR:<br />
XML_FreeNodeTree( pNode );<br />
pParseStat-&gt;m_eParseStat = PSTAT_ERROR;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnTextEnd<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnTextEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
// Move up one layer<br />
pParseStat-&gt;m_lDepth&#8211;;</p>
<p>if ( NULL != pParseStat-&gt;m_pLastNode &amp;&amp;<br />
pParseStat-&gt;m_pLastNode-&gt;m_lDepth &gt; pParseStat-&gt;m_lDepth )<br />
pParseStat-&gt;m_pLastNode = pParseStat-&gt;m_pLastNode-&gt;m_pParent;</p>
<p>pParseStat-&gt;m_eParseStat = PSTAT_INITIAL;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnCommBegin<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnCommBegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_INITIAL;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnCommEnd<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnCommEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnCDATABegin<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnCDATABegin( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
pParseStat-&gt;m_eParseStat = PSTAT_INITIAL;<br />
// Should convert to text here<br />
}</p>
<p>/*********************************************************************\<br />
* Function: Parser_OnCDATAEnd<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void Parser_OnCDATAEnd( LPXMLPARSESTAT pParseStat, LPSTR lpszTag )<br />
{<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_IterateTree<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void XML_IterateTree( LPXMLNODE pTree, LPXMLITERFATOR pIterator )<br />
{<br />
register ITERSTAT eStat;<br />
if ( NULL != pTree )<br />
{<br />
pIterator-&gt;m_pStation = pTree;<br />
eStat = pIterator-&gt;m_pfnProc( pTree, pIterator-&gt;m_pvParam );<br />
if ( eStat == ISTAT_STOP )<br />
return;<br />
if ( eStat != ISTAT_PASS )<br />
pIterator-&gt;m_lCount++;</p>
<p>XML_IterateTree( pTree-&gt;m_pFirstChild, pIterator );<br />
XML_IterateTree( pTree-&gt;m_pNextSibling, pIterator );<br />
}<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_ForEachNode<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
LONG XML_ForEachNode( LPXMLDOCUMENT pDoc, LPXMLNODE pStartPoint, LPFNNODEPROC pfnNodeProc, LPVOID pvParam )<br />
{<br />
XMLITERFATOR    iter;</p>
<p>assert( NULL != pDoc );<br />
assert( NULL != pfnNodeProc );</p>
<p>if ( pDoc-&gt;m_eDocStat == DSTAT_UNOPEN || (NULL != pStartPoint &amp;&amp; pStartPoint-&gt;m_pRoot != pDoc-&gt;m_lpRootNode) )<br />
return 0;</p>
<p>iter.m_lCount   = 0;<br />
iter.m_pStation = NULL;<br />
iter.m_pvParam  = pvParam;<br />
iter.m_pfnProc  = pfnNodeProc;</p>
<p>pStartPoint = (NULL == pStartPoint ? pDoc-&gt;m_lpRootNode : pStartPoint);<br />
XML_IterateTree( pStartPoint, &amp;iter );<br />
return iter.m_lCount;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XMLCmpNode_EqualTag<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
ITERSTAT XMLCmpNode_EqualTag( LPCXMLNODE pNode, LPVOID pvParam )<br />
{<br />
if ( FALSE != BSTR_EQUAL(pNode-&gt;m_pbstrTag, BSTR_CAST(pvParam)) )<br />
return ISTAT_STOP;<br />
else<br />
return ISTAT_CONTINUE;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_GetNode<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
LPXMLNODE XML_GetNode( LPXMLDOCUMENT pDoc, LPXMLNODE pStartPoint, LPCSTR lpszTag, LONG lLen )<br />
{<br />
BSTRING         bStr;<br />
XMLITERFATOR    iter;</p>
<p>assert( NULL != lpszTag );<br />
assert( NULL != pDoc );</p>
<p>if ( pDoc-&gt;m_eDocStat == DSTAT_UNOPEN || pStartPoint-&gt;m_pRoot != pDoc-&gt;m_lpRootNode )<br />
return NULL;</p>
<p>bStr.m_lLength  = lLen;<br />
bStr.m_pszStr   = lpszTag;</p>
<p>iter.m_lCount   = 0;<br />
iter.m_pfnProc  = &amp;XMLCmpNode_EqualTag;<br />
iter.m_pStation = NULL;<br />
iter.m_pvParam  = (LPVOID)&amp;bStr;</p>
<p>pStartPoint = (NULL == pStartPoint ? pDoc-&gt;m_lpRootNode : pStartPoint);<br />
XML_IterateTree( pStartPoint, &amp;iter );<br />
return (iter.m_pStation);<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_GetNodeAttrib<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
LPXMLATTRIB    XML_GetNodeAttrib( LPXMLNODE pNode, LPCSTR lpszAttr, LONG lLen )<br />
{<br />
BSTRING     bStr;<br />
LPXMLATTRIB pAttrib;</p>
<p>assert( NULL != lpszAttr );<br />
assert( NULL != pNode );<br />
bStr.m_lLength  = lLen;<br />
bStr.m_pszStr   = lpszAttr;</p>
<p>for ( pAttrib = XML_GetNodeFirstAttrib(pNode); NULL != pAttrib; pAttrib = XML_GetNodeNextAttrib(pAttrib) )<br />
{<br />
if ( FALSE != BSTR_EQUAL(pAttrib-&gt;m_pbstrName, &amp;bStr) )<br />
break;<br />
}</p>
<p>return pAttrib;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_GetNodeSibling<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
LPXMLNODE XML_GetNodeSibling( LPXMLNODE pNode, LPCSTR lpszTag, LONG lLen, BOOL bIncludeThis )<br />
{<br />
BSTRING     bStr;</p>
<p>assert( NULL != lpszTag );<br />
assert( NULL != pNode );<br />
bStr.m_lLength  = lLen;<br />
bStr.m_pszStr   = lpszTag;</p>
<p>if ( FALSE != bIncludeThis &amp;&amp; FALSE != BSTR_EQUAL(pNode-&gt;m_pbstrTag, &amp;bStr) )<br />
return pNode;</p>
<p>for ( pNode = XML_GetNodeNextSibling(pNode); NULL != pNode; pNode = XML_GetNodeNextSibling(pNode) )<br />
{<br />
if ( FALSE != BSTR_EQUAL(pNode-&gt;m_pbstrTag, &amp;bStr) )<br />
break;<br />
}</p>
<p>return pNode;<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_FreeNodeTree<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void XML_FreeNodeTree( LPXMLNODE pNode )<br />
{<br />
if ( NULL != pNode )<br />
{<br />
BSTR_FREE( pNode-&gt;m_pbstrTag );</p>
<p>XML_FreeAttribList( pNode-&gt;m_pFirstAttrib );</p>
<p>if ( is_FirstChild(pNode) &amp;&amp; NULL != pNode-&gt;m_pParent )<br />
pNode-&gt;m_pParent-&gt;m_pFirstChild = pNode-&gt;m_pNextSibling;</p>
<p>if ( NULL != pNode-&gt;m_pNextSibling )<br />
pNode-&gt;m_pNextSibling-&gt;m_pPrevSibling = pNode-&gt;m_pPrevSibling;<br />
if ( NULL != pNode-&gt;m_pPrevSibling )<br />
pNode-&gt;m_pPrevSibling-&gt;m_pNextSibling = pNode-&gt;m_pNextSibling;</p>
<p>XML_FreeNodeTree( pNode-&gt;m_pFirstChild );<br />
XML_FreeNodeTree( pNode-&gt;m_pNextSibling );</p>
<p>free( pNode );<br />
}<br />
}</p>
<p>/*********************************************************************\<br />
* Function: XML_FreeAttribList<br />
* Purpose:<br />
* Params:<br />
* Return<br />
* Remarks<br />
**********************************************************************/<br />
void XML_FreeAttribList( LPXMLATTRIB pAttrib )<br />
{<br />
LPXMLATTRIB pNext;</p>
<p>while ( NULL != pAttrib )<br />
{<br />
pNext = pAttrib-&gt;m_pNext;<br />
BSTR_FREE( pAttrib-&gt;m_pbstrName );<br />
BSTR_FREE( pAttrib-&gt;m_pbstrValue );<br />
free( pAttrib );<br />
pAttrib = pNext;<br />
}<br />
}</p>
<p>#if defined(__cplusplus)<br />
}   // extern &#8220;C&#8221; {<br />
#endif</p>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/353.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP:set_error_handler &#8230;&#8230;need more</title>
		<link>http://www.donevii.com/post/350.html</link>
		<comments>http://www.donevii.com/post/350.html#comments</comments>
		<pubDate>Sat, 29 Sep 2007 10:17:41 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[server]]></category>

		<guid isPermaLink="false">http://www.donevii.com/?p=350</guid>
		<description><![CDATA[本来想自己写个 error 处理的 logger 结果发现通过 set_error_handler 没办法捕获到 fatal error &#38; parse error 唉，真愁人呐。 在 php.net 上也没有找到办法，后来反到是在 zend.com 上找到了解决 catch fatal err... ]]></description>
			<content:encoded><![CDATA[<p>本来想自己写个 <a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">error</a> 处理的 logger 结果发现通过 set_<a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">error</a>_handler 没办法捕获到 fatal <a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">error</a> &amp; parse <a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">error</a> 唉，真愁人呐。</p>
<p>在 <a href="http://www.donevii.com/post/tag/php" class="st_tag internal_tag" rel="tag" title="Posts tagged with php">php</a>.net 上也没有找到办法，后来反到是在 zend.com 上找到了解决 catch fatal error 的办法就是在 auto_prepend_file 和 auto_append_file 上做手脚。</p>
<p>prepend 的文件里面有一个 string 里面是个 error page 的 <a href="http://www.donevii.com/post/tag/html" class="st_tag internal_tag" rel="tag" title="Posts tagged with html">html</a> 包括一个 script 可以把错误信息发送到 <a href="http://www.donevii.com/post/tag/server" class="st_tag internal_tag" rel="tag" title="Posts tagged with server">server</a> 的一个 api 上。</p>
<p>而在 append 的文件里通过 ob_get_contents() 来把那个 string 给去掉，如果能去掉就说明程序中间的执行流程正确，无错，如果有 fatal error 则没有办法到达 append 文件这步，所以会显示那个 html 页面。</p>
<p>方法还可以，但是因为每个 php 都要 prepend &amp; append 可能效率会不行，和 Xuanyan 讨论了一小会暂时还是没有什么好办法来捕获 fatal &amp; parse error 。</p>
<p>:(</p>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/350.html/feed</wfw:commentRss>
		<slash:comments>2</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 <a href="http://www.donevii.com/post/tag/windows" class="st_tag internal_tag" rel="tag" title="Posts tagged with windows">Windows</a> 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">// Debug 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" class="broken_link">PVDasm</a> is an admirable disassembler by the <a href="http://community.reverse-engineering.net/" target="new" class="broken_link">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" class="broken_link">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" class="broken_link">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" class="broken_link">CFF Explorer </a>by <a href="http://www.pmode.net/USERS/116/UserInfo.xml" target="new" class="broken_link">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" class="broken_link">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>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/330.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>修改PE文件结构</title>
		<link>http://www.donevii.com/post/328.html</link>
		<comments>http://www.donevii.com/post/328.html#comments</comments>
		<pubDate>Thu, 24 May 2007 01:17:56 +0000</pubDate>
		<dc:creator>dengwei</dc:creator>
				<category><![CDATA[doc]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[平台]]></category>
		<category><![CDATA[类]]></category>

		<guid isPermaLink="false">http://www.donevii.com/?p=328</guid>
		<description><![CDATA[转至http://www.xfocus.net 在windows 9x、NT、2000下，所有的可执行文件都是基于Microsoft设计的一种新的文件格式Portable Executable File Format（可移植的执行体），即PE格式。有一些时候，我们需要对这些可... ]]></description>
			<content:encoded><![CDATA[<p>转至<a href="http://www.xfocus.net">http://www.xfocus.net</a></p>
<p>在windows 9x、NT、2000下，所有的可执行文件都是基于Microsoft设计的一种新的文件格式Portable Executable File Format（可移植的执行体），即PE格式。有一些时候，我们需要对这些可执行文件进行修改，下面文字试图详细的描述PE文件的格式及对PE格式文件的修改。<br />1、PE文件框架构成<br />DOS MZ header<br />DOS stub <br />PE header <br />Section table <br />Section 1 <br />Section 2 <br />Section &#8230; <br />Section n <br />上表是PE文件结构的总体层次分布。所有 PE文件(甚至32位的 DLLs) 必须以一个简单的 DOS MZ header 开始，在偏移0处有DOS下可执行文件的&ldquo;MZ标志&rdquo;，有了它，一旦程序在DOS下执行，DOS就能识别出这是有效的执行体，然后运行紧随 MZ header 之后的 DOS stub。DOS stub实际上是个有效的EXE，在不支持 PE文件格式的操作系统中，它将简单显示一个错误提示，类似于字符串 &quot; This program cannot run in DOS mode &quot; 或者程序员可根据自己的意图实现完整的 DOS代码。通常DOS stub由汇编器/编译器自动生成，对我们的用处不是很大，它简单调用中断21h服务9来显示字符串&quot;This program cannot run in DOS mode&quot;。<br />紧接着 DOS stub 的是 PE header。 PE header 是PE相关结构 IMAGE_NT_HEADERS 的简称，其中包含了许多PE装载器用到的重要域。可执行文件在支持PE文件结构的操作系统中执行时，PE装载器将从 DOS MZ header的偏移3CH处找到 PE header 的起始偏移量。因而跳过了 DOS stub 直接定位到真正的文件头 PE header。<br />PE文件的真正内容划分成块，称之为sections（节）。每节是一块拥有共同属性的数据，比如&ldquo;.text&rdquo;节等，那么，每一节的内容都是什么呢？实际上PE格式的文件把具有相同属性的内容放入同一个节中，而不必关心类似&ldquo;.text&rdquo;、&ldquo;.data&rdquo;的命名，其命名只是为了便于识别，所有，我们如果对PE格式的文件进行修改，理论上讲可以写入任何一个节内，并调整此节的属性就可以了。<br />PE header 接下来的数组结构 section table（节表）。 每个结构包含对应节的属性、文件偏移量、虚拟偏移量等。如果PE文件里有5个节，那么此结构数组内就有5个成员。<br />以上就是PE文件格式的物理分布，下面将总结一下装载一PE文件的主要步骤：<br />1、&nbsp;&nbsp;&nbsp;&nbsp;PE文件被执行，PE装载器检查 DOS MZ header 里的 PE header 偏移量。如果找到，则跳转到 PE header。 <br />2、PE装载器检查 PE header 的有效性。如果有效，就跳转到PE header的尾部。 <br />3、紧跟 PE header 的是节表。PE装载器读取其中的节信息，并采用文件映射方法将这些节映射到内存，同时付上节表里指定的节属性。 <br />4、PE文件映射入内存后，PE装载器将处理PE文件中类似 import table（引入表）逻辑部分。 <br />上述步骤是一些前辈分析的结果简述。<br />2、PE文件头概述<br />我们可以在winnt.h这个文件中找到关于PE文件头的定义：<br />typedef struct _IMAGE_NT_HEADERS {<br />DWORD Signature;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />//PE文件头标志 ：&ldquo;PE\0\0&rdquo;。在开始DOS header的偏移3CH处所指向的地址开始<br />IMAGE_FILE_HEADER FileHeader;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//PE文件物理分布的信息<br />IMAGE_OPTIONAL_HEADER32 OptionalHeader;&nbsp;&nbsp;&nbsp;&nbsp;//PE文件逻辑分布的信息<br />} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;</p>
<p>typedef struct _IMAGE_FILE_HEADER {<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;Machine;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//该文件运行所需要的CPU，对于Intel平台是14Ch<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;NumberOfSections;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//文件的节数目<br />DWORD&nbsp;&nbsp; TimeDateStamp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//文件创建日期和时间<br />DWORD&nbsp;&nbsp; PointerToSymbolTable;&nbsp;&nbsp;&nbsp;&nbsp;//用于调试<br />DWORD&nbsp;&nbsp; NumberOfSymbols;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//符号表中符号个数<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;SizeOfOptionalHeader;&nbsp;&nbsp;&nbsp;&nbsp;//OptionalHeader 结构大小<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;Characteristics;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//文件信息标记，区分文件是exe还是dll<br />} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;</p>
<p>typedef struct _IMAGE_OPTIONAL_HEADER {<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;Magic;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//标志字(总是010bh)<br />BYTE&nbsp;&nbsp;&nbsp;&nbsp;MajorLinkerVersion;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//连接器版本号<br />BYTE&nbsp;&nbsp;&nbsp;&nbsp;MinorLinkerVersion;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//<br />DWORD&nbsp;&nbsp; SizeOfCode;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//代码段大小<br />DWORD&nbsp;&nbsp; SizeOfInitializedData;&nbsp;&nbsp;&nbsp;&nbsp;//已初始化数据块大小<br />DWORD&nbsp;&nbsp; SizeOfUninitializedData;&nbsp;&nbsp;&nbsp;&nbsp;//未初始化数据块大小<br />DWORD&nbsp;&nbsp; AddressOfEntryPoint;&nbsp;&nbsp;&nbsp;&nbsp;//PE装载器准备运行的PE文件的第一个指令的RVA，若要改变整个执行的流程，可以将该值指定到新的RVA，这样新RVA处的指令首先被执行。（许多文章都有介绍RVA，请去了解）<br />DWORD&nbsp;&nbsp; BaseOfCode;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//代码段起始RVA<br />DWORD&nbsp;&nbsp; BaseOfData;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//数据段起始RVA<br />DWORD&nbsp;&nbsp; ImageBase;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//PE文件的装载地址<br />DWORD&nbsp;&nbsp; SectionAlignment;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//块对齐<br />DWORD&nbsp;&nbsp; FileAlignment;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//文件块对齐<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;MajorOperatingSystemVersion;//所需操作系统版本号<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;MinorOperatingSystemVersion;//<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;MajorImageVersion;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//用户自定义版本号<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;MinorImageVersion;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;MajorSubsystemVersion;&nbsp;&nbsp;&nbsp;&nbsp;//win32子系统版本。若PE文件是专门为Win32设计的<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;MinorSubsystemVersion;&nbsp;&nbsp;&nbsp;&nbsp;//该子系统版本必定是4.0否则对话框不会有3维立体感<br />DWORD&nbsp;&nbsp; Win32VersionValue;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//保留<br />DWORD&nbsp;&nbsp; SizeOfImage;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//内存中整个PE映像体的尺寸<br />DWORD&nbsp;&nbsp; SizeOfHeaders;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//所有头+节表的大小<br />DWORD&nbsp;&nbsp; CheckSum;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//校验和<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;Subsystem;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//NT用来识别PE文件属于哪个子系统<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;DllCharacteristics;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//<br />DWORD&nbsp;&nbsp; SizeOfStackReserve;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//<br />DWORD&nbsp;&nbsp; SizeOfStackCommit;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//<br />DWORD&nbsp;&nbsp; SizeOfHeapReserve;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//<br />DWORD&nbsp;&nbsp; SizeOfHeapCommit;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//<br />DWORD&nbsp;&nbsp; LoaderFlags;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//<br />DWORD&nbsp;&nbsp; NumberOfRvaAndSizes;&nbsp;&nbsp;&nbsp;&nbsp;//<br />IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];<br />//IMAGE_DATA_DIRECTORY 结构数组。每个结构给出一个重要数据结构的RVA，比如引入地址表等<br />} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;</p>
<p>typedef struct _IMAGE_DATA_DIRECTORY {<br />DWORD&nbsp;&nbsp; VirtualAddress;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//表的RVA地址<br />DWORD&nbsp;&nbsp; Size;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//大小<br />} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;</p>
<p>PE文件头后是节表，在winnt.h下如下定义<br />typedef struct _IMAGE_SECTION_HEADER {<br />BYTE&nbsp;&nbsp;&nbsp;&nbsp;Name[IMAGE_SIZEOF_SHORT_NAME];//节表名称,如&ldquo;.text&rdquo;<br />union {<br />&nbsp;&nbsp;&nbsp;&nbsp;DWORD&nbsp;&nbsp; PhysicalAddress;&nbsp;&nbsp;&nbsp;&nbsp;//物理地址&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;DWORD&nbsp;&nbsp; VirtualSize;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//真实长度<br />} Misc;<br />DWORD&nbsp;&nbsp; VirtualAddress;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//RVA<br />DWORD&nbsp;&nbsp; SizeOfRawData;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//物理长度<br />DWORD&nbsp;&nbsp; PointerToRawData;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//节基于文件的偏移量<br />DWORD&nbsp;&nbsp; PointerToRelocations;&nbsp;&nbsp;&nbsp;&nbsp;//重定位的偏移<br />DWORD&nbsp;&nbsp; PointerToLinenumbers;&nbsp;&nbsp;&nbsp;&nbsp;//行号表的偏移<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;NumberOfRelocations;&nbsp;&nbsp;&nbsp;&nbsp;//重定位项数目<br />WORD&nbsp;&nbsp;&nbsp;&nbsp;NumberOfLinenumbers;&nbsp;&nbsp;&nbsp;&nbsp;//行号表的数目<br />DWORD&nbsp;&nbsp; Characteristics;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//节属性<br />} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;</p>
<p>以上结构就是在winnt.h中关于PE文件头的定义，如何我们用C/C++来进行PE可执行文件操作，就要用到上面的所有结构，它详细的描述了PE文件头的结构。</p>
<p>3、修改PE可执行文件<br />现在让我们把一段代码写入任何一个PE格式的可执行文件，代码如下：<br />&#8211; test.asm &#8211;<br />.386p<br />.model flat, stdcall<br />option casemap:none</p>
<p>include \masm32\include\<a href="http://www.donevii.com/post/tag/windows" class="st_tag internal_tag" rel="tag" title="Posts tagged with windows">windows</a>.inc<br />include \masm32\include\user32.inc<br />includelib \masm32\lib\user32.lib </p>
<p>.code</p>
<p>start:<br />&nbsp;&nbsp;&nbsp;&nbsp;INVOKE MessageBoxA,0,0,0,MB_ICONINFORMATION or MB_OK<br />&nbsp;&nbsp;&nbsp;&nbsp;ret<br />end start</p>
<p>以上代码只显示一个MessageBox框，编译后得到二进制代码如下：<br />unsigned char writeline[18]={<br />0x6a,0&#215;40,0x6a,0&#215;0,0x6a,0&#215;0,0x6a,0&#215;0,0xe8,0&#215;01,0&#215;0,0&#215;0,0&#215;0,0xe9,0&#215;0,0&#215;0,0&#215;0,0&#215;0<br />};</p>
<p>好，现在让我们看看该把这些代码写到那。现在用Tdump.exe显示一个PE格式得可执行文件信息，可以发现如下描述：<br />Object table:<br />#&nbsp;&nbsp; Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;VirtSize&nbsp;&nbsp;&nbsp;&nbsp;RVA&nbsp;&nbsp;&nbsp;&nbsp; PhysSize&nbsp;&nbsp;Phys off&nbsp;&nbsp;Flags&nbsp;&nbsp; <br />&#8211;&nbsp;&nbsp;&#8212;&#8212;&#8211;&nbsp;&nbsp;&#8212;&#8212;&#8211;&nbsp;&nbsp;&#8212;&#8212;&#8211;&nbsp;&nbsp;&#8212;&#8212;&#8211;&nbsp;&nbsp;&#8212;&#8212;&#8211;&nbsp;&nbsp;&#8212;&#8212;&#8211;<br />01&nbsp;&nbsp;.text&nbsp;&nbsp;&nbsp;&nbsp; 0000CCC0&nbsp;&nbsp;00001000&nbsp;&nbsp;0000CE00&nbsp;&nbsp;00000600&nbsp;&nbsp;60000020 [CER]<br />02&nbsp;&nbsp;.data&nbsp;&nbsp;&nbsp;&nbsp; 00004628&nbsp;&nbsp;0000E000&nbsp;&nbsp;00002C00&nbsp;&nbsp;0000D400&nbsp;&nbsp;C0000040 [IRW]<br />03&nbsp;&nbsp;.rsrc&nbsp;&nbsp;&nbsp;&nbsp; 000003C8&nbsp;&nbsp;00013000&nbsp;&nbsp;00000400&nbsp;&nbsp;00010000&nbsp;&nbsp;40000040 [IR]</p>
<p>Key to section flags:<br />&nbsp;&nbsp;C &#8211; contains code<br />&nbsp;&nbsp;E &#8211; executable<br />&nbsp;&nbsp;I &#8211; contains initialized data<br />&nbsp;&nbsp;R &#8211; readable<br />&nbsp;&nbsp;W &#8211; writeable</p>
<p>上面描述此文件中存在3个段及每个段得信息，实际上我们的代码可以写入任何一个段，这里我选择&ldquo;.text&rdquo;段。</p>
<p>用如下代码得到一个PE格式可执行文件的头信息：</p>
<p>//writePE.cpp</p>
<p>#include &lt;windows.h&gt;<br />#include &lt;stdio.h&gt;<br />#include &lt;io.h&gt;<br />#include &lt;fcntl.h&gt;<br />#include &lt;time.h&gt;<br />#include &lt;SYS\STAT.H&gt;</p>
<p>unsigned char writeline[18]={<br />0x6a,0&#215;40,0x6a,0&#215;0,0x6a,0&#215;0,0x6a,0&#215;0,0xe8,0&#215;01,0&#215;0,0&#215;0,0&#215;0,0xe9,0&#215;0,0&#215;0,0&#215;0,0&#215;0<br />};</p>
<p>DWORD space;<br />DWORD entryaddress;<br />DWORD entrywrite;<br />DWORD progRAV;<br />DWORD oldentryaddress;<br />DWORD newentryaddress;<br />DWORD codeoffset;<br />DWORD peaddress;<br />DWORD flagaddress;<br />DWORD flags;</p>
<p>DWORD virtsize;<br />DWORD physaddress;<br />DWORD physsize;<br />DWORD MessageBoxAadaddress;</p>
<p>int main(int argc,char * * argv)<br />{<br />HANDLE hFile, hMapping;<br />void *basepointer;<br />FILETIME * Createtime;<br />FILETIME * Accesstime;<br />FILETIME * Writetime;<br />Createtime = new FILETIME;<br />Accesstime = new FILETIME;<br />Writetime = new FILETIME;</p>
<p>if ((hFile = CreateFile(argv[1], GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) == INVALID_HANDLE_VALUE)//打开要修改的文件<br />{<br />puts(&quot;(could not open)&quot;);<br />return EXIT_FAILURE;<br />}<br />if(!GetFileTime(hFile,Createtime,Accesstime,Writetime))<br />{<br />printf(&quot;\nerror getfiletime: %d\n&quot;,GetLastError());<br />}<br />//得到要修改文件的创建、修改等时间<br />if (!(hMapping = CreateFileMapping(hFile, 0, PAGE_READONLY | SEC_COMMIT, 0, 0, 0)))<br />{<br />puts(&quot;(mapping failed)&quot;);<br />CloseHandle(hFile);<br />return EXIT_FAILURE;<br />}<br />if (!(basepointer = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0)))<br />{<br />puts(&quot;(view failed)&quot;);<br />CloseHandle(hMapping);<br />CloseHandle(hFile);<br />return EXIT_FAILURE;<br />}<br />//把文件头映象存入baseointer<br />CloseHandle(hMapping);<br />CloseHandle(hFile);<br />map_exe(basepointer);//得到相关地址<br />UnmapViewOfFile(basepointer);<br />printaddress();<br />printf(&quot;\n\n&quot;);<br />if(space&lt;50)<br />{<br />printf(&quot;\n空隙太小,数据不能写入.\n&quot;);<br />}<br />else<br />{<br />writefile();//写文件<br />}</p>
<p>if ((hFile = CreateFile(argv[1], GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) == INVALID_HANDLE_VALUE)<br />{<br />puts(&quot;(could not open)&quot;);<br />return EXIT_FAILURE;<br />}</p>
<p>if(!SetFileTime(hFile,Createtime,Accesstime,Writetime))<br />{<br />printf(&quot;<a href="http://www.donevii.com/post/tag/error" class="st_tag internal_tag" rel="tag" title="Posts tagged with error">error</a> settime : %d\n&quot;,GetLastError());<br />}<br />//恢复修改后文件的建立时间等<br />delete Createtime;<br />delete Accesstime;<br />delete Writetime;<br />CloseHandle(hFile);<br />return 0;<br />}</p>
<p>void map_exe(const void *base)<br />{<br />IMAGE_DOS_HEADER * dos_head;<br />dos_head =(IMAGE_DOS_HEADER *)base;<br />#include &lt;pshpack1.h&gt;<br />typedef struct PE_HEADER_MAP<br />{<br />DWORD signature;<br />IMAGE_FILE_HEADER _head;<br />IMAGE_OPTIONAL_HEADER opt_head;<br />IMAGE_SECTION_HEADER section_header[];<br />} peHeader;<br />#include &lt;poppack.h&gt;</p>
<p>if (dos_head-&gt;e_magic != IMAGE_DOS_SIGNATURE)<br />{<br />puts(&quot;unknown type of file&quot;);<br />return;<br />}</p>
<p>peHeader * header;<br />header = (peHeader *)((char *)dos_head + dos_head-&gt;e_lfanew);//得到PE文件头<br />if (IsBadReadPtr(header, sizeof(*header))<br />{<br />puts(&quot;(no PE header, probably DOS executable)&quot;);<br />return;<br />}</p>
<p>DWORD mods;<br />char tmpstr[4]={0};<br />DWORD&nbsp;&nbsp;tmpaddress;<br />DWORD&nbsp;&nbsp;tmpaddress1;</p>
<p>if(strstr((const char *)header-&gt;section_header[0].Name,&quot;.text&quot;)!=NULL)<br />{<br />virtsize=header-&gt;section_header[0].Misc.VirtualSize;<br />//此段的真实长度<br />physaddress=header-&gt;section_header[0].PointerToRawData;<br />//此段的物理偏移<br />physsize=header-&gt;section_header[0].SizeOfRawData;<br />//此段的物理长度<br />peaddress=dos_head-&gt;e_lfanew; <br />//得到PE文件头的开始偏移</p>
<p>peHeader peH;<br />tmpaddress=(unsigned long )&amp;peH;<br />//得到结构的偏移<br />tmpaddress1=(unsigned long )&amp;(peH.section_header[0].Characteristics);<br />//得到变量的偏移<br />flagaddress=tmpaddress1-tmpaddress+2;<br />//得到属性的相对偏移<br />flags=0&#215;8000;<br />//一般情况下，&ldquo;.text&rdquo;段是不可读写的，如果我们要把数据写入这个段需要改变其属性，实际上这个程序并没有把数据写入&ldquo;.text&rdquo;段，所以并不需要更改，但如果你实现复杂的功能，肯定需要数据，肯定需要更改这个值，</p>
<p>space=physsize-virtsize;<br />//得到代码段的可用空间，用以判断可不可以写入我们的代码<br />//用此段的物理长度减去此段的真实长度就可以得到<br />progRAV=header-&gt;opt_head.ImageBase; <br />//得到程序的装载地址，一般为400000<br />codeoffset=header-&gt;opt_head.BaseOfCode-physaddress;<br />//得到代码偏移，用代码段起始RVA减去此段的物理偏移<br />//应为程序的入口计算公式是一个相对的偏移地址，计算公式为：<br />//代码的写入地址＋codeoffset</p>
<p>entrywrite=header-&gt;section_header[0].PointerToRawData+header-&gt;section_header[0].Misc.VirtualSize;<br />//代码写入的物理偏移<br />mods=entrywrite%16;<br />//对齐边界<br />if(mods!=0)<br />{<br />entrywrite+=(16-mods);<br />}<br />oldentryaddress=header-&gt;opt_head.AddressOfEntryPoint;<br />//保存旧的程序入口地址<br />newentryaddress=entrywrite+codeoffset;<br />//计算新的程序入口地址&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />return;<br />}</p>
<p>void printaddress()<br />{<br />HINSTANCE gLibMsg=NULL;<br />DWORD funaddress;<br />gLibMsg=LoadLibrary(&quot;user32.dll&quot;); <br />funaddress=(DWORD)GetProcAddress(gLibMsg,&quot;MessageBoxA&quot;);<br />MessageBoxAadaddress=funaddress;<br />gLibAMsg=LoadLibrary(&quot;kernel32.dll&quot;); <br />//得到MessageBox在内存中的地址，以便我们使用<br />}</p>
<p>void writefile()<br />{<br />int ret;<br />long retf;<br />DWORD address;<br />int tmp;<br />unsigned char waddress[4]={0};</p>
<p>ret=_open(filename,_O_RDWR | _O_CREAT | _O_BINARY,_S_IREAD | _S_IWRITE);<br />if(!ret)<br />{<br />printf(&quot;error open\n&quot;);<br />return;<br />}<br />&nbsp;&nbsp;&nbsp;&nbsp;<br />retf=_lseek(ret,(long)peaddress+40,SEEK_SET);<br />//程序的入口地址在PE文件头开始的40处<br />if(retf==-1)<br />{<br />printf(&quot;error seek\n&quot;);<br />return;<br />}<br />address=newentryaddress;<br />tmp=address&gt;&gt;24;<br />waddress[3]=tmp;<br />tmp=address&lt;&lt;8;<br />tmp=tmp&gt;&gt;24;<br />waddress[2]=tmp;<br />tmp=address&lt;&lt;16;<br />tmp=tmp&gt;&gt;24;<br />waddress[1]=tmp;<br />tmp=address&lt;&lt;24;<br />tmp=tmp&gt;&gt;24;<br />waddress[0]=tmp;<br />retf=_write(ret,waddress,4);<br />//把新的入口地址写入文件<br />if(retf==-1)<br />{<br />printf(&quot;error write: %d\n&quot;,GetLastError());<br />return;<br />}<br />&nbsp;&nbsp;&nbsp;&nbsp;<br />retf=_lseek(ret,(long)entrywrite,SEEK_SET);<br />if(retf==-1)<br />{<br />printf(&quot;error seek\n&quot;);<br />return;<br />}<br />retf=_write(ret,writeline,18);<br />if(retf==-1)<br />{<br />printf(&quot;error write: %d\n&quot;,GetLastError());<br />return;<br />}<br />//把writeline写入我们计算出的空间</p>
<p>retf=_lseek(ret,(long)entrywrite+9,SEEK_SET);<br />//更改MessageBox函数地址，它的二进制代码在writeline[10]处<br />if(retf==-1)<br />{<br />printf(&quot;error seek\n&quot;);<br />return;<br />}</p>
<p>address=MessageBoxAadaddress-(progRAV+newentryaddress+9+4);<br />//重新计算MessageBox函数的地址，MessageBox函数的原地址减去程序的装载地址加上新的入口地址加9（它的二进制代码相对偏移）加上4（地址长度）<br />tmp=address&gt;&gt;24;<br />waddress[3]=tmp;<br />tmp=address&lt;&lt;8;<br />tmp=tmp&gt;&gt;24;<br />waddress[2]=tmp;<br />tmp=address&lt;&lt;16;<br />tmp=tmp&gt;&gt;24;<br />waddress[1]=tmp;<br />tmp=address&lt;&lt;24;<br />tmp=tmp&gt;&gt;24;<br />waddress[0]=tmp;<br />retf=_write(ret,waddress,4);<br />//写入重新计算的MessageBox地址<br />if(retf==-1)<br />{<br />printf(&quot;error write: %d\n&quot;,GetLastError());<br />return;<br />}</p>
<p>retf=_lseek(ret,(long)entrywrite+14,SEEK_SET);<br />//更改返回地址，用jpm返回原程序入口地址，其它的二进制代码在writeline[15]处<br />if(retf==-1)<br />{<br />printf(&quot;error seek\n&quot;);<br />return;<br />}</p>
<p>address=0-(newentryaddress-oldentryaddress+4+15);<br />//返回地址计算的方法是新的入口地址减去老的入口地址加4（地址长度）加15（二进制代码相对偏移）后取反<br />tmp=address&gt;&gt;24;<br />waddress[3]=tmp;<br />tmp=address&lt;&lt;8;<br />tmp=tmp&gt;&gt;24;<br />waddress[2]=tmp;<br />tmp=address&lt;&lt;16;<br />tmp=tmp&gt;&gt;24;<br />waddress[1]=tmp;<br />tmp=address&lt;&lt;24;<br />tmp=tmp&gt;&gt;24;<br />waddress[0]=tmp;<br />retf=_write(ret,waddress,4);<br />//写入返回地址<br />if(retf==-1)<br />{<br />printf(&quot;error write: %d\n&quot;,GetLastError());<br />return;<br />}</p>
<p>_close(ret);<br />printf(&quot;\nall done&#8230;\n&quot;);<br />return;<br />}</p>
<p>//end<br />由于在PE格式的文件中，所有的地址都使用RVA地址，所以一些函数调用和返回地址都要经过计算才可以得到，以上是我在实践中的心得，如果你有更好的办法，真心的希望你能告诉我。</p>
<p>如果存在错误，请告诉我，以免误导看这篇文章的人。<br />写的较乱，请原谅。</p>
<p>ilsy@netguard.com.cn</p>
]]></content:encoded>
			<wfw:commentRss>http://www.donevii.com/post/328.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

