編譯OpenJDK主要為了學習HotSpot,編譯過程在很多相關書籍中都有所涉及,但由於機型、機子具體環境的不同,很難有資料能夠一步到位。還是得碰到具體問題通過上網查來一個個解決。
下載OpenJDK
由於網絡環境還不錯,所以這里采用通過版本管理來下代碼。
安裝mercurial版本管理
brew install mercurial
接下來clone源碼
hg clone http://hg.openjdk.java.net/jdk8/jdk8
cd jdk8 && sh get_source.sh
安裝一些依賴
安裝FreeType,否則會出現configure: error: Could not find freetype!
brew install freetype
如果遇到
configure: error: GCC compiler is required. Try setting --with-tools-dir.
安裝gcc48
$ brew install gcc48
$ sudo mkdir /usr/bin/backup && sudo mv /usr/bin/gcc /usr/bin/g++ /usr/bin/backup
$ sudo ln -s /usr/local/bin/gcc-4.8 /usr/bin/gcc
$ sudo ln -s /usr/local/bin/g++-4.8 /usr/bin/g++
安裝ccache加速編譯
$ brew install ccache
安裝x11,地址https://www.xquartz.org/
$ ln -s /opt/X11/include/X11 /usr/local/include/X11
修改一些配置
hotspot/make/bsd/makefiles/gcc.make
我們需要干掉下面的代碼,否則warnings會無法編譯下去
# Compiler warnings are treated as errors
ifneq ($(COMPILER_WARNINGS_FATAL),false)
WARNINGS_ARE_ERRORS = -Werror
endif
這一段也要干掉,否則在后續編譯中可能會出現clang: error: unknown argument: '-fpch-deps'
ifeq ($(USE_CLANG),)
ifneq ($(CC_VER_MAJOR), 2)
DEPFLAGS += -fpch-deps
endif
endif
加上下面這句話,否則在編譯adlc時可能會出錯
LFLAGS += -stdlib=libstdc++
common/autoconf/generate-config.sh
找到as_fn_error $? "GCC compiler is required. Try setting --with-tools-dir." "$LINENO" 5出現的位置干掉,否則在config的時候可能會出現configure: error: GCC compiler is required
編譯
配置configure
sudo sh ./configure --enable-debug
可以看到出現類似如下的內容
A new configuration has been successfully created in
/Users/robin/Code/cpp/jdk/jdk8/build/macosx-x86_64-normal-server-fastdebug
using configure arguments '--enable-debug'.
Configuration summary:
* Debug level: fastdebug
* JDK variant: normal
* JVM variants: server
* OpenJDK target: OS: macosx, CPU architecture: x86, address length: 64
Tools summary:
* Boot JDK: java version "1.8.0_112" Java(TM) SE Runtime Environment (build 1.8.0_112-b16) Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode) (at /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home)
* C Compiler: version (at /usr/bin/gcc)
* C++ Compiler: version (at /usr/bin/g++)
Build performance summary:
* Cores to use: 4
* Memory limit: 16384 MB
* ccache status: installed, but disabled (version older than 3.1.4)
開始編譯
$ make
在成功之后可以看到如下提示
Finished building OpenJDK for target 'default'
調試
在編譯好我們的OpenJDK后,我們可以開始調試了,這里我用的是Jetbrains的CLion作為IDE,Clion對makefile支持不是太好,不過就閱讀和調試C++程序而言已經相當強大了。

加上一個調試hotspot的配置,在這里的Executable選擇我們編譯出來的jdk的java程序,路徑如OpenJDK路徑/build/macosx-x86_64-normal-server-fastdebug/jdk/bin/java
接下來我們便可以從java命令開始調試hotspot學習了

后記
由於編譯過程因為OpenJDK版本、個人機型、軟件環境等眾多因素影響,以上流程、配置僅供參考。在遇到問題時多查查StackOverflow等網站,大多情況下都有人碰到過。
參考
《HotSpot實戰》
