1/*
2 * Copyright (C) 2015 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 <map>
18#include <sstream>
19#include <string>
20#include <vector>
21
22#include <unistd.h>
23
24#include <android-base/unique_fd.h>
25#include <binder/IInterface.h>
26#include <binder/IPCThreadState.h>
27#include <binder/IServiceManager.h>
28#include <binder/ProcessState.h>
29#include <binder/Status.h>
30#include <binder/Value.h>
31#include <utils/Errors.h>
32#include <utils/Log.h>
33#include <utils/Looper.h>
34#include <utils/StrongPointer.h>
35
36#include "android/aidl/tests/BnTestService.h"
37#include "android/aidl/tests/ITestService.h"
38
39#include "android/aidl/tests/BnNamedCallback.h"
40#include "android/aidl/tests/INamedCallback.h"
41
42// Used implicitly.
43#undef LOG_TAG
44#define LOG_TAG "aidl_native_service"
45
46// libbase
47using android::base::unique_fd;
48
49// libutils:
50using android::Looper;
51using android::LooperCallback;
52using android::OK;
53using android::sp;
54using android::String16;
55
56// libbinder:
57using android::BnInterface;
58using android::defaultServiceManager;
59using android::IInterface;
60using android::IPCThreadState;
61using android::Parcel;
62using android::ProcessState;
63using android::binder::Status;
64
65// Generated code:
66using android::aidl::tests::BnNamedCallback;
67using android::aidl::tests::BnTestService;
68using android::aidl::tests::INamedCallback;
69using android::aidl::tests::SimpleParcelable;
70using android::os::PersistableBundle;
71using android::binder::Map;
72
73// Standard library
74using std::map;
75using std::string;
76using std::unique_ptr;
77using std::vector;
78
79namespace {
80
81class BinderCallback : public LooperCallback {
82 public:
83  BinderCallback() {}
84  ~BinderCallback() override {}
85
86  int handleEvent(int /* fd */, int /* events */, void* /* data */) override {
87    IPCThreadState::self()->handlePolledCommands();
88    return 1;  // Continue receiving callbacks.
89  }
90};
91
92class NamedCallback : public BnNamedCallback {
93 public:
94  explicit NamedCallback(String16 name) : name_(name) {}
95
96  Status GetName(String16* ret) {
97    *ret = name_;
98    return Status::ok();
99  }
100
101 private:
102  String16 name_;
103};
104
105class NativeService : public BnTestService {
106 public:
107  NativeService() {}
108  virtual ~NativeService() = default;
109
110  void LogRepeatedStringToken(const String16& token) {
111    ALOGI("Repeating '%s' of length=%zu", android::String8(token).string(),
112          token.size());
113  }
114
115  template <typename T>
116  void LogRepeatedToken(const T& token) {
117    std::ostringstream token_str;
118    token_str << token;
119    ALOGI("Repeating token %s", token_str.str().c_str());
120  }
121
122  void LogRepeatedMapToken(const Map& token) {
123    ALOGI("Repeating Map with %d elements", (int)token.size());
124  }
125
126  Status RepeatBoolean(bool token, bool* _aidl_return) override {
127    LogRepeatedToken(token ? 1 : 0);
128    *_aidl_return = token;
129    return Status::ok();
130  }
131  Status RepeatByte(int8_t token, int8_t* _aidl_return) override {
132    LogRepeatedToken(token);
133    *_aidl_return = token;
134    return Status::ok();
135  }
136  Status RepeatChar(char16_t token, char16_t* _aidl_return) override {
137    LogRepeatedStringToken(String16(&token, 1));
138    *_aidl_return = token;
139    return Status::ok();
140  }
141  Status RepeatInt(int32_t token, int32_t* _aidl_return) override {
142    LogRepeatedToken(token);
143    *_aidl_return = token;
144    return Status::ok();
145  }
146  Status RepeatLong(int64_t token, int64_t* _aidl_return) override {
147    LogRepeatedToken(token);
148    *_aidl_return = token;
149    return Status::ok();
150  }
151  Status RepeatFloat(float token, float* _aidl_return) override {
152    LogRepeatedToken(token);
153    *_aidl_return = token;
154    return Status::ok();
155  }
156  Status RepeatDouble(double token, double* _aidl_return) override {
157    LogRepeatedToken(token);
158    *_aidl_return = token;
159    return Status::ok();
160  }
161  Status RepeatString(const String16& token, String16* _aidl_return) override {
162    LogRepeatedStringToken(token);
163    *_aidl_return = token;
164    return Status::ok();
165  }
166  Status RepeatMap(const Map& token, Map* _aidl_return) override {
167    LogRepeatedMapToken(token);
168    *_aidl_return = token;
169    return Status::ok();
170  }
171
172  Status RepeatSimpleParcelable(const SimpleParcelable& input,
173                                SimpleParcelable* repeat,
174                                SimpleParcelable* _aidl_return) override {
175    ALOGI("Repeated a SimpleParcelable %s", input.toString().c_str());
176    *repeat = input;
177    *_aidl_return = input;
178    return Status::ok();
179  }
180
181  Status RepeatPersistableBundle(const PersistableBundle& input,
182                                 PersistableBundle* _aidl_return) override {
183    ALOGI("Repeated a PersistableBundle");
184    *_aidl_return = input;
185    return Status::ok();
186  }
187
188  template <typename T>
189  Status ReverseArray(const vector<T>& input, vector<T>* repeated,
190                      vector<T>* _aidl_return) {
191    ALOGI("Reversing array of length %zu", input.size());
192    *repeated = input;
193    *_aidl_return = input;
194    std::reverse(_aidl_return->begin(), _aidl_return->end());
195    return Status::ok();
196  }
197
198  template<typename T>
199  Status RepeatNullable(const unique_ptr<T>& input,
200                        unique_ptr<T>* _aidl_return) {
201    ALOGI("Repeating nullable value");
202
203    _aidl_return->reset();
204    if (input) {
205      _aidl_return->reset(new T(*input));
206    }
207
208    return Status::ok();
209  }
210
211  Status ReverseBoolean(const vector<bool>& input,
212                        vector<bool>* repeated,
213                        vector<bool>* _aidl_return) override {
214    return ReverseArray(input, repeated, _aidl_return);
215  }
216  Status ReverseByte(const vector<uint8_t>& input,
217                     vector<uint8_t>* repeated,
218                     vector<uint8_t>* _aidl_return) override {
219    return ReverseArray(input, repeated, _aidl_return);
220  }
221  Status ReverseChar(const vector<char16_t>& input,
222                     vector<char16_t>* repeated,
223                     vector<char16_t>* _aidl_return) override {
224    return ReverseArray(input, repeated, _aidl_return);
225  }
226  Status ReverseInt(const vector<int32_t>& input,
227                    vector<int32_t>* repeated,
228                    vector<int32_t>* _aidl_return) override {
229    return ReverseArray(input, repeated, _aidl_return);
230  }
231  Status ReverseLong(const vector<int64_t>& input,
232                     vector<int64_t>* repeated,
233                     vector<int64_t>* _aidl_return) override {
234    return ReverseArray(input, repeated, _aidl_return);
235  }
236  Status ReverseFloat(const vector<float>& input,
237                      vector<float>* repeated,
238                      vector<float>* _aidl_return) override {
239    return ReverseArray(input, repeated, _aidl_return);
240  }
241  Status ReverseDouble(const vector<double>& input,
242                       vector<double>* repeated,
243                       vector<double>* _aidl_return) override {
244    return ReverseArray(input, repeated, _aidl_return);
245  }
246  Status ReverseString(const vector<String16>& input,
247                       vector<String16>* repeated,
248                       vector<String16>* _aidl_return) override {
249    return ReverseArray(input, repeated, _aidl_return);
250  }
251  Status ReverseSimpleParcelables(
252      const vector<SimpleParcelable>& input,
253      vector<SimpleParcelable>* repeated,
254      vector<SimpleParcelable>* _aidl_return) override {
255    return ReverseArray(input, repeated, _aidl_return);
256  }
257  Status ReversePersistableBundles(
258      const vector<PersistableBundle>& input,
259      vector<PersistableBundle>* repeated,
260      vector<PersistableBundle>* _aidl_return) override {
261    return ReverseArray(input, repeated, _aidl_return);
262  }
263
264  Status GetOtherTestService(const String16& name,
265                             sp<INamedCallback>* returned_service) override {
266    if (service_map_.find(name) == service_map_.end()) {
267      sp<INamedCallback> new_item(new NamedCallback(name));
268      service_map_[name] = new_item;
269    }
270
271    *returned_service = service_map_[name];
272    return Status::ok();
273  }
274
275  Status VerifyName(const sp<INamedCallback>& service, const String16& name,
276                    bool* returned_value) override {
277    String16 foundName;
278    Status status = service->GetName(&foundName);
279
280    if (status.isOk()) {
281      *returned_value = foundName == name;
282    }
283
284    return status;
285  }
286
287  Status ReverseStringList(const vector<String16>& input,
288                           vector<String16>* repeated,
289                           vector<String16>* _aidl_return) override {
290    return ReverseArray(input, repeated, _aidl_return);
291  }
292
293  Status ReverseNamedCallbackList(const vector<sp<IBinder>>& input,
294                                  vector<sp<IBinder>>* repeated,
295                                  vector<sp<IBinder>>* _aidl_return) override {
296    return ReverseArray(input, repeated, _aidl_return);
297  }
298
299  Status RepeatFileDescriptor(const unique_fd& read,
300                              unique_fd* _aidl_return) override {
301    ALOGE("Repeating file descriptor");
302    *_aidl_return = unique_fd(dup(read.get()));
303    return Status::ok();
304  }
305
306  Status ReverseFileDescriptorArray(const vector<unique_fd>& input,
307                                    vector<unique_fd>* repeated,
308                                    vector<unique_fd>* _aidl_return) override {
309    ALOGI("Reversing descriptor array of length %zu", input.size());
310    for (const auto& item : input) {
311      repeated->push_back(unique_fd(dup(item.get())));
312      _aidl_return->push_back(unique_fd(dup(item.get())));
313    }
314    std::reverse(_aidl_return->begin(), _aidl_return->end());
315    return Status::ok();
316  }
317
318  Status ThrowServiceException(int code) override {
319    return Status::fromServiceSpecificError(code);
320  }
321
322  Status RepeatNullableIntArray(const unique_ptr<vector<int32_t>>& input,
323                                unique_ptr<vector<int32_t>>* _aidl_return) {
324    return RepeatNullable(input, _aidl_return);
325  }
326
327  Status RepeatNullableStringList(
328             const unique_ptr<vector<unique_ptr<String16>>>& input,
329             unique_ptr<vector<unique_ptr<String16>>>* _aidl_return) {
330    ALOGI("Repeating nullable string list");
331    if (!input) {
332      _aidl_return->reset();
333      return Status::ok();
334    }
335
336    _aidl_return->reset(new vector<unique_ptr<String16>>);
337
338    for (const auto& item : *input) {
339      if (!item) {
340        (*_aidl_return)->emplace_back(nullptr);
341      } else {
342        (*_aidl_return)->emplace_back(new String16(*item));
343      }
344    }
345
346    return Status::ok();
347  }
348
349  Status RepeatNullableString(const unique_ptr<String16>& input,
350                              unique_ptr<String16>* _aidl_return) {
351    return RepeatNullable(input, _aidl_return);
352  }
353
354  Status RepeatNullableParcelable(const unique_ptr<SimpleParcelable>& input,
355                              unique_ptr<SimpleParcelable>* _aidl_return) {
356    return RepeatNullable(input, _aidl_return);
357  }
358
359  Status TakesAnIBinder(const sp<IBinder>& input) override {
360    (void)input;
361    return Status::ok();
362  }
363  Status TakesAnIBinderList(const vector<sp<IBinder>>& input) override {
364    (void)input;
365    return Status::ok();
366  }
367  Status TakesANullableIBinder(const sp<IBinder>& input) {
368    (void)input;
369    return Status::ok();
370  }
371  Status TakesANullableIBinderList(const unique_ptr<vector<sp<IBinder>>>& input) {
372    (void)input;
373    return Status::ok();
374  }
375
376  Status RepeatUtf8CppString(const string& token,
377                             string* _aidl_return) override {
378    ALOGI("Repeating utf8 string '%s' of length=%zu", token.c_str(), token.size());
379    *_aidl_return = token;
380    return Status::ok();
381  }
382
383  Status RepeatNullableUtf8CppString(
384      const unique_ptr<string>& token,
385      unique_ptr<string>* _aidl_return) override {
386    if (!token) {
387      ALOGI("Received null @utf8InCpp string");
388      return Status::ok();
389    }
390    ALOGI("Repeating utf8 string '%s' of length=%zu",
391          token->c_str(), token->size());
392    _aidl_return->reset(new string(*token));
393    return Status::ok();
394  }
395
396  Status ReverseUtf8CppString(const vector<string>& input,
397                              vector<string>* repeated,
398                              vector<string>* _aidl_return) {
399    return ReverseArray(input, repeated, _aidl_return);
400  }
401
402  Status ReverseUtf8CppStringList(
403      const unique_ptr<vector<unique_ptr<::string>>>& input,
404      unique_ptr<vector<unique_ptr<string>>>* repeated,
405      unique_ptr<vector<unique_ptr<string>>>* _aidl_return) {
406    if (!input) {
407      ALOGI("Received null list of utf8 strings");
408      return Status::ok();
409    }
410    _aidl_return->reset(new vector<unique_ptr<string>>);
411    repeated->reset(new vector<unique_ptr<string>>);
412
413    for (const auto& item : *input) {
414      (*repeated)->emplace_back(nullptr);
415      (*_aidl_return)->emplace_back(nullptr);
416      if (item) {
417        (*repeated)->back().reset(new string(*item));
418        (*_aidl_return)->back().reset(new string(*item));
419      }
420    }
421    std::reverse((*_aidl_return)->begin(), (*_aidl_return)->end());
422
423    return Status::ok();
424  }
425
426  Status GetCallback(bool return_null, sp<INamedCallback>* ret) {
427    if (!return_null) {
428      return GetOtherTestService(String16("ABT: always be testing"), ret);
429    }
430    return Status::ok();
431  }
432
433 private:
434  map<String16, sp<INamedCallback>> service_map_;
435};
436
437int Run() {
438  android::sp<NativeService> service = new NativeService;
439  sp<Looper> looper(Looper::prepare(0 /* opts */));
440
441  int binder_fd = -1;
442  ProcessState::self()->setThreadPoolMaxThreadCount(0);
443  IPCThreadState::self()->disableBackgroundScheduling(true);
444  IPCThreadState::self()->setupPolling(&binder_fd);
445  ALOGI("Got binder FD %d", binder_fd);
446  if (binder_fd < 0) return -1;
447
448  sp<BinderCallback> cb(new BinderCallback);
449  if (looper->addFd(binder_fd, Looper::POLL_CALLBACK, Looper::EVENT_INPUT, cb,
450                    nullptr) != 1) {
451    ALOGE("Failed to add binder FD to Looper");
452    return -1;
453  }
454
455  defaultServiceManager()->addService(service->getInterfaceDescriptor(),
456                                      service);
457
458  ALOGI("Entering loop");
459  while (true) {
460    const int result = looper->pollAll(-1 /* timeoutMillis */);
461    ALOGI("Looper returned %d", result);
462  }
463  return 0;
464}
465
466}  // namespace
467
468int main(int /* argc */, char* /* argv */ []) {
469  return Run();
470}
471