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 <brillo/binder_watcher.h>
18 
19 #include <base/bind.h>
20 #include <base/logging.h>
21 #include <binder/IPCThreadState.h>
22 #include <binder/ProcessState.h>
23 
24 using android::IPCThreadState;
25 using android::ProcessState;
26 
27 namespace {
28 // Called from the message loop whenever the binder file descriptor is ready.
OnBinderReadReady()29 void OnBinderReadReady() {
30   IPCThreadState::self()->handlePolledCommands();
31 }
32 }  // namespace
33 
34 namespace brillo {
35 
36 BinderWatcher::BinderWatcher() = default;
37 
38 BinderWatcher::~BinderWatcher() = default;
39 
Init()40 bool BinderWatcher::Init() {
41   int binder_fd = -1;
42   ProcessState::self()->setThreadPoolMaxThreadCount(0);
43   IPCThreadState::self()->disableBackgroundScheduling(true);
44   int err = IPCThreadState::self()->setupPolling(&binder_fd);
45   if (err != 0) {
46     LOG(ERROR) << "Error setting up binder polling: "
47                << logging::SystemErrorCodeToString(err);
48     return false;
49   }
50   if (binder_fd < 0) {
51     LOG(ERROR) << "Invalid binder FD " << binder_fd;
52     return false;
53   }
54   VLOG(1) << "Got binder FD " << binder_fd;
55 
56   watcher_ = base::FileDescriptorWatcher::WatchReadable(
57       binder_fd,
58       base::BindRepeating(&OnBinderReadReady));
59   if (!watcher_) {
60     LOG(ERROR) << "Failed to watch binder FD";
61     return false;
62   }
63   return true;
64 }
65 
66 }  // namespace brillo
67