1 /*
2  * Copyright 2019 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 //#define LOG_NDEBUG 0
18 #define LOG_TAG "MediaPlayerService-DeathNotifier"
19 #include <android-base/logging.h>
20 
21 #include "DeathNotifier.h"
22 
23 namespace android {
24 
25 class DeathNotifier::DeathRecipient :
26         public IBinder::DeathRecipient,
27         public hardware::hidl_death_recipient {
28 public:
29     using Notify = DeathNotifier::Notify;
30 
DeathRecipient(Notify const & notify)31     DeathRecipient(Notify const& notify): mNotify{notify} {
32     }
33 
binderDied(wp<IBinder> const &)34     virtual void binderDied(wp<IBinder> const&) override {
35         mNotify();
36     }
37 
serviceDied(uint64_t,wp<HBase> const &)38     virtual void serviceDied(uint64_t, wp<HBase> const&) override {
39         mNotify();
40     }
41 
42 private:
43     Notify mNotify;
44 };
45 
DeathNotifier(sp<IBinder> const & service,Notify const & notify)46 DeathNotifier::DeathNotifier(sp<IBinder> const& service, Notify const& notify)
47       : mService{std::in_place_index<1>, service},
48         mDeathRecipient{new DeathRecipient(notify)} {
49     service->linkToDeath(mDeathRecipient);
50 }
51 
DeathNotifier(sp<HBase> const & service,Notify const & notify)52 DeathNotifier::DeathNotifier(sp<HBase> const& service, Notify const& notify)
53       : mService{std::in_place_index<2>, service},
54         mDeathRecipient{new DeathRecipient(notify)} {
55     service->linkToDeath(mDeathRecipient, 0);
56 }
57 
DeathNotifier(DeathNotifier && other)58 DeathNotifier::DeathNotifier(DeathNotifier&& other)
59       : mService{other.mService}, mDeathRecipient{other.mDeathRecipient} {
60     other.mService.emplace<0>();
61     other.mDeathRecipient = nullptr;
62 }
63 
~DeathNotifier()64 DeathNotifier::~DeathNotifier() {
65     switch (mService.index()) {
66     case 0:
67         break;
68     case 1:
69         std::get<1>(mService)->unlinkToDeath(mDeathRecipient);
70         break;
71     case 2:
72         std::get<2>(mService)->unlinkToDeath(mDeathRecipient);
73         break;
74     default:
75         CHECK(false) << "Corrupted service type during destruction.";
76     }
77 }
78 
79 } // namespace android
80 
81