Java クラスファイルの先頭4バイトを読み込んで CAFEBABE を出力する

## Java クラスファイルの先頭4バイトを読み込んで CAFEBABE を出力する

ファイルの先頭4バイトを読み込んで16進数で出力する Java のソースコード。

```java
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class CafeBabe {

  public static void main(String[] args) throws Exception {
    String classFile = args[0];
    try (FileChannel fc = new FileInputStream(classFile).getChannel()) {
      MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, 4);
      byte[] bytes = new byte[4];
      bb.get(bytes);
      for (byte b : bytes) {
        System.out.print(String.format("%02X", b));
        Thread.sleep(1000L);
      }
      System.out.println();
    }
  }
}
```

コンパイルして CafeBabe.class ファイルを生成する。

```
$ javac CafeBabe.java 
```

java コマンドで CafeBabe を実行して CafeBabe.class を読み込む。

```
$ java CafeBabe CafeBabe.class 
CAFEBABE
```

## クラスファイルの先頭4バイトには Java クラスファイルであることを識別するマジックナンバーとして 0xCAFEBABE という値が入っている

JVM 仕様を参照。

[The Java® Virtual Machine Specification - Chapter 4\. The class File Format](https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-4.html#jvms-4.1)

```
ClassFile {
    u4             magic;
    u2             minor_version;
    u2             major_version;
    u2             constant_pool_count;
    cp_info        constant_pool[constant_pool_count-1];
    u2             access_flags;
    u2             this_class;
    u2             super_class;
    u2             interfaces_count;
    u2             interfaces[interfaces_count];
    u2             fields_count;
    field_info     fields[fields_count];
    u2             methods_count;
    method_info    methods[methods_count];
    u2             attributes_count;
    attribute_info attributes[attributes_count];
}
```

> The magic item supplies the magic number identifying the class file format; it has the value 0xCAFEBABE.

## なぜ 0xCAFEBABE になったのか

Java を開発した James Gosling が語ったところによると・・・

- カリフォルニアの Palo Alto に St. Michael's Alley というレストランがある
- Grateful Dead というロックバンドが有名になる前にそこでよく演奏していた
- Grateful Dead のメンバー Jerry Garcia が亡くなったときそこに小さな聖堂を建てるぐらいの場所だった
- そのため James Gosling たちはそのレストランを Cafe Dead と呼んでいた
- CAFEDEAD は16進数表記として解釈できることに気づいた
- 永続オブジェクトファイル用のマジックナンバーが必要だったため、これに CAFEDEAD を選んだ
- クラスファイル用のマジックナンバーが必要だったため、CAFE の後にフィットする4文字の16進数の単語を探していて BABE を選んだ

[bbum's rants, code & references](https://web.archive.org/web/20180320122839/http://radio-weblogs.com/0100490/2003/01/28.html)

> We used to go to lunch at a place called St Michael's Alley.  According to local legend, in the deep dark past, the Grateful Dead used to perform there before they made it big.  It was a pretty funky place that was definitely a Grateful Dead Kinda Place.  When Jerry died, they even put up a little Buddhist-esque shrine.  When we used to go there, we referred to the place as Cafe Dead.  Somewhere along the line it was noticed that this was a HEX number.  I was re-vamping some file format code and needed a couple of magic numbers: one for the persistent object file, and one for classes.  I used CAFEDEAD for the object file format, and in grepping for 4 character hex words that fit after "CAFE" (it seemed to be a good theme) I hit on BABE and decided to use it.  At that time, it didn't seem terribly important or destined to go anywhere but the trash-can of history.  So CAFEBABE  became the class file format, and CAFEDEAD was the persistent object format.  But the persistent object facility went away, and along with it went the use of CAFEDEAD - it was eventually replaced by RMI.

このレストラン Saint Michael's Alley はまだ存在するらしい (といっても少し離れた場所に移転したようだが)。

[Saint Michael's Alley](https://stmikes.com/)

> St. Michael's Alley was founded in 1959 by Vernon Gates. It was the first coffee house on the peninsula and was named for the alley in London which is home to London’s first coffeehouse, founded in 1652. St. Mike's bohemian atmosphere attracted many from the beatnick era and helped launch the careers of famous musicians and writers including the Grateful Dead, Joan Baez, Grayce Slick, Ken Kesey, Robert Hunter, and Jefferson Airplane. Vernon retired in 1994 and sold the restaurant to the current owners, Jenny Youll and Mike Sabina.
> 
> A new location, one block away from the original Brasserie, was opened in March 2009 at 140 Homer Ave. This larger space has a separate, full bar, outdoor patio, and an intimate dining room. Jenny and Mike spent 3 years designing and building the new St. Mike's, with Mike acting as draftsman, architect, engineer, general contractor and carpenter. There was also an endless stream of friends and relatives who came from around the country to help us with the project.

## 参考資料

- [Javaクラスファイル \- Wikipedia](https://ja.wikipedia.org/wiki/Java%E3%82%AF%E3%83%A9%E3%82%B9%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB)
- [bbum's rants, code & references](https://web.archive.org/web/20180320122839/http://radio-weblogs.com/0100490/2003/01/28.html)
- [グレイトフル・デッド \- Wikipedia](https://ja.wikipedia.org/wiki/%E3%82%B0%E3%83%AC%E3%82%A4%E3%83%88%E3%83%95%E3%83%AB%E3%83%BB%E3%83%87%E3%83%83%E3%83%89)