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 package android.os.cts;
18 
19 import android.app.Service;
20 import android.content.Intent;
21 import android.os.IBinder;
22 import android.os.RemoteException;
23 import android.os.SharedMemory;
24 import android.system.ErrnoException;
25 
26 import java.nio.ByteBuffer;
27 
28 public class SharedMemoryService extends Service {
29     @Override
onBind(Intent intent)30     public IBinder onBind(Intent intent) {
31         return new SharedMemoryServiceImpl();
32     }
33 
34     private static class SharedMemoryServiceImpl extends ISharedMemoryService.Stub {
35         private SharedMemory mSharedMemory;
36         private ByteBuffer mMappedBuffer;
37 
38         @Override
setup(SharedMemory memory, int prot)39         public void setup(SharedMemory memory, int prot) throws RemoteException {
40             mSharedMemory = memory;
41             try {
42                 mMappedBuffer = mSharedMemory.map(prot, 0, mSharedMemory.getSize());
43             } catch (ErrnoException ex) {
44                 throw new RuntimeException(ex);
45             }
46         }
47 
48         @Override
read(int index)49         public byte read(int index) throws RemoteException {
50             // Although we expect only one client we need to insert memory barriers to ensure
51             // visibility
52             synchronized (mMappedBuffer) {
53                 return mMappedBuffer.get(index);
54             }
55         }
56 
57         @Override
write(int index, byte value)58         public void write(int index, byte value) throws RemoteException {
59             // Although we expect only one client we need to insert memory barriers to ensure
60             // visibility
61             synchronized (mMappedBuffer) {
62                 mMappedBuffer.put(index, value);
63             }
64         }
65     }
66 }
67