Merge "ext4_utils: copy mke2fs.conf to /etc" into oc-dr1-dev
am: 7f60c1a8af

Change-Id: I6be2a4583eae7d7ffa1246316309fc7743396b9c
diff --git a/f2fs_utils/Android.bp b/f2fs_utils/Android.bp
index afa5627..86790c4 100644
--- a/f2fs_utils/Android.bp
+++ b/f2fs_utils/Android.bp
@@ -69,39 +69,6 @@
     },
 }
 
-cc_binary_host {
-    name: "make_f2fs",
-
-    srcs: ["make_f2fs_main.c"],
-
-    // libf2fs_dlutils_host will dlopen("libf2fs_fmt_host_dyn")
-    host_ldlibs: [
-        "-ldl",
-    ],
-
-    ldflags: [
-        "-rdynamic"
-    ],
-
-    // The following libf2fs_* are from system/extras/f2fs_utils,
-    // and do not use code in external/f2fs-tools.
-    static_libs: [
-        "libf2fs_utils_host",
-        "libf2fs_ioutils_host",
-        "libf2fs_dlutils_host",
-        "libsparse",
-        "libz",
-    ],
-
-    required: ["libf2fs_fmt_host_dyn"],
-
-    target: {
-        darwin: {
-            enabled: false,
-        },
-    },
-}
-
 cc_library_shared {
     name: "libf2fs_dlutils",
 
diff --git a/f2fs_utils/mkf2fsuserimg.sh b/f2fs_utils/mkf2fsuserimg.sh
index 93ec743..f7b6aa1 100755
--- a/f2fs_utils/mkf2fsuserimg.sh
+++ b/f2fs_utils/mkf2fsuserimg.sh
@@ -26,7 +26,7 @@
   exit 2
 fi
 
-MAKE_F2FS_CMD="make_f2fs -l $SIZE $OUTPUT_FILE"
+MAKE_F2FS_CMD="make_f2fs -S $SIZE $OUTPUT_FILE"
 echo $MAKE_F2FS_CMD
 $MAKE_F2FS_CMD
 if [ $? -ne 0 ]; then
diff --git a/simpleperf/Android.mk b/simpleperf/Android.mk
index eb72d88..b172746 100644
--- a/simpleperf/Android.mk
+++ b/simpleperf/Android.mk
@@ -53,6 +53,9 @@
   libLLVMSupport \
   libprotobuf-cpp-lite \
   libevent \
+
+simpleperf_static_libraries_with_libc_target := \
+  $(simpleperf_static_libraries_target) \
   libc \
 
 simpleperf_static_libraries_host := \
@@ -174,7 +177,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES)
 LOCAL_CPPFLAGS := $(simpleperf_cppflags_target)
 LOCAL_SRC_FILES := main.cpp
-LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_target)
+LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_with_libc_target)
 ifdef TARGET_2ND_ARCH
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := simpleperf32
@@ -217,6 +220,73 @@
 $(call dist-for-goals,win_sdk,$(ALL_MODULES.host_cross_simpleperf_host$(HOST_CROSS_2ND_ARCH_MODULE_SUFFIX).BUILT))
 endif
 
+# libsimpleperf_record.a and libsimpleperf_record.so
+# They are linked to user's program, to get profile
+# counters and samples for specified code ranges.
+# =========================================================
+
+# libsimpleperf_record.a on target
+include $(CLEAR_VARS)
+LOCAL_CLANG := true
+LOCAL_MODULE := libsimpleperf_record
+LOCAL_CPPFLAGS := $(simpleperf_cppflags_target)
+LOCAL_SRC_FILES := record_lib_interface.cpp
+LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_target)
+LOCAL_MULTILIB := both
+LOCAL_CXX_STL := libc++_static
+LOCAL_LDLIBS := -Wl,--exclude-libs,ALL
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+include $(LLVM_DEVICE_BUILD_MK)
+include $(BUILD_STATIC_LIBRARY)
+
+# libsimpleperf_record.so on target
+include $(CLEAR_VARS)
+LOCAL_CLANG := true
+LOCAL_MODULE := libsimpleperf_record
+LOCAL_CPPFLAGS := $(simpleperf_cppflags_target)
+LOCAL_SRC_FILES := record_lib_interface.cpp
+LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_target)
+LOCAL_MULTILIB := both
+LOCAL_CXX_STL := libc++_static
+LOCAL_LDLIBS := -Wl,--exclude-libs,ALL
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+include $(LLVM_DEVICE_BUILD_MK)
+include $(BUILD_SHARED_LIBRARY)
+
+# libsimpleperf_record.a on host
+include $(CLEAR_VARS)
+LOCAL_CLANG := true
+LOCAL_MODULE := libsimpleperf_record
+LOCAL_MODULE_HOST_OS := linux
+LOCAL_CPPFLAGS := $(simpleperf_cppflags_host)
+LOCAL_CPPFLAGS_linux := $(simpleperf_cppflags_host_linux)
+LOCAL_SRC_FILES := record_lib_interface.cpp
+LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_host)
+LOCAL_STATIC_LIBRARIES_linux := $(simpleperf_static_libraries_host_linux)
+LOCAL_LDLIBS_linux := $(simpleperf_ldlibs_host_linux) -Wl,--exclude-libs,ALL
+LOCAL_MULTILIB := both
+LOCAL_CXX_STL := libc++_static
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+include $(LLVM_HOST_BUILD_MK)
+include $(BUILD_HOST_STATIC_LIBRARY)
+
+# libsimpleperf_record.so on host
+include $(CLEAR_VARS)
+LOCAL_CLANG := true
+LOCAL_MODULE := libsimpleperf_record
+LOCAL_MODULE_HOST_OS := linux
+LOCAL_CPPFLAGS := $(simpleperf_cppflags_host)
+LOCAL_CPPFLAGS_linux := $(simpleperf_cppflags_host_linux)
+LOCAL_SRC_FILES := record_lib_interface.cpp
+LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_host)
+LOCAL_STATIC_LIBRARIES_linux := $(simpleperf_static_libraries_host_linux)
+LOCAL_LDLIBS_linux := $(simpleperf_ldlibs_host_linux) -Wl,--exclude-libs,ALL
+LOCAL_MULTILIB := both
+LOCAL_CXX_STL := libc++_static
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+include $(LLVM_HOST_BUILD_MK)
+include $(BUILD_HOST_SHARED_LIBRARY)
+
 
 # libsimpleperf_report.so
 # It is the shared library used on host by python scripts
@@ -253,16 +323,13 @@
 # signal handlers in each thread.
 # =========================================================
 
-libsimpleperf_inplace_sampler_static_libraries_target := \
-	$(filter-out libc,$(simpleperf_static_libraries_target)) \
-
 # libsimpleperf_inplace_sampler.so on target
 include $(CLEAR_VARS)
 LOCAL_CLANG := true
 LOCAL_MODULE := libsimpleperf_inplace_sampler
 LOCAL_CPPFLAGS := $(simpleperf_cppflags_target)
 LOCAL_SRC_FILES := inplace_sampler_lib.cpp
-LOCAL_STATIC_LIBRARIES := libsimpleperf $(libsimpleperf_inplace_sampler_static_libraries_target)
+LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_target)
 LOCAL_MULTILIB := both
 LOCAL_CXX_STL := libc++_static
 LOCAL_LDLIBS := -Wl,--exclude-libs,ALL
@@ -321,7 +388,7 @@
   $(simpleperf_unit_test_src_files) \
   $(simpleperf_unit_test_src_files_linux) \
 
-LOCAL_STATIC_LIBRARIES += libsimpleperf $(simpleperf_static_libraries_target)
+LOCAL_STATIC_LIBRARIES += libsimpleperf $(simpleperf_static_libraries_with_libc_target)
 LOCAL_TEST_DATA := $(call find-test-data-in-subdirs,$(LOCAL_PATH),"*",testdata)
 LOCAL_MULTILIB := both
 LOCAL_FORCE_STATIC_EXECUTABLE := true
@@ -358,7 +425,7 @@
 LOCAL_COMPATIBILITY_SUITE := device-tests
 LOCAL_CPPFLAGS := $(simpleperf_cppflags_target)
 LOCAL_SRC_FILES := $(simpleperf_cpu_hotplug_test_src_files)
-LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_target)
+LOCAL_STATIC_LIBRARIES := libsimpleperf $(simpleperf_static_libraries_with_libc_target)
 LOCAL_MULTILIB := both
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 include $(LLVM_DEVICE_BUILD_MK)
@@ -415,4 +482,30 @@
 include $(LLVM_HOST_BUILD_MK)
 include $(BUILD_HOST_STATIC_TEST_LIBRARY)
 
+# simpleperf_record_test
+# ============================================================
+
+# simpleperf_record_test target
+include $(CLEAR_VARS)
+LOCAL_CLANG := true
+LOCAL_MODULE := simpleperf_record_test
+LOCAL_CPPFLAGS := $(simpleperf_cppflags_target)
+LOCAL_SRC_FILES := record_lib_test.cpp
+LOCAL_SHARED_LIBRARIES := libsimpleperf_record
+LOCAL_MULTILIB := both
+include $(BUILD_NATIVE_TEST)
+
+# simpleperf_record_test linux host
+include $(CLEAR_VARS)
+LOCAL_CLANG := true
+LOCAL_MODULE := simpleperf_record_test
+LOCAL_MODULE_HOST_OS := linux
+LOCAL_CPPFLAGS := $(simpleperf_cppflags_host)
+LOCAL_CPPFLAGS_linux := $(simpleperf_cppflags_host_linux)
+LOCAL_SRC_FILES := record_lib_test.cpp
+LOCAL_SHARED_LIBRARIES := libsimpleperf_record
+LOCAL_LDLIBS_linux := $(simpleperf_ldlibs_host_linux)
+LOCAL_MULTILIB := both
+include $(BUILD_HOST_NATIVE_TEST)
+
 include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/simpleperf/README.md b/simpleperf/README.md
index a5da220..d6c9c7f 100644
--- a/simpleperf/README.md
+++ b/simpleperf/README.md
@@ -28,6 +28,8 @@
     - [Record and report call graph](#record-and-report-call-graph)
     - [Visualize profiling data](#visualize-profiling-data)
     - [Annotate source code](#annotate-source-code)
+- [Answers to common issues](#answers-to-common-issues)
+    - [The correct way to pull perf.data on host](#the-correct-way-to-pull-perfdata-on-host)
 
 
 ## Simpleperf introduction
@@ -617,7 +619,8 @@
 **6. Report perf.data**
 
     # Pull perf.data on host.
-    $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava cat perf.data >perf.data
+    $ adb shell "run-as com.example.simpleperf.simpleperfexamplepurejava cat perf.data | tee /data/local/tmp/perf.data >/dev/null"
+    $ adb pull /data/local/tmp/perf.data
 
     # Report samples using corresponding simpleperf executable on host.
     # On windows, use "bin\windows\x86_64\simpleperf" instead.
@@ -627,6 +630,7 @@
     83.54%    Thread-2  6885  6900  /data/app/com.example.simpleperf.simpleperfexamplepurejava-2/oat/arm64/base.odex  void com.example.simpleperf.simpleperfexamplepurejava.MainActivity$1.run()
     16.11%    Thread-2  6885  6900  /data/app/com.example.simpleperf.simpleperfexamplepurejava-2/oat/arm64/base.odex  int com.example.simpleperf.simpleperfexamplepurejava.MainActivity$1.callFunction(int)
 
+See [here](#the-correct-way-to-pull-perfdata-on-host) for why we use tee rather than just >.
 There are many ways to show reports, check [report command](#simpleperf-report) for details.
 
 
@@ -808,3 +812,15 @@
     // p field means how much time is spent just in current line.
     /* acc_p: 99.966552%, p: 83.628188%        */                    i = callFunction(i);
 
+
+## Answers to common issues
+
+### The correct way to pull perf.data on host
+As perf.data is generated in app's context, it can't be pulled directly to host.
+One way is to `adb shell run-as xxx cat perf.data >perf.data`. However, it
+doesn't work well on Windows, because the content can be modified when it goes
+through the pipe. So we first copy it from app's context to shell's context,
+then pull it on host. The commands are as below:
+
+    $adb shell "run-as xxx cat perf.data | tee /data/local/tmp/perf.data >/dev/null"
+    $adb pull /data/local/tmp/perf.data
diff --git a/simpleperf/demo/README.md b/simpleperf/demo/README.md
index 8530dc6..1ecd9dd 100644
--- a/simpleperf/demo/README.md
+++ b/simpleperf/demo/README.md
@@ -5,6 +5,7 @@
 - [Introduction](#introduction)
 - [Profiling Java application](#profiling-java-application)
 - [Profiling Java/C++ application](#profiling-javac-application)
+- [Profiling Kotlin application](#profiling-kotlin-application)
 
 ## Introduction
 
@@ -17,6 +18,7 @@
     ../scripts/                  -- contain simpleperf binaries and scripts.
     SimpleperfExamplePureJava/   -- contains an Android Studio project using only Java code.
     SimpleperfExampleWithNative/ -- contains an Android Studio project using both Java and C++ code.
+    SimpleperfExampleOfKotlin/   -- contains an Android Studio project using Kotlin code.
 
 It can be downloaded as below:
 
@@ -75,7 +77,7 @@
 steps:
 1. Build and install app:
 ```
-# Open SimpleperfExamplesPureJava project with Android Studio,
+# Open SimpleperfExamplesWithNative project with Android Studio,
 # and build this project sucessfully, otherwise the `./gradlew` command below will fail.
 $ cd SimpleperfExampleWithNative
 
@@ -107,4 +109,47 @@
     $ python annotate.py
     $ find . -name "native-lib.cpp" | xargs gvim
         check the annoated source file native-lib.cpp.
-```
\ No newline at end of file
+```
+
+## Profiling Kotlin application
+
+    Android Studio project: SimpleExampleOfKotlin
+    test device: Android O (Google Pixel XL)
+    test device: Android N (Google Nexus 5X)
+
+steps:
+1. Build and install app:
+```
+# Open SimpleperfExamplesOfKotlin project with Android Studio,
+# and build this project sucessfully, otherwise the `./gradlew` command below will fail.
+$ cd SimpleperfExampleOfKotlin
+
+# On windows, use "gradlew" instead.
+$ ./gradlew clean assemble
+$ adb install -r app/build/outputs/apk/profiling/app-profiling.apk
+```
+
+2. Record profiling data:
+```
+$ cd ../../scripts/
+$ gvim app_profiler.config
+    change app_package_name line to: app_package_name = "com.example.simpleperf.simpleperfexampleofkotlin"
+$ python app_profiler.py
+    It runs the application and collects profiling data in perf.data, binaries on device in binary_cache/.
+```
+
+3. Show profiling data:
+```
+a. show call graph in txt mode
+    # On windows, use "bin\windows\x86\simpleperf" instead.
+    $ bin/linux/x86_64/simpleperf report -g | more
+        If on other hosts, use corresponding simpleperf binary.
+b. show call graph in gui mode
+    $ python report.py -g
+c. show samples in source code
+    $ gvim annotate.config
+        change source_dirs line to: source_dirs = ["../demo/SimpleperfExampleOfKotlin"]
+    $ python annotate.py
+    $ find . -name "MainActivity.kt" | xargs gvim
+        check the annoated source file MainActivity.kt.
+```
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/.gitignore b/simpleperf/demo/SimpleperfExampleOfKotlin/.gitignore
new file mode 100644
index 0000000..39fb081
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/.gitignore
@@ -0,0 +1,9 @@
+*.iml
+.gradle
+/local.properties
+/.idea/workspace.xml
+/.idea/libraries
+.DS_Store
+/build
+/captures
+.externalNativeBuild
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/gradle.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/gradle.xml
new file mode 100644
index 0000000..7ac24c7
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/gradle.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="GradleSettings">
+    <option name="linkedExternalProjectsSettings">
+      <GradleProjectSettings>
+        <option name="distributionType" value="DEFAULT_WRAPPED" />
+        <option name="externalProjectPath" value="$PROJECT_DIR$" />
+        <option name="modules">
+          <set>
+            <option value="$PROJECT_DIR$" />
+            <option value="$PROJECT_DIR$/app" />
+          </set>
+        </option>
+        <option name="resolveModulePerSourceSet" value="false" />
+      </GradleProjectSettings>
+    </option>
+  </component>
+</project>
\ No newline at end of file
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/misc.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/misc.xml
new file mode 100644
index 0000000..f342a0b
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/misc.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="NullableNotNullManager">
+    <option name="myDefaultNullable" value="android.support.annotation.Nullable" />
+    <option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
+    <option name="myNullables">
+      <value>
+        <list size="4">
+          <item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
+          <item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
+          <item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
+          <item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
+        </list>
+      </value>
+    </option>
+    <option name="myNotNulls">
+      <value>
+        <list size="4">
+          <item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
+          <item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
+          <item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
+          <item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
+        </list>
+      </value>
+    </option>
+  </component>
+  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" project-jdk-name="JDK" project-jdk-type="JavaSDK">
+    <output url="file://$PROJECT_DIR$/build/classes" />
+  </component>
+  <component name="ProjectType">
+    <option name="id" value="Android" />
+  </component>
+</project>
\ No newline at end of file
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/modules.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/modules.xml
new file mode 100644
index 0000000..2bb601f
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/modules.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/SimpleperfExampleOfKotlin.iml" filepath="$PROJECT_DIR$/SimpleperfExampleOfKotlin.iml" />
+      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
+    </modules>
+  </component>
+</project>
\ No newline at end of file
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/runConfigurations.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/runConfigurations.xml
new file mode 100644
index 0000000..7f68460
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/.idea/runConfigurations.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="RunConfigurationProducerService">
+    <option name="ignoredProducers">
+      <set>
+        <option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
+        <option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
+        <option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
+      </set>
+    </option>
+  </component>
+</project>
\ No newline at end of file
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/.gitignore b/simpleperf/demo/SimpleperfExampleOfKotlin/app/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/build.gradle b/simpleperf/demo/SimpleperfExampleOfKotlin/app/build.gradle
new file mode 100644
index 0000000..e7110fb
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/build.gradle
@@ -0,0 +1,37 @@
+apply plugin: 'com.android.application'
+
+apply plugin: 'kotlin-android'
+
+apply plugin: 'kotlin-android-extensions'
+
+apply from: 'profiling.gradle'
+
+android {
+    compileSdkVersion 25
+    buildToolsVersion "26.0.0"
+    defaultConfig {
+        applicationId "com.example.simpleperf.simpleperfexampleofkotlin"
+        minSdkVersion 15
+        targetSdkVersion 26
+        versionCode 1
+        versionName "1.0"
+        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+    }
+    buildTypes {
+        release {
+            minifyEnabled false
+            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+        }
+    }
+}
+
+dependencies {
+    implementation fileTree(dir: 'libs', include: ['*.jar'])
+    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
+        exclude group: 'com.android.support', module: 'support-annotations'
+    })
+    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
+    implementation 'com.android.support:appcompat-v7:25.4.0'
+    testImplementation 'junit:junit:4.12'
+    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
+}
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling.gradle b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling.gradle
new file mode 100644
index 0000000..661d549
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling.gradle
@@ -0,0 +1,60 @@
+
+// Set when building only part of the abis in the apk.
+def abiFiltersForWrapScript = []
+
+android {
+    buildTypes {
+        profiling {
+            initWith debug
+            externalNativeBuild {
+                cmake {
+                    // cmake Debug build type uses -O0, which makes the code slow.
+                    arguments "-DCMAKE_BUILD_TYPE=Release"
+                }
+            }
+            packagingOptions {
+                // Contain debug info in the libraries.
+                doNotStrip "**.so"
+
+                // Exclude wrap.sh for architectures not built.
+                if (abiFiltersForWrapScript) {
+                    def exclude_abis = ["armeabi", "armeabi-v7a", "arm64-v8a",
+                                        "x86", "x86_64", "mips", "mips64"]
+                            .findAll{ !(it in abiFiltersForWrapScript) }
+                            .collect{ "**/" + it + "/wrap.sh" }
+                    excludes += exclude_abis
+                }
+            }
+
+            // Add lib/xxx/wrap.sh in the apk. This is to enable java profiling on Android O
+            // devices.
+            sourceSets {
+                main {
+                    resources {
+                        srcDir {
+                            "profiling_apk_add_dir"
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+def writeWrapScriptToFullyCompileJavaApp(wrapFile) {
+    wrapFile.withWriter { writer ->
+        writer.write('#!/system/bin/sh\n')
+        writer.write('\$@\n')
+    }
+}
+
+task createProfilingApkAddDir {
+    for (String abi : ["armeabi", "armeabi-v7a", "arm64-v8a", "x86", "x86_64", "mips", "mips64"]) {
+        def dir = new File("app/profiling_apk_add_dir/lib/" + abi)
+        dir.mkdirs()
+        def wrapFile = new File(dir, "wrap.sh")
+        writeWrapScriptToFullyCompileJavaApp(wrapFile)
+        println "write file " + wrapFile.path
+    }
+}
+
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/arm64-v8a/wrap.sh b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/arm64-v8a/wrap.sh
new file mode 100644
index 0000000..047ea6f
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/arm64-v8a/wrap.sh
@@ -0,0 +1,2 @@
+#!/system/bin/sh
+$@
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/armeabi-v7a/wrap.sh b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/armeabi-v7a/wrap.sh
new file mode 100644
index 0000000..047ea6f
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/armeabi-v7a/wrap.sh
@@ -0,0 +1,2 @@
+#!/system/bin/sh
+$@
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/armeabi/wrap.sh b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/armeabi/wrap.sh
new file mode 100644
index 0000000..047ea6f
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/armeabi/wrap.sh
@@ -0,0 +1,2 @@
+#!/system/bin/sh
+$@
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/mips/wrap.sh b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/mips/wrap.sh
new file mode 100644
index 0000000..047ea6f
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/mips/wrap.sh
@@ -0,0 +1,2 @@
+#!/system/bin/sh
+$@
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/mips64/wrap.sh b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/mips64/wrap.sh
new file mode 100644
index 0000000..047ea6f
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/mips64/wrap.sh
@@ -0,0 +1,2 @@
+#!/system/bin/sh
+$@
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/x86/wrap.sh b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/x86/wrap.sh
new file mode 100644
index 0000000..047ea6f
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/x86/wrap.sh
@@ -0,0 +1,2 @@
+#!/system/bin/sh
+$@
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/x86_64/wrap.sh b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/x86_64/wrap.sh
new file mode 100644
index 0000000..047ea6f
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/profiling_apk_add_dir/lib/x86_64/wrap.sh
@@ -0,0 +1,2 @@
+#!/system/bin/sh
+$@
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/proguard-rules.pro b/simpleperf/demo/SimpleperfExampleOfKotlin/app/proguard-rules.pro
new file mode 100644
index 0000000..bd13885
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/proguard-rules.pro
@@ -0,0 +1,25 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /usr/local/google/home/yabinc/Android/Sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/androidTest/java/com/example/simpleperf/simpleperfexampleofkotlin/ExampleInstrumentedTest.kt b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/androidTest/java/com/example/simpleperf/simpleperfexampleofkotlin/ExampleInstrumentedTest.kt
new file mode 100644
index 0000000..8946158
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/androidTest/java/com/example/simpleperf/simpleperfexampleofkotlin/ExampleInstrumentedTest.kt
@@ -0,0 +1,24 @@
+package com.example.simpleperf.simpleperfexampleofkotlin
+
+import android.support.test.InstrumentationRegistry
+import android.support.test.runner.AndroidJUnit4
+
+import org.junit.Test
+import org.junit.runner.RunWith
+
+import org.junit.Assert.*
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * See [testing documentation](http://d.android.com/tools/testing).
+ */
+@RunWith(AndroidJUnit4::class)
+class ExampleInstrumentedTest {
+    @Test
+    fun useAppContext() {
+        // Context of the app under test.
+        val appContext = InstrumentationRegistry.getTargetContext()
+        assertEquals("com.example.simpleperf.simpleperfexampleofkotlin", appContext.packageName)
+    }
+}
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/AndroidManifest.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..05eb9ee
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/AndroidManifest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.simpleperf.simpleperfexampleofkotlin">
+
+    <application
+        android:allowBackup="true"
+        android:icon="@mipmap/ic_launcher"
+        android:label="@string/app_name"
+        android:roundIcon="@mipmap/ic_launcher_round"
+        android:supportsRtl="true"
+        android:theme="@style/AppTheme">
+        <activity android:name=".MainActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
\ No newline at end of file
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/java/com/example/simpleperf/simpleperfexampleofkotlin/MainActivity.kt b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/java/com/example/simpleperf/simpleperfexampleofkotlin/MainActivity.kt
new file mode 100644
index 0000000..55d47aa
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/java/com/example/simpleperf/simpleperfexampleofkotlin/MainActivity.kt
@@ -0,0 +1,29 @@
+package com.example.simpleperf.simpleperfexampleofkotlin
+
+import android.support.v7.app.AppCompatActivity
+import android.os.Bundle
+
+class MainActivity : AppCompatActivity() {
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        setContentView(R.layout.activity_main)
+        createBusyThread()
+    }
+
+    fun createBusyThread() {
+        object : Thread() {
+            var i = 0
+
+            override fun run() {
+                while (true) {
+                    i = callFunction(i)
+                }
+            }
+
+            fun callFunction(i: Int): Int {
+                return i + 1
+            }
+        }.start()
+    }
+}
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/layout/activity_main.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..4c7edcf
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context="com.example.simpleperf.simpleperfexampleofkotlin.MainActivity">
+
+    <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="Hello World!"
+        app:layout_constraintBottom_toBottomOf="parent"
+        app:layout_constraintLeft_toLeftOf="parent"
+        app:layout_constraintRight_toRightOf="parent"
+        app:layout_constraintTop_toTopOf="parent" />
+
+</android.support.constraint.ConstraintLayout>
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-hdpi/ic_launcher.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..5507303
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-hdpi/ic_launcher.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
new file mode 100644
index 0000000..8fab6a3
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-mdpi/ic_launcher.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..6bc7fcd
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-mdpi/ic_launcher.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
new file mode 100644
index 0000000..1eecc0e
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..ec87dce
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..05ca079
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..6f67f21
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..8bac0f2
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..0327e13
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..bacd3e7
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/colors.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..3ab3e9c
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/colors.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <color name="colorPrimary">#3F51B5</color>
+    <color name="colorPrimaryDark">#303F9F</color>
+    <color name="colorAccent">#FF4081</color>
+</resources>
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/strings.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..7972edf
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/strings.xml
@@ -0,0 +1,3 @@
+<resources>
+    <string name="app_name">SimpleperfExampleOfKotlin</string>
+</resources>
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/styles.xml b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..5885930
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/main/res/values/styles.xml
@@ -0,0 +1,11 @@
+<resources>
+
+    <!-- Base application theme. -->
+    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
+        <!-- Customize your theme here. -->
+        <item name="colorPrimary">@color/colorPrimary</item>
+        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
+        <item name="colorAccent">@color/colorAccent</item>
+    </style>
+
+</resources>
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/test/java/com/example/simpleperf/simpleperfexampleofkotlin/ExampleUnitTest.kt b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/test/java/com/example/simpleperf/simpleperfexampleofkotlin/ExampleUnitTest.kt
new file mode 100644
index 0000000..39fbbf8
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/app/src/test/java/com/example/simpleperf/simpleperfexampleofkotlin/ExampleUnitTest.kt
@@ -0,0 +1,17 @@
+package com.example.simpleperf.simpleperfexampleofkotlin
+
+import org.junit.Test
+
+import org.junit.Assert.*
+
+/**
+ * Example local unit test, which will execute on the development machine (host).
+ *
+ * See [testing documentation](http://d.android.com/tools/testing).
+ */
+class ExampleUnitTest {
+    @Test
+    fun addition_isCorrect() {
+        assertEquals(4, 2 + 2)
+    }
+}
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/build.gradle b/simpleperf/demo/SimpleperfExampleOfKotlin/build.gradle
new file mode 100644
index 0000000..2e0233b
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/build.gradle
@@ -0,0 +1,28 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+    ext.kotlin_version = '1.1.2-4'
+    repositories {
+        google()
+        jcenter()
+    }
+    dependencies {
+        classpath 'com.android.tools.build:gradle:3.0.0-alpha4'
+        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+
+        // NOTE: Do not place your application dependencies here; they belong
+        // in the individual module build.gradle files
+    }
+}
+
+allprojects {
+    repositories {
+        google()
+        jcenter()
+        mavenCentral()
+    }
+}
+
+task clean(type: Delete) {
+    delete rootProject.buildDir
+}
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/gradle.properties b/simpleperf/demo/SimpleperfExampleOfKotlin/gradle.properties
new file mode 100644
index 0000000..aac7c9b
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/gradle.properties
@@ -0,0 +1,17 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx1536m
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/gradle/wrapper/gradle-wrapper.jar b/simpleperf/demo/SimpleperfExampleOfKotlin/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..13372ae
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/gradle/wrapper/gradle-wrapper.properties b/simpleperf/demo/SimpleperfExampleOfKotlin/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..96b0280
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Mon Jun 26 18:23:25 PDT 2017
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-rc-1-all.zip
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/gradlew b/simpleperf/demo/SimpleperfExampleOfKotlin/gradlew
new file mode 100755
index 0000000..9d82f78
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+    JAVACMD=`cygpath --unix "$JAVACMD"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/gradlew.bat b/simpleperf/demo/SimpleperfExampleOfKotlin/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off

+@rem ##########################################################################

+@rem

+@rem  Gradle startup script for Windows

+@rem

+@rem ##########################################################################

+

+@rem Set local scope for the variables with windows NT shell

+if "%OS%"=="Windows_NT" setlocal

+

+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.

+set DEFAULT_JVM_OPTS=

+

+set DIRNAME=%~dp0

+if "%DIRNAME%" == "" set DIRNAME=.

+set APP_BASE_NAME=%~n0

+set APP_HOME=%DIRNAME%

+

+@rem Find java.exe

+if defined JAVA_HOME goto findJavaFromJavaHome

+

+set JAVA_EXE=java.exe

+%JAVA_EXE% -version >NUL 2>&1

+if "%ERRORLEVEL%" == "0" goto init

+

+echo.

+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:findJavaFromJavaHome

+set JAVA_HOME=%JAVA_HOME:"=%

+set JAVA_EXE=%JAVA_HOME%/bin/java.exe

+

+if exist "%JAVA_EXE%" goto init

+

+echo.

+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%

+echo.

+echo Please set the JAVA_HOME variable in your environment to match the

+echo location of your Java installation.

+

+goto fail

+

+:init

+@rem Get command-line arguments, handling Windowz variants

+

+if not "%OS%" == "Windows_NT" goto win9xME_args

+if "%@eval[2+2]" == "4" goto 4NT_args

+

+:win9xME_args

+@rem Slurp the command line arguments.

+set CMD_LINE_ARGS=

+set _SKIP=2

+

+:win9xME_args_slurp

+if "x%~1" == "x" goto execute

+

+set CMD_LINE_ARGS=%*

+goto execute

+

+:4NT_args

+@rem Get arguments from the 4NT Shell from JP Software

+set CMD_LINE_ARGS=%$

+

+:execute

+@rem Setup the command line

+

+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

+

+@rem Execute Gradle

+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

+

+:end

+@rem End local scope for the variables with windows NT shell

+if "%ERRORLEVEL%"=="0" goto mainEnd

+

+:fail

+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of

+rem the _cmd.exe /c_ return code!

+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1

+exit /b 1

+

+:mainEnd

+if "%OS%"=="Windows_NT" endlocal

+

+:omega

diff --git a/simpleperf/demo/SimpleperfExampleOfKotlin/settings.gradle b/simpleperf/demo/SimpleperfExampleOfKotlin/settings.gradle
new file mode 100644
index 0000000..e7b4def
--- /dev/null
+++ b/simpleperf/demo/SimpleperfExampleOfKotlin/settings.gradle
@@ -0,0 +1 @@
+include ':app'
diff --git a/simpleperf/include/simpleperf.h b/simpleperf/include/simpleperf.h
new file mode 100644
index 0000000..de3736d
--- /dev/null
+++ b/simpleperf/include/simpleperf.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _SIMPLEPERF_H
+#define _SIMPLEPERF_H
+
+#include <sys/types.h>
+
+#include <string>
+#include <vector>
+
+#ifndef SIMPLEPERF_EXPORT
+#define SIMPLEPERF_EXPORT
+#endif
+
+namespace simpleperf {
+
+std::vector<std::string> GetAllEvents() SIMPLEPERF_EXPORT;
+bool IsEventSupported(const std::string& name) SIMPLEPERF_EXPORT;
+
+struct Counter {
+  std::string event;
+  uint64_t value;
+  // If there is not enough hardware counters, kernel will share counters between events.
+  // time_enabled_in_ns is the period when counting is enabled, and time_running_in_ns is
+  // the period when counting really happens in hardware.
+  uint64_t time_enabled_in_ns;
+  uint64_t time_running_in_ns;
+};
+
+// PerfEventSet can be used to count perf events or record perf events in perf.data.
+// To count perf events, you can do as follows:
+//  1. Create PerfEventSet instance.
+//  2. Select perf events to count. You can add more than one events.
+//  3. Set monitored targets.
+//  4. Start/stop/read counters when needed.
+// An example is as below:
+//    PerfEventSet* perf = PerfEventSet::CreateInstance(PerfEventSetType::kPerfForCounting);
+//    perf->AddEvent("cpu-cycles");
+//    perf->AddEvent("instructions");
+//    perf->MonitorCurrentProcess();
+//    perf->StartCounters();
+//    perf->StopCounters();
+//    perf->ReadCounters(&counters);
+//
+// PerfEventSet is not thread-safe. To access it from different threads, please protect
+// it under locks.
+class SIMPLEPERF_EXPORT PerfEventSet {
+ public:
+  enum Type {
+    kPerfForCounting,
+    kPerfForRecording,
+  };
+
+  static PerfEventSet* CreateInstance(Type type);
+  virtual ~PerfEventSet() {}
+
+  // Add event in the set. All valid events are returned by GetAllEvents().
+  // To only monitor events happen in user space, add :u suffix, like cpu-cycles:u.
+  virtual bool AddEvent(const std::string& name);
+
+  // Set monitored target. You can only monitor threads in current process.
+  virtual bool MonitorCurrentProcess();
+  virtual bool MonitorCurrentThread();
+  virtual bool MonitorThreadsInCurrentProcess(const std::vector<pid_t>& threads);
+
+  // Counting interface:
+  // Start counters. When the PerfEventSet instance is created, the counters are stopped.
+  virtual bool StartCounters();
+  // Stop counters. The values of the counters will not change until the next StartCounters().
+  virtual bool StopCounters();
+  // Read counter values. There is a value for each event. You don't need to stop counters before
+  // reading them. The counter values are the accumulated value from the first StartCounters().
+  virtual bool ReadCounters(std::vector<Counter>* counters);
+
+ protected:
+  PerfEventSet() {}
+};
+
+}  // namespace simpleperf
+
+#undef SIMPLEPERF_EXPORT
+
+#endif  // _SIMPLEPERF_H
diff --git a/simpleperf/perf_regs.cpp b/simpleperf/perf_regs.cpp
index d27b62a..6aa8bad 100644
--- a/simpleperf/perf_regs.cpp
+++ b/simpleperf/perf_regs.cpp
@@ -99,7 +99,8 @@
 uint64_t GetSupportedRegMask(ArchType arch) {
   switch (arch) {
     case ARCH_X86_32:
-      return ((1ULL << PERF_REG_X86_32_MAX) - 1);
+      return ((1ULL << PERF_REG_X86_32_MAX) - 1) & ~(1ULL << PERF_REG_X86_DS) &
+          ~(1ULL << PERF_REG_X86_ES) & ~(1ULL << PERF_REG_X86_FS) & ~(1ULL << PERF_REG_X86_GS);
     case ARCH_X86_64:
       return (((1ULL << PERF_REG_X86_64_MAX) - 1) & ~(1ULL << PERF_REG_X86_DS) &
               ~(1ULL << PERF_REG_X86_ES) & ~(1ULL << PERF_REG_X86_FS) & ~(1ULL << PERF_REG_X86_GS));
diff --git a/simpleperf/record_lib_interface.cpp b/simpleperf/record_lib_interface.cpp
new file mode 100644
index 0000000..9b16012
--- /dev/null
+++ b/simpleperf/record_lib_interface.cpp
@@ -0,0 +1,295 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define SIMPLEPERF_EXPORT __attribute__((visibility("default")))
+#include "include/simpleperf.h"
+
+#include <memory>
+#include <set>
+#include <string>
+#include <vector>
+
+#include <android-base/logging.h>
+
+#include "environment.h"
+#include "event_attr.h"
+#include "event_fd.h"
+#include "event_selection_set.h"
+#include "event_type.h"
+
+namespace simpleperf {
+
+std::vector<std::string> GetAllEvents() {
+  std::vector<std::string> result;
+  if (!CheckPerfEventLimit()) {
+    return result;
+  }
+  for (auto& type : GetAllEventTypes()) {
+    perf_event_attr attr = CreateDefaultPerfEventAttr(type);
+    if (IsEventAttrSupported(attr)) {
+      result.push_back(type.name);
+    }
+  }
+  return result;
+}
+
+bool IsEventSupported(const std::string& name) {
+  if (!CheckPerfEventLimit()) {
+    return false;
+  }
+  std::unique_ptr<EventTypeAndModifier> type = ParseEventType(name);
+  if (type == nullptr) {
+    return false;
+  }
+  perf_event_attr attr = CreateDefaultPerfEventAttr(type->event_type);
+  return IsEventAttrSupported(attr);
+}
+
+class PerfEventSetImpl : public PerfEventSet {
+ public:
+  virtual ~PerfEventSetImpl() {}
+
+  bool AddEvent(const std::string& name) override {
+    if (!IsEventSupported(name)) {
+      return false;
+    }
+    event_names_.push_back(name);
+    return true;
+  }
+
+  bool MonitorCurrentProcess() override {
+    whole_process_ = true;
+    return true;
+  }
+
+  bool MonitorCurrentThread() override {
+    whole_process_ = false;
+    threads_.insert(gettid());
+    return true;
+  }
+
+  bool MonitorThreadsInCurrentProcess(const std::vector<pid_t>& threads) override {
+    whole_process_ = false;
+    std::vector<pid_t> tids = GetThreadsInProcess(getpid());
+    for (auto& tid : threads) {
+      if (std::find(tids.begin(), tids.end(), tid) == tids.end()) {
+        LOG(ERROR) << "Thread " << tid << " doesn't exist in current process.";
+        return false;
+      }
+    }
+    threads_.insert(threads.begin(), threads.end());
+    return true;
+  }
+
+ protected:
+  PerfEventSetImpl() : whole_process_(false) {}
+
+  std::vector<std::string> event_names_;
+  bool whole_process_;
+  std::set<pid_t> threads_;
+};
+
+class PerfEventSetForCounting : public PerfEventSetImpl {
+ public:
+  PerfEventSetForCounting() : in_counting_state_(false) {}
+  virtual ~PerfEventSetForCounting() {}
+
+  bool StartCounters() override;
+  bool StopCounters() override;
+  bool ReadCounters(std::vector<Counter>* counters) override;
+
+ private:
+  bool CreateEventSelectionSet();
+  void InitAccumulatedCounters();
+  bool ReadRawCounters(std::vector<Counter>* counters);
+  // Add counter b to a.
+  void AddCounter(Counter& a, const Counter& b);
+  // Sub counter b from a.
+  void SubCounter(Counter& a, const Counter& b);
+
+  bool in_counting_state_;
+  std::unique_ptr<EventSelectionSet> event_selection_set_;
+  // The counters at the last time calling StartCounting().
+  std::vector<Counter> last_start_counters_;
+  // The accumulated counters of counting periods, excluding
+  // the last one.
+  std::vector<Counter> accumulated_counters_;
+};
+
+bool PerfEventSetForCounting::CreateEventSelectionSet() {
+  std::unique_ptr<EventSelectionSet> set(new EventSelectionSet(true));
+  if (event_names_.empty()) {
+    LOG(ERROR) << "No events.";
+    return false;
+  }
+  for (const auto& name : event_names_) {
+    if (!set->AddEventType(name)) {
+      return false;
+    }
+  }
+  if (whole_process_) {
+    set->AddMonitoredProcesses({getpid()});
+  } else {
+    if (threads_.empty()) {
+      LOG(ERROR) << "No monitored threads.";
+      return false;
+    }
+    set->AddMonitoredThreads(threads_);
+  }
+  if (!set->OpenEventFiles({-1})) {
+    return false;
+  }
+  event_selection_set_ = std::move(set);
+  return true;
+}
+
+void PerfEventSetForCounting::InitAccumulatedCounters() {
+  for (const auto& name : event_names_) {
+    Counter counter;
+    counter.event = name;
+    counter.value = 0;
+    counter.time_enabled_in_ns = 0;
+    counter.time_running_in_ns = 0;
+    accumulated_counters_.push_back(counter);
+  }
+}
+
+bool PerfEventSetForCounting::ReadRawCounters(std::vector<Counter>* counters) {
+  CHECK(event_selection_set_);
+  std::vector<CountersInfo> s;
+  if (!event_selection_set_->ReadCounters(&s)) {
+    return false;
+  }
+  CHECK_EQ(s.size(), event_names_.size());
+  counters->resize(s.size());
+  for (size_t i = 0; i < s.size(); ++i) {
+    CountersInfo& info = s[i];
+    std::string name = info.event_modifier.empty() ? info.event_name :
+        info.event_name + ":" + info.event_modifier;
+    CHECK_EQ(name, event_names_[i]);
+    Counter& sum = (*counters)[i];
+    sum.event = name;
+    sum.value = 0;
+    sum.time_enabled_in_ns = 0;
+    sum.time_running_in_ns = 0;
+    for (CounterInfo& c : info.counters) {
+      sum.value += c.counter.value;
+      sum.time_enabled_in_ns += c.counter.time_enabled;
+      sum.time_running_in_ns += c.counter.time_running;
+    }
+  }
+  return true;
+}
+
+void PerfEventSetForCounting::AddCounter(Counter& a, const Counter& b) {
+  a.value += b.value;
+  a.time_enabled_in_ns += b.time_enabled_in_ns;
+  a.time_running_in_ns += b.time_enabled_in_ns;
+}
+
+void PerfEventSetForCounting::SubCounter(Counter& a, const Counter& b) {
+  a.value -= b.value;
+  a.time_enabled_in_ns -= b.time_enabled_in_ns;
+  a.time_running_in_ns -= b.time_running_in_ns;
+}
+
+bool PerfEventSetForCounting::StartCounters() {
+  if (in_counting_state_) {
+    return true;
+  }
+  if (event_selection_set_ == nullptr) {
+    if (!CreateEventSelectionSet()) {
+      return false;
+    }
+    InitAccumulatedCounters();
+  }
+  if (!ReadRawCounters(&last_start_counters_)) {
+    return false;
+  }
+  in_counting_state_ = true;
+  return true;
+}
+
+bool PerfEventSetForCounting::StopCounters() {
+  if (!in_counting_state_) {
+    return true;
+  }
+  std::vector<Counter> cur;
+  if (!ReadRawCounters(&cur)) {
+    return false;
+  }
+  for (size_t i = 0; i < event_names_.size(); ++i) {
+    SubCounter(cur[i], last_start_counters_[i]);
+    AddCounter(accumulated_counters_[i], cur[i]);
+  }
+  in_counting_state_ = false;
+  return true;
+}
+
+bool PerfEventSetForCounting::ReadCounters(std::vector<Counter>* counters) {
+  if (!in_counting_state_) {
+    *counters = accumulated_counters_;
+    return true;
+  }
+  if (!ReadRawCounters(counters)) {
+    return false;
+  }
+  for (size_t i = 0; i < event_names_.size(); ++i) {
+    SubCounter((*counters)[i], last_start_counters_[i]);
+    AddCounter((*counters)[i], accumulated_counters_[i]);
+  }
+  return true;
+}
+
+PerfEventSet* PerfEventSet::CreateInstance(PerfEventSet::Type type) {
+  if (!CheckPerfEventLimit()) {
+    return nullptr;
+  }
+  if (type == Type::kPerfForCounting) {
+    return new PerfEventSetForCounting;
+  }
+  return nullptr;
+}
+
+bool PerfEventSet::AddEvent(const std::string&) {
+  return false;
+}
+
+bool PerfEventSet::MonitorCurrentProcess() {
+  return false;
+}
+
+bool PerfEventSet::MonitorCurrentThread() {
+  return false;
+}
+
+bool PerfEventSet::MonitorThreadsInCurrentProcess(const std::vector<pid_t>&) {
+  return false;
+}
+
+bool PerfEventSet::StartCounters() {
+  return false;
+}
+
+bool PerfEventSet::StopCounters() {
+  return false;
+}
+
+bool PerfEventSet::ReadCounters(std::vector<Counter>*) {
+  return false;
+}
+
+}  // namespace simpleperf
diff --git a/simpleperf/record_lib_test.cpp b/simpleperf/record_lib_test.cpp
new file mode 100644
index 0000000..5fdaea4
--- /dev/null
+++ b/simpleperf/record_lib_test.cpp
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "simpleperf.h"
+
+#include <gtest/gtest.h>
+
+#include <memory>
+
+using namespace simpleperf;
+
+TEST(get_all_events, smoke) {
+  std::vector<std::string> events = GetAllEvents();
+  ASSERT_GT(events.size(), 0u);
+  ASSERT_NE(std::find(events.begin(), events.end(), "cpu-cycles"), events.end());
+  ASSERT_TRUE(IsEventSupported("cpu-cycles"));
+  ASSERT_TRUE(IsEventSupported("cpu-cycles:u"));
+  ASSERT_TRUE(IsEventSupported("cpu-cycles:k"));
+}
+
+static void DoSomeWork() {
+  for (volatile int i = 0; i < 100000000; ++i) {
+  }
+}
+
+TEST(counter, add_event) {
+  std::unique_ptr<PerfEventSet> perf(PerfEventSet::CreateInstance(
+      PerfEventSet::Type::kPerfForCounting));
+  ASSERT_TRUE(perf);
+  ASSERT_TRUE(perf->AddEvent("cpu-cycles"));
+  ASSERT_TRUE(perf->AddEvent("cpu-cycles:u"));
+  ASSERT_TRUE(perf->AddEvent("cpu-cycles:k"));
+  ASSERT_TRUE(perf->MonitorCurrentProcess());
+  ASSERT_TRUE(perf->StartCounters());
+  DoSomeWork();
+  ASSERT_TRUE(perf->StopCounters());
+  std::vector<Counter> counters;
+  ASSERT_TRUE(perf->ReadCounters(&counters));
+  ASSERT_EQ(counters.size(), 3u);
+  ASSERT_EQ(counters[0].event, "cpu-cycles");
+  ASSERT_EQ(counters[1].event, "cpu-cycles:u");
+  ASSERT_EQ(counters[2].event, "cpu-cycles:k");
+  for (auto& counter : counters) {
+    ASSERT_GE(counter.value, 0u);
+    ASSERT_GE(counter.time_enabled_in_ns, 0u);
+    ASSERT_GE(counter.time_running_in_ns, 0u);
+    ASSERT_LE(counter.time_running_in_ns, counter.time_enabled_in_ns);
+  }
+}
+
+TEST(counter, different_targets) {
+  auto test_function = [](std::function<void(PerfEventSet*)> set_target_func) {
+    std::unique_ptr<PerfEventSet> perf(PerfEventSet::CreateInstance(
+        PerfEventSet::Type::kPerfForCounting));
+    ASSERT_TRUE(perf);
+    ASSERT_TRUE(perf->AddEvent("cpu-cycles"));
+    set_target_func(perf.get());
+    ASSERT_TRUE(perf->MonitorCurrentProcess());
+    ASSERT_TRUE(perf->StartCounters());
+    DoSomeWork();
+    ASSERT_TRUE(perf->StopCounters());
+    std::vector<Counter> counters;
+    ASSERT_TRUE(perf->ReadCounters(&counters));
+    ASSERT_EQ(counters.size(), 1u);
+    ASSERT_EQ(counters[0].event, "cpu-cycles");
+    ASSERT_GT(counters[0].value, 0u);
+    ASSERT_GT(counters[0].time_enabled_in_ns, 0u);
+    ASSERT_GT(counters[0].time_running_in_ns, 0u);
+    ASSERT_LE(counters[0].time_running_in_ns, counters[0].time_enabled_in_ns);
+  };
+  test_function([](PerfEventSet* perf) {
+    ASSERT_TRUE(perf->MonitorCurrentProcess());
+  });
+  test_function([](PerfEventSet* perf) {
+    ASSERT_TRUE(perf->MonitorCurrentThread());
+  });
+  test_function([](PerfEventSet* perf) {
+    ASSERT_TRUE(perf->MonitorThreadsInCurrentProcess({getpid()}));
+  });
+}
+
+TEST(counter, start_stop_multiple_times) {
+  const size_t TEST_COUNT = 10;
+  std::unique_ptr<PerfEventSet> perf(PerfEventSet::CreateInstance(
+      PerfEventSet::Type::kPerfForCounting));
+  ASSERT_TRUE(perf);
+  ASSERT_TRUE(perf->AddEvent("cpu-cycles"));
+  ASSERT_TRUE(perf->MonitorCurrentProcess());
+  Counter prev_counter;
+  for (size_t i = 0; i < TEST_COUNT; ++i) {
+    ASSERT_TRUE(perf->StartCounters());
+    DoSomeWork();
+    ASSERT_TRUE(perf->StopCounters());
+    std::vector<Counter> counters;
+    ASSERT_TRUE(perf->ReadCounters(&counters));
+    ASSERT_EQ(counters.size(), 1u);
+    ASSERT_EQ(counters[0].event, "cpu-cycles");
+    ASSERT_GT(counters[0].value, 0u);
+    ASSERT_GT(counters[0].time_enabled_in_ns, 0u);
+    ASSERT_GT(counters[0].time_running_in_ns, 0u);
+    ASSERT_LE(counters[0].time_running_in_ns, counters[0].time_enabled_in_ns);
+    if (i > 0u) {
+      ASSERT_GT(counters[0].value, prev_counter.value);
+      ASSERT_GT(counters[0].time_enabled_in_ns, prev_counter.time_enabled_in_ns);
+      ASSERT_GT(counters[0].time_running_in_ns, prev_counter.time_running_in_ns);
+    }
+    prev_counter = counters[0];
+  }
+}
+
+TEST(counter, no_change_after_stop) {
+  std::unique_ptr<PerfEventSet> perf(PerfEventSet::CreateInstance(
+      PerfEventSet::Type::kPerfForCounting));
+  ASSERT_TRUE(perf);
+  ASSERT_TRUE(perf->AddEvent("cpu-cycles"));
+  ASSERT_TRUE(perf->MonitorCurrentProcess());
+  ASSERT_TRUE(perf->StartCounters());
+  DoSomeWork();
+  ASSERT_TRUE(perf->StopCounters());
+  std::vector<Counter> counters;
+  ASSERT_TRUE(perf->ReadCounters(&counters));
+  ASSERT_EQ(counters.size(), 1u);
+  ASSERT_EQ(counters[0].event, "cpu-cycles");
+  ASSERT_GT(counters[0].value, 0u);
+  ASSERT_GT(counters[0].time_enabled_in_ns, 0u);
+  ASSERT_GT(counters[0].time_running_in_ns, 0u);
+  ASSERT_LE(counters[0].time_running_in_ns, counters[0].time_enabled_in_ns);
+  Counter prev_counter = counters[0];
+  DoSomeWork();
+  ASSERT_TRUE(perf->ReadCounters(&counters));
+  ASSERT_EQ(counters.size(), 1u);
+  ASSERT_EQ(counters[0].value, prev_counter.value);
+  ASSERT_EQ(counters[0].time_enabled_in_ns, prev_counter.time_enabled_in_ns);
+  ASSERT_EQ(counters[0].time_running_in_ns, prev_counter.time_running_in_ns);
+}
diff --git a/simpleperf/scripts/annotate.py b/simpleperf/scripts/annotate.py
index a77f6a2..2b253bd 100644
--- a/simpleperf/scripts/annotate.py
+++ b/simpleperf/scripts/annotate.py
@@ -515,7 +515,7 @@
 
     def _collect_source_files(self):
         self.source_file_dict = dict()
-        source_file_suffix = ['h', 'c', 'cpp', 'cc', 'java']
+        source_file_suffix = ['h', 'c', 'cpp', 'cc', 'java', 'kt']
         for source_dir in self.config['source_dirs']:
             for root, _, files in os.walk(source_dir):
                 for file in files:
@@ -633,4 +633,4 @@
     config = load_config(args.config)
     annotator = SourceFileAnnotator(config)
     annotator.annotate()
-    log_info('annotate finish successfully, please check result in annotated_files/.')
\ No newline at end of file
+    log_info('annotate finish successfully, please check result in annotated_files/.')
diff --git a/simpleperf/scripts/app_profiler.config b/simpleperf/scripts/app_profiler.config
index 63dbd96..752b85f 100644
--- a/simpleperf/scripts/app_profiler.config
+++ b/simpleperf/scripts/app_profiler.config
@@ -49,7 +49,7 @@
 
 
 # Profiling record options that will be passed directly to `simpleperf record` command on device.
-# As we can't stop profiling by Ctrl-C, we need to set how long to profile using "--duration".
+# You can set how long to profile using "--duration" option, or use Ctrl-C to stop profiling.
 record_options = "-e cpu-cycles:u -f 4000 -g --duration 10"
 
 
diff --git a/simpleperf/scripts/app_profiler.py b/simpleperf/scripts/app_profiler.py
index 25098d3..e2a137f 100644
--- a/simpleperf/scripts/app_profiler.py
+++ b/simpleperf/scripts/app_profiler.py
@@ -265,13 +265,41 @@
 
 
     def start_and_wait_profiling(self):
-        self.run_in_app_dir([
-            './simpleperf', 'record', self.config['record_options'], '-p',
-            str(self.app_pid), '--symfs', '.'])
+        subproc = None
+        returncode = None
+        try:
+            args = self.get_run_in_app_dir_args([
+                './simpleperf', 'record', self.config['record_options'], '-p',
+                str(self.app_pid), '--symfs', '.'])
+            adb_args = [self.adb.adb_path] + args
+            log_debug('run adb cmd: %s' % adb_args)
+            subproc = subprocess.Popen(adb_args)
+            returncode = subproc.wait()
+        except KeyboardInterrupt:
+            if subproc:
+                self.stop_profiling()
+                returncode = 0
+        log_debug('run adb cmd: %s [result %s]' % (adb_args, returncode == 0))
+
+
+    def stop_profiling(self):
+        """ Stop profiling by sending SIGINT to simpleperf, and wait until it exits
+            to make sure perf.data is completely generated."""
+        has_killed = False
+        while True:
+            (result, _) = self.run_in_app_dir(['pidof', 'simpleperf'], check_result=False)
+            if not result:
+                break
+            if not has_killed:
+                has_killed = True
+                self.run_in_app_dir(['pkill', '-l', '2', 'simpleperf'], check_result=False)
+            time.sleep(1)
 
 
     def collect_profiling_data(self):
-        self.run_in_app_dir(['cat', 'perf.data'], self.config['perf_data_path'])
+        self.run_in_app_dir(['cat perf.data | tee /data/local/tmp/perf.data >/dev/null'])
+        self.adb.check_run_and_return_output(['pull', '/data/local/tmp/perf.data',
+                                              self.config['perf_data_path']])
         config = copy.copy(self.config)
         config['symfs_dirs'] = []
         if self.config['native_lib_dir']:
@@ -280,13 +308,20 @@
         binary_cache_builder.build_binary_cache()
 
 
-    def run_in_app_dir(self, args, stdout_file=None):
-        if self.is_root_device:
-            cmd = 'cd /data/data/' + self.config['app_package_name'] + ' && ' + (' '.join(args))
-            return self.adb.check_run_and_return_output(['shell', cmd], stdout_file)
+    def run_in_app_dir(self, args, stdout_file=None, check_result=True):
+        args = self.get_run_in_app_dir_args(args)
+        if check_result:
+            return self.adb.check_run_and_return_output(args, stdout_file)
         else:
-            return self.adb.check_run_and_return_output(
-                ['shell', 'run-as', self.config['app_package_name']] + args, stdout_file)
+            return self.adb.run_and_return_output(args, stdout_file)
+
+
+    def get_run_in_app_dir_args(self, args):
+        if self.is_root_device:
+            return ['shell', 'cd /data/data/' + self.config['app_package_name'] + ' && ' +
+                      (' '.join(args))]
+        else:
+            return ['shell', 'run-as', self.config['app_package_name']] + args
 
 
 if __name__ == '__main__':
diff --git a/simpleperf/scripts/bin/android/arm/simpleperf b/simpleperf/scripts/bin/android/arm/simpleperf
index 4bb1ef9..a2b1031 100755
--- a/simpleperf/scripts/bin/android/arm/simpleperf
+++ b/simpleperf/scripts/bin/android/arm/simpleperf
Binary files differ
diff --git a/simpleperf/scripts/bin/android/arm64/simpleperf b/simpleperf/scripts/bin/android/arm64/simpleperf
index 365a943..e50c357 100755
--- a/simpleperf/scripts/bin/android/arm64/simpleperf
+++ b/simpleperf/scripts/bin/android/arm64/simpleperf
Binary files differ
diff --git a/simpleperf/scripts/bin/android/x86/simpleperf b/simpleperf/scripts/bin/android/x86/simpleperf
index 6d77115..dd2cb09 100755
--- a/simpleperf/scripts/bin/android/x86/simpleperf
+++ b/simpleperf/scripts/bin/android/x86/simpleperf
Binary files differ
diff --git a/simpleperf/scripts/bin/android/x86_64/simpleperf b/simpleperf/scripts/bin/android/x86_64/simpleperf
index c31dc40..f3d955d 100755
--- a/simpleperf/scripts/bin/android/x86_64/simpleperf
+++ b/simpleperf/scripts/bin/android/x86_64/simpleperf
Binary files differ
diff --git a/simpleperf/scripts/bin/darwin/x86/libsimpleperf_report.dylib b/simpleperf/scripts/bin/darwin/x86/libsimpleperf_report.dylib
index cccfd9c..044364d 100755
--- a/simpleperf/scripts/bin/darwin/x86/libsimpleperf_report.dylib
+++ b/simpleperf/scripts/bin/darwin/x86/libsimpleperf_report.dylib
Binary files differ
diff --git a/simpleperf/scripts/bin/darwin/x86/simpleperf b/simpleperf/scripts/bin/darwin/x86/simpleperf
index a73138b..5e9bd0c 100755
--- a/simpleperf/scripts/bin/darwin/x86/simpleperf
+++ b/simpleperf/scripts/bin/darwin/x86/simpleperf
Binary files differ
diff --git a/simpleperf/scripts/bin/darwin/x86_64/libsimpleperf_report.dylib b/simpleperf/scripts/bin/darwin/x86_64/libsimpleperf_report.dylib
index a734c87..7f0c579 100755
--- a/simpleperf/scripts/bin/darwin/x86_64/libsimpleperf_report.dylib
+++ b/simpleperf/scripts/bin/darwin/x86_64/libsimpleperf_report.dylib
Binary files differ
diff --git a/simpleperf/scripts/bin/darwin/x86_64/simpleperf b/simpleperf/scripts/bin/darwin/x86_64/simpleperf
index 3ca9e1a..09ec4c5 100755
--- a/simpleperf/scripts/bin/darwin/x86_64/simpleperf
+++ b/simpleperf/scripts/bin/darwin/x86_64/simpleperf
Binary files differ
diff --git a/simpleperf/scripts/bin/linux/x86/libsimpleperf_report.so b/simpleperf/scripts/bin/linux/x86/libsimpleperf_report.so
index d79ed74..66a9be5 100755
--- a/simpleperf/scripts/bin/linux/x86/libsimpleperf_report.so
+++ b/simpleperf/scripts/bin/linux/x86/libsimpleperf_report.so
Binary files differ
diff --git a/simpleperf/scripts/bin/linux/x86/simpleperf b/simpleperf/scripts/bin/linux/x86/simpleperf
index 7459a3e..e836871 100755
--- a/simpleperf/scripts/bin/linux/x86/simpleperf
+++ b/simpleperf/scripts/bin/linux/x86/simpleperf
Binary files differ
diff --git a/simpleperf/scripts/bin/linux/x86_64/libsimpleperf_report.so b/simpleperf/scripts/bin/linux/x86_64/libsimpleperf_report.so
index 5f5671b..9bb449c 100755
--- a/simpleperf/scripts/bin/linux/x86_64/libsimpleperf_report.so
+++ b/simpleperf/scripts/bin/linux/x86_64/libsimpleperf_report.so
Binary files differ
diff --git a/simpleperf/scripts/bin/linux/x86_64/simpleperf b/simpleperf/scripts/bin/linux/x86_64/simpleperf
index 186cf1a..4537da4 100755
--- a/simpleperf/scripts/bin/linux/x86_64/simpleperf
+++ b/simpleperf/scripts/bin/linux/x86_64/simpleperf
Binary files differ
diff --git a/simpleperf/scripts/bin/windows/x86/libsimpleperf_report.dll b/simpleperf/scripts/bin/windows/x86/libsimpleperf_report.dll
index 1f985ed..6b33169 100755
--- a/simpleperf/scripts/bin/windows/x86/libsimpleperf_report.dll
+++ b/simpleperf/scripts/bin/windows/x86/libsimpleperf_report.dll
Binary files differ
diff --git a/simpleperf/scripts/bin/windows/x86/simpleperf.exe b/simpleperf/scripts/bin/windows/x86/simpleperf.exe
index 46822bd..820b874 100755
--- a/simpleperf/scripts/bin/windows/x86/simpleperf.exe
+++ b/simpleperf/scripts/bin/windows/x86/simpleperf.exe
Binary files differ
diff --git a/simpleperf/scripts/bin/windows/x86_64/libsimpleperf_report.dll b/simpleperf/scripts/bin/windows/x86_64/libsimpleperf_report.dll
index e774593..ab84253 100755
--- a/simpleperf/scripts/bin/windows/x86_64/libsimpleperf_report.dll
+++ b/simpleperf/scripts/bin/windows/x86_64/libsimpleperf_report.dll
Binary files differ
diff --git a/simpleperf/scripts/bin/windows/x86_64/simpleperf.exe b/simpleperf/scripts/bin/windows/x86_64/simpleperf.exe
index 46822bd..820b874 100755
--- a/simpleperf/scripts/bin/windows/x86_64/simpleperf.exe
+++ b/simpleperf/scripts/bin/windows/x86_64/simpleperf.exe
Binary files differ
diff --git a/simpleperf/scripts/report.py b/simpleperf/scripts/report.py
index 908b9e9..87a7c97 100644
--- a/simpleperf/scripts/report.py
+++ b/simpleperf/scripts/report.py
@@ -29,9 +29,14 @@
 import subprocess
 import sys
 
-from tkinter import *
-from tkinter.font import Font
-from tkinter.ttk import *
+try:
+    from tkinter import *
+    from tkinter.font import Font
+    from tkinter.ttk import *
+except ImportError:
+    from Tkinter import *
+    from tkFont import Font
+    from ttk import *
 
 from utils import *
 
@@ -190,7 +195,7 @@
     frame = Frame(master)
     frame.pack(fill=BOTH, expand=1)
 
-    font = Font(family='courier', size=10)
+    font = Font(family='courier', size=12)
 
     # Report Context
     for line in report_context:
diff --git a/tests/kernel.config/pstore_test.cpp b/tests/kernel.config/pstore_test.cpp
index 1dd5e72..29b8dff 100644
--- a/tests/kernel.config/pstore_test.cpp
+++ b/tests/kernel.config/pstore_test.cpp
@@ -23,7 +23,8 @@
 }
 
 TEST(kernel_config, CONFIG_PSTORE_CONSOLE) {
-  EXPECT_EQ(0, access("/sys/fs/pstore/console-ramoops", F_OK));
+  EXPECT_TRUE(!access("/sys/fs/pstore/console-ramoops-0", F_OK) ^
+              !access("/sys/fs/pstore/console-ramoops", F_OK));
 }
 
 TEST(kernel_config, CONFIG_PSTORE_PMSG) {