Tag Archives: mac

How to print assembly for your Java code in OS X

0. Write program.

package name.dhruba;
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello World!");
  }
}

1. Add JVM arguments to your program.

-XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly

2. Run your program. You will probably see the output below.

Java HotSpot(TM) 64-Bit Server VM warning: PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output
Could not load hsdis-amd64.dylib; library not loadable; PrintAssembly is disabled
Hello World!
Process finished with exit code 0

3. Download the missing library from here. The direct link to the lib file itself is here. I downloaded the one named ‘gnu-bsd-libhsdis-amd64.dylib’ as I’m running 64-bit. This produces a file on your system called ‘hsdis-amd64.dylib’.

4. Move it to where, the JDK that you are running with, looks for it. I was using Java8.

sudo mv ~/Downloads/hsdis-amd64.dylib /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/jre/lib/hsdis-amd64.dylib

5. Run your program again and see assembly! The output for Hello World is huge so I can’t paste all of it here but here’s the initial bit where you can see that the disassembler has been loaded.

Java HotSpot(TM) 64-Bit Server VM warning: PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output
Loaded disassembler from /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/jre/lib/hsdis-amd64.dylib
Decoding compiled method 0x000000010f4c23d0:
Code:
[Disassembling for mach='i386:x86-64']
[Entry Point]
  # {method} {0x00000001280fe660} 'arraycopy' '(Ljava/lang/Object;ILjava/lang/Object;II)V' in 'java/lang/System'
  # parm0:    rsi:rsi   = 'java/lang/Object'
  # parm1:    rdx       = int
  # parm2:    rcx:rcx   = 'java/lang/Object'
  # parm3:    r8        = int
  # parm4:    r9        = int
  #           [sp+0x60]  (sp of caller)
  0x000000010f4c2540: mov    0x8(%rsi),%r10d
  0x000000010f4c2544: shl    $0x3,%r10
  0x000000010f4c2548: cmp    %r10,%rax
  0x000000010f4c254b: je     0x000000010f4c2558
  0x000000010f4c2551: jmpq   0x000000010f407b60  ;   {runtime_call}
  0x000000010f4c2556: xchg   %ax,%ax

Credit: Nitsan Wakart.

Adding a JDK and sources to Eclipse on a Mac

I just downloaded Eclipse on my Mac after a good six months without needing it and had numerous issues using it. First, it wouldn’t start and gave the error message below.

Alert: The JVM shared library "/Library/Java/JavaVirtualMachines/1.7.0.jdk" does not contain the JNI_CreateJavaVM symbol.

I realised that the openjdk 1.7.0 package I’d installed must be somehow overriding or interfering with the 1.6.0 JDK that Apple installs by default. So I went into Applications > Utilities > Java Preferences. As soon as I opened that I was prompted by a message that said that in order to open Java Preferences I must install a Java 6 runtime and asked me if I would like to do so. I obviously said yes after which I reviewed the order of JDKs in Java Preferences which was correct.

I also removed the openjdk 1.7.0 package I’d installed earlier to prevent it from disrupting my work again by running the command below which removed this entry from Java Preferences.

sudo rm -rf /Library/Java/JavaVirtualMachines/1.7.0.jdk/

Next, as I created a Java project, I realised Eclipse was still operating with a JRE and unsurprisingly I couldn’t access the source code of the JDK libraries. To resolve both these issues at once I went into Eclipse > Preferences > Java > Installed JREs > Add and added the following path.

/Library/Java/JavaVirtualMachines/1.6.0_24-b07-334.jdk/Contents/Home

You’ll notice this path contains the essential src.jar. Then I went into Project > Properties > Java Build Path > Libraries, removed the existing JRE and added the new JDK. I was now able to open String.class and see the source and all was well.

Why is Java still such a nightmare on OS X after all this time? I really hope it improves with Java 8. Anyway, I wrote all this up in the hope that it helps others also struggling with such problems.

Fix home, end, pageup, pagedown keys in mac terminal vim

If you use vim in the mac terminal follow the steps below to regain use of these vital keys.

  1. Open Terminal.
  2. Open Preferences.
  3. Select Settings.
  4. Select your desired theme.
  5. Select Keyboard.
  6. Double click each key in title above.
  7. For each key set Action to ‘send string to shell:’ and set string as below.
    • Home: 33[7~
    • End: 33[4~
    • Page Up: 33[5~
    • Page Down: 33[6~

These will alter the key bindings not only in vim but in the terminal in general. If you want vim specific bindings another option is to use vim specific shortcuts. Personally, I prefer to use the above bindings and then in bash use ctrl-a for home and ctrl-e for end.

Did this tip help you? Let me know in the comments! [Credit]

Bash: Working with filenames containing spaces

Here’s a quick tip for part time bash hackers like me. Let’s say you want to iterate over all mp3’s in a directory and add a prefix string (the album name) to each filename. The only problem is that the fool who created these files has added spaces in the filenames (shock, horror, gasp).

Your first reaction may to be write something like below.

PREFIX="my-album-name"
for FILENAME in $(ls *.mp3); do
  mv -v "${FILENAME}" "${PREFIX} - ${FILENAME}"
done

On the face of it this looks like it should work but it doesn’t. Bash will iterate tokens split not only by filename but also by the spaces in each filename so you will get far more tokens than you expected and the move operation will go horribly wrong.

In fact the correct answer, upon investigation, emerges to be as below.

PREFIX="my-album-name"
find . -name '*.mp3' | while read FILENAME; do
  mv -v "${FILENAME}" "${PREFIX} - ${FILENAME#./}"; 
done

Note the use of parameter expansion in the destination filename: ${I#./}. This is necessary because by default the $FILENAME variable begins with ./ to say that it lives in the current directory so that code simply removes the smallest match of ./ from the beginning of the string. This was tested on OS X Lion only. Done.

Incidentally – this script was actually being used to prefix mp3 files (with album names) that belong to a new band I’ve just come across called LDUK. Check them out if you haven’t heard of them. They’re very good – twitter, facebook, youtube. My favourite tracks are Room of Anger Jungle and Artistic Vortex. You can also download three free full albums here.

Three Java releases in one day!

Oracle have just made three java releases (or maybe I’ve only just noticed them).

The 7u1 release fixes six bugs of which two appear to be loop related (1,2). The bug with loop predication was the one that originally tainted the release of Java 7 as you might remember. If I was working for a startup or running my own company I’d move to 7u1 straight away but in a bank that’ll never happen. Still, at least, I’ve managed to persuade them to move to 1.6.0_25 due to a critical CMS fragmentation bug afflicting 1.6.0_23. 🙁

The 6u29 release appears to have skipped a build number which is justified in the release notes. This one has two bug fixes worthy of mention out of a total of five – one is where ‘java.net.InterfaceAddress’s equals method may throw NPE’ (odd) and the other is where there is a ‘Memory leak of java.lang.ref.WeakReference objects’ (how ironic!).

Regarding the mac release it is great to see the Mac get official recognition on the oracle java homepage and have the release packaged as a dmg rather than needing to be built from source. (It’s quite possible by the way that I’ve only just noticed this one and that it’s been there all along or maybe I’d seen this earlier and have forgotten!). Though I’m liking the steady progress Oracle. Keep up the good work. I hope you are working on Java 8 as planned for end of next year!

Apple WWDC 2009 over

The Apple WWDC 2009 is now over. I had been following it this evening on twitter in real time courtesy of macrumors live. Below is a summary extract from the macrumors live twitter account. Points of note that are relevant to me – I’ll be upgrading to Snow Leopard for $29 in September and I’ll also be getting the 32GB iPhone 3GS June 19th onwards or at the soonest possible opportunity (assuming they allow premature upgrades). If I am not able to get my hands on the new iPhone 3GS I’ll be upgrading to the new v3.0 OS on June 17th for free. As much as I’d like the new 15″ macbook pro it’ll be a while before I can afford it. Apple have now updated their website. Overall great news.

  • iPhone 3GS available June 19th in US, UK, and 6 others. More come a week later, others this summer. 8 GB iPhone for $99 available today.42 minutes ago from web
  • iPhone 3GS: $199/16 GB and $299/32 GB for new and qualifying AT&T customers. Available in black and white. Current 8GB avail for $99.about 1 hour ago from web
  • iPhone 3GS: VoiceOver accessibility, Nike+ support, data encryption, improved battery life (up to 50% on Wi-Fi), eco-friendlyabout 1 hour ago from web
  • iPhone 3GS: API allows devs to integrate video capture; Voice control for call dialing, iPod playback; Digital compass integrates with Maps.about 1 hour ago from web
  • iPhone 3GS camera has still and video modes. Video mode: 30 fps VGA with audio, auto-focus, auto-exposure. Can trim video right on iPhone.about 1 hour ago from web
  • iPhone 3GS supports 7.2Mbps HSPDA data, has 3 MP auto-focus camera with “tap to focus” and improved low-light sensitivityabout 1 hour ago from web
  • iPhone 3GS announced (“S” for “speed”). 2-3x faster at tasks. Looks essentially identical to iPhone 3G. No front-facing camera.about 1 hour ago from web
  • iPhone OS 3.0 available June 17th. Free to all iPhone users, $9.95 for iPod touch users.about 1 hour ago from web
  • More Zipcar: iPhone app can honk vehicle’s horn and unlock car; Line6/Planet Waves: add guitar effects from iPhoneabout 1 hour ago from web
  • Ngmoco: Star Defense; Pasco: hardware accessories for scientific experiments for children; Zipcar: car-sharing reservationsabout 1 hour ago from web
  • TomTom: turn-by-turn GPS directions (apps and hardware). Car kit will hold iPhone on suction mount and integrate charging.about 1 hour ago from web
  • Dev Demos: Gameloft (Asphalt 5 racer), AirStrip Tech (Critical Care medical data app), ScrollMotion (digital books via in-app purchasing)about 1 hour ago from web
  • Turn-by-turn directions apps supported. Push notifications: alerts, sounds, badges. Now developer demos.about 2 hours ago from web
  • Reviewing OS 3.0 APIs: in-app purchasing, peer-to-peer connectivity, hardware accessory support, Google Maps available for use by devsabout 2 hours ago from web
  • “Find My iPhone”: Allows MobileMe customers to locate lost iPhones, send alerts, and remote wipe.about 2 hours ago from web
  • Safari for iPhone: HTTP audio/video streaming support, autofill, JavaScript 3x faster than OS 2.2.1., HTML 5 supportabout 2 hours ago from web
  • Tethering via USB or Bluetooth. Supported on 22 carriers, but not on AT&T at launch.about 2 hours ago from web
  • Cut, copy, paste, undo. Search. MMS in 3.0, but AT&T not supporting until later this summer. iTunes movie rentals/purchases from iPhone.about 2 hours ago from web
  • Video of developers and customers talking about the revolutionary platform and apps. Now moving on to talk about iPhone OS 3.0.about 2 hours ago from web
  • Now shifting to iPhone: 1,000,000 SDK downloads, 50,000 apps, 40 million iPhones/iPod touches, 1 billion+ appsabout 2 hours ago from web
  • Snow Leopard available in September for all Intel Macs. $29 for Leopard users, $49 family pack.about 2 hours ago from web
  • More Snow Leopard: Grand Central Station/OpenCL harness the processing power of GPUs, Demoing Exchange support for Mail, iCal, Address Bookabout 2 hours ago from web
  • Safari 4 final version released today on all platforms. Also showing demos of new QuickTime (brand-new interface), Stacks and Expose in SLabout 2 hours ago from web
  • Previewing Snow Leopard: Streamlined installation, Expose built into Dock icons, Preview and Mail 2x faster.about 2 hours ago from web
  • MacBook Air update: now starting at $1499, $1799 with 256 GB SSDabout 2 hours ago from web
  • 13″ MacBook now called MacBook Pro: starts at $1199. Same RAM and HD options as 15″ MBP, backlit KB, FW800. All models available today.about 3 hours ago from web
  • 17″ MBP updated: starting at $2499, retains ExpressCard slot, CPU and HD spec bumpsabout 3 hours ago from web
  • New 15″ MacBook Pro: non-removable 7 hr battery, improved display, SD card slot, up to 3.06Ghz, 8 GB RAM, and 500 GB HD/256GB SSD – $1699about 3 hours ago from web

Compiling Java 1.6 projects using Maven on Mac OS X

The following maven pom file configuration works on Windows and Linux but not on Mac OS X.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
    </configuration>
</plugin>

The error that occurs is as follows.

Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
Failure executing javac, but could not parse the error:
javac: invalid target release: 1.6

The reason is that the following environment variable isn’t set by default.

export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home"

You can declare this either as a one time export in your current shell above, in /etc/profile as I normally do or in any other startup file of your choice. Afterwards be sure to refresh your shell before you try again. This can be done either by closing your current terminal window and opening a new one or by sourcing whichever file you’ve put the above information into.

source /etc/profile

In order to make sure that it has taken effect one can output it in the shell as follows.

echo $JAVA_HOME

If it shows nothing then the shell has not picked up your change.

If your tomcat had already been started prior to setting the environment variable then don’t forget to restart it in the new shell otherwise you will get the following error on startup when deploying your maven application.

Caused by: java.lang.UnsupportedClassVersionError: Bad version number in .class file (unable to load class service.ServiceImpl)
	at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1851)
	at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:890)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1354)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
	at org.springframework.util.ClassUtils.forName(ClassUtils.java:211)
	at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:385)
	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1138)
	... 40 more

Check that your compiler and loader are using the same version of Java.

Apple releases Java 6 update 7 for Leopard

Today Apple released (through Software Update) an update to Java on Leopard which updates Java SE 6 to version 1.6.0_07, J2SE 5.0 to version 1.5.0_16, and J2SE 1.4.2 to 1.4.2_18.

Leopard Java update

Leopard Java update

This is great in that Apple is demonstrating its committment not only to supporting three different versions of Java on Leopard but also their respective updates. On the downside I couldn’t find the jvisualvm or visualvm executable anywhere in the various Java distributions on the mac.

Continue reading