Merge changes from topic "Alloc Stress Cert"

* changes:
  Add memory allocation stress test
  Memory allocation stress test app
diff --git a/AndroidTest.xml b/AndroidTest.xml
index fb9e17d..4abc3a4 100644
--- a/AndroidTest.xml
+++ b/AndroidTest.xml
@@ -26,5 +26,13 @@
       <option name="class" value="com.android.game.qualification.test.FunctionalTests" />
     </test>
 
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="test-file-name" value="GameQualificationAllocstress.apk" />
+        <option name="cleanup-apks" value="true" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.HostTest" >
+      <option name="class" value="com.android.game.qualification.test.MemoryTests" />
+    </test>
+
     <result_reporter class="com.android.game.qualification.reporter.GameQualificationResultReporter"/>
 </configuration>
diff --git a/alloc_stress_app/Android.mk b/alloc_stress_app/Android.mk
new file mode 100644
index 0000000..85dbc9e
--- /dev/null
+++ b/alloc_stress_app/Android.mk
@@ -0,0 +1,40 @@
+# Copyright 2018, 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SDK_VERSION := 26  # Oreo
+LOCAL_MODULE := libstress
+LOCAL_MODULE_TAGS := tests
+LOCAL_CPPFLAGS := -std=c++11
+LOCAL_SRC_FILES := src/cpp/alloc_stress_activity.cpp
+LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_NDK_STL_VARIANT := c++_static
+
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_SDK_VERSION := 26  # Oreo
+LOCAL_PACKAGE_NAME := GameQualificationAllocstress
+LOCAL_MODULE_TAGS := tests
+LOCAL_JNI_SHARED_LIBRARIES := libstress
+LOCAL_COMPATIBILITY_SUITE := device-tests
+LOCAL_SRC_FILES := $(call all-java-files-under, src/java)
+
+include $(BUILD_PACKAGE)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/alloc_stress_app/AndroidManifest.xml b/alloc_stress_app/AndroidManifest.xml
new file mode 100644
index 0000000..f380e31
--- /dev/null
+++ b/alloc_stress_app/AndroidManifest.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.game.qualification.allocstress">
+
+  <application
+      android:allowBackup="false"
+      android:label="AllocStressApp">
+    <activity android:name="com.android.game.qualification.allocstress.MainActivity" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+  </application>
+</manifest>
diff --git a/alloc_stress_app/src/cpp/alloc_stress_activity.cpp b/alloc_stress_app/src/cpp/alloc_stress_activity.cpp
new file mode 100644
index 0000000..cb0feb9
--- /dev/null
+++ b/alloc_stress_app/src/cpp/alloc_stress_activity.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2010 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 <jni.h>
+#include <iostream>
+#include <tuple>
+#include <algorithm>
+#include <numeric>
+#include <string>
+#include <sstream>
+#include <cstring>
+#include <fstream>
+
+#include <android/log.h>
+#define LOG(...) __android_log_write(ANDROID_LOG_INFO, "ALLOC-STRESS",__VA_ARGS__)
+
+using namespace std;
+
+size_t s = 4 * (1 << 20); // 4 MB
+extern "C"
+JNIEXPORT void JNICALL
+Java_com_android_game_qualification_allocstress_MainActivity_cmain(JNIEnv* , jobject /* this */)
+{
+
+    long long allocCount = 0;
+    while (1) {
+        char *ptr = (char *) malloc(s);
+        memset(ptr, (int) allocCount >> 10, s);
+        std::stringstream ss;
+        ss << "total alloc: " << (allocCount >> 20) << endl;
+        LOG(ss.str().c_str());
+        allocCount += s;
+    }
+}
diff --git a/alloc_stress_app/src/java/com/android/game/qualification/allocstress/MainActivity.java b/alloc_stress_app/src/java/com/android/game/qualification/allocstress/MainActivity.java
new file mode 100644
index 0000000..26c11b1
--- /dev/null
+++ b/alloc_stress_app/src/java/com/android/game/qualification/allocstress/MainActivity.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+package com.android.game.qualification.allocstress;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class MainActivity extends Activity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        new Thread(new Runnable() {
+            public void run() {
+                cmain();
+            }
+        }).start();
+
+    }
+
+    public native void cmain();
+
+    static {
+        System.loadLibrary("stress");
+    }
+}
diff --git a/hostside/src/com/android/game/qualification/metric/MetricSummary.java b/hostside/src/com/android/game/qualification/metric/MetricSummary.java
index ec611e6..b02188a 100644
--- a/hostside/src/com/android/game/qualification/metric/MetricSummary.java
+++ b/hostside/src/com/android/game/qualification/metric/MetricSummary.java
@@ -64,7 +64,11 @@
     @Nullable
     public static MetricSummary parseRunMetrics(
             IInvocationContext context, HashMap<String, Metric> metrics) {
-        int loopCount = (int) metrics.get("loop_count").getMeasurements().getSingleInt();
+        int loopCount = 0;
+        if (metrics.containsKey("loop_count")) {
+            loopCount = (int) metrics.get("loop_count").getMeasurements().getSingleInt();
+        }
+
         if (loopCount == 0) {
             return null;
         }
diff --git a/hostside/src/com/android/game/qualification/reporter/GameQualificationResultReporter.java b/hostside/src/com/android/game/qualification/reporter/GameQualificationResultReporter.java
index 3875f94..b4bd61c 100644
--- a/hostside/src/com/android/game/qualification/reporter/GameQualificationResultReporter.java
+++ b/hostside/src/com/android/game/qualification/reporter/GameQualificationResultReporter.java
@@ -56,6 +56,7 @@
     private List<Throwable> invocationFailures = new ArrayList<>();
     private List<LogFile> mLogFiles = new ArrayList<>();
     private ILogSaver mLogSaver;
+    private int mTotalAllocated = 0;
 
     public void putRequirements(TestDescription testId, CertificationRequirements requirements) {
         mRequirements.put(testId, requirements);
@@ -66,7 +67,6 @@
         super.invocationFailed(cause);
         invocationFailures.add(cause);
     }
-
     /**
      * Collect metrics produces by
      * {@link GameQualificationFpsCollector}.
@@ -75,10 +75,12 @@
     public void testEnded(TestDescription testId, long elapsedTime, HashMap<String, Metric> metrics) {
         super.testEnded(testId, elapsedTime, metrics);
         if (!metrics.isEmpty()) {
-            MetricSummary summary = MetricSummary.parseRunMetrics(getInvocationContext(), metrics);
-            if (summary != null) {
-                summaries.put(testId, summary);
-            }
+                MetricSummary summary = MetricSummary.parseRunMetrics(getInvocationContext(), metrics);
+                if (summary != null) {
+                    summaries.put(testId, summary);
+                } else if (metrics.containsKey("memory_allocated")) {
+                    mTotalAllocated = (int) metrics.get("memory_allocated").getMeasurements().getSingleInt();
+                }
         }
     }
 
@@ -158,6 +160,11 @@
             sb.append(String.format("\n%s Metrics:\n%s\n", entry.getKey(), entry.getValue()));
         }
 
+        // Print memory allocation metrics
+        sb.append("Total Memory Allocated During Allocation Stress Test: ");
+        sb.append(mTotalAllocated);
+        sb.append("\n\n");
+
         // Determine certification level.
         sb.append("Certification:\n");
 
diff --git a/hostside/src/com/android/game/qualification/test/MemoryTests.java b/hostside/src/com/android/game/qualification/test/MemoryTests.java
new file mode 100644
index 0000000..00bacdb
--- /dev/null
+++ b/hostside/src/com/android/game/qualification/test/MemoryTests.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+
+package com.android.game.qualification.test;
+
+import org.junit.runner.RunWith;
+import org.junit.Test;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner.TestMetrics;
+import com.android.tradefed.metrics.proto.MetricMeasurement.DataType;
+import com.android.tradefed.metrics.proto.MetricMeasurement.Measurements;
+import com.android.tradefed.metrics.proto.MetricMeasurement.Metric;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.NativeDevice;
+import com.android.tradefed.result.InputStreamSource;
+import com.android.tradefed.log.LogUtil.CLog;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import org.junit.Rule;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class MemoryTests extends BaseHostJUnit4Test {
+
+     @Rule
+     public TestMetrics metrics = new TestMetrics();
+
+    @Test
+    public void testMemoryAllocationLimit()
+        throws DeviceNotAvailableException, IOException {
+            getDevice().startLogcat();
+            getDevice().clearLogcat();
+
+            String pkgname = "com.android.game.qualification.allocstress";
+            String actname = pkgname + ".MainActivity";
+            getDevice().executeShellCommand("am start -W " + pkgname + "/" + actname);
+
+            // Wait until app is finished.
+            while((getDevice().executeShellCommand("dumpsys activity | grep top-activity")).contains("allocstress"));
+
+            boolean hasAllocStats = false;
+            int totalAllocated = 0;
+
+            try (
+                InputStreamSource logcatSource = getDevice().getLogcat();
+                BufferedReader logcat = new BufferedReader(new InputStreamReader(logcatSource.createInputStream()));
+            ) {
+
+                String s = logcat.readLine();
+                String pattern = "total alloc: ";
+                String p = null;
+                while (s != null) {
+                    if (s.contains(pattern)) {
+                        hasAllocStats = true;
+                        p = s;
+                    }
+                    s = logcat.readLine();
+                }
+                int totalAllocIndex = p.indexOf(pattern) + pattern.length();
+                totalAllocated = Integer.parseInt(p.substring(totalAllocIndex));
+
+            }
+
+            getDevice().stopLogcat();
+
+            assertTrue(hasAllocStats);
+            metrics.addTestMetric("memory_allocated", Metric.newBuilder()
+                                                            .setType(DataType.RAW)
+                                                            .setMeasurements(Measurements.newBuilder().setSingleInt(totalAllocated))
+                                                            .build());
+            assertTrue("Device failed to allocate an appropriate amount of memory (2.3GB) before being killed", totalAllocated > 2300);
+    }
+
+}