Merge "Don't crash if KVM is busy"
diff --git a/Makefile.android b/Makefile.android
index 22d7438..6fccf71 100644
--- a/Makefile.android
+++ b/Makefile.android
@@ -45,20 +45,23 @@
 
 MY_LDLIBS :=
 
-# this is needed to build the emulator on 64-bit Linux systems
-ifeq ($(HOST_OS)-$(HOST_ARCH),linux-x86)
-  MY_CFLAGS += -Wa,--32
-endif
-
 ifeq ($(HOST_OS),freebsd)
-  MY_CFLAGS += -Wa,--32 -I /usr/local/include
+  MY_CFLAGS += -I /usr/local/include
 endif
 
 ifeq ($(HOST_OS),windows)
-  MY_CFLAGS += -D_WIN32
-  # we need Win32 features  that are available since Windows 2000 Professional/Server (NT 5.0)
+  # we need Win32 features that are available since Windows 2000 Professional/Server (NT 5.0)
   MY_CFLAGS += -DWINVER=0x501
-  MY_LDLIBS += -lvfw32
+  MY_CFLAGS += -D_WIN32
+  ifneq ($(BUILD_HOST_64bit),)
+    # Microsoft 64-bit compiler define both _WIN32 and _WIN64
+    MY_CFLAGS += -D_WIN64
+    # amd64-mingw32msvc- toolchain still name it vfw32.  May change it once amd64-mingw32msvc-
+    # is stabilized
+    MY_LDLIBS += -lvfw32
+  else
+    MY_LDLIBS += -lvfw32
+  endif
 endif
 
 ifeq ($(HOST_ARCH),ppc)
@@ -91,17 +94,17 @@
 # adequate values for HOST_CC
 #
 ifneq ($(BUILD_STANDALONE_EMULATOR),true)
-  # On Linux, use our custom 32-bit host toolchain, which contains the
-  # relevant headers and 32-bit libraries for audio (The host 64-bit Lucid
-  # doesn't provide these anymore, only their 64-bit versions).
+  # On Linux, use our custom 32-bit host toolchain (unless BUILD_HOST_64bit=1)
+  # which contains the relevant headers and 32-bit libraries for audio (The host 64-bit
+  # Lucid doesn't provide these anymore, only their 64-bit versions).
   ifeq ($(HOST_OS),linux)
-    HOST_SDK_TOOLCHAIN_PREFIX := prebuilt/linux-x86/toolchain/i686-linux-glibc2.7-4.4.3/bin/i686-linux
+    HOST_SDK_TOOLCHAIN_PREFIX := prebuilts/tools/gcc-sdk
     # Don't do anything if the toolchain is not there
-    ifneq (,$(strip $(wildcard $(HOST_SDK_TOOLCHAIN_PREFIX)-gcc)))
-      MY_CC  := $(HOST_SDK_TOOLCHAIN_PREFIX)-gcc
-      MY_CXX := $(HOST_SDK_TOOLCHAIN_PREFIX)-g++
-      MY_AR  := $(HOST_SDK_TOOLCHAIN_PREFIX)-ar
-    endif # $(HOST_SDK_TOOLCHAIN_PREFIX)-gcc exists
+    ifneq (,$(strip $(wildcard $(HOST_SDK_TOOLCHAIN_PREFIX)/gcc)))
+      MY_CC  := $(HOST_SDK_TOOLCHAIN_PREFIX)/gcc
+      MY_CXX := $(HOST_SDK_TOOLCHAIN_PREFIX)/g++
+      MY_AR  := $(HOST_SDK_TOOLCHAIN_PREFIX)/ar
+    endif # $(HOST_SDK_TOOLCHAIN_PREFIX)/gcc exists
   endif # HOST_OS == linux
 
   ifneq ($(USE_CCACHE),)
@@ -109,6 +112,7 @@
     ccache := $(strip $(wildcard $(ccache)))
     ifneq ($(ccache),$(firstword $(MY_CC)))
       MY_CC := $(ccache) $(MY_CC)
+      MY_CXX := $(ccache) $(MY_CXX)
     endif
     ccache :=
   endif
@@ -116,9 +120,14 @@
 
 
 ifneq ($(combo_target)$(TARGET_SIMULATOR),HOST_true)
-  ifneq ($(HOST_ARCH),x86_64)
-    MY_CFLAGS += -m32
-    MY_LDLIBS += -m32
+  ifneq ($(BUILD_HOST_64bit),)
+    MY_CFLAGS += -m64
+    MY_LDLIBS += -m64
+  else
+    ifneq ($(HOST_ARCH),x86_64)
+      MY_CFLAGS += -m32
+      MY_LDLIBS += -m32
+    endif
   endif
 endif
 
@@ -184,6 +193,8 @@
 endif
 
 ifeq ($(HOST_OS),windows)
+  # amd64-mingw32msvc- toolchain still name it ws2_32.  May change it once amd64-mingw32msvc-
+  # is stabilized
   QEMU_SYSTEM_LDLIBS += -lwinmm -lws2_32 -liphlpapi
 else
   QEMU_SYSTEM_LDLIBS += -lpthread
diff --git a/Makefile.common b/Makefile.common
index 54ab704..a72d719 100644
--- a/Makefile.common
+++ b/Makefile.common
@@ -54,7 +54,8 @@
 ###  THESE ARE POTENTIALLY USED BY ALL COMPONENTS
 ###
 
-$(call start-emulator-library, emulator-common)
+common_LOCAL_CFLAGS =
+common_LOCAL_SRC_FILES =
 
 EMULATOR_COMMON_CFLAGS :=
 
@@ -90,12 +91,12 @@
 include $(LOCAL_PATH)/$(ZLIB_DIR)/sources.make
 EMULATOR_COMMON_CFLAGS += -I$(LOCAL_PATH)/$(ZLIB_DIR)
 
-LOCAL_SRC_FILES += $(ZLIB_SOURCES)
+common_LOCAL_SRC_FILES += $(ZLIB_SOURCES)
 
 ###########################################################
 # Android utility functions
 #
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
 	sockets.c \
 	iolooper-select.c \
 	android/async-console.c \
@@ -127,12 +128,31 @@
 	android/utils/tempfile.c \
 	android/utils/vector.c \
 
+common_LOCAL_CFLAGS += $(EMULATOR_COMMON_CFLAGS)
+
+
+## one for 32-bit
+$(call start-emulator-library, emulator-common)
+LOCAL_CFLAGS += $(common_LOCAL_CFLAGS)
+LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
 $(call gen-hw-config-defs)
-
-LOCAL_CFLAGS += $(EMULATOR_COMMON_CFLAGS)
-
 $(call end-emulator-library)
 
+## another for 64-bit
+# NOTE: only linux in non-standalone mode is supported, because
+#  1) For Windows: amd64-mingw32msvc-gcc doesn't work, see http://b/issue?id=5949152.
+#  2) For MacOSX: 64-bit libSDL*.a 1.2.x depends on NSQuickDrawView doesn't exist
+#  3) Standalone has --try-64
+ifeq ($(HOST_OS),linux)
+  ifneq ($(BUILD_STANDALONE_EMULATOR),true)
+    $(call start-emulator-library, emulator64-common)
+    LOCAL_CFLAGS += $(common_LOCAL_CFLAGS) -m64
+    LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+    $(call gen-hw-config-defs)
+    $(call end-emulator-library)
+  endif # BUILD_STANDALONE_EMULATOR == nil
+endif # HOST_OS == linux
+
 ##############################################################################
 ##############################################################################
 ###
@@ -141,11 +161,12 @@
 ###  THESE ARE USED BY 'emulator-ui' AND THE STANDALONE PROGRAMS
 ###
 
-$(call start-emulator-library, emulator-libui)
+common_LOCAL_CFLAGS =
+common_LOCAL_SRC_FILES =
 
 EMULATOR_LIBUI_CFLAGS :=
 
-LOCAL_CFLAGS += $(EMULATOR_COMMON_CFLAGS)
+common_LOCAL_CFLAGS += $(EMULATOR_COMMON_CFLAGS)
 
 ###########################################################
 # Libpng configuration
@@ -157,7 +178,7 @@
     $(LIBPNG_CFLAGS) \
     -I$(LOCAL_PATH)/$(LIBPNG_DIR)
 
-LOCAL_SRC_FILES += $(LIBPNG_SOURCES) loadpng.c
+common_LOCAL_SRC_FILES += $(LIBPNG_SOURCES) loadpng.c
 
 ##############################################################################
 # SDL-related definitions
@@ -211,12 +232,13 @@
     # Circular dependencies between libSDL and libSDLmain
     # We repeat the libraries in the final link to work around it
     SDL_STATIC_LIBRARIES := libSDL libSDLmain libSDL libSDLmain
+    SDL_STATIC_LIBRARIES_64 := lib64SDL lib64SDLmain lib64SDL lib64SDLmain
 
 else # BUILD_SDL_FROM_SOURCES
 
     SDL_DIR := distrib/sdl-1.2.12
     include $(LOCAL_PATH)/$(SDL_DIR)/sources.make
-    LOCAL_SRC_FILES += $(SDL_SOURCES)
+    common_LOCAL_SRC_FILES += $(SDL_SOURCES)
 
     EMULATOR_LIBUI_CFLAGS += \
         -I$(LOCAL_PATH)/$(SDL_DIR)/include
@@ -247,25 +269,42 @@
                 composer.c \
                 surface.c \
 
-LOCAL_SRC_FILES += $(SKIN_SOURCES:%=android/skin/%)
+common_LOCAL_SRC_FILES += $(SKIN_SOURCES:%=android/skin/%)
 
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
              android/user-config.c \
              android/resource.c \
              android/qemulator.c \
              android/keycode.c \
 
-$(call gen-hw-config-defs)
-
 # enable MMX code for our skin scaler
 ifeq ($(HOST_ARCH),x86)
-LOCAL_CFLAGS += -DUSE_MMX=1 -mmmx
+common_LOCAL_CFLAGS += -DUSE_MMX=1 -mmmx
 endif
 
-LOCAL_CFLAGS += $(EMULATOR_LIBUI_CFLAGS)
+common_LOCAL_CFLAGS += $(EMULATOR_LIBUI_CFLAGS)
 
+
+## one for 32-bit
+$(call start-emulator-library, emulator-libui)
+LOCAL_CFLAGS += $(common_LOCAL_CFLAGS)
+LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+$(call gen-hw-config-defs)
 $(call end-emulator-library)
 
+
+## another for 64-bit, see note in emulator64-common
+ifeq ($(HOST_OS),linux)
+  ifneq ($(BUILD_STANDALONE_EMULATOR),true)
+    $(call start-emulator-library, emulator64-libui)
+    LOCAL_CFLAGS += $(common_LOCAL_CFLAGS) -m64
+    LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+    $(call gen-hw-config-defs)
+    $(call end-emulator-library)
+  endif # BUILD_STANDALONE_EMULATOR == nil
+endif # HOST_OS == linux
+
+
 ##############################################################################
 ##############################################################################
 ###
@@ -274,11 +313,13 @@
 ###  THESE ARE USED BY EVERYTHING EXCEPT 'emulator-ui'
 ###
 
-$(call start-emulator-library, emulator-libqemu)
+common_LOCAL_CFLAGS =
+common_LOCAL_SRC_FILES =
+
 
 EMULATOR_LIBQEMU_CFLAGS :=
 
-LOCAL_CFLAGS += $(EMULATOR_COMMON_CFLAGS)
+common_LOCAL_CFLAGS += $(EMULATOR_COMMON_CFLAGS)
 
 ###########################################################
 # Jpeg configuration
@@ -290,13 +331,13 @@
     $(LIBJPEG_CFLAGS) \
     -I$(LOCAL_PATH)/$(LIBJPEG_DIR)
 
-LOCAL_SRC_FILES += $(LIBJPEG_SOURCES)
+common_LOCAL_SRC_FILES += $(LIBJPEG_SOURCES)
 
 AUDIO_SOURCES := noaudio.c wavaudio.c wavcapture.c mixeng.c
 AUDIO_CFLAGS  := -I$(LOCAL_PATH)/audio -DHAS_AUDIO
 AUDIO_LDLIBS  :=
 
-LOCAL_CFLAGS += -Wall -Wno-missing-field-initializers
+common_LOCAL_CFLAGS += -Wall -Wno-missing-field-initializers
 
 ifeq ($(HOST_OS),darwin)
   CONFIG_COREAUDIO ?= yes
@@ -351,17 +392,17 @@
 
 AUDIO_SOURCES := $(call sort,$(AUDIO_SOURCES:%=audio/%))
 
-LOCAL_CFLAGS += -Wno-sign-compare \
+common_LOCAL_CFLAGS += -Wno-sign-compare \
                 -fno-strict-aliasing -W -Wall -Wno-unused-parameter \
 
 # this is very important, otherwise the generated binaries may
 # not link properly on our build servers
 ifeq ($(HOST_OS),linux)
-LOCAL_CFLAGS += -fno-stack-protector
+common_LOCAL_CFLAGS += -fno-stack-protector
 endif
 
-LOCAL_SRC_FILES += $(AUDIO_SOURCES)
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += $(AUDIO_SOURCES)
+common_LOCAL_SRC_FILES += \
     android/audio-test.c
 
 # other flags
@@ -374,14 +415,14 @@
 EMULATOR_LIBQEMU_CFLAGS += $(AUDIO_CFLAGS)
 EMULATOR_LIBQEMU_LDLIBS += $(AUDIO_LDLIBS)
 
-LOCAL_CFLAGS += -Wno-missing-field-initializers
+common_LOCAL_CFLAGS += -Wno-missing-field-initializers
 
 # migration sources
 #
 ifeq ($(HOST_OS),windows)
-  LOCAL_SRC_FILES += migration-dummy-android.c
+  common_LOCAL_SRC_FILES += migration-dummy-android.c
 else
-  LOCAL_SRC_FILES += migration.c \
+  common_LOCAL_SRC_FILES += migration.c \
                      migration-exec.c \
                      migration-tcp-android.c
 endif
@@ -447,8 +488,6 @@
     android/multitouch-port.c \
     android/utils/jpeg-compress.c
 
-$(call gen-hw-config-defs)
-
 ifeq ($(HOST_ARCH),x86)
     CORE_MISC_SOURCES += i386-dis.c
 endif
@@ -480,10 +519,10 @@
   CORE_MISC_SOURCES   += android/camera/camera-capture-mac.m
 endif
 
-LOCAL_SRC_FILES += $(CORE_MISC_SOURCES)
+common_LOCAL_SRC_FILES += $(CORE_MISC_SOURCES)
 
 # Required
-LOCAL_CFLAGS += -D_XOPEN_SOURCE=600 -D_BSD_SOURCE=1
+common_LOCAL_CFLAGS += -D_XOPEN_SOURCE=600 -D_BSD_SOURCE=1
 
 SLIRP_SOURCES := \
     bootp.c \
@@ -505,7 +544,7 @@
     tftp.c \
     udp.c
 
-LOCAL_SRC_FILES += $(SLIRP_SOURCES:%=slirp-android/%)
+common_LOCAL_SRC_FILES += $(SLIRP_SOURCES:%=slirp-android/%)
 EMULATOR_LIBQEMU_CFLAGS += -I$(LOCAL_PATH)/slirp-android
 
 # socket proxy support
@@ -516,7 +555,7 @@
     proxy_http_connector.c \
     proxy_http_rewriter.c \
 
-LOCAL_SRC_FILES += $(PROXY_SOURCES:%=proxy/%)
+common_LOCAL_SRC_FILES += $(PROXY_SOURCES:%=proxy/%)
 EMULATOR_LIBQEMU_CFLAGS += -I$(LOCAL_PATH)/proxy
 
 # include telephony stuff
@@ -530,13 +569,13 @@
     sms.c \
     remote_call.c
 
-LOCAL_SRC_FILES += $(TELEPHONY_SOURCES:%=telephony/%)
+common_LOCAL_SRC_FILES += $(TELEPHONY_SOURCES:%=telephony/%)
 EMULATOR_LIBQEMU_CFLAGS += -I$(LOCAL_PATH)/telephony
 
 # sources inherited from upstream, but not fully
 # integrated into android emulator
 #
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
     json-lexer.c \
     json-parser.c \
     json-streamer.c \
@@ -548,32 +587,58 @@
     qlist.c \
     qstring.c \
 
-# gdbstub-xml.c contains C-compilable arrays corresponding to the content
-# of $(LOCAL_PATH)/gdb-xml/, and is generated with the 'feature_to_c.sh' script.
-#
-intermediates := $(call intermediates-dir-for,STATIC_LIBRARIES,$(LOCAL_MODULE),true)
-
 ifeq ($(QEMU_TARGET_XML_SOURCES),)
     QEMU_TARGET_XML_SOURCES := arm-core arm-neon arm-vfp arm-vfp3
     QEMU_TARGET_XML_SOURCES := $(QEMU_TARGET_XML_SOURCES:%=$(LOCAL_PATH)/gdb-xml/%.xml)
 endif
 
-QEMU_GDBSTUB_XML_C := $(intermediates)/gdbstub-xml.c
+common_LOCAL_CFLAGS += $(EMULATOR_LIBQEMU_CFLAGS)
+
+
+## one for 32-bit
+$(call start-emulator-library, emulator-libqemu)
+# gdbstub-xml.c contains C-compilable arrays corresponding to the content
+# of $(LOCAL_PATH)/gdb-xml/, and is generated with the 'feature_to_c.sh' script.
+#
+intermediates = $(call intermediates-dir-for,STATIC_LIBRARIES,$(LOCAL_MODULE),true)
+QEMU_GDBSTUB_XML_C = $(intermediates)/gdbstub-xml.c
 $(QEMU_GDBSTUB_XML_C): PRIVATE_PATH := $(LOCAL_PATH)
 $(QEMU_GDBSTUB_XML_C): PRIVATE_SOURCES := $(TARGET_XML_SOURCES)
 $(QEMU_GDBSTUB_XML_C): PRIVATE_CUSTOM_TOOL = $(PRIVATE_PATH)/feature_to_c.sh $@ $(QEMU_TARGET_XML_SOURCES)
 $(QEMU_GDBSTUB_XML_C): $(QEMU_TARGET_XML_SOURCES) $(LOCAL_PATH)/feature_to_c.sh
 	$(hide) rm -f $@
 	$(transform-generated-source)
-
 LOCAL_GENERATED_SOURCES += $(QEMU_GDBSTUB_XML_C)
-
-EMULATOR_LIBQEMU_CFLAGS += -I$(intermediates)
-
-LOCAL_CFLAGS += $(EMULATOR_LIBQEMU_CFLAGS)
-
+LOCAL_CFLAGS += $(common_LOCAL_CFLAGS) -I$(intermediates)
+LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+$(call gen-hw-config-defs)
 $(call end-emulator-library)
 
+
+## another for 64-bit, see note in emulator64-common
+ifeq ($(HOST_OS),linux)
+  ifneq ($(BUILD_STANDALONE_EMULATOR),true)
+    $(call start-emulator-library, emulator64-libqemu)
+    # gdbstub-xml.c contains C-compilable arrays corresponding to the content
+    # of $(LOCAL_PATH)/gdb-xml/, and is generated with the 'feature_to_c.sh' script.
+    #
+    intermediates = $(call intermediates-dir-for,STATIC_LIBRARIES,$(LOCAL_MODULE),true)
+    QEMU_GDBSTUB_XML_C = $(intermediates)/gdbstub-xml.c
+    $(QEMU_GDBSTUB_XML_C): PRIVATE_PATH := $(LOCAL_PATH)
+    $(QEMU_GDBSTUB_XML_C): PRIVATE_SOURCES := $(TARGET_XML_SOURCES)
+    $(QEMU_GDBSTUB_XML_C): PRIVATE_CUSTOM_TOOL = $(PRIVATE_PATH)/feature_to_c.sh $@ $(QEMU_TARGET_XML_SOURCES)
+    $(QEMU_GDBSTUB_XML_C): $(QEMU_TARGET_XML_SOURCES) $(LOCAL_PATH)/feature_to_c.sh
+	$(hide) rm -f $@
+	$(transform-generated-source)
+    LOCAL_GENERATED_SOURCES += $(QEMU_GDBSTUB_XML_C)
+    LOCAL_CFLAGS += $(common_LOCAL_CFLAGS) -I$(intermediates) -m64
+    LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+    $(call gen-hw-config-defs)
+    $(call end-emulator-library)
+  endif # BUILD_STANDALONE_EMULATOR == nil
+endif # HOST_OS == linux
+
+
 # Block sources, we must compile them with each executable because they
 # are only referenced by the rest of the code using constructor functions.
 # If their object files are put in a static library, these are never compiled
@@ -614,9 +679,8 @@
 ###  THEM IN emulator-libqemu SINCE THE SOURCES ARE C++
 ###
 
-$(call start-emulator-library, emulator-libelff)
-
-LOCAL_CPP_EXTENSION := .cc
+common_LOCAL_CFLAGS =
+common_LOCAL_SRC_FILES =
 
 ELFF_CFLAGS := -I$(LOCAL_PATH)/elff
 ELFF_LDLIBS := -lstdc++
@@ -630,15 +694,33 @@
     elf_mapped_section.cc \
     elff_api.cc \
 
-LOCAL_SRC_FILES += $(ELFF_SOURCES:%=elff/%)
+common_LOCAL_SRC_FILES += $(ELFF_SOURCES:%=elff/%)
 
-LOCAL_CFLAGS += \
+common_LOCAL_CFLAGS += \
     -fno-exceptions \
     $(ELFF_CFLAGS) \
 
+
+## one for 32-bit
+$(call start-emulator-library, emulator-libelff)
+LOCAL_CPP_EXTENSION := .cc
+LOCAL_CFLAGS += $(common_LOCAL_CFLAGS)
+LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
 $(call end-emulator-library)
 
 
+## another for 64-bit, see note in emulator64-common
+ifeq ($(HOST_OS),linux)
+  ifneq ($(BUILD_STANDALONE_EMULATOR),true)
+    $(call start-emulator-library, emulator64-libelff)
+    LOCAL_CPP_EXTENSION := .cc
+    LOCAL_CFLAGS += $(common_LOCAL_CFLAGS) -m64
+    LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+    $(call end-emulator-library)
+  endif # BUILD_STANDALONE_EMULATOR == nil
+endif # HOST_OS == linux
+
+
 ##############################################################################
 ##############################################################################
 ###
diff --git a/Makefile.target b/Makefile.target
index e1c4e28..1961acf 100644
--- a/Makefile.target
+++ b/Makefile.target
@@ -42,13 +42,15 @@
     -DTARGET_ARCH=\"$(EMULATOR_TARGET_ARCH)\"
 
 
-$(call start-emulator-library, emulator-target-$(EMULATOR_TARGET_CPU))
+common_LOCAL_CFLAGS =
+common_LOCAL_SRC_FILES =
+
 
 # The following is to ensure that "config.h" will map to a target-specific
 # configuration file header.
-LOCAL_CFLAGS += $(EMULATOR_TARGET_CFLAGS)
+common_LOCAL_CFLAGS += $(EMULATOR_TARGET_CFLAGS)
 
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
     tcg/tcg.c \
 
 ##############################################################################
@@ -86,7 +88,6 @@
     usb.c \
     watchdog.c
 
-$(call gen-hw-config-defs)
 
 ifeq ($(EMULATOR_TARGET_ARCH),arm)
 HW_SOURCES += android_arm.c \
@@ -102,14 +103,14 @@
 HW_OBJ_SOURCES := hw/smc91c111.c
 HW_OBJ_CFLAGS  := $(EMULATOR_TARGET_CFLAGS)
 
-LOCAL_SRC_FILES += arm-dis.c
+common_LOCAL_SRC_FILES += arm-dis.c
 
 # smc91c111.c requires <zlib.h>
-LOCAL_CFLAGS += $(ZLIB_CFLAGS)
+common_LOCAL_CFLAGS += $(ZLIB_CFLAGS)
 endif
 
 # required to ensure we properly initialize virtual audio hardware
-LOCAL_CFLAGS += -DHAS_AUDIO
+common_LOCAL_CFLAGS += -DHAS_AUDIO
 
 ifeq ($(EMULATOR_TARGET_ARCH),x86)
 HW_SOURCES += \
@@ -134,9 +135,9 @@
 
 endif
 
-LOCAL_SRC_FILES += $(HW_SOURCES:%=hw/%)
+common_LOCAL_SRC_FILES += $(HW_SOURCES:%=hw/%)
 
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
     cpu-exec.c  \
     exec.c \
     translate-all.c \
@@ -147,14 +148,14 @@
 ##############################################################################
 # CPU-specific emulation.
 #
-LOCAL_CFLAGS += -fno-PIC -fomit-frame-pointer -Wno-sign-compare
+common_LOCAL_CFLAGS += -fno-PIC -fomit-frame-pointer -Wno-sign-compare
 
 ifeq ($(HOST_ARCH),ppc)
-    LOCAL_CFLAGS += -D__powerpc__
+    common_LOCAL_CFLAGS += -D__powerpc__
 endif
 
 ifeq ($(EMULATOR_TARGET_ARCH),arm)
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
     target-arm/op_helper.c \
     target-arm/iwmmxt_helper.c \
     target-arm/neon_helper.c \
@@ -166,36 +167,36 @@
     hw/armv7m_nvic.c \
     arm-semi.c \
 
-LOCAL_SRC_FILES += fpu/softfloat.c
+common_LOCAL_SRC_FILES += fpu/softfloat.c
 endif
 
 ifeq ($(EMULATOR_TARGET_ARCH), x86)
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
     target-i386/op_helper.c \
     target-i386/helper.c \
     target-i386/translate.c \
     target-i386/machine.c \
 
 ifeq ($(HOST_OS),darwin)
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
       target-i386/hax-all.c       \
       target-i386/hax-darwin.c
 endif
 
 ifeq ($(HOST_OS),windows)
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
       target-i386/hax-all.c       \
       target-i386/hax-windows.c
 endif
 
-LOCAL_SRC_FILES += fpu/softfloat-native.c
+common_LOCAL_SRC_FILES += fpu/softfloat-native.c
 endif
 
 # compile KVM only if target is x86 on x86 Linux
 QEMU_KVM_TAG := $(QEMU_HOST_TAG)-$(EMULATOR_TARGET_ARCH)
 QEMU_DO_KVM := $(if $(filter linux-x86-x86 linux-x86_64-x86,$(QEMU_KVM_TAG)),true,false)
 ifeq ($(QEMU_DO_KVM),true)
-    LOCAL_SRC_FILES += \
+    common_LOCAL_SRC_FILES += \
         target-i386/kvm.c \
         target-i386/kvm-gs-restore.c \
         kvm-all.c \
@@ -210,7 +211,7 @@
 # memory is within allocated block. This information also allows detecting
 # memory leaks and attempts to free/realloc invalid pointers.
 #
-LOCAL_CFLAGS += \
+common_LOCAL_CFLAGS += \
     -I$(LOCAL_PATH)/memcheck \
     -I$(LOCAL_PATH)/elff
 
@@ -221,23 +222,43 @@
     memcheck_mmrange_map.c \
     memcheck_util.c \
 
-LOCAL_SRC_FILES += $(MCHK_SOURCES:%=memcheck/%)
+common_LOCAL_SRC_FILES += $(MCHK_SOURCES:%=memcheck/%)
 
-LOCAL_SRC_FILES += \
+common_LOCAL_SRC_FILES += \
     cpus.c \
     arch_init.c
 
 # What a mess, os-posix.c depends on the exact values of options
 # which are target specific.
 ifeq ($(HOST_OS),windows)
-    LOCAL_SRC_FILES += os-win32.c oslib-win32.c
+    common_LOCAL_SRC_FILES += os-win32.c oslib-win32.c
 else
-    LOCAL_SRC_FILES += os-posix.c oslib-posix.c
+    common_LOCAL_SRC_FILES += os-posix.c oslib-posix.c
 endif
-$(call gen-hx-header,qemu-options.hx,qemu-options.def,os-posix.c os-win32.c)
 
+
+## one for 32-bit
+$(call start-emulator-library, emulator-target-$(EMULATOR_TARGET_CPU))
+LOCAL_CFLAGS += $(common_LOCAL_CFLAGS)
+LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+$(call gen-hw-config-defs)
+$(call gen-hx-header,qemu-options.hx,qemu-options.def,os-posix.c os-win32.c)
 $(call end-emulator-library)
 
+## another for 64-bit, see note in file Makefile.common emulator64-common
+ifeq ($(HOST_OS),linux)
+  ifneq ($(BUILD_STANDALONE_EMULATOR),true)
+    $(call start-emulator-library, emulator64-target-$(EMULATOR_TARGET_CPU))
+    LOCAL_CFLAGS += $(common_LOCAL_CFLAGS) -m64
+    LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+    $(call gen-hw-config-defs)
+    $(call gen-hx-header,qemu-options.hx,qemu-options.def,os-posix.c os-win32.c)
+    $(call end-emulator-library)
+  endif # BUILD_STANDALONE_EMULATOR == nil
+endif # HOST_OS == linux
+
+
+
 ##############################################################################
 ##############################################################################
 ###
@@ -326,28 +347,31 @@
 ###
 ###
 
-$(call start-emulator-program, emulator-$(EMULATOR_TARGET_ARCH))
+common_LOCAL_LDLIBS =
+common_LOCAL_CFLAGS =
+common_LOCAL_SRC_FILES =
 
-LOCAL_STATIC_LIBRARIES := \
+
+common_LOCAL_STATIC_LIBRARIES := \
     emulator-libui \
     emulator-libqemu \
     emulator-target-$(EMULATOR_TARGET_CPU) \
     emulator-libelff \
     emulator-common \
 
-LOCAL_LDLIBS += \
+common_LOCAL_LDLIBS += \
     $(EMULATOR_COMMON_LDLIBS) \
     $(EMULATOR_LIBQEMU_LDLIBS) \
     $(EMULATOR_LIBUI_LDLIBS) \
     $(ELFF_LDLIBS) \
 
-LOCAL_CFLAGS += \
+common_LOCAL_CFLAGS += \
     $(EMULATOR_TARGET_CFLAGS) \
     $(EMULATOR_COMMON_CFLAGS) \
     $(EMULATOR_LIBQEMU_CFLAGS) \
     $(EMULATOR_LIBUI_CFLAGS)
 
-LOCAL_SRC_FILES := \
+common_LOCAL_SRC_FILES := \
     audio/audio.c \
     disas.c \
     dma-helpers.c \
@@ -371,28 +395,60 @@
     android/protocol/ui-commands-qemu.c \
     android/
 
-$(call gen-hx-header,qemu-monitor.hx,qemu-monitor.h,monitor.c)
-$(call gen-hx-header,qemu-options.hx,qemu-options.def,vl-android.c qemu-options.h)
-$(call gen-hw-config-defs)
 
 # The following files cannot be in static libraries because they contain
 # constructor functions that are otherwise stripped by the final linker
-LOCAL_SRC_FILES += $(HW_OBJ_SOURCES)
-LOCAL_CFLAGS    += $(HW_OBJ_CFLAGS)
+common_LOCAL_SRC_FILES += $(HW_OBJ_SOURCES)
+common_LOCAL_CFLAGS    += $(HW_OBJ_CFLAGS)
 
-LOCAL_SRC_FILES += $(BLOCK_SOURCES)
-LOCAL_CFLAGS    += $(BLOCK_CFLAGS)
+common_LOCAL_SRC_FILES += $(BLOCK_SOURCES)
+common_LOCAL_CFLAGS    += $(BLOCK_CFLAGS)
 
-LOCAL_SRC_FILES += $(SDLMAIN_SOURCES)
+common_LOCAL_SRC_FILES += $(SDLMAIN_SOURCES)
 
 # Generate a completely static executable if needed.
 # Note that this means no sound and graphics on Linux.
 #
 ifeq ($(CONFIG_STATIC_EXECUTABLE),true)
-    LOCAL_SRC_FILES += dynlink-static.c
-    LOCAL_LDLIBS    += -static
+    common_LOCAL_SRC_FILES += dynlink-static.c
+    common_LOCAL_LDLIBS    += -static
 endif
 
-LOCAL_STATIC_LIBRARIES += $(SDL_STATIC_LIBRARIES)
-
+## one for 32-bit
+$(call start-emulator-program, emulator-$(EMULATOR_TARGET_ARCH))
+LOCAL_STATIC_LIBRARIES += \
+    emulator-libui \
+    emulator-libqemu \
+    emulator-target-$(EMULATOR_TARGET_CPU) \
+    emulator-libelff \
+    emulator-common \
+    $(SDL_STATIC_LIBRARIES)
+LOCAL_LDLIBS += $(common_LOCAL_LDLIBS)
+LOCAL_CFLAGS += $(common_LOCAL_CFLAGS)
+LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+$(call gen-hx-header,qemu-monitor.hx,qemu-monitor.h,monitor.c)
+$(call gen-hx-header,qemu-options.hx,qemu-options.def,vl-android.c qemu-options.h)
+$(call gen-hw-config-defs)
 $(call end-emulator-program)
+
+
+## another for 64-bit, see note in file Makefile.common emulator64-common
+ifeq ($(HOST_OS),linux)
+  ifneq ($(BUILD_STANDALONE_EMULATOR),true)
+    $(call start-emulator-program, emulator64-$(EMULATOR_TARGET_ARCH))
+    LOCAL_STATIC_LIBRARIES += \
+        emulator64-libui \
+        emulator64-libqemu \
+        emulator64-target-$(EMULATOR_TARGET_CPU) \
+        emulator64-libelff \
+        emulator64-common \
+        $(SDL_STATIC_LIBRARIES_64)
+    LOCAL_LDLIBS += $(common_LOCAL_LDLIBS) -m64
+    LOCAL_CFLAGS += $(common_LOCAL_CFLAGS) -m64
+    LOCAL_SRC_FILES += $(common_LOCAL_SRC_FILES)
+    $(call gen-hx-header,qemu-monitor.hx,qemu-monitor.h,monitor.c)
+    $(call gen-hx-header,qemu-options.hx,qemu-options.def,vl-android.c qemu-options.h)
+    $(call gen-hw-config-defs)
+    $(call end-emulator-program)
+  endif # BUILD_STANDALONE_EMULATOR == nil
+endif # HOST_OS == linux
diff --git a/android-configure.sh b/android-configure.sh
index 6d25d20..5620e0e 100755
--- a/android-configure.sh
+++ b/android-configure.sh
@@ -116,12 +116,12 @@
     exit 1
 fi
 
-# On Linux, try to use our 32-bit prebuilt toolchain to generate binaries
+# On Linux, try to use our prebuilt toolchain to generate binaries
 # that are compatible with Ubuntu 8.04
-if [ -z "$CC" -a -z "$OPTION_CC" -a "$HOST_OS" = linux -a "$OPTION_TRY_64" != "yes" ] ; then
-    HOST_CC=`dirname $0`/../../prebuilt/linux-x86/toolchain/i686-linux-glibc2.7-4.4.3/bin/i686-linux-gcc
+if [ -z "$CC" -a -z "$OPTION_CC" -a "$HOST_OS" = linux ] ; then
+    HOST_CC=`dirname $0`/../../prebuilts/tools/gcc-sdk/gcc
     if [ -f "$HOST_CC" ] ; then
-        echo "Using prebuilt 32-bit toolchain: $HOST_CC"
+        echo "Using prebuilt toolchain: $HOST_CC"
         CC="$HOST_CC"
     fi
 fi
@@ -132,6 +132,10 @@
     CC="$OPTION_CC"
 fi
 
+if [ -z "$CC" ]; then
+  CC=$HOST_CC
+fi
+
 # we only support generating 32-bit binaris on 64-bit systems.
 # And we may need to add a -Wa,--32 to CFLAGS to let the assembler
 # generate 32-bit binaries on Linux x86_64.
@@ -180,7 +184,11 @@
 # platform build tree and copy them into objs/lib/ automatically, unless
 # you use --gles-libs to point explicitely to a different directory.
 #
-GLES_SHARED_LIBRARIES="libOpenglRender libGLES_CM_translator libGLES_V2_translator libEGL_translator"
+if [ "$OPTION_TRY_64" != "yes" ] ; then
+    GLES_SHARED_LIBRARIES="libOpenglRender libGLES_CM_translator libGLES_V2_translator libEGL_translator"
+else
+    GLES_SHARED_LIBRARIES="lib64OpenglRender lib64GLES_CM_translator lib64GLES_V2_translator lib64EGL_translator"
+fi
 
 if [ "$IN_ANDROID_BUILD" = "yes" ] ; then
     locate_android_prebuilt
@@ -196,10 +204,15 @@
         if [ ! -f $CCACHE ] ; then
             CCACHE="$ANDROID_PREBUILT/ccache$EXE"
         fi
+        if [ ! -f $CCACHE ] ; then
+            CCACHE="$ANDROID_PREBUILTS/ccache/ccache$EXE"
+        fi
         if [ -f $CCACHE ] ; then
             CC="$CCACHE $CC"
+            log "Prebuilt   : CCACHE=$CCACHE"
+	else
+            log "Prebuilt   : CCACHE can't be found"
         fi
-        log "Prebuilt   : CCACHE=$CCACHE"
     fi
 
     # finally ensure that our new binary is copied to the 'out'
@@ -511,6 +524,7 @@
 echo "HOST_PREBUILT_TAG := $TARGET_OS" >> $config_mk
 echo "HOST_EXEEXT       := $TARGET_EXEEXT" >> $config_mk
 echo "PREBUILT          := $ANDROID_PREBUILT" >> $config_mk
+echo "PREBUILTS         := $ANDROID_PREBUILTS" >> $config_mk
 
 PWD=`pwd`
 echo "SRC_PATH          := $PWD" >> $config_mk
diff --git a/android/build/common.sh b/android/build/common.sh
index de4e3c1..c7235ae 100644
--- a/android/build/common.sh
+++ b/android/build/common.sh
@@ -493,21 +493,20 @@
 # Locate the Android prebuilt directory for your os
 # you should only call this if IN_ANDROID_BUILD is "yes"
 #
-# This will set ANDROID_PREBUILT_HOST_TAG and ANDROID_PREBUILT
+# This will set ANDROID_PREBUILT_HOST_TAG, ANDROID_PREBUILT and ANDROID_PREBUILTS
 #
 locate_android_prebuilt ()
 {
     # locate prebuilt directory
     ANDROID_PREBUILT_HOST_TAG=$OS
     ANDROID_PREBUILT=$ANDROID_TOP/prebuilt/$ANDROID_PREBUILT_HOST_TAG
+    ANDROID_PREBUILTS=$ANDROID_TOP/prebuilts/misc/$ANDROID_PREBUILT_HOST_TAG
     if [ ! -d $ANDROID_PREBUILT ] ; then
         # this can happen when building on x86_64
         case $OS in
             linux-x86_64)
                 ANDROID_PREBUILT_HOST_TAG=linux-x86
                 ANDROID_PREBUILT=$ANDROID_TOP/prebuilt/$ANDROID_PREBUILT_HOST_TAG
-                log "Forcing usage of 32-bit prebuilts"
-                force_32bit_binaries
                 ;;
             *)
         esac
@@ -516,7 +515,22 @@
             exit 1
         fi
     fi
+    if [ ! -d $ANDROID_PREBUILTS ] ; then
+        # this can happen when building on x86_64
+        case $OS in
+            linux-x86_64)
+                ANDROID_PREBUILT_HOST_TAG=linux-x86
+                ANDROID_PREBUILTS=$ANDROID_TOP/prebuilts/misc/$ANDROID_PREBUILT_HOST_TAG
+                ;;
+            *)
+        esac
+        if [ ! -d $ANDROID_PREBUILTS ] ; then
+            echo "Can't find the prebuilts directory $ANDROID_PREBUILTS in Android build"
+            exit 1
+        fi
+    fi
     log "Prebuilt   : ANDROID_PREBUILT=$ANDROID_PREBUILT"
+    log "Prebuilts  : ANDROID_PREBUILTS=$ANDROID_PREBUILTS"
 }
 
 ## Build configuration file support
@@ -561,6 +575,7 @@
     fi
     echo "HOST_PREBUILT_TAG := $HOST_TAG" >> $config_mk
     echo "PREBUILT          := $ANDROID_PREBUILT" >> $config_mk
+    echo "PREBUILTS         := $ANDROID_PREBUILTS" >> $config_mk
 }
 
 # Find pattern $1 in string $2
diff --git a/android/camera/camera-service.c b/android/camera/camera-service.c
index bfdde56..51af2de 100644
--- a/android/camera/camera-service.c
+++ b/android/camera/camera-service.c
@@ -407,7 +407,7 @@
 _qemu_client_reply_payload(QemudClient* qc, size_t payload_size)
 {
     char payload_size_str[9];
-    snprintf(payload_size_str, sizeof(payload_size_str), "%08x", payload_size);
+    snprintf(payload_size_str, sizeof(payload_size_str), "%08zx", payload_size);
     qemud_client_send(qc, (const uint8_t*)payload_size_str, 8);
 }
 
@@ -1203,7 +1203,7 @@
     static const char _query_frame[]      = "frame";
 
     char query_name[64];
-    const char* query_param;
+    const char* query_param = NULL;
     CameraClient* cc = (CameraClient*)opaque;
 
     /*
diff --git a/android/config/darwin-x86/config-host.h b/android/config/darwin-x86/config-host.h
index 0395918..97a83dc 100644
--- a/android/config/darwin-x86/config-host.h
+++ b/android/config/darwin-x86/config-host.h
@@ -1,6 +1,15 @@
 /* This file was autogenerated by 'android-configure.sh' */
 #define CONFIG_QEMU_SHAREDIR   "/usr/local/share/qemu"
+#if defined(__x86_64__)
+#define HOST_X86_64    1
+#define HOST_LONG_BITS  64
+#elif defined(__i386__)
+#define HOST_I386    1
 #define HOST_LONG_BITS  32
+#else
+#error Unknown architecture for codegen
+#endif
+
 #define CONFIG_FNMATCH  1
 #define CONFIG_GDBSTUB  1
 #define CONFIG_SLIRP    1
@@ -9,7 +18,6 @@
 #define CONFIG_NAND_LIMITS  1
 #define QEMU_VERSION    "0.10.50"
 #define QEMU_PKGVERSION "Android"
-#define HOST_I386    1
 #define CONFIG_IOVEC 1
 #define CONFIG_DARWIN   1
 #define CONFIG_BSD       1
diff --git a/android/config/freebsd-x86/config-host.h b/android/config/freebsd-x86/config-host.h
index 2e44a83..fd31de4 100644
--- a/android/config/freebsd-x86/config-host.h
+++ b/android/config/freebsd-x86/config-host.h
@@ -1,7 +1,15 @@
 /* Automatically generated by configure - do not modify */
 #define CONFIG_QEMU_SHAREDIR "/usr/local/share/qemu"
-#define HOST_I386 1
-#define HOST_LONG_BITS 32
+#if defined(__x86_64__)
+#define HOST_X86_64    1
+#define HOST_LONG_BITS  64
+#elif defined(__i386__)
+#define HOST_I386    1
+#define HOST_LONG_BITS  32
+#else
+#error Unknown architecture for codegen
+#endif
+
 #define CONFIG_MACHINE_BSWAP_H 1
 #define CONFIG_FNMATCH 1
 #define CONFIG_GDBSTUB 1
diff --git a/android/config/linux-x86/config-host.h b/android/config/linux-x86/config-host.h
index 70a0eed..70b9ce7 100644
--- a/android/config/linux-x86/config-host.h
+++ b/android/config/linux-x86/config-host.h
@@ -1,6 +1,15 @@
 /* This file was autogenerated by 'android-configure.sh' */
 #define CONFIG_QEMU_SHAREDIR   "/usr/local/share/qemu"
+#if defined(__x86_64__)
+#define HOST_X86_64    1
+#define HOST_LONG_BITS  64
+#elif defined(__i386__)
+#define HOST_I386    1
 #define HOST_LONG_BITS  32
+#else
+#error Unknown architecture for codegen
+#endif
+
 #define CONFIG_BYTESWAP_H 1
 #define CONFIG_FNMATCH  1
 #define CONFIG_GDBSTUB  1
@@ -11,7 +20,6 @@
 #define CONFIG_NAND_LIMITS  1
 #define QEMU_VERSION    "0.10.50"
 #define QEMU_PKGVERSION "Android"
-#define HOST_I386    1
 #define CONFIG_KVM_GS_RESTORE   1
 #define CONFIG_IOVEC 1
 #define CONFIG_LINUX   1
diff --git a/android/config/windows/config-host.h b/android/config/windows/config-host.h
index ef36e4c..1b50927 100644
--- a/android/config/windows/config-host.h
+++ b/android/config/windows/config-host.h
@@ -1,12 +1,20 @@
 /* This file was autogenerated by 'android-configure.sh' */
 #define CONFIG_QEMU_SHAREDIR   "/usr/local/share/qemu"
+#if defined(__x86_64__)
+#define HOST_X86_64    1
+#define HOST_LONG_BITS  64
+#elif defined(__i386__)
+#define HOST_I386    1
 #define HOST_LONG_BITS  32
+#else
+#error Unknown architecture for codegen
+#endif
+
 #define CONFIG_GDBSTUB  1
 #define CONFIG_SLIRP    1
 #define CONFIG_SKINS    1
 #define CONFIG_TRACE    1
 #define QEMU_VERSION    "0.10.50"
 #define QEMU_PKGVERSION "Android"
-#define HOST_I386    1
 #define CONFIG_WIN32   1
 #define CONFIG_ANDROID       1
diff --git a/android/console.c b/android/console.c
index ed02db5..07a59d2 100644
--- a/android/console.c
+++ b/android/console.c
@@ -1867,7 +1867,7 @@
         if (q == p)
             break;
 
-        snprintf(temp, sizeof temp, "%.*s", q-p, p);
+        snprintf(temp, sizeof temp, "%.*s", (int)(intptr_t)(q-p), p);
         ret = android_event_from_str( temp, &type, &code, &value );
         if (ret < 0) {
             if (ret == -1) {
diff --git a/android/hw-sensors.c b/android/hw-sensors.c
index 51170cb..17b2491 100644
--- a/android/hw-sensors.c
+++ b/android/hw-sensors.c
@@ -339,7 +339,7 @@
 
     now_ns = qemu_get_clock_ns(vm_clock);
 
-    snprintf(buffer, sizeof buffer, "sync:%lld", now_ns/1000);
+    snprintf(buffer, sizeof buffer, "sync:%" PRId64, now_ns/1000);
     _hwSensorClient_send(cl, (uint8_t*)buffer, strlen(buffer));
 
     /* rearm timer, use a minimum delay of 20 ms, just to
diff --git a/android/main-emulator.c b/android/main-emulator.c
index a6e95c7..f2e30e2 100644
--- a/android/main-emulator.c
+++ b/android/main-emulator.c
@@ -50,7 +50,17 @@
 #  define DLL_EXTENSION  ".so"
 #endif
 
+#if defined(__x86_64__)
+/* Normally emulator is compiled in 32-bit.  In standalone it can be compiled
+   in 64-bit (with ,/android-configure.sh --try-64).  In this case, emulator-$ARCH
+   are also compiled in 64-bit and will search for lib64*.so instead of lib*so */
+#define  GLES_EMULATION_LIB  "lib64OpenglRender" DLL_EXTENSION
+#elif defined(__i386__)
 #define  GLES_EMULATION_LIB  "libOpenglRender" DLL_EXTENSION
+#else
+#error Unknown architecture for codegen
+#endif
+
 
 /* Forward declarations */
 static char* getTargetEmulatorPath(const char* progName, const char* avdArch);
@@ -173,6 +183,29 @@
     return errno;
 }
 
+static int
+getHostOSBitness()
+{
+  /*
+     This function returns 64 if host is running 64-bit OS, or 32 otherwise.
+
+     It uses the same technique in ndk/build/core/ndk-common.sh.
+     Here are comments from there:
+
+  ## On Linux or Darwin, a 64-bit kernel (*) doesn't mean that the user-land
+  ## is always 32-bit, so use "file" to determine the bitness of the shell
+  ## that invoked us. The -L option is used to de-reference symlinks.
+  ##
+  ## Note that on Darwin, a single executable can contain both x86 and
+  ## x86_64 machine code, so just look for x86_64 (darwin) or x86-64 (Linux)
+  ## in the output.
+
+    (*) ie. The following code doesn't always work:
+        struct utsname u;
+        int host_runs_64bit_OS = (uname(&u) == 0 && strcmp(u.machine, "x86_64") == 0);
+  */
+    return system("file -L \"$SHELL\" | grep -q \"x86[_-]64\"") == 0 ? 64 : 32;
+}
 
 /* Find the target-specific emulator binary. This will be something
  * like  <programDir>/emulator-<targetArch>, where <programDir> is
@@ -182,24 +215,43 @@
 getTargetEmulatorPath(const char* progName, const char* avdArch)
 {
     char*  progDir;
-    char   temp[PATH_MAX], *p=temp, *end=p+sizeof(temp);
+    char   path[PATH_MAX], *pathEnd=path+sizeof(path), *p;
+    const char* emulatorPrefix = "emulator-";
+    const char* emulator64Prefix = "emulator64-";
 #ifdef _WIN32
     const char* exeExt = ".exe";
+    /* ToDo: currently amd64-mingw32msvc-gcc doesn't work (http://b/issue?id=5949152)
+             which prevents us from generating 64-bit emulator for Windows */
+    int host_runs_64bit_OS = 0;
 #else
     const char* exeExt = "";
+    int host_runs_64bit_OS = getHostOSBitness() == 64;
 #endif
 
     /* Get program's directory name in progDir */
     path_split(progName, &progDir, NULL);
 
-    p = bufprint(temp, end, "%s/emulator-%s%s", progDir, avdArch, exeExt);
+    if (host_runs_64bit_OS) {
+        /* Find 64-bit emulator first */
+        p = bufprint(path, pathEnd, "%s/%s%s%s", progDir, emulator64Prefix, avdArch, exeExt);
+        if (p >= pathEnd) {
+            APANIC("Path too long: %s\n", progName);
+        }
+        if (path_exists(path)) {
+            free(progDir);
+            return strdup(path);
+        }
+    }
+
+    /* Find 32-bit emulator */
+    p = bufprint(path, pathEnd, "%s/%s%s%s", progDir, emulatorPrefix, avdArch, exeExt);
     free(progDir);
-    if (p >= end) {
+    if (p >= pathEnd) {
         APANIC("Path too long: %s\n", progName);
     }
 
-    if (path_exists(temp)) {
-        return strdup(temp);
+    if (path_exists(path)) {
+        return strdup(path);
     }
 
     /* Mmm, the file doesn't exist, If there is no slash / backslash
@@ -210,16 +262,25 @@
 #else
     if (strchr(progName, '/') == NULL) {
 #endif
-        p = bufprint(temp, end, "emulator-%s%s", avdArch, exeExt);
-        if (p < end) {
-            char*  resolved = path_search_exec(temp);
+        if (host_runs_64bit_OS) {
+           p = bufprint(path, pathEnd, "%s%s%s", emulator64Prefix, avdArch, exeExt);
+           if (p < pathEnd) {
+               char*  resolved = path_search_exec(path);
+               if (resolved != NULL)
+                   return resolved;
+           }
+        }
+
+        p = bufprint(path, pathEnd, "%s%s%s", emulatorPrefix, avdArch, exeExt);
+        if (p < pathEnd) {
+            char*  resolved = path_search_exec(path);
             if (resolved != NULL)
                 return resolved;
         }
     }
 
     /* Otherwise, the program is missing */
-    APANIC("Missing arch-specific emulator program: %s\n", temp);
+    APANIC("Missing arch-specific emulator program: %s\n", path);
     return NULL;
 }
 
@@ -271,7 +332,7 @@
     }
 
     /* try in $progDir/../lib, this corresponds to the platform build
-     * where the emulator binary is under out/host/<system>/lib and
+     * where the emulator binary is under out/host/<system>/bin and
      * the libraries are under out/host/<system>/lib
      */
     {
diff --git a/android/main.c b/android/main.c
index bd5a2fc..5aaf65e 100644
--- a/android/main.c
+++ b/android/main.c
@@ -145,7 +145,7 @@
     if (imageMB > defaultMB) {
         snprintf(temp, sizeof temp, "(%d MB > %d MB)", imageMB, defaultMB);
     } else {
-        snprintf(temp, sizeof temp, "(%lld bytes > %lld bytes)", imageBytes, defaultBytes);
+        snprintf(temp, sizeof temp, "(%" PRIu64 "  bytes > %" PRIu64 " bytes)", imageBytes, defaultBytes);
     }
 
     if (inAndroidBuild) {
diff --git a/android/opengles.c b/android/opengles.c
index 4913d0c..5a29d3a 100644
--- a/android/opengles.c
+++ b/android/opengles.c
@@ -27,7 +27,13 @@
 int  android_gles_fast_pipes = 1;
 
 /* Name of the GLES rendering library we're going to use */
+#if HOST_LONG_BITS == 32
 #define RENDERER_LIB_NAME  "libOpenglRender"
+#elif HOST_LONG_BITS == 64
+#define RENDERER_LIB_NAME  "lib64OpenglRender"
+#else
+#error Unknown HOST_LONG_BITS
+#endif
 
 /* These definitions *must* match those under:
  * development/tools/emulator/opengl/host/include/libOpenglRender/render_api.h
diff --git a/android/utils/system.c b/android/utils/system.c
index e65c602..6a6a4e1 100644
--- a/android/utils/system.c
+++ b/android/utils/system.c
@@ -67,7 +67,7 @@
     if (block2 != NULL)
         return block2;
 
-    fprintf(stderr, "PANIC: not enough memory to reallocate %lld bytes\n", (uint64_t)size);
+    fprintf(stderr, "PANIC: not enough memory to reallocate %zu bytes\n", size);
     exit(1);
     return NULL;
 }
diff --git a/android/utils/system.h b/android/utils/system.h
index 464957d..531c7eb 100644
--- a/android/utils/system.h
+++ b/android/utils/system.h
@@ -14,6 +14,7 @@
 
 #include <string.h>
 #include <stdint.h>
+#define __STDC_FORMAT_MACROS 1
 #include <inttypes.h>  /* for PRId64 et al. */
 #include "android/utils/assert.h"
 
@@ -173,11 +174,8 @@
 #ifndef PRIx64
 #  define PRIx64  "llx"
 #endif
-#ifndef PRUd64
-#  define PRUd64  "llu"
-#endif
-#ifndef PRUx64
-#  define PRUx64  "llx"
+#ifndef PRIu64
+#  define PRIu64  "llu"
 #endif
 
 /* */
diff --git a/distrib/jpeg-6b/jmorecfg.h b/distrib/jpeg-6b/jmorecfg.h
index 236bbcb..9dfde01 100644
--- a/distrib/jpeg-6b/jmorecfg.h
+++ b/distrib/jpeg-6b/jmorecfg.h
@@ -17,12 +17,14 @@
  * 
  */
 
+#include <inttypes.h>
+
 #define ANDROID_RGB
 
 #ifdef ANDROID_RGB
 #define PACK_SHORT_565(r,g,b)  ((((r)<<8)&0xf800)|(((g)<<3)&0x7E0)|((b)>>3))
 #define PACK_TWO_PIXELS(l,r)   ((r<<16) | l)
-#define PACK_NEED_ALIGNMENT(ptr) (((int)(ptr))&3)
+#define PACK_NEED_ALIGNMENT(ptr) (((int)(intptr_t)(ptr))&3)
 #define WRITE_TWO_PIXELS(addr, pixels) do {     \
          ((INT16*)(addr))[0] = (pixels);        \
          ((INT16*)(addr))[1] = (pixels)>>16;    \
diff --git a/elff/dwarf_utils.cc b/elff/dwarf_utils.cc
index 1d84b66..3b998b4 100644
--- a/elff/dwarf_utils.cc
+++ b/elff/dwarf_utils.cc
@@ -14,7 +14,9 @@
  * Contains implementation of misc. DWARF utility routines.
  */
 
-#include "stdio.h"
+#include <stdio.h>
+#define __STDC_FORMAT_MACROS 1
+#include <inttypes.h>
 #include "dwarf_utils.h"
 
 /* "Stringifies" the parameter. */
@@ -275,12 +277,12 @@
       break;
 
     case DWARF_VALUE_U64:
-      printf("XWORD)  = %" FMT_I64 "u (x%" FMT_I64 "X)\n", attr_value->u64,
+      printf("XWORD)  = %" PRIu64 " (x%" PRIX64 ")\n", attr_value->u64,
                                           attr_value->u64);
       break;
 
     case DWARF_VALUE_S64:
-      printf("SXWORD) = %" FMT_I64 "d (x%" FMT_I64 "X)\n", attr_value->s64,
+      printf("SXWORD) = %" PRId64 " (x%" PRIX64 ")\n", attr_value->s64,
                                           attr_value->s64);
       break;
 
@@ -293,7 +295,7 @@
       break;
 
     case DWARF_VALUE_PTR64:
-      printf("PTR64)  = x%08" FMT_I64 "X\n", attr_value->ptr64);
+      printf("PTR64)  = x%08" PRIX64 "\n", attr_value->ptr64);
       break;
 
     case DWARF_VALUE_BLOCK:
diff --git a/target-i386/cpu.h b/target-i386/cpu.h
index 88547cb..adf91cb 100644
--- a/target-i386/cpu.h
+++ b/target-i386/cpu.h
@@ -258,9 +258,9 @@
 
 #define MCG_STATUS_MCIP        (1UL<<2)   /* machine check in progress */
 
-#define MCI_STATUS_VAL (1UL<<63)  /* valid error */
-#define MCI_STATUS_OVER        (1UL<<62)  /* previous errors lost */
-#define MCI_STATUS_UC  (1UL<<61)  /* uncorrected error */
+#define MCI_STATUS_VAL (1ULL<<63)  /* valid error */
+#define MCI_STATUS_OVER        (1ULL<<62)  /* previous errors lost */
+#define MCI_STATUS_UC  (1ULL<<61)  /* uncorrected error */
 
 #define MSR_IA32_TSC                    0x10
 #define MSR_IA32_APICBASE               0x1b
diff --git a/vl-android.c b/vl-android.c
index 171d763..b7d4bb9 100644
--- a/vl-android.c
+++ b/vl-android.c
@@ -3576,10 +3576,10 @@
         uint64_t    sysBytes = android_hw->disk_systemPartition_size;
 
         if (sysBytes == 0) {
-            PANIC("Invalid system partition size: %" PRUd64, sysBytes);
+            PANIC("Invalid system partition size: %" PRIu64, sysBytes);
         }
 
-        snprintf(tmp,sizeof(tmp),"system,size=0x%" PRUx64, sysBytes);
+        snprintf(tmp,sizeof(tmp),"system,size=0x%" PRIx64, sysBytes);
 
         if (sysImage && *sysImage) {
             if (filelock_create(sysImage) == NULL) {
@@ -3611,10 +3611,10 @@
         uint64_t    dataBytes = android_hw->disk_dataPartition_size;
 
         if (dataBytes == 0) {
-            PANIC("Invalid data partition size: %" PRUd64, dataBytes);
+            PANIC("Invalid data partition size: %" PRIu64, dataBytes);
         }
 
-        snprintf(tmp,sizeof(tmp),"userdata,size=0x%" PRUx64, dataBytes);
+        snprintf(tmp,sizeof(tmp),"userdata,size=0x%" PRIx64, dataBytes);
 
         if (dataImage && *dataImage) {
             if (filelock_create(dataImage) == NULL) {
@@ -3834,7 +3834,7 @@
         const char* partPath = android_hw->disk_cachePartition_path;
         uint64_t    partSize = android_hw->disk_cachePartition_size;
 
-        snprintf(tmp,sizeof(tmp),"cache,size=0x%" PRUx64, partSize);
+        snprintf(tmp,sizeof(tmp),"cache,size=0x%" PRIx64, partSize);
 
         if (partPath && *partPath && strcmp(partPath, "<temp>") != 0) {
             if (filelock_create(partPath) == NULL) {