Home | History | Annotate | Download | only in runtime
      1 /*
      2  * Copyright (C) 2011 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 "memory_region.h"
     18 
     19 #include <stdint.h>
     20 #include <string.h>
     21 
     22 namespace art {
     23 
     24 void MemoryRegion::CopyFrom(size_t offset, const MemoryRegion& from) const {
     25   CHECK(from.pointer() != nullptr);
     26   CHECK_GT(from.size(), 0U);
     27   CHECK_GE(this->size(), from.size());
     28   CHECK_LE(offset, this->size() - from.size());
     29   memmove(reinterpret_cast<void*>(begin() + offset), from.pointer(), from.size());
     30 }
     31 
     32 void MemoryRegion::StoreBits(uintptr_t bit_offset, uint32_t value, size_t length) {
     33   DCHECK_LE(value, MaxInt<uint32_t>(length));
     34   DCHECK_LE(length, BitSizeOf<uint32_t>());
     35   DCHECK_LE(bit_offset + length, size_in_bits());
     36   if (length == 0) {
     37     return;
     38   }
     39   // Bits are stored in this order {7 6 5 4 3 2 1 0}.
     40   // How many remaining bits in current byte is (bit_offset % kBitsPerByte) + 1.
     41   uint8_t* out = ComputeInternalPointer<uint8_t>(bit_offset >> kBitsPerByteLog2);
     42   size_t orig_len = length;
     43   uint32_t orig_value = value;
     44   uintptr_t bit_remainder = bit_offset % kBitsPerByte;
     45   while (true) {
     46     const uintptr_t remaining_bits = kBitsPerByte - bit_remainder;
     47     if (length <= remaining_bits) {
     48       // Length is smaller than all of remainder bits.
     49       size_t mask = ((1 << length) - 1) << bit_remainder;
     50       *out = (*out & ~mask) | (value << bit_remainder);
     51       break;
     52     }
     53     // Copy remaining bits in current byte.
     54     size_t value_mask = (1 << remaining_bits) - 1;
     55     *out = (*out & ~(value_mask << bit_remainder)) | ((value & value_mask) << bit_remainder);
     56     value >>= remaining_bits;
     57     bit_remainder = 0;
     58     length -= remaining_bits;
     59     ++out;
     60   }
     61   DCHECK_EQ(LoadBits(bit_offset, orig_len), orig_value) << bit_offset << " " << orig_len;
     62 }
     63 
     64 }  // namespace art
     65