1 /* 2 * Copyright 2016 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 #pragma once 18 19 #include <binder/Common.h> 20 #include <binder/IInterface.h> 21 #include <binder/Parcel.h> 22 23 // Set to 1 to enable CallStacks when logging errors 24 #define SI_DUMP_CALLSTACKS 0 25 #if SI_DUMP_CALLSTACKS 26 #include <utils/CallStack.h> 27 #endif 28 29 #include <utils/NativeHandle.h> 30 31 #include <functional> 32 #include <type_traits> 33 34 namespace android { 35 namespace SafeInterface { 36 37 /** 38 * WARNING: Prefer to use AIDL-generated interfaces. Using SafeInterface to generate interfaces 39 * does not support tracing, and many other AIDL features out of the box. The general direction 40 * we should go is to migrate safe interface users to AIDL and then remove this so that there 41 * is only one thing to learn/use/test/integrate, not this as well. 42 */ 43 44 // ParcelHandler is responsible for writing/reading various types to/from a Parcel in a generic way 45 class LIBBINDER_EXPORTED ParcelHandler { 46 public: ParcelHandler(const char * logTag)47 explicit ParcelHandler(const char* logTag) : mLogTag(logTag) {} 48 49 // Specializations for types with dedicated handling in Parcel read(const Parcel & parcel,bool * b)50 status_t read(const Parcel& parcel, bool* b) const { 51 return callParcel("readBool", [&]() { return parcel.readBool(b); }); 52 } write(Parcel * parcel,bool b)53 status_t write(Parcel* parcel, bool b) const { 54 return callParcel("writeBool", [&]() { return parcel->writeBool(b); }); 55 } 56 template <typename E> read(const Parcel & parcel,E * e)57 typename std::enable_if<std::is_enum<E>::value, status_t>::type read(const Parcel& parcel, 58 E* e) const { 59 typename std::underlying_type<E>::type u{}; 60 status_t result = read(parcel, &u); 61 *e = static_cast<E>(u); 62 return result; 63 } 64 template <typename E> write(Parcel * parcel,E e)65 typename std::enable_if<std::is_enum<E>::value, status_t>::type write(Parcel* parcel, 66 E e) const { 67 return write(parcel, static_cast<typename std::underlying_type<E>::type>(e)); 68 } 69 template <typename T> read(const Parcel & parcel,T * t)70 typename std::enable_if<std::is_base_of<Flattenable<T>, T>::value, status_t>::type read( 71 const Parcel& parcel, T* t) const { 72 return callParcel("read(Flattenable)", [&]() { return parcel.read(*t); }); 73 } 74 template <typename T> write(Parcel * parcel,const T & t)75 typename std::enable_if<std::is_base_of<Flattenable<T>, T>::value, status_t>::type write( 76 Parcel* parcel, const T& t) const { 77 return callParcel("write(Flattenable)", [&]() { return parcel->write(t); }); 78 } 79 template <typename T> read(const Parcel & parcel,sp<T> * t)80 typename std::enable_if<std::is_base_of<Flattenable<T>, T>::value, status_t>::type read( 81 const Parcel& parcel, sp<T>* t) const { 82 *t = sp<T>::make(); 83 return callParcel("read(sp<Flattenable>)", [&]() { return parcel.read(*(t->get())); }); 84 } 85 template <typename T> write(Parcel * parcel,const sp<T> & t)86 typename std::enable_if<std::is_base_of<Flattenable<T>, T>::value, status_t>::type write( 87 Parcel* parcel, const sp<T>& t) const { 88 return callParcel("write(sp<Flattenable>)", [&]() { return parcel->write(*(t.get())); }); 89 } 90 template <typename T> read(const Parcel & parcel,T * t)91 typename std::enable_if<std::is_base_of<LightFlattenable<T>, T>::value, status_t>::type read( 92 const Parcel& parcel, T* t) const { 93 return callParcel("read(LightFlattenable)", [&]() { return parcel.read(*t); }); 94 } 95 template <typename T> write(Parcel * parcel,const T & t)96 typename std::enable_if<std::is_base_of<LightFlattenable<T>, T>::value, status_t>::type write( 97 Parcel* parcel, const T& t) const { 98 return callParcel("write(LightFlattenable)", [&]() { return parcel->write(t); }); 99 } 100 template <typename NH> read(const Parcel & parcel,NH * nh)101 typename std::enable_if<std::is_same<NH, sp<NativeHandle>>::value, status_t>::type read( 102 const Parcel& parcel, NH* nh) { 103 *nh = NativeHandle::create(parcel.readNativeHandle(), true); 104 return NO_ERROR; 105 } 106 template <typename NH> write(Parcel * parcel,const NH & nh)107 typename std::enable_if<std::is_same<NH, sp<NativeHandle>>::value, status_t>::type write( 108 Parcel* parcel, const NH& nh) { 109 return callParcel("write(sp<NativeHandle>)", 110 [&]() { return parcel->writeNativeHandle(nh->handle()); }); 111 } 112 template <typename T> read(const Parcel & parcel,T * t)113 typename std::enable_if<std::is_base_of<Parcelable, T>::value, status_t>::type read( 114 const Parcel& parcel, T* t) const { 115 return callParcel("readParcelable", [&]() { return parcel.readParcelable(t); }); 116 } 117 template <typename T> write(Parcel * parcel,const T & t)118 typename std::enable_if<std::is_base_of<Parcelable, T>::value, status_t>::type write( 119 Parcel* parcel, const T& t) const { 120 return callParcel("writeParcelable", [&]() { return parcel->writeParcelable(t); }); 121 } read(const Parcel & parcel,String8 * str)122 status_t read(const Parcel& parcel, String8* str) const { 123 return callParcel("readString8", [&]() { return parcel.readString8(str); }); 124 } write(Parcel * parcel,const String8 & str)125 status_t write(Parcel* parcel, const String8& str) const { 126 return callParcel("writeString8", [&]() { return parcel->writeString8(str); }); 127 } 128 template <typename T> read(const Parcel & parcel,sp<T> * pointer)129 typename std::enable_if<std::is_same<IBinder, T>::value, status_t>::type read( 130 const Parcel& parcel, sp<T>* pointer) const { 131 return callParcel("readNullableStrongBinder", 132 [&]() { return parcel.readNullableStrongBinder(pointer); }); 133 } 134 template <typename T> write(Parcel * parcel,const sp<T> & pointer)135 typename std::enable_if<std::is_same<IBinder, T>::value, status_t>::type write( 136 Parcel* parcel, const sp<T>& pointer) const { 137 return callParcel("writeStrongBinder", 138 [&]() { return parcel->writeStrongBinder(pointer); }); 139 } 140 template <typename T> read(const Parcel & parcel,sp<T> * pointer)141 typename std::enable_if<std::is_base_of<IInterface, T>::value, status_t>::type read( 142 const Parcel& parcel, sp<T>* pointer) const { 143 return callParcel("readNullableStrongBinder[IInterface]", 144 [&]() { return parcel.readNullableStrongBinder(pointer); }); 145 } 146 template <typename T> write(Parcel * parcel,const sp<T> & interface)147 typename std::enable_if<std::is_base_of<IInterface, T>::value, status_t>::type write( 148 Parcel* parcel, const sp<T>& interface) const { 149 return write(parcel, IInterface::asBinder(interface)); 150 } 151 template <typename T> read(const Parcel & parcel,std::vector<T> * v)152 typename std::enable_if<std::is_base_of<Parcelable, T>::value, status_t>::type read( 153 const Parcel& parcel, std::vector<T>* v) const { 154 return callParcel("readParcelableVector", [&]() { return parcel.readParcelableVector(v); }); 155 } 156 template <typename T> write(Parcel * parcel,const std::vector<T> & v)157 typename std::enable_if<std::is_base_of<Parcelable, T>::value, status_t>::type write( 158 Parcel* parcel, const std::vector<T>& v) const { 159 return callParcel("writeParcelableVector", 160 [&]() { return parcel->writeParcelableVector(v); }); 161 } 162 read(const Parcel & parcel,std::vector<bool> * v)163 status_t read(const Parcel& parcel, std::vector<bool>* v) const { 164 return callParcel("readBoolVector", [&]() { return parcel.readBoolVector(v); }); 165 } write(Parcel * parcel,const std::vector<bool> & v)166 status_t write(Parcel* parcel, const std::vector<bool>& v) const { 167 return callParcel("writeBoolVector", [&]() { return parcel->writeBoolVector(v); }); 168 } 169 read(const Parcel & parcel,float * f)170 status_t read(const Parcel& parcel, float* f) const { 171 return callParcel("readFloat", [&]() { return parcel.readFloat(f); }); 172 } write(Parcel * parcel,float f)173 status_t write(Parcel* parcel, float f) const { 174 return callParcel("writeFloat", [&]() { return parcel->writeFloat(f); }); 175 } 176 177 // Templates to handle integral types. We use a struct template to require that the called 178 // function exactly matches the signedness and size of the argument (e.g., the argument isn't 179 // silently widened). 180 template <bool isSigned, size_t size, typename I> 181 struct HandleInt; 182 template <typename I> 183 struct HandleInt<true, 4, I> { 184 static status_t read(const ParcelHandler& handler, const Parcel& parcel, I* i) { 185 return handler.callParcel("readInt32", [&]() { return parcel.readInt32(i); }); 186 } 187 static status_t write(const ParcelHandler& handler, Parcel* parcel, I i) { 188 return handler.callParcel("writeInt32", [&]() { return parcel->writeInt32(i); }); 189 } 190 }; 191 template <typename I> 192 struct HandleInt<false, 4, I> { 193 static status_t read(const ParcelHandler& handler, const Parcel& parcel, I* i) { 194 return handler.callParcel("readUint32", [&]() { return parcel.readUint32(i); }); 195 } 196 static status_t write(const ParcelHandler& handler, Parcel* parcel, I i) { 197 return handler.callParcel("writeUint32", [&]() { return parcel->writeUint32(i); }); 198 } 199 }; 200 template <typename I> 201 struct HandleInt<true, 8, I> { 202 static status_t read(const ParcelHandler& handler, const Parcel& parcel, I* i) { 203 return handler.callParcel("readInt64", [&]() { return parcel.readInt64(i); }); 204 } 205 static status_t write(const ParcelHandler& handler, Parcel* parcel, I i) { 206 return handler.callParcel("writeInt64", [&]() { return parcel->writeInt64(i); }); 207 } 208 }; 209 template <typename I> 210 struct HandleInt<false, 8, I> { 211 static status_t read(const ParcelHandler& handler, const Parcel& parcel, I* i) { 212 return handler.callParcel("readUint64", [&]() { return parcel.readUint64(i); }); 213 } 214 static status_t write(const ParcelHandler& handler, Parcel* parcel, I i) { 215 return handler.callParcel("writeUint64", [&]() { return parcel->writeUint64(i); }); 216 } 217 }; 218 template <typename I> 219 typename std::enable_if<std::is_integral<I>::value, status_t>::type read(const Parcel& parcel, 220 I* i) const { 221 return HandleInt<std::is_signed<I>::value, sizeof(I), I>::read(*this, parcel, i); 222 } 223 template <typename I> 224 typename std::enable_if<std::is_integral<I>::value, status_t>::type write(Parcel* parcel, 225 I i) const { 226 return HandleInt<std::is_signed<I>::value, sizeof(I), I>::write(*this, parcel, i); 227 } 228 229 private: 230 const char* const mLogTag; 231 232 // Helper to encapsulate error handling while calling the various Parcel methods 233 template <typename Function> 234 status_t callParcel(const char* name, Function f) const { 235 status_t error = f(); 236 if (error != NO_ERROR) [[unlikely]] { 237 ALOG(LOG_ERROR, mLogTag, "Failed to %s, (%d: %s)", name, error, strerror(-error)); 238 #if SI_DUMP_CALLSTACKS 239 CallStack callStack(mLogTag); 240 #endif 241 } 242 return error; 243 } 244 }; 245 246 // Utility struct template which allows us to retrieve the types of the parameters of a member 247 // function pointer 248 template <typename T> 249 struct ParamExtractor; 250 template <typename Class, typename Return, typename... Params> 251 struct ParamExtractor<Return (Class::*)(Params...)> { 252 using ParamTuple = std::tuple<Params...>; 253 }; 254 template <typename Class, typename Return, typename... Params> 255 struct ParamExtractor<Return (Class::*)(Params...) const> { 256 using ParamTuple = std::tuple<Params...>; 257 }; 258 259 } // namespace SafeInterface 260 261 template <typename Interface> 262 class LIBBINDER_EXPORTED SafeBpInterface : public BpInterface<Interface> { 263 protected: 264 SafeBpInterface(const sp<IBinder>& impl, const char* logTag) 265 : BpInterface<Interface>(impl), mLogTag(logTag) {} 266 ~SafeBpInterface() override = default; 267 268 // callRemote is used to invoke a synchronous procedure call over Binder 269 template <typename Method, typename TagType, typename... Args> 270 status_t callRemote(TagType tag, Args&&... args) const { 271 static_assert(sizeof(TagType) <= sizeof(uint32_t), "Tag must fit inside uint32_t"); 272 273 // Verify that the arguments are compatible with the parameters 274 using ParamTuple = typename SafeInterface::ParamExtractor<Method>::ParamTuple; 275 static_assert(ArgsMatchParams<std::tuple<Args...>, ParamTuple>::value, 276 "Invalid argument type"); 277 278 // Write the input arguments to the data Parcel 279 Parcel data; 280 data.writeInterfaceToken(this->getInterfaceDescriptor()); 281 282 status_t error = writeInputs(&data, std::forward<Args>(args)...); 283 if (error != NO_ERROR) [[unlikely]] { 284 // A message will have been logged by writeInputs 285 return error; 286 } 287 288 // Send the data Parcel to the remote and retrieve the reply parcel 289 Parcel reply; 290 error = this->remote()->transact(static_cast<uint32_t>(tag), data, &reply); 291 if (error != NO_ERROR) [[unlikely]] { 292 ALOG(LOG_ERROR, mLogTag, "Failed to transact (%d)", error); 293 #if SI_DUMP_CALLSTACKS 294 CallStack callStack(mLogTag); 295 #endif 296 return error; 297 } 298 299 // Read the outputs from the reply Parcel into the output arguments 300 error = readOutputs(reply, std::forward<Args>(args)...); 301 if (error != NO_ERROR) [[unlikely]] { 302 // A message will have been logged by readOutputs 303 return error; 304 } 305 306 // Retrieve the result code from the reply Parcel 307 status_t result = NO_ERROR; 308 error = reply.readInt32(&result); 309 if (error != NO_ERROR) [[unlikely]] { 310 ALOG(LOG_ERROR, mLogTag, "Failed to obtain result"); 311 #if SI_DUMP_CALLSTACKS 312 CallStack callStack(mLogTag); 313 #endif 314 return error; 315 } 316 return result; 317 } 318 319 // callRemoteAsync is used to invoke an asynchronous procedure call over Binder 320 template <typename Method, typename TagType, typename... Args> 321 void callRemoteAsync(TagType tag, Args&&... args) const { 322 static_assert(sizeof(TagType) <= sizeof(uint32_t), "Tag must fit inside uint32_t"); 323 324 // Verify that the arguments are compatible with the parameters 325 using ParamTuple = typename SafeInterface::ParamExtractor<Method>::ParamTuple; 326 static_assert(ArgsMatchParams<std::tuple<Args...>, ParamTuple>::value, 327 "Invalid argument type"); 328 329 // Write the input arguments to the data Parcel 330 Parcel data; 331 data.writeInterfaceToken(this->getInterfaceDescriptor()); 332 status_t error = writeInputs(&data, std::forward<Args>(args)...); 333 if (error != NO_ERROR) [[unlikely]] { 334 // A message will have been logged by writeInputs 335 return; 336 } 337 338 // There will be no data in the reply Parcel since the call is one-way 339 Parcel reply; 340 error = this->remote()->transact(static_cast<uint32_t>(tag), data, &reply, 341 IBinder::FLAG_ONEWAY); 342 if (error != NO_ERROR) [[unlikely]] { 343 ALOG(LOG_ERROR, mLogTag, "Failed to transact (%d)", error); 344 #if SI_DUMP_CALLSTACKS 345 CallStack callStack(mLogTag); 346 #endif 347 } 348 } 349 350 private: 351 const char* const mLogTag; 352 353 // This struct provides information on whether the decayed types of the elements at Index in the 354 // tuple types T and U (that is, the types after stripping cv-qualifiers, removing references, 355 // and a few other less common operations) are the same 356 template <size_t Index, typename T, typename U> 357 struct DecayedElementsMatch { 358 private: 359 using FirstT = typename std::tuple_element<Index, T>::type; 360 using DecayedT = typename std::decay<FirstT>::type; 361 using FirstU = typename std::tuple_element<Index, U>::type; 362 using DecayedU = typename std::decay<FirstU>::type; 363 364 public: 365 static constexpr bool value = std::is_same<DecayedT, DecayedU>::value; 366 }; 367 368 // When comparing whether the argument types match the parameter types, we first decay them (see 369 // DecayedElementsMatch) to avoid falsely flagging, say, T&& against T even though they are 370 // equivalent enough for our purposes 371 template <typename T, typename U> 372 struct ArgsMatchParams {}; 373 template <typename... Args, typename... Params> 374 struct ArgsMatchParams<std::tuple<Args...>, std::tuple<Params...>> { 375 static_assert(sizeof...(Args) <= sizeof...(Params), "Too many arguments"); 376 static_assert(sizeof...(Args) >= sizeof...(Params), "Not enough arguments"); 377 378 private: 379 template <size_t Index> 380 static constexpr typename std::enable_if<(Index < sizeof...(Args)), bool>::type 381 elementsMatch() { 382 if (!DecayedElementsMatch<Index, std::tuple<Args...>, std::tuple<Params...>>::value) { 383 return false; 384 } 385 return elementsMatch<Index + 1>(); 386 } 387 template <size_t Index> 388 static constexpr typename std::enable_if<(Index >= sizeof...(Args)), bool>::type 389 elementsMatch() { 390 return true; 391 } 392 393 public: 394 static constexpr bool value = elementsMatch<0>(); 395 }; 396 397 // Since we assume that pointer arguments are outputs, we can use this template struct to 398 // determine whether or not a given argument is fundamentally a pointer type and thus an output 399 template <typename T> 400 struct IsPointerIfDecayed { 401 private: 402 using Decayed = typename std::decay<T>::type; 403 404 public: 405 static constexpr bool value = std::is_pointer<Decayed>::value; 406 }; 407 408 template <typename T> 409 typename std::enable_if<!IsPointerIfDecayed<T>::value, status_t>::type writeIfInput( 410 Parcel* data, T&& t) const { 411 return SafeInterface::ParcelHandler{mLogTag}.write(data, std::forward<T>(t)); 412 } 413 template <typename T> 414 typename std::enable_if<IsPointerIfDecayed<T>::value, status_t>::type writeIfInput( 415 Parcel* /*data*/, T&& /*t*/) const { 416 return NO_ERROR; 417 } 418 419 // This method iterates through all of the arguments, writing them to the data Parcel if they 420 // are an input (i.e., if they are not a pointer type) 421 template <typename T, typename... Remaining> 422 status_t writeInputs(Parcel* data, T&& t, Remaining&&... remaining) const { 423 status_t error = writeIfInput(data, std::forward<T>(t)); 424 if (error != NO_ERROR) [[unlikely]] { 425 // A message will have been logged by writeIfInput 426 return error; 427 } 428 return writeInputs(data, std::forward<Remaining>(remaining)...); 429 } 430 static status_t writeInputs(Parcel* /*data*/) { return NO_ERROR; } 431 432 template <typename T> 433 typename std::enable_if<IsPointerIfDecayed<T>::value, status_t>::type readIfOutput( 434 const Parcel& reply, T&& t) const { 435 return SafeInterface::ParcelHandler{mLogTag}.read(reply, std::forward<T>(t)); 436 } 437 template <typename T> 438 static typename std::enable_if<!IsPointerIfDecayed<T>::value, status_t>::type readIfOutput( 439 const Parcel& /*reply*/, T&& /*t*/) { 440 return NO_ERROR; 441 } 442 443 // Similar to writeInputs except that it reads output arguments from the reply Parcel 444 template <typename T, typename... Remaining> 445 status_t readOutputs(const Parcel& reply, T&& t, Remaining&&... remaining) const { 446 status_t error = readIfOutput(reply, std::forward<T>(t)); 447 if (error != NO_ERROR) [[unlikely]] { 448 // A message will have been logged by readIfOutput 449 return error; 450 } 451 return readOutputs(reply, std::forward<Remaining>(remaining)...); 452 } 453 static status_t readOutputs(const Parcel& /*data*/) { return NO_ERROR; } 454 }; 455 456 template <typename Interface> 457 class LIBBINDER_EXPORTED SafeBnInterface : public BnInterface<Interface> { 458 public: 459 explicit SafeBnInterface(const char* logTag) : mLogTag(logTag) {} 460 461 protected: 462 template <typename Method> 463 status_t callLocal(const Parcel& data, Parcel* reply, Method method) { 464 CHECK_INTERFACE(this, data, reply); 465 466 // Since we need to both pass inputs into the call as well as retrieve outputs, we create a 467 // "raw" tuple, where the inputs are interleaved with actual, non-pointer versions of the 468 // outputs. When we ultimately call into the method, we will pass the addresses of the 469 // output arguments instead of their tuple members directly, but the storage will live in 470 // the tuple. 471 using ParamTuple = typename SafeInterface::ParamExtractor<Method>::ParamTuple; 472 typename RawConverter<std::tuple<>, ParamTuple>::type rawArgs{}; 473 474 // Read the inputs from the data Parcel into the argument tuple 475 status_t error = InputReader<ParamTuple>{mLogTag}.readInputs(data, &rawArgs); 476 if (error != NO_ERROR) [[unlikely]] { 477 // A message will have been logged by read 478 return error; 479 } 480 481 // Call the local method 482 status_t result = MethodCaller<ParamTuple>::call(this, method, &rawArgs); 483 484 // Extract the outputs from the argument tuple and write them into the reply Parcel 485 error = OutputWriter<ParamTuple>{mLogTag}.writeOutputs(reply, &rawArgs); 486 if (error != NO_ERROR) [[unlikely]] { 487 // A message will have been logged by write 488 return error; 489 } 490 491 // Return the result code in the reply Parcel 492 error = reply->writeInt32(result); 493 if (error != NO_ERROR) [[unlikely]] { 494 ALOG(LOG_ERROR, mLogTag, "Failed to write result"); 495 #if SI_DUMP_CALLSTACKS 496 CallStack callStack(mLogTag); 497 #endif 498 return error; 499 } 500 return NO_ERROR; 501 } 502 503 template <typename Method> 504 status_t callLocalAsync(const Parcel& data, Parcel* /*reply*/, Method method) { 505 // reply is not actually used by CHECK_INTERFACE 506 CHECK_INTERFACE(this, data, reply); 507 508 // Since we need to both pass inputs into the call as well as retrieve outputs, we create a 509 // "raw" tuple, where the inputs are interleaved with actual, non-pointer versions of the 510 // outputs. When we ultimately call into the method, we will pass the addresses of the 511 // output arguments instead of their tuple members directly, but the storage will live in 512 // the tuple. 513 using ParamTuple = typename SafeInterface::ParamExtractor<Method>::ParamTuple; 514 typename RawConverter<std::tuple<>, ParamTuple>::type rawArgs{}; 515 516 // Read the inputs from the data Parcel into the argument tuple 517 status_t error = InputReader<ParamTuple>{mLogTag}.readInputs(data, &rawArgs); 518 if (error != NO_ERROR) [[unlikely]] { 519 // A message will have been logged by read 520 return error; 521 } 522 523 // Call the local method 524 MethodCaller<ParamTuple>::callVoid(this, method, &rawArgs); 525 526 // After calling, there is nothing more to do since asynchronous calls do not return a value 527 // to the caller 528 return NO_ERROR; 529 } 530 531 private: 532 const char* const mLogTag; 533 534 // RemoveFirst strips the first element from a tuple. 535 // For example, given T = std::tuple<A, B, C>, RemoveFirst<T>::type = std::tuple<B, C> 536 template <typename T, typename... Args> 537 struct RemoveFirst; 538 template <typename T, typename... Args> 539 struct RemoveFirst<std::tuple<T, Args...>> { 540 using type = std::tuple<Args...>; 541 }; 542 543 // RawConverter strips a tuple down to its fundamental types, discarding both pointers and 544 // references. This allows us to allocate storage for both input (non-pointer) arguments and 545 // output (pointer) arguments in one tuple. 546 // For example, given T = std::tuple<const A&, B*>, RawConverter<T>::type = std::tuple<A, B> 547 template <typename Unconverted, typename... Converted> 548 struct RawConverter; 549 template <typename Unconverted, typename... Converted> 550 struct RawConverter<std::tuple<Converted...>, Unconverted> { 551 private: 552 using ElementType = typename std::tuple_element<0, Unconverted>::type; 553 using Decayed = typename std::decay<ElementType>::type; 554 using WithoutPointer = typename std::remove_pointer<Decayed>::type; 555 556 public: 557 using type = typename RawConverter<std::tuple<Converted..., WithoutPointer>, 558 typename RemoveFirst<Unconverted>::type>::type; 559 }; 560 template <typename... Converted> 561 struct RawConverter<std::tuple<Converted...>, std::tuple<>> { 562 using type = std::tuple<Converted...>; 563 }; 564 565 // This provides a simple way to determine whether the indexed element of Args... is a pointer 566 template <size_t I, typename... Args> 567 struct ElementIsPointer { 568 private: 569 using ElementType = typename std::tuple_element<I, std::tuple<Args...>>::type; 570 571 public: 572 static constexpr bool value = std::is_pointer<ElementType>::value; 573 }; 574 575 // This class iterates over the parameter types, and if a given parameter is an input 576 // (i.e., is not a pointer), reads the corresponding argument tuple element from the data Parcel 577 template <typename... Params> 578 class InputReader; 579 template <typename... Params> 580 class InputReader<std::tuple<Params...>> { 581 public: 582 explicit InputReader(const char* logTag) : mLogTag(logTag) {} 583 584 // Note that in this case (as opposed to in SafeBpInterface), we iterate using an explicit 585 // index (starting with 0 here) instead of using recursion and stripping the first element. 586 // This is because in SafeBpInterface we aren't actually operating on a real tuple, but are 587 // instead just using a tuple as a convenient container for variadic types, whereas here we 588 // can't modify the argument tuple without causing unnecessary copies or moves of the data 589 // contained therein. 590 template <typename RawTuple> 591 status_t readInputs(const Parcel& data, RawTuple* args) { 592 return dispatchArg<0>(data, args); 593 } 594 595 private: 596 const char* const mLogTag; 597 598 template <std::size_t I, typename RawTuple> 599 typename std::enable_if<!ElementIsPointer<I, Params...>::value, status_t>::type readIfInput( 600 const Parcel& data, RawTuple* args) { 601 return SafeInterface::ParcelHandler{mLogTag}.read(data, &std::get<I>(*args)); 602 } 603 template <std::size_t I, typename RawTuple> 604 typename std::enable_if<ElementIsPointer<I, Params...>::value, status_t>::type readIfInput( 605 const Parcel& /*data*/, RawTuple* /*args*/) { 606 return NO_ERROR; 607 } 608 609 // Recursively iterate through the arguments 610 template <std::size_t I, typename RawTuple> 611 typename std::enable_if<(I < sizeof...(Params)), status_t>::type dispatchArg( 612 const Parcel& data, RawTuple* args) { 613 status_t error = readIfInput<I>(data, args); 614 if (error != NO_ERROR) [[unlikely]] { 615 // A message will have been logged in read 616 return error; 617 } 618 return dispatchArg<I + 1>(data, args); 619 } 620 template <std::size_t I, typename RawTuple> 621 typename std::enable_if<(I >= sizeof...(Params)), status_t>::type dispatchArg( 622 const Parcel& /*data*/, RawTuple* /*args*/) { 623 return NO_ERROR; 624 } 625 }; 626 627 // getForCall uses the types of the parameters to determine whether a given element of the 628 // argument tuple is an input, which should be passed directly into the call, or an output, for 629 // which its address should be passed into the call 630 template <size_t I, typename RawTuple, typename... Params> 631 static typename std::enable_if< 632 ElementIsPointer<I, Params...>::value, 633 typename std::tuple_element<I, std::tuple<Params...>>::type>::type 634 getForCall(RawTuple* args) { 635 return &std::get<I>(*args); 636 } 637 template <size_t I, typename RawTuple, typename... Params> 638 static typename std::enable_if< 639 !ElementIsPointer<I, Params...>::value, 640 typename std::tuple_element<I, std::tuple<Params...>>::type>::type& 641 getForCall(RawTuple* args) { 642 return std::get<I>(*args); 643 } 644 645 // This template class uses std::index_sequence and parameter pack expansion to call the given 646 // method using the elements of the argument tuple (after those arguments are passed through 647 // getForCall to get addresses instead of values for output arguments) 648 template <typename... Params> 649 struct MethodCaller; 650 template <typename... Params> 651 struct MethodCaller<std::tuple<Params...>> { 652 public: 653 // The calls through these to the helper methods are necessary to generate the 654 // std::index_sequences used to unpack the argument tuple into the method call 655 template <typename Class, typename MemberFunction, typename RawTuple> 656 static status_t call(Class* instance, MemberFunction function, RawTuple* args) { 657 return callHelper(instance, function, args, std::index_sequence_for<Params...>{}); 658 } 659 template <typename Class, typename MemberFunction, typename RawTuple> 660 static void callVoid(Class* instance, MemberFunction function, RawTuple* args) { 661 callVoidHelper(instance, function, args, std::index_sequence_for<Params...>{}); 662 } 663 664 private: 665 template <typename Class, typename MemberFunction, typename RawTuple, std::size_t... I> 666 static status_t callHelper(Class* instance, MemberFunction function, RawTuple* args, 667 std::index_sequence<I...> /*unused*/) { 668 return (instance->*function)(getForCall<I, RawTuple, Params...>(args)...); 669 } 670 template <typename Class, typename MemberFunction, typename RawTuple, std::size_t... I> 671 static void callVoidHelper(Class* instance, MemberFunction function, RawTuple* args, 672 std::index_sequence<I...> /*unused*/) { 673 (instance->*function)(getForCall<I, RawTuple, Params...>(args)...); 674 } 675 }; 676 677 // This class iterates over the parameter types, and if a given parameter is an output 678 // (i.e., is a pointer), writes the corresponding argument tuple element into the reply Parcel 679 template <typename... Params> 680 struct OutputWriter; 681 template <typename... Params> 682 struct OutputWriter<std::tuple<Params...>> { 683 public: 684 explicit OutputWriter(const char* logTag) : mLogTag(logTag) {} 685 686 // See the note on InputReader::readInputs for why this differs from the arguably simpler 687 // RemoveFirst approach in SafeBpInterface 688 template <typename RawTuple> 689 status_t writeOutputs(Parcel* reply, RawTuple* args) { 690 return dispatchArg<0>(reply, args); 691 } 692 693 private: 694 const char* const mLogTag; 695 696 template <std::size_t I, typename RawTuple> 697 typename std::enable_if<ElementIsPointer<I, Params...>::value, status_t>::type 698 writeIfOutput(Parcel* reply, RawTuple* args) { 699 return SafeInterface::ParcelHandler{mLogTag}.write(reply, std::get<I>(*args)); 700 } 701 template <std::size_t I, typename RawTuple> 702 typename std::enable_if<!ElementIsPointer<I, Params...>::value, status_t>::type 703 writeIfOutput(Parcel* /*reply*/, RawTuple* /*args*/) { 704 return NO_ERROR; 705 } 706 707 // Recursively iterate through the arguments 708 template <std::size_t I, typename RawTuple> 709 typename std::enable_if<(I < sizeof...(Params)), status_t>::type dispatchArg( 710 Parcel* reply, RawTuple* args) { 711 status_t error = writeIfOutput<I>(reply, args); 712 if (error != NO_ERROR) [[unlikely]] { 713 // A message will have been logged in read 714 return error; 715 } 716 return dispatchArg<I + 1>(reply, args); 717 } 718 template <std::size_t I, typename RawTuple> 719 typename std::enable_if<(I >= sizeof...(Params)), status_t>::type dispatchArg( 720 Parcel* /*reply*/, RawTuple* /*args*/) { 721 return NO_ERROR; 722 } 723 }; 724 }; 725 726 } // namespace android 727