Home | History | Annotate | Download | only in shared
      1 /*
      2  * Copyright (C) 2017 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 #include "chre/platform/memory_manager.h"
     18 
     19 #include "chre/util/system/debug_dump.h"
     20 
     21 namespace chre {
     22 
     23 void *MemoryManager::nanoappAlloc(Nanoapp *app, uint32_t bytes) {
     24   AllocHeader *header = nullptr;
     25   if (bytes > 0) {
     26     if (mAllocationCount >= kMaxAllocationCount) {
     27       LOGE("Failed to allocate memory from Nanoapp ID %" PRIu32
     28            ": allocation count exceeded limit.", app->getInstanceId());
     29     } else if ((mTotalAllocatedBytes + bytes) > kMaxAllocationBytes) {
     30       LOGE("Failed to allocate memory from Nanoapp ID %" PRIu32
     31            ": not enough space.", app->getInstanceId());
     32     } else {
     33       header = static_cast<AllocHeader*>(
     34           doAlloc(app, sizeof(AllocHeader) + bytes));
     35 
     36       if (header != nullptr) {
     37         mTotalAllocatedBytes += bytes;
     38         mAllocationCount++;
     39         header->data.bytes = bytes;
     40         header->data.instanceId = app->getInstanceId();
     41         header++;
     42       }
     43     }
     44   }
     45   return header;
     46 }
     47 
     48 void MemoryManager::nanoappFree(Nanoapp *app, void *ptr) {
     49   if (ptr != nullptr) {
     50     AllocHeader *header = static_cast<AllocHeader*>(ptr);
     51     header--;
     52 
     53     if (mTotalAllocatedBytes >= header->data.bytes) {
     54       mTotalAllocatedBytes -= header->data.bytes;
     55     } else {
     56       mTotalAllocatedBytes = 0;
     57     }
     58     if (mAllocationCount > 0) {
     59       mAllocationCount--;
     60     }
     61 
     62     doFree(app, header);
     63   }
     64 }
     65 
     66 bool MemoryManager::logStateToBuffer(char *buffer, size_t *bufferPos,
     67                                      size_t bufferSize) const {
     68   return debugDumpPrint(buffer, bufferPos, bufferSize,
     69                         "\nNanoapp heap usage: %zu bytes allocated, count %zu\n",
     70                         getTotalAllocatedBytes(), getAllocationCount());
     71 }
     72 
     73 }  // namespace chre
     74