1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 #include <android/log.h>
19 #include <jni.h>
20 #include <sys/mman.h>
21 #include <unistd.h>
22 
23 #include <sstream>
24 #define LOG(...) __android_log_write(ANDROID_LOG_INFO, "ALLOC-STRESS", __VA_ARGS__)
25 
26 size_t s = 4 * (1 << 20); // 4 MB
27 volatile void *gptr;
28 extern "C" JNIEXPORT void JNICALL
Java_com_android_server_cts_device_statsdatom_MemoryHogger_allocate(JNIEnv *,jobject)29 Java_com_android_server_cts_device_statsdatom_MemoryHogger_allocate(JNIEnv *, jobject /* this */) {
30     volatile void *ptr;
31     long long allocCount = 0;
32     while (1) {
33         ptr = mmap(NULL, s, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
34         if (ptr == MAP_FAILED) {
35             // Likely exhausted address space
36             break;
37         }
38         memset((void *)ptr, (int)allocCount >> 10, s);
39         allocCount += s;
40         std::stringstream ss;
41         ss << "total alloc: " << allocCount / (1 << 20);
42         LOG(ss.str().c_str());
43         gptr = ptr;
44 
45         // If we are too aggressive allocating, we will end up triggering the
46         // OOM reaper instead of LMKd.
47         usleep(5000);
48     }
49 }
50