<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Mathew Hall</title>
	<atom:link href="http://mathewjhall.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://mathewjhall.wordpress.com</link>
	<description>Computer Science, Coding and other Ramblings of a PhD candidate.</description>
	<lastBuildDate>Tue, 19 Feb 2013 18:47:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='mathewjhall.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Mathew Hall</title>
		<link>http://mathewjhall.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://mathewjhall.wordpress.com/osd.xml" title="Mathew Hall" />
	<atom:link rel='hub' href='http://mathewjhall.wordpress.com/?pushpress=hub'/>
		<item>
		<title>JGAP Default Initialisation Configuration</title>
		<link>http://mathewjhall.wordpress.com/2013/02/18/jgap-default-initialisation/</link>
		<comments>http://mathewjhall.wordpress.com/2013/02/18/jgap-default-initialisation/#comments</comments>
		<pubDate>Mon, 18 Feb 2013 09:12:18 +0000</pubDate>
		<dc:creator>mathewjhall</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technical Stuff]]></category>
		<category><![CDATA[Genetic Algorithms]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JGAP]]></category>

		<guid isPermaLink="false">http://mathewjhall.wordpress.com/?p=237</guid>
		<description><![CDATA[I use JGAP as part of my Crunch clustering tool. For my thesis writeup, I needed to describe the specific parameters to the genetic algorithm it used. This post details how JGAP starts up, and where to find the defaults, what they are and what the values actually mean. These values are probably specific to [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathewjhall.wordpress.com&#038;blog=21735407&#038;post=237&#038;subd=mathewjhall&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I use JGAP as part of my Crunch clustering tool. For my thesis writeup, I needed to describe the specific parameters to the genetic algorithm it used. This post details how JGAP starts up, and where to find the defaults, what they are and what the values actually mean. These values are probably specific to the version I&#8217;m looking at (3.62), although they <a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/impl/DefaultConfiguration.java?r1=1.26&amp;view=log">haven&#8217;t changed in roughly 4 years</a> at the time of writing.</p>
<h1>Startup</h1>
<p>The search parameters are contained in a <a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/Configuration.java?revision=1.102&amp;view=markup"><code>Configuration</code></a> object. The configuration is initialised with various parameters and the type of chromosome to produce. The <a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/Genotype.java?view=markup"><code>Genotype</code></a> represents the population, and exposes the GA component to the user (via the <code>evolve</code> and <code>getFittestIndividual</code> methods).</p>
<h1>Genotype</h1>
<p><code>Genotype</code>s can be bootstrapped from a <code>Configuration</code> via the <code>randomInitialGenotype</code> method. This constructs the population (which uses <code>randomInitialChromosome</code> to produce random individuals) and returns the initialised <code>Genotype</code> object.</p>
<h1>Genotype.evolve()</h1>
<p><code>evolve</code> has three overloaded methods, the two that take arguments internally call the no-argument version.</p>
<p>The evolve method simply obtains an <a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/IBreeder.java?view=markup"><code>IBreeder</code></a> object from the <code>Configuration</code> and uses it to construct a new <a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/Population.java?view=markup"><code>Population</code></a>, before setting the current population to the newly constructed version.</p>
<h1>IBreeder</h1>
<p><code>IBreeder</code>s coordinate the evolution step, however they do not actually perform or store any of the genetic operators. These are kept in the <code>Configuration</code> object&#8217;s m_geneticOperators field.</p>
<h1>GABreeder</h1>
<p>The default Breeder used is the <a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/impl/GABreeder.java?view=markup"><code>GABreeder</code></a>. The following stages are applied to the population:</p>
<h3>Fitness Evaluation</h3>
<p>The fitness of each individual in the population is first calculated, using the bulk fitness function, or via <code>updateChromosomes</code> if one isn&#8217;t provided.</p>
<h3>Natural Selectors (Before Genetic Operators)</h3>
<p>Each of the <code>NaturalSelectors</code> registered for application before the genetic operator chain runs is run on the population. The default configuration does not set any of these selectors.</p>
<h3>Genetic Operators</h3>
<p>Each of the genetic operators registered in the configuration is run, one at a time, in order of addition to the Configuration. Implementation for this step appears in <code><a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/BreederBase.java?view=markup">BreederBase</a>.applyGeneticOperators</code>. The genetic operators implement an <code>operate</code> method, which runs over the population. These may only add to the population, however; an operator should never modify an individual in the population. A <code>List</code> of <a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/IChromosome.java?view=markup"><code>IChromosome</code>s</a> is passed as well as a <code>Population</code>, although this is just a reference to the <code>Population</code>&#8216;s internal list.</p>
<p><code>DefaultConfiguration</code> uses a Crossover operator, followed by a Mutation operator. Parameters to these are given at the end of this post.</p>
<h3>Evaluation</h3>
<p>The population is then re-evaluated, as it contains new individuals not present before the first round of selection.</p>
<h3>Natural Selectors (After Genetic Operators)</h3>
<p>Finally, the new population is produced by applying a <code>NaturalSelector</code> to it. If the selector selects too few individuals, JGAP can optionally fill the remainder with random individuals &#8211; change <code>MinimumPopSizePercent</code> to turn this on, but it&#8217;s off by default.</p>
<h1>The Default JGAP Configuration</h1>
<p>DefaultConfiguration sets up the following operator chain:</p>
<h3>Genetic Operators</h3>
<p><a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/impl/CrossoverOperator.java?view=markup"><code>CrossoverOperator</code></a>:</p>
<p>Rate: 35%, which translates to populationSize * 0.35 crossover operations per generation. Each crossover produces 2 individuals. Crossover point is random.</p>
<p><a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/impl/MutationOperator.java?view=markup"><code>MutationOperator</code></a>:</p>
<p>Desired Rate: 12. The rate for this one is a little different; mutation occurs if a random integer between 0 and the rate (12) is 0, thus it equates to a probability of 1/12. This operation is applied to each gene in each element of the population (excluding those produced by crossover), so the rough likelihood of a mutation being applied is (1/rate) * popSize * chromosomeSize. For each gene that is to be mutated, a copy of the whole <code>IChromosome</code> that contains it is made, with the selected <code>Gene</code> mutated via its <code>applyMutation</code> method.</p>
<h3>Natural Selector</h3>
<p>One selector is defined by default, which is the <a href="http://jgap.cvs.sourceforge.net/viewvc/jgap/jgap/src/org/jgap/impl/BestChromosomesSelector.java?view=markup">BestChromosomesSelector</a>. This selector is given the following parameters:</p>
<p>Original Rate: 0.9. 90% of the population size allotted to this selector will actually be used. The selector is elitist, so this will return the top populationSize * 0.9 elements. The remaining 10% is filled by cloning the selected elements, one by one, in order of fitness until the population size reaches the limit.</p>
<p>Doublette Chromosomes Allowed? Yes. <a href="http://old.nabble.com/Re%3A-What-does-%22Doublette-Chromosome%22-mean--p27383730.html">Doublettes are equivalent chromosomes</a> (by <code>equals()</code>).</p>
<h2>Configuration Parameters</h2>
<p>The configuration specifies that the pool of selectors will select 100% of the population size. However, the only selector is configured to produce only 90% of the population size each time.</p>
<p><code>keepPopulationSizeConstant</code> is also set to true, which dictates that the population is trimmed to size at each iteration. Somewhat counter-intuitively, this does not cause the population size to be increased if it falls below the user supplied value; it doesn&#8217;t enforce a minimum, only a maximum</p>
<p><code>minimumPopSizePercent</code> is set to zero, so random individuals will never be used to fill the population if it declines below the limit (won&#8217;t ever happen under these conditions).</p>
<h1>So What is the Default?</h1>
<p>The default configuration is an elitist ranking selector that clones the top 90% of the user-specified population size, repeating it to fill the rest. Crossover is random point with a rate of populationSize * 0.35. Mutation is random and applied at  to 1 in 12 <em>genes</em> in the whole population (i.e. the rate is dictated by chromosome size * population size / 12).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathewjhall.wordpress.com/237/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathewjhall.wordpress.com/237/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathewjhall.wordpress.com&#038;blog=21735407&#038;post=237&#038;subd=mathewjhall&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathewjhall.wordpress.com/2013/02/18/jgap-default-initialisation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7a3546122734b84a2b5280178b029fad?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathewjhall</media:title>
		</media:content>
	</item>
		<item>
		<title>Restoring sudo access after an Ubuntu upgrade</title>
		<link>http://mathewjhall.wordpress.com/2013/02/10/restoring-sudo-access-after-an-ubuntu-upgrade/</link>
		<comments>http://mathewjhall.wordpress.com/2013/02/10/restoring-sudo-access-after-an-ubuntu-upgrade/#comments</comments>
		<pubDate>Sun, 10 Feb 2013 18:47:08 +0000</pubDate>
		<dc:creator>mathewjhall</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[Technical Stuff]]></category>
		<category><![CDATA[grub]]></category>
		<category><![CDATA[mini itx]]></category>
		<category><![CDATA[root shell]]></category>
		<category><![CDATA[sudo]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://mathewjhall.wordpress.com/?p=227</guid>
		<description><![CDATA[I recently brought back an old mini ITX box which had an unsupported Ubuntu version on it (last booted well over a year ago). During the upgrade process from Maverick to Natty, one of the scripts asked if I wanted a new /etc/sudoers file. Stupidly, I assumed that my user was in the correct group [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathewjhall.wordpress.com&#038;blog=21735407&#038;post=227&#038;subd=mathewjhall&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I recently brought back an old mini ITX box which had an unsupported Ubuntu version on it (last booted well over a year ago). During the upgrade process from Maverick to Natty, one of the scripts asked if I wanted a new <code>/etc/sudoers</code> file. Stupidly, I assumed that my user was in the correct group and took the new one.</p>
<p>On rebooting it turned out that my choice was unwise &#8211; I didn&#8217;t have sudo access nor did I have the root password for recovery. Unfortunately, the trick of using /bin/bash as an init replacement to get a root shell didn&#8217;t work either (it&#8217;s a <a href="http://ubuntuforums.org/showthread.php?t=2018217">common problem</a>).</p>
<p>The fix was to write a small C program which just executed a script with <code>/bin/sh</code> to replace the sudoers file:</p>
<pre class="brush: cpp; title: ; notranslate">
#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;
#include&lt;unistd.h&gt;
int main(void){
	execl(&quot;/bin/sh&quot;, &quot;-e&quot;, &quot;/home/mat/replace_sudoers.sh&quot;,0);
	return 0;
}
</pre>
<p>Compile this with gcc: <code>gcc -o replace replace_sudoers.c</code> then create a replace_sudoers.sh with the following contents (with the home directory changed):</p>
<pre class="brush: bash; title: ; notranslate">
echo &quot;Backing up old sudoers&quot;

cp /etc/sudoers /home/mat/old_sudoers
chmod 777 /home/mat/old_sudoers

echo &quot;moving new one&quot;
cp -fr /home/mat/sudoers /etc/sudoers
chown root /etc/sudoers
chmod 0440 /etc/sudoers

echo &quot;moved new sudoers successfully, will halt in 5s&quot;
sleep 5
halt
</pre>
<p>I replaced my old sudoers with the following bare-bones one:</p>
<pre>
#/etc/sudoers

Defaults env_reset

root	ALL=(ALL) ALL
mat	ALL=(ALL) ALL
%admin	ALL=(ALL) ALL
</pre>
<p>Now, instead of using <code>init=/bin/sh</code>, <code>init=/home/mat/replace</code> can be used which will launch the script and overwrite the old sudoers file. On rebooting, you&#8217;ll have your sudo privileges back.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathewjhall.wordpress.com/227/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathewjhall.wordpress.com/227/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathewjhall.wordpress.com&#038;blog=21735407&#038;post=227&#038;subd=mathewjhall&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathewjhall.wordpress.com/2013/02/10/restoring-sudo-access-after-an-ubuntu-upgrade/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7a3546122734b84a2b5280178b029fad?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathewjhall</media:title>
		</media:content>
	</item>
		<item>
		<title>Reading ROMs and Saving Pokemon</title>
		<link>http://mathewjhall.wordpress.com/2012/04/26/reading-roms-and-saving-pokemon/</link>
		<comments>http://mathewjhall.wordpress.com/2012/04/26/reading-roms-and-saving-pokemon/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 23:41:10 +0000</pubDate>
		<dc:creator>mathewjhall</dc:creator>
				<category><![CDATA[Hardware]]></category>
		<category><![CDATA[PIC]]></category>
		<category><![CDATA[Technical Stuff]]></category>
		<category><![CDATA[electronics]]></category>
		<category><![CDATA[gadgets]]></category>
		<category><![CDATA[game boy]]></category>
		<category><![CDATA[game boy cartridges]]></category>
		<category><![CDATA[gaming]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[pic]]></category>

		<guid isPermaLink="false">http://mathewjhall.wordpress.com/?p=196</guid>
		<description><![CDATA[Early Game Boy cartridges that save games use battery-backed SRAM cartridges to hold data between plays. It&#8217;s recently arisen that the batteries in them are expected to start dying soon. Critically: a lot of Pokemon from a lot of childhoods are facing extinction. Luckily, thanks to the Pandocs [1] and a lot of patience from [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathewjhall.wordpress.com&#038;blog=21735407&#038;post=196&#038;subd=mathewjhall&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Early Game Boy cartridges that save games use battery-backed SRAM cartridges to hold data between plays. It&#8217;s recently arisen that the batteries in them are expected to start dying soon. Critically: a lot of Pokemon from a lot of childhoods are facing extinction.</p>
<p>Luckily, thanks to the Pandocs [1] and a lot of patience from other developers, people have started building their own dumpers. This post details another implementation, built for PIC16 devices instead of the existing Arduino and AVR implementations. It is heavily based on the InsideGadgets Arduino GBCartRead project [2].</p>
<div id="attachment_204" class="wp-caption aligncenter" style="width: 310px"><a href="http://mathewjhall.files.wordpress.com/2012/04/dvqck.jpg"><img class="size-medium wp-image-204 " title="Not pretty, but it works" src="http://mathewjhall.files.wordpress.com/2012/04/dvqck.jpg?w=300&#038;h=210" alt="" width="300" height="210" /></a><p class="wp-caption-text">There's a ROM dumper under this rat's nest, honest.</p></div>
<h1>The Hardware</h1>
<p>I built my dumper around a PIC16F690. It&#8217;s got just enough pins to drive a couple of shift registers, a UART and to leave enough pins left over for I/O. The most difficult part to get is the cartridge connector &#8211; a donor Game Boy is required unfortunately.</p>
<p style="text-align:center;"><a href="http://mathewjhall.files.wordpress.com/2012/04/schematic28schematic29.png"><img class="aligncenter  wp-image-201" title="Schematic" src="http://mathewjhall.files.wordpress.com/2012/04/schematic28schematic29.png?w=669&#038;h=200" alt="Schematic for the dumper" width="669" height="200" /></a></p>
<p style="text-align:left;">The schematic is fairly straightforward. The PIC communicates with the PC via a MAX232. The address lines are driven via two 74HC594 shift registers. Data and control pins take up the remaining pins. Power is supplied via a LM7805 linear regulator (not shown).</p>
<p style="text-align:left;">The cartridge requires a connection to GND and +5V, as well as a pull-up resistor from +5V to the /RST pin (30)</p>
<h1>The Software</h1>
<p>Game Boy cartridges are fairly simple devices. They use a 32-pin connector which consists of power, three control lines, a 16-bit address bus and an 8-bit data bus. The cartridge shares the address bus with other devices and is mapped to the region 0&#215;0000 to 0x7FFFF [3].</p>
<p>Talking to a cartridge is fairly simple:</p>
<ol>
<li>Write the address you want to read or write to the address bus</li>
<li>(optional) Write the data you want to write to the data bus</li>
<li>(optional) Raise MREQ if you&#8217;re reading SRAM (Pokemon live there)</li>
<li>Raise RD or WR to read or write respectively</li>
<li>Drop RD, WR and MREQ</li>
<li>(optional) Read the data from the address bus</li>
</ol>
<p>The WR, RD and MREQ pins are all active high.</p>
<p>Cartridges larger 16KB require bank switching which is handled by  a device called the memory bank controller (MBC). The MBC also controls access to the SRAM, as well as any other peripherals on the cartridge.</p>
<p>The MBC is controlled by writing commands to specific addresses. These addresses vary between MBCs, although most seem to enable RAM when 0xA0 is written to 0&#215;0000. The MBC type is readable from the cartridge descriptor which is at 0&#215;0134-0&#215;0148 [1].</p>
<p>The firmware for the PIC is available at GitHub [4].</p>
<h1>Rescuing the Pokemon</h1>
<p>To use the dumper just connect to it via the serial port. The interface is fairly straight forward. It waits for confirmation before reading the descriptor, it&#8217;s pretty straight forward from there. The most important mode to use first is the diagnostics mode, which needs to be run without a cartridge connected.</p>
<h2>On the Importance of Testing</h2>
<p><img class="alignright size-thumbnail wp-image-203" title="Bad joint on WR pin" src="http://mathewjhall.files.wordpress.com/2012/04/rlfse.jpg?w=150&#038;h=119" alt="Continuity testing is important!" width="150" height="119" /></p>
<p>The diagnostics mode is ideal for catching faults before they have real implications.</p>
<p>Faults like this one. In this case the WR pin hadn&#8217;t been properly soldered. Since the pins are active low and they&#8217;re connected via pull-down resistors. That means that the WR signal was 1, so the attempt to read RAM ended up writing garbage to it. I euthanised my Pokemon.</p>
<h2>Dumping Data</h2>
<p>Retrieving data (hopefully having not destroyed it) can be done using RealTerm [5]. It features true raw logging which is necessary, as, for example, PuTTY interprets some control characters, even in raw logging mode.</p>
<h1>Future Work</h1>
<p>At the moment the interface is a bit clunky, as is having to use RealTerm to dump things. I&#8217;ll be changing it to speak the same protocol as the original Arduino GBCartRead [2] which will make dumping things easier.</p>
<h1>Links</h1>
<p>[1] : <a title="http://nocash.emubase.de/pandocs.htm" href="http://nocash.emubase.de/pandocs.htm">The Pandocs &#8211; Everything you wanted to know about Game Boy but were afraid to ask</a></p>
<p>[2] : <a title="Inside Gadgets: GBCartRead" href="http://www.insidegadgets.com/projects/gbcartread-gameboy-cart-reader/">GBCartRead</a></p>
<p>[3] : <a title="Game Boy memory map" href="http://gameboy.mongenel.com/dmg/asmmemmap.html">Game Boy memory map</a></p>
<p>[4] : <a title="GitHub: GBCartRead-PIC16" href="https://github.com/mathew-hall/GBCartRead-PIC16">GBCartRead-PIC16</a></p>
<p>[5] : <a title="RealTerm" href="http://realterm.sourceforge.net/">RealTerm</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathewjhall.wordpress.com/196/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathewjhall.wordpress.com/196/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathewjhall.wordpress.com&#038;blog=21735407&#038;post=196&#038;subd=mathewjhall&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathewjhall.wordpress.com/2012/04/26/reading-roms-and-saving-pokemon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7a3546122734b84a2b5280178b029fad?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathewjhall</media:title>
		</media:content>

		<media:content url="http://mathewjhall.files.wordpress.com/2012/04/dvqck.jpg?w=300" medium="image">
			<media:title type="html">Not pretty, but it works</media:title>
		</media:content>

		<media:content url="http://mathewjhall.files.wordpress.com/2012/04/schematic28schematic29.png?w=1024" medium="image">
			<media:title type="html">Schematic</media:title>
		</media:content>

		<media:content url="http://mathewjhall.files.wordpress.com/2012/04/rlfse.jpg?w=150" medium="image">
			<media:title type="html">Bad joint on WR pin</media:title>
		</media:content>
	</item>
		<item>
		<title>Tracing Java Method Execution with AspectJ</title>
		<link>http://mathewjhall.wordpress.com/2011/03/31/tracing-java-method-execution-with-aspectj/</link>
		<comments>http://mathewjhall.wordpress.com/2011/03/31/tracing-java-method-execution-with-aspectj/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 14:13:21 +0000</pubDate>
		<dc:creator>mathewjhall</dc:creator>
				<category><![CDATA[Technical Stuff]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[dynamic analysis]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[reverse engineering]]></category>
		<category><![CDATA[tracing]]></category>

		<guid isPermaLink="false">http://mathewjhall.wordpress.com/?p=4</guid>
		<description><![CDATA[ApectJ is a project to bring aspect oriented programming to Java.  Sidestepping the whole issue around whether or not aspect-oriented programming is a good idea; it can be used to insert code at points you define and is a very useful tool for dynamic program analysis. Some terminology needs explaining here before we go further. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathewjhall.wordpress.com&#038;blog=21735407&#038;post=4&#038;subd=mathewjhall&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="AspectJ" href="http://www.eclipse.org/aspectj/">ApectJ</a> is a project to bring aspect oriented programming to Java.  Sidestepping the whole issue around whether or not aspect-oriented programming is a good idea; it can be used to insert code at points you define and is a very useful tool for dynamic program analysis.</p>
<p>Some terminology needs explaining here before we go further.  AspectJ defines a point in the source to stop execution and pass it to your code as a &#8220;Pointcut&#8221;, the actual code executed on this pause is termed &#8220;advice&#8221;.  Although I use the word &#8220;pause&#8221; it&#8217;s not strictly correct; AspectJ &#8220;weaves&#8221; the advice code for matching pointcuts at compile time.  Additionally (and perhaps most significantly) AspectJ can weave on class load time (&#8220;Load Time Weaving&#8221;), this is what we&#8217;ll be using.</p>
<p>So we have a way of inserting code in places in an existing code base, what can we do with it?  A lot of horrible things (playing around with returned values and parameters to name a few); but for now we&#8217;ll stick to what we want to do, tracing method calls.</p>
<p>The most obvious way to instrument a program is to insert calls to some logging library at the top of every method.  Although this works it takes a lot of time, either manually logging everything or figuring out how to use a regex/parser to do it for you.  With AspectJ we can simply weave code that logs the current method at every method execution point.</p>
<p>So how do we do that?  First we need to get AspectJ working; Eclipse will do that for you, alternatively you can do everything from the command line (assuming you have AspectJ installed, including the <tt>ajc</tt> command on your PATH).</p>
<p>We&#8217;ll define an Aspect that defines a pointcut on every method execution, as well as some advice to run when they turn up when the code is executed.</p>
<pre class="brush: java; title: ; notranslate">
package aspects;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.aspectj.lang.Signature;

aspect Trace{


	pointcut traceMethods() : (execution(* *(..))&amp;&amp; !cflow(within(Trace)));

	before(): traceMethods(){
		Signature sig = thisJoinPointStaticPart.getSignature();
		String line =&quot;&quot;+ thisJoinPointStaticPart.getSourceLocation().getLine();
		String sourceName = thisJoinPointStaticPart.getSourceLocation().getWithinType().getCanonicalName();
		Logger.getLogger(&quot;Tracing&quot;).log(
                Level.INFO, 
                &quot;Call from &quot;
                	+  sourceName
                    +&quot; line &quot; +
                    line
                    +&quot; to &quot; +sig.getDeclaringTypeName() + &quot;.&quot; + sig.getName()
		);
	}

}
</pre>
<p>So what exactly does this do?  Firstly, the <tt>pointcut traceMethods()</tt> defines a new pointcut called traceMethods.  This pointcut matches execution of every method in every class, as long as the control flow isn&#8217;t in the current class (Trace).  The latter constraint is to stop an infinite loop occurring.</p>
<p>The <tt>before():</tt> part of the class defines advice.  This is the code that gets inserted just before the execution of the method.  Advice can also be given after a pointcut is hit (using the <tt>after</tt> keyword instead).  Our &#8220;advice&#8221; doesn&#8217;t modify execution flow, it just logs some information about the state of the program when the pointcut was hit, but it could quite easily start modifying control flow.</p>
<p>Save this file as <tt>Trace.java</tt> and compile it using: <tt>ajc -outxml -outjar aspects.jar Trace.java</tt>.</p>
<p>This compiles the aspect and puts it into a jar ready for use.  The <tt>-outxml</tt> parameter will cause <tt>ajc</tt> to automatically generate an <tt>aop.xml</tt> file and save it in the jar&#8217;s <tt>META-INF</tt> directory.  The load time weaving agent will read this to determine which aspects to weave with the classes it loads.  The <tt>aop.xml</tt> file can do more than that, it can be used to set namespaces to ignore when weaving (such as <tt>java.*</tt>) to avoid mucking with the control flow of libraries.</p>
<p>So now we have our <tt>aspects.jar</tt> how do we use it?  The AspectJ weaving agent must be available somewhere on the filesystem (<tt>aspectjweaver.jar</tt>) and your <tt>aspect.jar</tt> (and the target application) must be on the classpath.</p>
<p>Once that&#8217;s sorted to trace the application, use</p>
<pre class="brush: plain; title: ; notranslate">
java -javaagent:&lt;path to aspectjweaver.jar&gt; -cp &lt;path to aspects.jar&gt;:&lt;path to target jar/folder&gt; &lt;name of main class to run&gt;
</pre>
<p>Hopefully that will run and you should see a large amount of console output:<br />
<code><br />
INFO: Call from main.RunFile line 206 to main.RunFile.main<br />
Mar 31, 2011 2:52:53 PM aspects.Trace ajc$before$aspects_Trace$1$b314f86e<br />
INFO: Call from main.RunFile line 186 to main.RunFile.runList<br />
Mar 31, 2011 2:52:53 PM main.RunFile main<br />
INFO: Starting clustering of 0 files<br />
Mar 31, 2011 2:52:53 PM aspects.Trace ajc$before$aspects_Trace$1$b314f86e<br />
INFO: Call from main.ExperimentRunner line 59 to main.ExperimentRunner.runExperiments<br />
</code></p>
<p>AspectJ lets you do far more than this, it&#8217;s an understatement to say this is all it can be used for.  Using LTW does make for some interesting possibilities, one obvious use would be monkey patching existing projects to fix bugs where source isn&#8217;t available (and the license permits it, of course).</p>
<p>AspectJ is an interesting piece of work; the official <a href="http://www.eclipse.org/aspectj/">project page</a> has far more resources on the types of pointcuts you can define and the more nitty-gritty details of making it mess with the traced program.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathewjhall.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mathewjhall.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mathewjhall.wordpress.com&#038;blog=21735407&#038;post=4&#038;subd=mathewjhall&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mathewjhall.wordpress.com/2011/03/31/tracing-java-method-execution-with-aspectj/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7a3546122734b84a2b5280178b029fad?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mathewjhall</media:title>
		</media:content>
	</item>
	</channel>
</rss>
