blob: 44ff62bf26759be8d4bf8551b2d369b40393eaac [file] [log] [blame]
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2005 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_TAG "Parcel"
18//#define LOG_NDEBUG 0
19
Mark Salyzynabed7f72016-01-27 08:02:48 -080020#include <errno.h>
Mark Salyzyn70f36652016-02-02 10:27:03 -080021#include <fcntl.h>
Mark Salyzynabed7f72016-01-27 08:02:48 -080022#include <inttypes.h>
Mark Salyzyn70f36652016-02-02 10:27:03 -080023#include <pthread.h>
Mark Salyzynabed7f72016-01-27 08:02:48 -080024#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <sys/mman.h>
Andrei Homescua9cca9c2022-05-03 04:48:01 +000028#include <sys/resource.h>
Mark Salyzyneab2afc2016-01-27 08:02:48 -080029#include <sys/stat.h>
30#include <sys/types.h>
31#include <unistd.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070032
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/Binder.h>
34#include <binder/BpBinder.h>
Mark Salyzynabed7f72016-01-27 08:02:48 -080035#include <binder/IPCThreadState.h>
36#include <binder/Parcel.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070037#include <binder/ProcessState.h>
Steven Moreland6e5a7752019-08-05 20:30:14 -070038#include <binder/Stability.h>
Christopher Wiley09eb7492015-11-09 15:06:15 -080039#include <binder/Status.h>
Mathias Agopian002e1e52013-05-06 20:20:50 -070040#include <binder/TextOutput.h>
41
Frederick Mayle69a0c992022-05-26 20:38:39 +000042#include <android-base/scopeguard.h>
Mark Salyzynabed7f72016-01-27 08:02:48 -080043#include <cutils/ashmem.h>
Steven Moreland3af936a2021-03-26 03:05:38 +000044#include <cutils/compiler.h>
Mark Salyzynabed7f72016-01-27 08:02:48 -080045#include <utils/Flattenable.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070046#include <utils/Log.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070047#include <utils/String16.h>
Steven Moreland3af936a2021-03-26 03:05:38 +000048#include <utils/String8.h>
49#include <utils/misc.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070050
Andrei Homescu24ad36e2022-08-04 01:33:33 +000051#include "OS.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000052#include "RpcState.h"
Steven Morelanda4853cd2019-07-12 15:44:37 -070053#include "Static.h"
Steven Morelandf183fdd2020-10-27 00:12:12 +000054#include "Utils.h"
Andrei Homescua9cca9c2022-05-03 04:48:01 +000055
56// A lot of code in this file uses definitions from the
57// Linux kernel header for Binder <linux/android/binder.h>
58// which is included indirectly via "binder_module.h".
59// Non-Linux OSes do not have that header, so libbinder should be
60// built for those targets without kernel binder support, i.e.,
61// without BINDER_WITH_KERNEL_IPC. For this reason, all code in this
62// file that depends on kernel binder, including the header itself,
63// is conditional on BINDER_WITH_KERNEL_IPC.
64#ifdef BINDER_WITH_KERNEL_IPC
65#include <linux/sched.h>
Steven Moreland6ba5a252021-05-04 22:49:00 +000066#include "binder_module.h"
Andrei Homescua9cca9c2022-05-03 04:48:01 +000067#else // BINDER_WITH_KERNEL_IPC
68// Needed by {read,write}Pointer
69typedef uintptr_t binder_uintptr_t;
70#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070071
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070072#define LOG_REFS(...)
Andrei Homescua9cca9c2022-05-03 04:48:01 +000073// #define LOG_REFS(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
Dianne Hackborn7e790af2014-11-11 12:22:53 -080074#define LOG_ALLOC(...)
Andrei Homescua9cca9c2022-05-03 04:48:01 +000075// #define LOG_ALLOC(...) ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070076
77// ---------------------------------------------------------------------------
78
Nick Kralevichb6b14232015-04-02 09:36:02 -070079// This macro should never be used at runtime, as a too large value
80// of s could cause an integer overflow. Instead, you should always
81// use the wrapper function pad_size()
Andrei Homescuf7f2c172022-03-08 22:52:49 +000082#define PAD_SIZE_UNSAFE(s) (((s) + 3) & ~3UL)
Nick Kralevichb6b14232015-04-02 09:36:02 -070083
84static size_t pad_size(size_t s) {
Steven Moreland28723ae2019-04-01 18:52:30 -070085 if (s > (std::numeric_limits<size_t>::max() - 3)) {
Steven Moreland6adf33c2019-09-25 13:18:09 -070086 LOG_ALWAYS_FATAL("pad size too big %zu", s);
Nick Kralevichb6b14232015-04-02 09:36:02 -070087 }
88 return PAD_SIZE_UNSAFE(s);
89}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070090
Brad Fitzpatricka877cd82010-07-07 16:06:39 -070091// Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
Jeff Sharkey05827be2018-06-26 10:52:38 -060092#define STRICT_MODE_PENALTY_GATHER (1 << 31)
Brad Fitzpatricka877cd82010-07-07 16:06:39 -070093
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070094namespace android {
95
Steven Moreland7b102262019-08-01 15:48:43 -070096// many things compile this into prebuilts on the stack
Steven Moreland90c1f9a2021-05-03 18:27:24 +000097#ifdef __LP64__
98static_assert(sizeof(Parcel) == 120);
99#else
100static_assert(sizeof(Parcel) == 60);
101#endif
Steven Moreland7b102262019-08-01 15:48:43 -0700102
Jeff Sharkey8994c182020-09-11 12:07:10 -0600103static std::atomic<size_t> gParcelGlobalAllocCount;
104static std::atomic<size_t> gParcelGlobalAllocSize;
Dianne Hackborna4cff882014-11-13 17:07:40 -0800105
Andrei Homescu1519b982022-06-09 02:04:44 +0000106// Maximum number of file descriptors per Parcel.
107constexpr size_t kMaxFds = 1024;
Christopher Tatee4e0ae82016-03-24 16:03:44 -0700108
Jeff Brown13b16042014-11-11 16:44:25 -0800109// Maximum size of a blob to transfer in-place.
110static const size_t BLOB_INPLACE_LIMIT = 16 * 1024;
111
112enum {
113 BLOB_INPLACE = 0,
114 BLOB_ASHMEM_IMMUTABLE = 1,
115 BLOB_ASHMEM_MUTABLE = 2,
116};
117
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000118#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandc673f1f2021-10-07 18:23:35 -0700119static void acquire_object(const sp<ProcessState>& proc, const flat_binder_object& obj,
120 const void* who) {
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -0700121 switch (obj.hdr.type) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700122 case BINDER_TYPE_BINDER:
123 if (obj.binder) {
yuxic05af3b2021-08-24 02:52:15 +0000124 LOG_REFS("Parcel %p acquiring reference on local %llu", who, obj.cookie);
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -0800125 reinterpret_cast<IBinder*>(obj.cookie)->incStrong(who);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700126 }
127 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700128 case BINDER_TYPE_HANDLE: {
129 const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
Yi Kong91635562018-06-07 14:38:36 -0700130 if (b != nullptr) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700131 LOG_REFS("Parcel %p acquiring reference on remote %p", who, b.get());
132 b->incStrong(who);
133 }
134 return;
135 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700136 case BINDER_TYPE_FD: {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700137 return;
138 }
139 }
140
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -0700141 ALOGD("Invalid object type 0x%08x", obj.hdr.type);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700142}
143
Steven Morelandc673f1f2021-10-07 18:23:35 -0700144static void release_object(const sp<ProcessState>& proc, const flat_binder_object& obj,
145 const void* who) {
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -0700146 switch (obj.hdr.type) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700147 case BINDER_TYPE_BINDER:
148 if (obj.binder) {
yuxic05af3b2021-08-24 02:52:15 +0000149 LOG_REFS("Parcel %p releasing reference on local %llu", who, obj.cookie);
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -0800150 reinterpret_cast<IBinder*>(obj.cookie)->decStrong(who);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700151 }
152 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700153 case BINDER_TYPE_HANDLE: {
154 const sp<IBinder> b = proc->getStrongProxyForHandle(obj.handle);
Yi Kong91635562018-06-07 14:38:36 -0700155 if (b != nullptr) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700156 LOG_REFS("Parcel %p releasing reference on remote %p", who, b.get());
157 b->decStrong(who);
158 }
159 return;
160 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700161 case BINDER_TYPE_FD: {
Mark Salyzynb454d8f2016-01-27 08:02:48 -0800162 if (obj.cookie != 0) { // owned
Mark Salyzynb454d8f2016-01-27 08:02:48 -0800163 close(obj.handle);
Adrian Rooscbf37262015-10-22 16:12:53 -0700164 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700165 return;
166 }
167 }
168
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -0700169 ALOGE("Invalid object type 0x%08x", obj.hdr.type);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700170}
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000171#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700172
Frederick Mayle69a0c992022-05-26 20:38:39 +0000173static int toRawFd(const std::variant<base::unique_fd, base::borrowed_fd>& v) {
174 return std::visit([](const auto& fd) { return fd.get(); }, v);
175}
176
Frederick Mayled3c595a2022-05-09 23:02:54 +0000177Parcel::RpcFields::RpcFields(const sp<RpcSession>& session) : mSession(session) {
178 LOG_ALWAYS_FATAL_IF(mSession == nullptr);
179}
180
Steven Moreland34b48cb2020-12-01 22:45:38 +0000181status_t Parcel::finishFlattenBinder(const sp<IBinder>& binder)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700182{
Steven Moreland6e5a7752019-08-05 20:30:14 -0700183 internal::Stability::tryMarkCompilationUnit(binder.get());
Steven Moreland16a41062021-07-23 13:35:25 -0700184 int16_t rep = internal::Stability::getRepr(binder.get());
Steven Moreland14e4cfa2021-06-03 21:40:45 +0000185 return writeInt32(rep);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700186}
187
Steven Morelanda86a3562019-08-01 23:28:34 +0000188status_t Parcel::finishUnflattenBinder(
189 const sp<IBinder>& binder, sp<IBinder>* out) const
190{
191 int32_t stability;
192 status_t status = readInt32(&stability);
193 if (status != OK) return status;
194
Steven Moreland14e4cfa2021-06-03 21:40:45 +0000195 status = internal::Stability::setRepr(binder.get(), static_cast<int16_t>(stability),
196 true /*log*/);
Steven Morelanda86a3562019-08-01 23:28:34 +0000197 if (status != OK) return status;
198
199 *out = binder;
200 return OK;
201}
202
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000203#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandbf1915b2020-07-16 22:43:02 +0000204static constexpr inline int schedPolicyMask(int policy, int priority) {
205 return (priority & FLAT_BINDER_FLAG_PRIORITY_MASK) | ((policy & 3) << FLAT_BINDER_FLAG_SCHED_POLICY_SHIFT);
206}
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000207#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandbf1915b2020-07-16 22:43:02 +0000208
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500209status_t Parcel::flattenBinder(const sp<IBinder>& binder) {
210 BBinder* local = nullptr;
211 if (binder) local = binder->localBinder();
212 if (local) local->setParceled();
213
Frederick Mayled3c595a2022-05-09 23:02:54 +0000214 if (const auto* rpcFields = maybeRpcFields()) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000215 if (binder) {
216 status_t status = writeInt32(1); // non-null
217 if (status != OK) return status;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700218 uint64_t address;
Steven Morelanda5036f02021-06-08 02:26:57 +0000219 // TODO(b/167966510): need to undo this if the Parcel is not sent
Frederick Mayled3c595a2022-05-09 23:02:54 +0000220 status = rpcFields->mSession->state()->onBinderLeaving(rpcFields->mSession, binder,
221 &address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000222 if (status != OK) return status;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700223 status = writeUint64(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000224 if (status != OK) return status;
225 } else {
226 status_t status = writeInt32(0); // null
227 if (status != OK) return status;
228 }
229 return finishFlattenBinder(binder);
230 }
231
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000232#ifdef BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700233 flat_binder_object obj;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700234
Steven Morelandbf1915b2020-07-16 22:43:02 +0000235 int schedBits = 0;
236 if (!IPCThreadState::self()->backgroundSchedulingDisabled()) {
237 schedBits = schedPolicyMask(SCHED_NORMAL, 19);
Martijn Coenen2b631742017-05-05 11:16:59 -0700238 }
239
Yi Kong91635562018-06-07 14:38:36 -0700240 if (binder != nullptr) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700241 if (!local) {
242 BpBinder *proxy = binder->remoteBinder();
Yi Kong91635562018-06-07 14:38:36 -0700243 if (proxy == nullptr) {
Steve Blocke6f43dd2012-01-06 19:20:56 +0000244 ALOGE("null proxy");
Steven Moreland5553ac42020-11-11 02:14:45 +0000245 } else {
246 if (proxy->isRpcBinder()) {
Steven Morelanda9231112021-09-22 10:08:14 -0700247 ALOGE("Sending a socket binder over kernel binder is prohibited");
Steven Moreland5553ac42020-11-11 02:14:45 +0000248 return INVALID_OPERATION;
249 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700250 }
Steven Moreland99157622021-09-13 16:27:34 -0700251 const int32_t handle = proxy ? proxy->getPrivateAccessor().binderHandle() : 0;
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -0700252 obj.hdr.type = BINDER_TYPE_HANDLE;
Arve Hjønnevåg07fd0f12014-02-18 21:10:29 -0800253 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
Steven Moreland49c27532022-03-01 10:21:07 +0000254 obj.flags = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700255 obj.handle = handle;
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -0800256 obj.cookie = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700257 } else {
Steven Morelandbf1915b2020-07-16 22:43:02 +0000258 int policy = local->getMinSchedulerPolicy();
259 int priority = local->getMinSchedulerPriority();
260
261 if (policy != 0 || priority != 0) {
262 // override value, since it is set explicitly
263 schedBits = schedPolicyMask(policy, priority);
264 }
Steven Moreland49c27532022-03-01 10:21:07 +0000265 obj.flags = FLAT_BINDER_FLAG_ACCEPTS_FDS;
Steven Morelandf0212002018-12-26 13:59:23 -0800266 if (local->isRequestingSid()) {
267 obj.flags |= FLAT_BINDER_FLAG_TXN_SECURITY_CTX;
268 }
Steven Morelandcf03cf12020-12-04 02:58:40 +0000269 if (local->isInheritRt()) {
270 obj.flags |= FLAT_BINDER_FLAG_INHERIT_RT;
271 }
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -0700272 obj.hdr.type = BINDER_TYPE_BINDER;
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -0800273 obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
274 obj.cookie = reinterpret_cast<uintptr_t>(local);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700275 }
276 } else {
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -0700277 obj.hdr.type = BINDER_TYPE_BINDER;
Steven Moreland49c27532022-03-01 10:21:07 +0000278 obj.flags = 0;
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -0800279 obj.binder = 0;
280 obj.cookie = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700281 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700282
Steven Morelandbf1915b2020-07-16 22:43:02 +0000283 obj.flags |= schedBits;
284
Steven Moreland34b48cb2020-12-01 22:45:38 +0000285 status_t status = writeObject(obj, false);
286 if (status != OK) return status;
287
288 return finishFlattenBinder(binder);
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000289#else // BINDER_WITH_KERNEL_IPC
290 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
291 return INVALID_OPERATION;
292#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700293}
294
Steven Morelanda86a3562019-08-01 23:28:34 +0000295status_t Parcel::unflattenBinder(sp<IBinder>* out) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700296{
Frederick Mayled3c595a2022-05-09 23:02:54 +0000297 if (const auto* rpcFields = maybeRpcFields()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700298 int32_t isPresent;
299 status_t status = readInt32(&isPresent);
Steven Moreland5553ac42020-11-11 02:14:45 +0000300 if (status != OK) return status;
301
302 sp<IBinder> binder;
303
Steven Moreland5623d1a2021-09-10 15:45:34 -0700304 if (isPresent & 1) {
305 uint64_t addr;
306 if (status_t status = readUint64(&addr); status != OK) return status;
Frederick Mayled3c595a2022-05-09 23:02:54 +0000307 if (status_t status =
308 rpcFields->mSession->state()->onBinderEntering(rpcFields->mSession, addr,
309 &binder);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000310 status != OK)
311 return status;
Frederick Mayled3c595a2022-05-09 23:02:54 +0000312 if (status_t status =
313 rpcFields->mSession->state()->flushExcessBinderRefs(rpcFields->mSession,
314 addr, binder);
Steven Morelandd8083312021-09-22 13:37:10 -0700315 status != OK)
316 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000317 }
318
319 return finishUnflattenBinder(binder, out);
320 }
321
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000322#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelanda86a3562019-08-01 23:28:34 +0000323 const flat_binder_object* flat = readObject(false);
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700324
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700325 if (flat) {
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -0700326 switch (flat->hdr.type) {
Steven Morelanda86a3562019-08-01 23:28:34 +0000327 case BINDER_TYPE_BINDER: {
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000328 sp<IBinder> binder =
329 sp<IBinder>::fromExisting(reinterpret_cast<IBinder*>(flat->cookie));
Steven Morelanda86a3562019-08-01 23:28:34 +0000330 return finishUnflattenBinder(binder, out);
331 }
332 case BINDER_TYPE_HANDLE: {
333 sp<IBinder> binder =
334 ProcessState::self()->getStrongProxyForHandle(flat->handle);
335 return finishUnflattenBinder(binder, out);
336 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700337 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700338 }
339 return BAD_TYPE;
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000340#else // BINDER_WITH_KERNEL_IPC
341 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
342 return INVALID_OPERATION;
343#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700344}
345
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700346// ---------------------------------------------------------------------------
347
348Parcel::Parcel()
349{
Dianne Hackborn7e790af2014-11-11 12:22:53 -0800350 LOG_ALLOC("Parcel %p: constructing", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700351 initState();
352}
353
354Parcel::~Parcel()
355{
356 freeDataNoInit();
Dianne Hackborn7e790af2014-11-11 12:22:53 -0800357 LOG_ALLOC("Parcel %p: destroyed", this);
358}
359
360size_t Parcel::getGlobalAllocSize() {
Jeff Sharkey8994c182020-09-11 12:07:10 -0600361 return gParcelGlobalAllocSize.load();
Dianne Hackborn7e790af2014-11-11 12:22:53 -0800362}
363
364size_t Parcel::getGlobalAllocCount() {
Jeff Sharkey8994c182020-09-11 12:07:10 -0600365 return gParcelGlobalAllocCount.load();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700366}
367
368const uint8_t* Parcel::data() const
369{
370 return mData;
371}
372
373size_t Parcel::dataSize() const
374{
375 return (mDataSize > mDataPos ? mDataSize : mDataPos);
376}
377
378size_t Parcel::dataAvail() const
379{
Nick Kralevichcfe27de2015-09-16 09:49:15 -0700380 size_t result = dataSize() - dataPosition();
381 if (result > INT32_MAX) {
Steven Moreland6adf33c2019-09-25 13:18:09 -0700382 LOG_ALWAYS_FATAL("result too big: %zu", result);
Nick Kralevichcfe27de2015-09-16 09:49:15 -0700383 }
384 return result;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700385}
386
387size_t Parcel::dataPosition() const
388{
389 return mDataPos;
390}
391
392size_t Parcel::dataCapacity() const
393{
394 return mDataCapacity;
395}
396
397status_t Parcel::setDataSize(size_t size)
398{
Nick Kralevichb6b14232015-04-02 09:36:02 -0700399 if (size > INT32_MAX) {
400 // don't accept size_t values which may have come from an
401 // inadvertent conversion from a negative int.
402 return BAD_VALUE;
403 }
404
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700405 status_t err;
406 err = continueWrite(size);
407 if (err == NO_ERROR) {
408 mDataSize = size;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700409 ALOGV("setDataSize Setting data size of %p to %zu", this, mDataSize);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700410 }
411 return err;
412}
413
414void Parcel::setDataPosition(size_t pos) const
415{
Nick Kralevichb6b14232015-04-02 09:36:02 -0700416 if (pos > INT32_MAX) {
417 // don't accept size_t values which may have come from an
418 // inadvertent conversion from a negative int.
Steven Moreland6adf33c2019-09-25 13:18:09 -0700419 LOG_ALWAYS_FATAL("pos too big: %zu", pos);
Nick Kralevichb6b14232015-04-02 09:36:02 -0700420 }
421
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700422 mDataPos = pos;
Frederick Mayled3c595a2022-05-09 23:02:54 +0000423 if (const auto* kernelFields = maybeKernelFields()) {
424 kernelFields->mNextObjectHint = 0;
425 kernelFields->mObjectsSorted = false;
426 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700427}
428
429status_t Parcel::setDataCapacity(size_t size)
430{
Nick Kralevichb6b14232015-04-02 09:36:02 -0700431 if (size > INT32_MAX) {
432 // don't accept size_t values which may have come from an
433 // inadvertent conversion from a negative int.
434 return BAD_VALUE;
435 }
436
Dianne Hackborn97e2bcd2011-04-13 18:15:56 -0700437 if (size > mDataCapacity) return continueWrite(size);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700438 return NO_ERROR;
439}
440
441status_t Parcel::setData(const uint8_t* buffer, size_t len)
442{
Nick Kralevichb6b14232015-04-02 09:36:02 -0700443 if (len > INT32_MAX) {
444 // don't accept size_t values which may have come from an
445 // inadvertent conversion from a negative int.
446 return BAD_VALUE;
447 }
448
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700449 status_t err = restartWrite(len);
450 if (err == NO_ERROR) {
451 memcpy(const_cast<uint8_t*>(data()), buffer, len);
452 mDataSize = len;
Frederick Mayled3c595a2022-05-09 23:02:54 +0000453 if (auto* kernelFields = maybeKernelFields()) {
454 kernelFields->mFdsKnown = false;
455 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700456 }
457 return err;
458}
459
Frederick Mayled3c595a2022-05-09 23:02:54 +0000460status_t Parcel::appendFrom(const Parcel* parcel, size_t offset, size_t len) {
461 if (isForRpc() != parcel->isForRpc()) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700462 ALOGE("Cannot append Parcel from one context to another. They may be different formats, "
463 "and objects are specific to a context.");
Steven Moreland67753c32021-04-02 18:45:19 +0000464 return BAD_TYPE;
465 }
Frederick Mayled3c595a2022-05-09 23:02:54 +0000466 if (isForRpc() && maybeRpcFields()->mSession != parcel->maybeRpcFields()->mSession) {
467 ALOGE("Cannot append Parcels from different sessions");
468 return BAD_TYPE;
469 }
Steven Moreland67753c32021-04-02 18:45:19 +0000470
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700471 status_t err;
Frederick Mayled3c595a2022-05-09 23:02:54 +0000472 const uint8_t* data = parcel->mData;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700473 int startPos = mDataPos;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700474
475 if (len == 0) {
476 return NO_ERROR;
477 }
478
Nick Kralevichb6b14232015-04-02 09:36:02 -0700479 if (len > INT32_MAX) {
480 // don't accept size_t values which may have come from an
481 // inadvertent conversion from a negative int.
482 return BAD_VALUE;
483 }
484
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700485 // range checks against the source parcel size
486 if ((offset > parcel->mDataSize)
487 || (len > parcel->mDataSize)
488 || (offset + len > parcel->mDataSize)) {
489 return BAD_VALUE;
490 }
491
Dianne Hackborn97e2bcd2011-04-13 18:15:56 -0700492 if ((mDataSize+len) > mDataCapacity) {
493 // grow data
494 err = growData(len);
495 if (err != NO_ERROR) {
496 return err;
497 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700498 }
499
500 // append data
501 memcpy(mData + mDataPos, data + offset, len);
502 mDataPos += len;
503 mDataSize += len;
504
Dianne Hackborn8938ed22011-09-28 23:19:47 -0400505 err = NO_ERROR;
506
Frederick Mayled3c595a2022-05-09 23:02:54 +0000507 if (auto* kernelFields = maybeKernelFields()) {
Andrei Homescu88012462022-07-07 04:30:05 +0000508#ifdef BINDER_WITH_KERNEL_IPC
Frederick Mayled3c595a2022-05-09 23:02:54 +0000509 auto* otherKernelFields = parcel->maybeKernelFields();
510 LOG_ALWAYS_FATAL_IF(otherKernelFields == nullptr);
511
512 const binder_size_t* objects = otherKernelFields->mObjects;
513 size_t size = otherKernelFields->mObjectsSize;
514 // Count objects in range
515 int firstIndex = -1, lastIndex = -2;
516 for (int i = 0; i < (int)size; i++) {
517 size_t off = objects[i];
518 if ((off >= offset) && (off + sizeof(flat_binder_object) <= offset + len)) {
519 if (firstIndex == -1) {
520 firstIndex = i;
521 }
522 lastIndex = i;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700523 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700524 }
Frederick Mayled3c595a2022-05-09 23:02:54 +0000525 int numObjects = lastIndex - firstIndex + 1;
526 if (numObjects > 0) {
527 const sp<ProcessState> proc(ProcessState::self());
528 // grow objects
529 if (kernelFields->mObjectsCapacity < kernelFields->mObjectsSize + numObjects) {
530 if ((size_t)numObjects > SIZE_MAX - kernelFields->mObjectsSize)
531 return NO_MEMORY; // overflow
532 if (kernelFields->mObjectsSize + numObjects > SIZE_MAX / 3)
533 return NO_MEMORY; // overflow
534 size_t newSize = ((kernelFields->mObjectsSize + numObjects) * 3) / 2;
535 if (newSize > SIZE_MAX / sizeof(binder_size_t)) return NO_MEMORY; // overflow
536 binder_size_t* objects = (binder_size_t*)realloc(kernelFields->mObjects,
537 newSize * sizeof(binder_size_t));
538 if (objects == (binder_size_t*)nullptr) {
539 return NO_MEMORY;
540 }
541 kernelFields->mObjects = objects;
542 kernelFields->mObjectsCapacity = newSize;
543 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700544
Frederick Mayled3c595a2022-05-09 23:02:54 +0000545 // append and acquire objects
546 int idx = kernelFields->mObjectsSize;
547 for (int i = firstIndex; i <= lastIndex; i++) {
548 size_t off = objects[i] - offset + startPos;
549 kernelFields->mObjects[idx++] = off;
550 kernelFields->mObjectsSize++;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700551
Frederick Mayled3c595a2022-05-09 23:02:54 +0000552 flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(mData + off);
553 acquire_object(proc, *flat, this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700554
Frederick Mayled3c595a2022-05-09 23:02:54 +0000555 if (flat->hdr.type == BINDER_TYPE_FD) {
556 // If this is a file descriptor, we need to dup it so the
557 // new Parcel now owns its own fd, and can declare that we
558 // officially know we have fds.
559 flat->handle = fcntl(flat->handle, F_DUPFD_CLOEXEC, 0);
560 flat->cookie = 1;
561 kernelFields->mHasFds = kernelFields->mFdsKnown = true;
562 if (!mAllowFds) {
563 err = FDS_NOT_ALLOWED;
564 }
Dianne Hackborn8938ed22011-09-28 23:19:47 -0400565 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700566 }
567 }
Andrei Homescu88012462022-07-07 04:30:05 +0000568#else
569 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
570 return INVALID_OPERATION;
571#endif // BINDER_WITH_KERNEL_IPC
Frederick Mayle69a0c992022-05-26 20:38:39 +0000572 } else {
573 auto* rpcFields = maybeRpcFields();
574 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
575 auto* otherRpcFields = parcel->maybeRpcFields();
576 if (otherRpcFields == nullptr) {
577 return BAD_TYPE;
578 }
579 if (rpcFields->mSession != otherRpcFields->mSession) {
580 return BAD_TYPE;
581 }
582
583 const size_t savedDataPos = mDataPos;
584 base::ScopeGuard scopeGuard = [&]() { mDataPos = savedDataPos; };
585
586 rpcFields->mObjectPositions.reserve(otherRpcFields->mObjectPositions.size());
587 if (otherRpcFields->mFds != nullptr) {
588 if (rpcFields->mFds == nullptr) {
589 rpcFields->mFds = std::make_unique<decltype(rpcFields->mFds)::element_type>();
590 }
591 rpcFields->mFds->reserve(otherRpcFields->mFds->size());
592 }
593 for (size_t i = 0; i < otherRpcFields->mObjectPositions.size(); i++) {
594 const binder_size_t objPos = otherRpcFields->mObjectPositions[i];
595 if (offset <= objPos && objPos < offset + len) {
596 size_t newDataPos = objPos - offset + startPos;
597 rpcFields->mObjectPositions.push_back(newDataPos);
598
599 mDataPos = newDataPos;
600 int32_t objectType;
601 if (status_t status = readInt32(&objectType); status != OK) {
602 return status;
603 }
604 if (objectType != RpcFields::TYPE_NATIVE_FILE_DESCRIPTOR) {
605 continue;
606 }
607
608 if (!mAllowFds) {
609 return FDS_NOT_ALLOWED;
610 }
611
612 // Read FD, duplicate, and add to list.
613 int32_t fdIndex;
614 if (status_t status = readInt32(&fdIndex); status != OK) {
615 return status;
616 }
Andrei Homescufc221502022-10-08 03:51:17 +0000617 int oldFd = toRawFd(otherRpcFields->mFds->at(fdIndex));
Frederick Mayle69a0c992022-05-26 20:38:39 +0000618 // To match kernel binder behavior, we always dup, even if the
619 // FD was unowned in the source parcel.
Andrei Homescufc221502022-10-08 03:51:17 +0000620 int newFd = -1;
621 if (status_t status = dupFileDescriptor(oldFd, &newFd); status != OK) {
622 ALOGW("Failed to duplicate file descriptor %d: %s", oldFd, strerror(-status));
623 }
624 rpcFields->mFds->emplace_back(base::unique_fd(newFd));
Frederick Mayle69a0c992022-05-26 20:38:39 +0000625 // Fixup the index in the data.
626 mDataPos = newDataPos + 4;
627 if (status_t status = writeInt32(rpcFields->mFds->size() - 1); status != OK) {
628 return status;
629 }
630 }
631 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700632 }
633
Dianne Hackborn8938ed22011-09-28 23:19:47 -0400634 return err;
635}
636
Dianne Hackborn15feb9b2017-04-10 15:34:35 -0700637int Parcel::compareData(const Parcel& other) {
638 size_t size = dataSize();
639 if (size != other.dataSize()) {
640 return size < other.dataSize() ? -1 : 1;
641 }
642 return memcmp(data(), other.data(), size);
643}
644
Bernardo Rufino897b1652021-10-08 10:30:20 +0100645status_t Parcel::compareDataInRange(size_t thisOffset, const Parcel& other, size_t otherOffset,
646 size_t len, int* result) const {
647 if (len > INT32_MAX || thisOffset > INT32_MAX || otherOffset > INT32_MAX) {
648 // Don't accept size_t values which may have come from an inadvertent conversion from a
649 // negative int.
650 return BAD_VALUE;
651 }
652 size_t thisLimit;
653 if (__builtin_add_overflow(thisOffset, len, &thisLimit) || thisLimit > mDataSize) {
654 return BAD_VALUE;
655 }
656 size_t otherLimit;
657 if (__builtin_add_overflow(otherOffset, len, &otherLimit) || otherLimit > other.mDataSize) {
658 return BAD_VALUE;
659 }
660 *result = memcmp(data() + thisOffset, other.data() + otherOffset, len);
661 return NO_ERROR;
662}
663
Jeff Brown13b16042014-11-11 16:44:25 -0800664bool Parcel::allowFds() const
665{
666 return mAllowFds;
667}
668
Dianne Hackborn7746cc32011-10-03 21:09:35 -0700669bool Parcel::pushAllowFds(bool allowFds)
Dianne Hackborn8938ed22011-09-28 23:19:47 -0400670{
671 const bool origValue = mAllowFds;
Dianne Hackborn7746cc32011-10-03 21:09:35 -0700672 if (!allowFds) {
673 mAllowFds = false;
674 }
Dianne Hackborn8938ed22011-09-28 23:19:47 -0400675 return origValue;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700676}
677
Dianne Hackborn7746cc32011-10-03 21:09:35 -0700678void Parcel::restoreAllowFds(bool lastValue)
679{
680 mAllowFds = lastValue;
681}
682
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700683bool Parcel::hasFileDescriptors() const
684{
Frederick Mayled3c595a2022-05-09 23:02:54 +0000685 if (const auto* rpcFields = maybeRpcFields()) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000686 return rpcFields->mFds != nullptr && !rpcFields->mFds->empty();
Frederick Mayled3c595a2022-05-09 23:02:54 +0000687 }
688 auto* kernelFields = maybeKernelFields();
689 if (!kernelFields->mFdsKnown) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700690 scanForFds();
691 }
Frederick Mayled3c595a2022-05-09 23:02:54 +0000692 return kernelFields->mHasFds;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700693}
694
Steven Moreland4b2f18d2022-03-24 00:32:25 +0000695std::vector<sp<IBinder>> Parcel::debugReadAllStrongBinders() const {
696 std::vector<sp<IBinder>> ret;
697
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000698#ifdef BINDER_WITH_KERNEL_IPC
Frederick Mayled3c595a2022-05-09 23:02:54 +0000699 const auto* kernelFields = maybeKernelFields();
700 if (kernelFields == nullptr) {
701 return ret;
702 }
703
Steven Moreland4b2f18d2022-03-24 00:32:25 +0000704 size_t initPosition = dataPosition();
Frederick Mayled3c595a2022-05-09 23:02:54 +0000705 for (size_t i = 0; i < kernelFields->mObjectsSize; i++) {
706 binder_size_t offset = kernelFields->mObjects[i];
Steven Moreland4b2f18d2022-03-24 00:32:25 +0000707 const flat_binder_object* flat =
708 reinterpret_cast<const flat_binder_object*>(mData + offset);
709 if (flat->hdr.type != BINDER_TYPE_BINDER) continue;
710
711 setDataPosition(offset);
712
713 sp<IBinder> binder = readStrongBinder();
714 if (binder != nullptr) ret.push_back(binder);
715 }
716
717 setDataPosition(initPosition);
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000718#endif // BINDER_WITH_KERNEL_IPC
719
Steven Moreland4b2f18d2022-03-24 00:32:25 +0000720 return ret;
721}
722
723std::vector<int> Parcel::debugReadAllFileDescriptors() const {
724 std::vector<int> ret;
725
Frederick Mayle69a0c992022-05-26 20:38:39 +0000726 if (const auto* kernelFields = maybeKernelFields()) {
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000727#ifdef BINDER_WITH_KERNEL_IPC
Frederick Mayle69a0c992022-05-26 20:38:39 +0000728 size_t initPosition = dataPosition();
729 for (size_t i = 0; i < kernelFields->mObjectsSize; i++) {
730 binder_size_t offset = kernelFields->mObjects[i];
731 const flat_binder_object* flat =
732 reinterpret_cast<const flat_binder_object*>(mData + offset);
733 if (flat->hdr.type != BINDER_TYPE_FD) continue;
734
735 setDataPosition(offset);
736
737 int fd = readFileDescriptor();
738 LOG_ALWAYS_FATAL_IF(fd == -1);
739 ret.push_back(fd);
740 }
741 setDataPosition(initPosition);
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000742#else
743 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
744#endif
Frederick Mayle69a0c992022-05-26 20:38:39 +0000745 } else if (const auto* rpcFields = maybeRpcFields(); rpcFields && rpcFields->mFds) {
746 for (const auto& fd : *rpcFields->mFds) {
747 ret.push_back(toRawFd(fd));
748 }
Frederick Mayled3c595a2022-05-09 23:02:54 +0000749 }
750
Steven Moreland4b2f18d2022-03-24 00:32:25 +0000751 return ret;
752}
753
Bernardo Rufinobbbd88d2021-10-15 14:54:30 +0100754status_t Parcel::hasFileDescriptorsInRange(size_t offset, size_t len, bool* result) const {
Bernardo Rufino22092af2021-10-07 14:09:24 +0100755 if (len > INT32_MAX || offset > INT32_MAX) {
756 // Don't accept size_t values which may have come from an inadvertent conversion from a
757 // negative int.
758 return BAD_VALUE;
759 }
Bernardo Rufinobbbd88d2021-10-15 14:54:30 +0100760 size_t limit;
761 if (__builtin_add_overflow(offset, len, &limit) || limit > mDataSize) {
Bernardo Rufino22092af2021-10-07 14:09:24 +0100762 return BAD_VALUE;
763 }
Bernardo Rufinobbbd88d2021-10-15 14:54:30 +0100764 *result = false;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000765 if (const auto* kernelFields = maybeKernelFields()) {
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000766#ifdef BINDER_WITH_KERNEL_IPC
Frederick Mayle69a0c992022-05-26 20:38:39 +0000767 for (size_t i = 0; i < kernelFields->mObjectsSize; i++) {
768 size_t pos = kernelFields->mObjects[i];
769 if (pos < offset) continue;
770 if (pos + sizeof(flat_binder_object) > offset + len) {
771 if (kernelFields->mObjectsSorted) {
772 break;
773 } else {
774 continue;
775 }
776 }
777 const flat_binder_object* flat =
778 reinterpret_cast<const flat_binder_object*>(mData + pos);
779 if (flat->hdr.type == BINDER_TYPE_FD) {
780 *result = true;
Frederick Mayled3c595a2022-05-09 23:02:54 +0000781 break;
Frederick Mayled3c595a2022-05-09 23:02:54 +0000782 }
Bernardo Rufino22092af2021-10-07 14:09:24 +0100783 }
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000784#else
785 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
786 return INVALID_OPERATION;
787#endif // BINDER_WITH_KERNEL_IPC
Frederick Mayle69a0c992022-05-26 20:38:39 +0000788 } else if (const auto* rpcFields = maybeRpcFields()) {
789 for (uint32_t pos : rpcFields->mObjectPositions) {
790 if (offset <= pos && pos < limit) {
791 const auto* type = reinterpret_cast<const RpcFields::ObjectType*>(mData + pos);
792 if (*type == RpcFields::TYPE_NATIVE_FILE_DESCRIPTOR) {
793 *result = true;
794 break;
795 }
796 }
Bernardo Rufino22092af2021-10-07 14:09:24 +0100797 }
798 }
Bernardo Rufinobbbd88d2021-10-15 14:54:30 +0100799 return NO_ERROR;
Bernardo Rufino22092af2021-10-07 14:09:24 +0100800}
801
Steven Morelandf183fdd2020-10-27 00:12:12 +0000802void Parcel::markSensitive() const
803{
804 mDeallocZero = true;
805}
806
Steven Moreland5553ac42020-11-11 02:14:45 +0000807void Parcel::markForBinder(const sp<IBinder>& binder) {
Steven Moreland1fda67b2021-04-02 18:35:50 +0000808 LOG_ALWAYS_FATAL_IF(mData != nullptr, "format must be set before data is written");
809
Steven Moreland5553ac42020-11-11 02:14:45 +0000810 if (binder && binder->remoteBinder() && binder->remoteBinder()->isRpcBinder()) {
Steven Moreland99157622021-09-13 16:27:34 -0700811 markForRpc(binder->remoteBinder()->getPrivateAccessor().rpcSession());
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 }
813}
814
Steven Morelandc9939062021-05-05 17:57:41 +0000815void Parcel::markForRpc(const sp<RpcSession>& session) {
Steven Moreland1fda67b2021-04-02 18:35:50 +0000816 LOG_ALWAYS_FATAL_IF(mData != nullptr && mOwner == nullptr,
817 "format must be set before data is written OR on IPC data");
818
Frederick Mayled3c595a2022-05-09 23:02:54 +0000819 mVariantFields.emplace<RpcFields>(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000820}
821
822bool Parcel::isForRpc() const {
Frederick Mayled3c595a2022-05-09 23:02:54 +0000823 return std::holds_alternative<RpcFields>(mVariantFields);
Steven Moreland5553ac42020-11-11 02:14:45 +0000824}
825
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000826void Parcel::updateWorkSourceRequestHeaderPosition() const {
Frederick Mayled3c595a2022-05-09 23:02:54 +0000827 auto* kernelFields = maybeKernelFields();
828 if (kernelFields == nullptr) {
829 return;
830 }
831
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000832 // Only update the request headers once. We only want to point
833 // to the first headers read/written.
Frederick Mayled3c595a2022-05-09 23:02:54 +0000834 if (!kernelFields->mRequestHeaderPresent) {
835 kernelFields->mWorkSourceRequestHeaderPosition = dataPosition();
836 kernelFields->mRequestHeaderPresent = true;
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000837 }
838}
839
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000840#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandb6c7e222021-02-18 19:20:14 +0000841#if defined(__ANDROID_VNDK__)
Steven Morelandd70160f2019-07-23 10:20:38 -0700842constexpr int32_t kHeader = B_PACK_CHARS('V', 'N', 'D', 'R');
Yifan Hong70786532021-10-20 21:41:18 -0700843#elif defined(__ANDROID_RECOVERY__)
844constexpr int32_t kHeader = B_PACK_CHARS('R', 'E', 'C', 'O');
Steven Morelandd70160f2019-07-23 10:20:38 -0700845#else
846constexpr int32_t kHeader = B_PACK_CHARS('S', 'Y', 'S', 'T');
847#endif
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000848#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd70160f2019-07-23 10:20:38 -0700849
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700850// Write RPC headers. (previously just the interface token)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700851status_t Parcel::writeInterfaceToken(const String16& interface)
852{
Steven Morelanddbc76c72020-10-01 18:02:48 +0000853 return writeInterfaceToken(interface.string(), interface.size());
854}
855
856status_t Parcel::writeInterfaceToken(const char16_t* str, size_t len) {
Frederick Mayled3c595a2022-05-09 23:02:54 +0000857 if (auto* kernelFields = maybeKernelFields()) {
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000858#ifdef BINDER_WITH_KERNEL_IPC
Steven Moreland3af936a2021-03-26 03:05:38 +0000859 const IPCThreadState* threadState = IPCThreadState::self();
860 writeInt32(threadState->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER);
861 updateWorkSourceRequestHeaderPosition();
862 writeInt32(threadState->shouldPropagateWorkSource() ? threadState->getCallingWorkSourceUid()
863 : IPCThreadState::kUnsetWorkSource);
864 writeInt32(kHeader);
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000865#else // BINDER_WITH_KERNEL_IPC
866 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
867 return INVALID_OPERATION;
868#endif // BINDER_WITH_KERNEL_IPC
Steven Moreland3af936a2021-03-26 03:05:38 +0000869 }
Steven Morelanddbc76c72020-10-01 18:02:48 +0000870
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700871 // currently the interface identification token is just its name as a string
Steven Morelanddbc76c72020-10-01 18:02:48 +0000872 return writeString16(str, len);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700873}
874
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000875bool Parcel::replaceCallingWorkSourceUid(uid_t uid)
876{
Frederick Mayled3c595a2022-05-09 23:02:54 +0000877 auto* kernelFields = maybeKernelFields();
878 if (kernelFields == nullptr) {
879 return false;
880 }
881 if (!kernelFields->mRequestHeaderPresent) {
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000882 return false;
883 }
884
885 const size_t initialPosition = dataPosition();
Frederick Mayled3c595a2022-05-09 23:02:54 +0000886 setDataPosition(kernelFields->mWorkSourceRequestHeaderPosition);
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000887 status_t err = writeInt32(uid);
888 setDataPosition(initialPosition);
889 return err == NO_ERROR;
890}
891
Steven Morelandf1b1e492019-05-06 15:05:13 -0700892uid_t Parcel::readCallingWorkSourceUid() const
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000893{
Frederick Mayled3c595a2022-05-09 23:02:54 +0000894 auto* kernelFields = maybeKernelFields();
895 if (kernelFields == nullptr) {
896 return false;
897 }
898 if (!kernelFields->mRequestHeaderPresent) {
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000899 return IPCThreadState::kUnsetWorkSource;
900 }
901
902 const size_t initialPosition = dataPosition();
Frederick Mayled3c595a2022-05-09 23:02:54 +0000903 setDataPosition(kernelFields->mWorkSourceRequestHeaderPosition);
Olivier Gaillarddc848a02019-01-30 17:10:44 +0000904 uid_t uid = readInt32();
905 setDataPosition(initialPosition);
906 return uid;
907}
908
Mathias Agopian83c04462009-05-22 19:00:22 -0700909bool Parcel::checkInterface(IBinder* binder) const
910{
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700911 return enforceInterface(binder->getInterfaceDescriptor());
Mathias Agopian83c04462009-05-22 19:00:22 -0700912}
913
Brad Fitzpatricka877cd82010-07-07 16:06:39 -0700914bool Parcel::enforceInterface(const String16& interface,
Brad Fitzpatrick70081a12010-07-27 09:49:11 -0700915 IPCThreadState* threadState) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700916{
Daniel Colascione0bb330d2019-10-29 16:44:19 -0700917 return enforceInterface(interface.string(), interface.size(), threadState);
918}
919
920bool Parcel::enforceInterface(const char16_t* interface,
921 size_t len,
922 IPCThreadState* threadState) const
923{
Frederick Mayled3c595a2022-05-09 23:02:54 +0000924 if (auto* kernelFields = maybeKernelFields()) {
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000925#ifdef BINDER_WITH_KERNEL_IPC
Steven Moreland3af936a2021-03-26 03:05:38 +0000926 // StrictModePolicy.
927 int32_t strictPolicy = readInt32();
928 if (threadState == nullptr) {
929 threadState = IPCThreadState::self();
930 }
931 if ((threadState->getLastTransactionBinderFlags() & IBinder::FLAG_ONEWAY) != 0) {
932 // For one-way calls, the callee is running entirely
933 // disconnected from the caller, so disable StrictMode entirely.
934 // Not only does disk/network usage not impact the caller, but
935 // there's no way to communicate back violations anyway.
936 threadState->setStrictModePolicy(0);
937 } else {
938 threadState->setStrictModePolicy(strictPolicy);
939 }
940 // WorkSource.
941 updateWorkSourceRequestHeaderPosition();
942 int32_t workSource = readInt32();
943 threadState->setCallingWorkSourceUidWithoutPropagation(workSource);
944 // vendor header
945 int32_t header = readInt32();
946 if (header != kHeader) {
947 ALOGE("Expecting header 0x%x but found 0x%x. Mixing copies of libbinder?", kHeader,
948 header);
949 return false;
950 }
Andrei Homescua9cca9c2022-05-03 04:48:01 +0000951#else // BINDER_WITH_KERNEL_IPC
952 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
953 (void)threadState;
954 return false;
955#endif // BINDER_WITH_KERNEL_IPC
Brad Fitzpatricka877cd82010-07-07 16:06:39 -0700956 }
Steven Moreland3af936a2021-03-26 03:05:38 +0000957
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100958 // Interface descriptor.
Daniel Colascione0bb330d2019-10-29 16:44:19 -0700959 size_t parcel_interface_len;
960 const char16_t* parcel_interface = readString16Inplace(&parcel_interface_len);
961 if (len == parcel_interface_len &&
962 (!len || !memcmp(parcel_interface, interface, len * sizeof (char16_t)))) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700963 return true;
964 } else {
Mark Salyzynd4ecccf2014-05-30 16:35:57 -0700965 ALOGW("**** enforceInterface() expected '%s' but read '%s'",
Daniel Colascione0bb330d2019-10-29 16:44:19 -0700966 String8(interface, len).string(),
967 String8(parcel_interface, parcel_interface_len).string());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700968 return false;
969 }
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700970}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700971
Pawan Wagh104654a2022-11-15 21:18:42 +0000972void Parcel::setEnforceNoDataAvail(bool enforceNoDataAvail) {
973 mEnforceNoDataAvail = enforceNoDataAvail;
974}
975
Jooyung Hand23f9502021-12-23 14:39:57 +0900976binder::Status Parcel::enforceNoDataAvail() const {
Pawan Wagh104654a2022-11-15 21:18:42 +0000977 if (!mEnforceNoDataAvail) {
978 return binder::Status::ok();
979 }
980
Jooyung Hand23f9502021-12-23 14:39:57 +0900981 const auto n = dataAvail();
982 if (n == 0) {
983 return binder::Status::ok();
984 }
985 return binder::Status::
986 fromExceptionCode(binder::Status::Exception::EX_BAD_PARCELABLE,
987 String8::format("Parcel data not fully consumed, unread size: %zu",
988 n));
989}
990
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700991size_t Parcel::objectsCount() const
992{
Frederick Mayled3c595a2022-05-09 23:02:54 +0000993 if (const auto* kernelFields = maybeKernelFields()) {
994 return kernelFields->mObjectsSize;
995 }
996 return 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700997}
998
999status_t Parcel::errorCheck() const
1000{
1001 return mError;
1002}
1003
1004void Parcel::setError(status_t err)
1005{
1006 mError = err;
1007}
1008
1009status_t Parcel::finishWrite(size_t len)
1010{
Nick Kralevichb6b14232015-04-02 09:36:02 -07001011 if (len > INT32_MAX) {
1012 // don't accept size_t values which may have come from an
1013 // inadvertent conversion from a negative int.
1014 return BAD_VALUE;
1015 }
1016
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001017 //printf("Finish write of %d\n", len);
1018 mDataPos += len;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07001019 ALOGV("finishWrite Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001020 if (mDataPos > mDataSize) {
1021 mDataSize = mDataPos;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07001022 ALOGV("finishWrite Setting data size of %p to %zu", this, mDataSize);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001023 }
1024 //printf("New pos=%d, size=%d\n", mDataPos, mDataSize);
1025 return NO_ERROR;
1026}
1027
1028status_t Parcel::writeUnpadded(const void* data, size_t len)
1029{
Nick Kralevichb6b14232015-04-02 09:36:02 -07001030 if (len > INT32_MAX) {
1031 // don't accept size_t values which may have come from an
1032 // inadvertent conversion from a negative int.
1033 return BAD_VALUE;
1034 }
1035
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001036 size_t end = mDataPos + len;
1037 if (end < mDataPos) {
1038 // integer overflow
1039 return BAD_VALUE;
1040 }
1041
1042 if (end <= mDataCapacity) {
1043restart_write:
1044 memcpy(mData+mDataPos, data, len);
1045 return finishWrite(len);
1046 }
1047
1048 status_t err = growData(len);
1049 if (err == NO_ERROR) goto restart_write;
1050 return err;
1051}
1052
1053status_t Parcel::write(const void* data, size_t len)
1054{
Nick Kralevichb6b14232015-04-02 09:36:02 -07001055 if (len > INT32_MAX) {
1056 // don't accept size_t values which may have come from an
1057 // inadvertent conversion from a negative int.
1058 return BAD_VALUE;
1059 }
1060
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001061 void* const d = writeInplace(len);
1062 if (d) {
1063 memcpy(d, data, len);
1064 return NO_ERROR;
1065 }
1066 return mError;
1067}
1068
1069void* Parcel::writeInplace(size_t len)
1070{
Nick Kralevichb6b14232015-04-02 09:36:02 -07001071 if (len > INT32_MAX) {
1072 // don't accept size_t values which may have come from an
1073 // inadvertent conversion from a negative int.
Yi Kong91635562018-06-07 14:38:36 -07001074 return nullptr;
Nick Kralevichb6b14232015-04-02 09:36:02 -07001075 }
1076
1077 const size_t padded = pad_size(len);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001078
Khalid Ramadanb3d817b2021-11-18 07:02:50 +00001079 // check for integer overflow
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001080 if (mDataPos+padded < mDataPos) {
Yi Kong91635562018-06-07 14:38:36 -07001081 return nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001082 }
1083
1084 if ((mDataPos+padded) <= mDataCapacity) {
1085restart_write:
1086 //printf("Writing %ld bytes, padded to %ld\n", len, padded);
1087 uint8_t* const data = mData+mDataPos;
1088
1089 // Need to pad at end?
1090 if (padded != len) {
1091#if BYTE_ORDER == BIG_ENDIAN
1092 static const uint32_t mask[4] = {
1093 0x00000000, 0xffffff00, 0xffff0000, 0xff000000
1094 };
1095#endif
1096#if BYTE_ORDER == LITTLE_ENDIAN
1097 static const uint32_t mask[4] = {
1098 0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
1099 };
1100#endif
1101 //printf("Applying pad mask: %p to %p\n", (void*)mask[padded-len],
1102 // *reinterpret_cast<void**>(data+padded-4));
1103 *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len];
1104 }
1105
1106 finishWrite(padded);
1107 return data;
1108 }
1109
1110 status_t err = growData(padded);
1111 if (err == NO_ERROR) goto restart_write;
Yi Kong91635562018-06-07 14:38:36 -07001112 return nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001113}
1114
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08001115status_t Parcel::writeUtf8AsUtf16(const std::string& str) {
1116 const uint8_t* strData = (uint8_t*)str.data();
1117 const size_t strLen= str.length();
1118 const ssize_t utf16Len = utf8_to_utf16_length(strData, strLen);
Sergio Girof4607432016-07-21 14:46:35 +01001119 if (utf16Len < 0 || utf16Len > std::numeric_limits<int32_t>::max()) {
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08001120 return BAD_VALUE;
1121 }
1122
1123 status_t err = writeInt32(utf16Len);
1124 if (err) {
1125 return err;
1126 }
1127
1128 // Allocate enough bytes to hold our converted string and its terminating NULL.
1129 void* dst = writeInplace((utf16Len + 1) * sizeof(char16_t));
1130 if (!dst) {
1131 return NO_MEMORY;
1132 }
1133
Sergio Girof4607432016-07-21 14:46:35 +01001134 utf8_to_utf16(strData, strLen, (char16_t*)dst, (size_t) utf16Len + 1);
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08001135
1136 return NO_ERROR;
1137}
1138
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001139
Andy Hung49198cf2020-11-18 11:02:39 -08001140status_t Parcel::writeUtf8AsUtf16(const std::optional<std::string>& str) { return writeData(str); }
1141status_t Parcel::writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) { return writeData(str); }
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08001142
Andy Hung49198cf2020-11-18 11:02:39 -08001143status_t Parcel::writeString16(const std::optional<String16>& str) { return writeData(str); }
1144status_t Parcel::writeString16(const std::unique_ptr<String16>& str) { return writeData(str); }
Casey Dahlin451ff582015-10-19 18:12:18 -07001145
Andy Hung49198cf2020-11-18 11:02:39 -08001146status_t Parcel::writeByteVector(const std::vector<int8_t>& val) { return writeData(val); }
1147status_t Parcel::writeByteVector(const std::optional<std::vector<int8_t>>& val) { return writeData(val); }
1148status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val) { return writeData(val); }
1149status_t Parcel::writeByteVector(const std::vector<uint8_t>& val) { return writeData(val); }
1150status_t Parcel::writeByteVector(const std::optional<std::vector<uint8_t>>& val) { return writeData(val); }
1151status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val){ return writeData(val); }
1152status_t Parcel::writeInt32Vector(const std::vector<int32_t>& val) { return writeData(val); }
1153status_t Parcel::writeInt32Vector(const std::optional<std::vector<int32_t>>& val) { return writeData(val); }
1154status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val) { return writeData(val); }
1155status_t Parcel::writeInt64Vector(const std::vector<int64_t>& val) { return writeData(val); }
1156status_t Parcel::writeInt64Vector(const std::optional<std::vector<int64_t>>& val) { return writeData(val); }
1157status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val) { return writeData(val); }
1158status_t Parcel::writeUint64Vector(const std::vector<uint64_t>& val) { return writeData(val); }
1159status_t Parcel::writeUint64Vector(const std::optional<std::vector<uint64_t>>& val) { return writeData(val); }
1160status_t Parcel::writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val) { return writeData(val); }
1161status_t Parcel::writeFloatVector(const std::vector<float>& val) { return writeData(val); }
1162status_t Parcel::writeFloatVector(const std::optional<std::vector<float>>& val) { return writeData(val); }
1163status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val) { return writeData(val); }
1164status_t Parcel::writeDoubleVector(const std::vector<double>& val) { return writeData(val); }
1165status_t Parcel::writeDoubleVector(const std::optional<std::vector<double>>& val) { return writeData(val); }
1166status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val) { return writeData(val); }
1167status_t Parcel::writeBoolVector(const std::vector<bool>& val) { return writeData(val); }
1168status_t Parcel::writeBoolVector(const std::optional<std::vector<bool>>& val) { return writeData(val); }
1169status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val) { return writeData(val); }
1170status_t Parcel::writeCharVector(const std::vector<char16_t>& val) { return writeData(val); }
1171status_t Parcel::writeCharVector(const std::optional<std::vector<char16_t>>& val) { return writeData(val); }
1172status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val) { return writeData(val); }
Casey Dahlin451ff582015-10-19 18:12:18 -07001173
Andy Hung49198cf2020-11-18 11:02:39 -08001174status_t Parcel::writeString16Vector(const std::vector<String16>& val) { return writeData(val); }
Casey Dahlinb9872622015-11-25 15:09:45 -08001175status_t Parcel::writeString16Vector(
Andy Hung49198cf2020-11-18 11:02:39 -08001176 const std::optional<std::vector<std::optional<String16>>>& val) { return writeData(val); }
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001177status_t Parcel::writeString16Vector(
Andy Hung49198cf2020-11-18 11:02:39 -08001178 const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val) { return writeData(val); }
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08001179status_t Parcel::writeUtf8VectorAsUtf16Vector(
Andy Hung49198cf2020-11-18 11:02:39 -08001180 const std::optional<std::vector<std::optional<std::string>>>& val) { return writeData(val); }
Jooyung Han9fcc4ef2020-01-23 12:45:10 +09001181status_t Parcel::writeUtf8VectorAsUtf16Vector(
Andy Hung49198cf2020-11-18 11:02:39 -08001182 const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) { return writeData(val); }
1183status_t Parcel::writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val) { return writeData(val); }
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08001184
Andy Hung49198cf2020-11-18 11:02:39 -08001185status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<base::unique_fd>& val) { return writeData(val); }
1186status_t Parcel::writeUniqueFileDescriptorVector(const std::optional<std::vector<base::unique_fd>>& val) { return writeData(val); }
1187status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<base::unique_fd>>& val) { return writeData(val); }
1188
1189status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val) { return writeData(val); }
1190status_t Parcel::writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>>& val) { return writeData(val); }
1191status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val) { return writeData(val); }
1192
1193status_t Parcel::writeParcelable(const Parcelable& parcelable) { return writeData(parcelable); }
1194
1195status_t Parcel::readUtf8FromUtf16(std::optional<std::string>* str) const { return readData(str); }
1196status_t Parcel::readUtf8FromUtf16(std::unique_ptr<std::string>* str) const { return readData(str); }
1197
1198status_t Parcel::readString16(std::optional<String16>* pArg) const { return readData(pArg); }
1199status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const { return readData(pArg); }
1200
1201status_t Parcel::readByteVector(std::vector<int8_t>* val) const { return readData(val); }
1202status_t Parcel::readByteVector(std::vector<uint8_t>* val) const { return readData(val); }
1203status_t Parcel::readByteVector(std::optional<std::vector<int8_t>>* val) const { return readData(val); }
1204status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const { return readData(val); }
1205status_t Parcel::readByteVector(std::optional<std::vector<uint8_t>>* val) const { return readData(val); }
1206status_t Parcel::readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const { return readData(val); }
1207status_t Parcel::readInt32Vector(std::optional<std::vector<int32_t>>* val) const { return readData(val); }
1208status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const { return readData(val); }
1209status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const { return readData(val); }
1210status_t Parcel::readInt64Vector(std::optional<std::vector<int64_t>>* val) const { return readData(val); }
1211status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const { return readData(val); }
1212status_t Parcel::readInt64Vector(std::vector<int64_t>* val) const { return readData(val); }
1213status_t Parcel::readUint64Vector(std::optional<std::vector<uint64_t>>* val) const { return readData(val); }
1214status_t Parcel::readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const { return readData(val); }
1215status_t Parcel::readUint64Vector(std::vector<uint64_t>* val) const { return readData(val); }
1216status_t Parcel::readFloatVector(std::optional<std::vector<float>>* val) const { return readData(val); }
1217status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const { return readData(val); }
1218status_t Parcel::readFloatVector(std::vector<float>* val) const { return readData(val); }
1219status_t Parcel::readDoubleVector(std::optional<std::vector<double>>* val) const { return readData(val); }
1220status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const { return readData(val); }
1221status_t Parcel::readDoubleVector(std::vector<double>* val) const { return readData(val); }
1222status_t Parcel::readBoolVector(std::optional<std::vector<bool>>* val) const { return readData(val); }
1223status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const { return readData(val); }
1224status_t Parcel::readBoolVector(std::vector<bool>* val) const { return readData(val); }
1225status_t Parcel::readCharVector(std::optional<std::vector<char16_t>>* val) const { return readData(val); }
1226status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const { return readData(val); }
1227status_t Parcel::readCharVector(std::vector<char16_t>* val) const { return readData(val); }
1228
1229status_t Parcel::readString16Vector(
1230 std::optional<std::vector<std::optional<String16>>>* val) const { return readData(val); }
1231status_t Parcel::readString16Vector(
1232 std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const { return readData(val); }
1233status_t Parcel::readString16Vector(std::vector<String16>* val) const { return readData(val); }
1234status_t Parcel::readUtf8VectorFromUtf16Vector(
1235 std::optional<std::vector<std::optional<std::string>>>* val) const { return readData(val); }
1236status_t Parcel::readUtf8VectorFromUtf16Vector(
1237 std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const { return readData(val); }
1238status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const { return readData(val); }
1239
1240status_t Parcel::readUniqueFileDescriptorVector(std::optional<std::vector<base::unique_fd>>* val) const { return readData(val); }
1241status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<base::unique_fd>>* val) const { return readData(val); }
1242status_t Parcel::readUniqueFileDescriptorVector(std::vector<base::unique_fd>* val) const { return readData(val); }
1243
1244status_t Parcel::readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const { return readData(val); }
1245status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const { return readData(val); }
1246status_t Parcel::readStrongBinderVector(std::vector<sp<IBinder>>* val) const { return readData(val); }
1247
1248status_t Parcel::readParcelable(Parcelable* parcelable) const { return readData(parcelable); }
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08001249
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001250status_t Parcel::writeInt32(int32_t val)
1251{
Andreas Huber84a6d042009-08-17 13:33:27 -07001252 return writeAligned(val);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001253}
Dan Stoza41a0f2f2014-12-01 10:01:10 -08001254
1255status_t Parcel::writeUint32(uint32_t val)
1256{
1257 return writeAligned(val);
1258}
1259
Marco Nelissen5c0106e2013-10-16 10:57:51 -07001260status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
Nick Kralevichb6b14232015-04-02 09:36:02 -07001261 if (len > INT32_MAX) {
1262 // don't accept size_t values which may have come from an
1263 // inadvertent conversion from a negative int.
1264 return BAD_VALUE;
1265 }
1266
Marco Nelissen5c0106e2013-10-16 10:57:51 -07001267 if (!val) {
Chad Brubakere59cb432015-06-30 14:03:55 -07001268 return writeInt32(-1);
Marco Nelissen5c0106e2013-10-16 10:57:51 -07001269 }
Chad Brubakere59cb432015-06-30 14:03:55 -07001270 status_t ret = writeInt32(static_cast<uint32_t>(len));
Marco Nelissen5c0106e2013-10-16 10:57:51 -07001271 if (ret == NO_ERROR) {
1272 ret = write(val, len * sizeof(*val));
1273 }
1274 return ret;
1275}
Marco Nelissenf0190bf2014-03-13 14:17:40 -07001276status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
Nick Kralevichb6b14232015-04-02 09:36:02 -07001277 if (len > INT32_MAX) {
1278 // don't accept size_t values which may have come from an
1279 // inadvertent conversion from a negative int.
1280 return BAD_VALUE;
1281 }
1282
Marco Nelissenf0190bf2014-03-13 14:17:40 -07001283 if (!val) {
Chad Brubakere59cb432015-06-30 14:03:55 -07001284 return writeInt32(-1);
Marco Nelissenf0190bf2014-03-13 14:17:40 -07001285 }
Chad Brubakere59cb432015-06-30 14:03:55 -07001286 status_t ret = writeInt32(static_cast<uint32_t>(len));
Marco Nelissenf0190bf2014-03-13 14:17:40 -07001287 if (ret == NO_ERROR) {
1288 ret = write(val, len * sizeof(*val));
1289 }
1290 return ret;
1291}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001292
Casey Dahlind6848f52015-10-15 15:44:59 -07001293status_t Parcel::writeBool(bool val)
1294{
1295 return writeInt32(int32_t(val));
1296}
1297
1298status_t Parcel::writeChar(char16_t val)
1299{
1300 return writeInt32(int32_t(val));
1301}
1302
1303status_t Parcel::writeByte(int8_t val)
1304{
1305 return writeInt32(int32_t(val));
1306}
1307
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001308status_t Parcel::writeInt64(int64_t val)
1309{
Andreas Huber84a6d042009-08-17 13:33:27 -07001310 return writeAligned(val);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001311}
1312
Ronghua Wu2d13afd2015-03-16 11:11:07 -07001313status_t Parcel::writeUint64(uint64_t val)
1314{
1315 return writeAligned(val);
1316}
1317
Serban Constantinescuf683e012013-11-05 16:53:55 +00001318status_t Parcel::writePointer(uintptr_t val)
1319{
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08001320 return writeAligned<binder_uintptr_t>(val);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001321}
1322
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001323status_t Parcel::writeFloat(float val)
1324{
Andreas Huber84a6d042009-08-17 13:33:27 -07001325 return writeAligned(val);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001326}
1327
Douglas Leungcc1a4bb2013-01-11 15:00:55 -08001328#if defined(__mips__) && defined(__mips_hard_float)
1329
1330status_t Parcel::writeDouble(double val)
1331{
1332 union {
1333 double d;
1334 unsigned long long ll;
1335 } u;
1336 u.d = val;
1337 return writeAligned(u.ll);
1338}
1339
1340#else
1341
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001342status_t Parcel::writeDouble(double val)
1343{
Andreas Huber84a6d042009-08-17 13:33:27 -07001344 return writeAligned(val);
1345}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001346
Douglas Leungcc1a4bb2013-01-11 15:00:55 -08001347#endif
1348
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001349status_t Parcel::writeCString(const char* str)
1350{
1351 return write(str, strlen(str)+1);
1352}
1353
1354status_t Parcel::writeString8(const String8& str)
1355{
Jeff Sharkey2f8bdb52020-04-19 21:41:26 -06001356 return writeString8(str.string(), str.size());
1357}
1358
1359status_t Parcel::writeString8(const char* str, size_t len)
1360{
1361 if (str == nullptr) return writeInt32(-1);
1362
Jeff Sharkey18220902020-11-05 08:36:20 -07001363 // NOTE: Keep this logic in sync with android_os_Parcel.cpp
Jeff Sharkey2f8bdb52020-04-19 21:41:26 -06001364 status_t err = writeInt32(len);
1365 if (err == NO_ERROR) {
1366 uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char));
1367 if (data) {
1368 memcpy(data, str, len);
1369 *reinterpret_cast<char*>(data+len) = 0;
1370 return NO_ERROR;
1371 }
1372 err = mError;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001373 }
1374 return err;
1375}
1376
1377status_t Parcel::writeString16(const String16& str)
1378{
1379 return writeString16(str.string(), str.size());
1380}
1381
1382status_t Parcel::writeString16(const char16_t* str, size_t len)
1383{
Yi Kong91635562018-06-07 14:38:36 -07001384 if (str == nullptr) return writeInt32(-1);
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07001385
Jeff Sharkey18220902020-11-05 08:36:20 -07001386 // NOTE: Keep this logic in sync with android_os_Parcel.cpp
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001387 status_t err = writeInt32(len);
1388 if (err == NO_ERROR) {
1389 len *= sizeof(char16_t);
1390 uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
1391 if (data) {
1392 memcpy(data, str, len);
1393 *reinterpret_cast<char16_t*>(data+len) = 0;
1394 return NO_ERROR;
1395 }
1396 err = mError;
1397 }
1398 return err;
1399}
1400
1401status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
1402{
Steven Morelanda86a3562019-08-01 23:28:34 +00001403 return flattenBinder(val);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001404}
1405
Casey Dahlineb8e15f2015-11-03 13:50:37 -08001406
Casey Dahlinb9872622015-11-25 15:09:45 -08001407status_t Parcel::writeRawNullableParcelable(const Parcelable* parcelable) {
1408 if (!parcelable) {
1409 return writeInt32(0);
1410 }
1411
1412 return writeParcelable(*parcelable);
1413}
1414
Mathias Agopiana47f02a2009-05-21 16:29:38 -07001415status_t Parcel::writeNativeHandle(const native_handle* handle)
The Android Open Source Project5f78a482009-01-20 14:03:58 -08001416{
Mathias Agopian1d0a95b2009-07-31 16:12:13 -07001417 if (!handle || handle->version != sizeof(native_handle))
The Android Open Source Project5f78a482009-01-20 14:03:58 -08001418 return BAD_TYPE;
1419
1420 status_t err;
Mathias Agopiana47f02a2009-05-21 16:29:38 -07001421 err = writeInt32(handle->numFds);
The Android Open Source Project5f78a482009-01-20 14:03:58 -08001422 if (err != NO_ERROR) return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001423
Mathias Agopiana47f02a2009-05-21 16:29:38 -07001424 err = writeInt32(handle->numInts);
The Android Open Source Project5f78a482009-01-20 14:03:58 -08001425 if (err != NO_ERROR) return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001426
Mathias Agopiana47f02a2009-05-21 16:29:38 -07001427 for (int i=0 ; err==NO_ERROR && i<handle->numFds ; i++)
1428 err = writeDupFileDescriptor(handle->data[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001429
1430 if (err != NO_ERROR) {
Steve Block9d453682011-12-20 16:23:08 +00001431 ALOGD("write native handle, write dup fd failed");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001432 return err;
1433 }
Mathias Agopiana47f02a2009-05-21 16:29:38 -07001434 err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
The Android Open Source Project5f78a482009-01-20 14:03:58 -08001435 return err;
1436}
1437
Frederick Mayle69a0c992022-05-26 20:38:39 +00001438status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership) {
1439 if (auto* rpcFields = maybeRpcFields()) {
1440 std::variant<base::unique_fd, base::borrowed_fd> fdVariant;
1441 if (takeOwnership) {
1442 fdVariant = base::unique_fd(fd);
1443 } else {
1444 fdVariant = base::borrowed_fd(fd);
1445 }
1446 if (!mAllowFds) {
1447 return FDS_NOT_ALLOWED;
1448 }
1449 switch (rpcFields->mSession->getFileDescriptorTransportMode()) {
1450 case RpcSession::FileDescriptorTransportMode::NONE: {
1451 return FDS_NOT_ALLOWED;
1452 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001453 case RpcSession::FileDescriptorTransportMode::UNIX:
1454 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
Frederick Mayle69a0c992022-05-26 20:38:39 +00001455 if (rpcFields->mFds == nullptr) {
1456 rpcFields->mFds = std::make_unique<decltype(rpcFields->mFds)::element_type>();
1457 }
1458 size_t dataPos = mDataPos;
1459 if (dataPos > UINT32_MAX) {
1460 return NO_MEMORY;
1461 }
1462 if (status_t err = writeInt32(RpcFields::TYPE_NATIVE_FILE_DESCRIPTOR); err != OK) {
1463 return err;
1464 }
1465 if (status_t err = writeInt32(rpcFields->mFds->size()); err != OK) {
1466 return err;
1467 }
1468 rpcFields->mObjectPositions.push_back(dataPos);
1469 rpcFields->mFds->push_back(std::move(fdVariant));
1470 return OK;
1471 }
1472 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001473 }
1474
Andrei Homescua9cca9c2022-05-03 04:48:01 +00001475#ifdef BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001476 flat_binder_object obj;
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -07001477 obj.hdr.type = BINDER_TYPE_FD;
T.J. Mercierca0c2cb2022-12-19 21:56:35 +00001478 obj.flags = 0;
Arve Hjønnevåg07fd0f12014-02-18 21:10:29 -08001479 obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001480 obj.handle = fd;
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08001481 obj.cookie = takeOwnership ? 1 : 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001482 return writeObject(obj, true);
Andrei Homescua9cca9c2022-05-03 04:48:01 +00001483#else // BINDER_WITH_KERNEL_IPC
1484 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
1485 (void)fd;
1486 (void)takeOwnership;
1487 return INVALID_OPERATION;
1488#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001489}
1490
1491status_t Parcel::writeDupFileDescriptor(int fd)
1492{
Andrei Homescu24ad36e2022-08-04 01:33:33 +00001493 int dupFd;
1494 if (status_t err = dupFileDescriptor(fd, &dupFd); err != OK) {
1495 return err;
Jeff Brownd341c712011-11-04 20:19:33 -07001496 }
1497 status_t err = writeFileDescriptor(dupFd, true /*takeOwnership*/);
Casey Dahlin06673e32015-11-23 13:24:23 -08001498 if (err != OK) {
Jeff Brownd341c712011-11-04 20:19:33 -07001499 close(dupFd);
1500 }
1501 return err;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001502}
1503
Dianne Hackborn1941a402016-08-29 12:30:43 -07001504status_t Parcel::writeParcelFileDescriptor(int fd, bool takeOwnership)
1505{
1506 writeInt32(0);
1507 return writeFileDescriptor(fd, takeOwnership);
1508}
1509
Ryo Hashimotobf551892018-05-31 16:58:35 +09001510status_t Parcel::writeDupParcelFileDescriptor(int fd)
1511{
Andrei Homescu24ad36e2022-08-04 01:33:33 +00001512 int dupFd;
1513 if (status_t err = dupFileDescriptor(fd, &dupFd); err != OK) {
1514 return err;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001515 }
1516 status_t err = writeParcelFileDescriptor(dupFd, true /*takeOwnership*/);
1517 if (err != OK) {
1518 close(dupFd);
1519 }
1520 return err;
1521}
1522
Christopher Wiley2cf19952016-04-11 11:09:37 -07001523status_t Parcel::writeUniqueFileDescriptor(const base::unique_fd& fd) {
Casey Dahlin06673e32015-11-23 13:24:23 -08001524 return writeDupFileDescriptor(fd.get());
1525}
1526
Jeff Brown13b16042014-11-11 16:44:25 -08001527status_t Parcel::writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob)
Jeff Brown5707dbf2011-09-23 21:17:56 -07001528{
Nick Kralevichb6b14232015-04-02 09:36:02 -07001529 if (len > INT32_MAX) {
1530 // don't accept size_t values which may have come from an
1531 // inadvertent conversion from a negative int.
1532 return BAD_VALUE;
1533 }
1534
Jeff Brown13b16042014-11-11 16:44:25 -08001535 status_t status;
1536 if (!mAllowFds || len <= BLOB_INPLACE_LIMIT) {
Steve Block6807e592011-10-20 11:56:00 +01001537 ALOGV("writeBlob: write in place");
Jeff Brown13b16042014-11-11 16:44:25 -08001538 status = writeInt32(BLOB_INPLACE);
Jeff Brown5707dbf2011-09-23 21:17:56 -07001539 if (status) return status;
1540
1541 void* ptr = writeInplace(len);
1542 if (!ptr) return NO_MEMORY;
1543
Jeff Brown13b16042014-11-11 16:44:25 -08001544 outBlob->init(-1, ptr, len, false);
Jeff Brown5707dbf2011-09-23 21:17:56 -07001545 return NO_ERROR;
1546 }
1547
Steve Block6807e592011-10-20 11:56:00 +01001548 ALOGV("writeBlob: write to ashmem");
Jeff Brown5707dbf2011-09-23 21:17:56 -07001549 int fd = ashmem_create_region("Parcel Blob", len);
1550 if (fd < 0) return NO_MEMORY;
1551
1552 int result = ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
1553 if (result < 0) {
Jeff Brownec4e0062011-10-10 14:50:10 -07001554 status = result;
Jeff Brown5707dbf2011-09-23 21:17:56 -07001555 } else {
Yi Kong91635562018-06-07 14:38:36 -07001556 void* ptr = ::mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Jeff Brown5707dbf2011-09-23 21:17:56 -07001557 if (ptr == MAP_FAILED) {
1558 status = -errno;
1559 } else {
Jeff Brown13b16042014-11-11 16:44:25 -08001560 if (!mutableCopy) {
1561 result = ashmem_set_prot_region(fd, PROT_READ);
1562 }
Jeff Brown5707dbf2011-09-23 21:17:56 -07001563 if (result < 0) {
Jeff Brownec4e0062011-10-10 14:50:10 -07001564 status = result;
Jeff Brown5707dbf2011-09-23 21:17:56 -07001565 } else {
Jeff Brown13b16042014-11-11 16:44:25 -08001566 status = writeInt32(mutableCopy ? BLOB_ASHMEM_MUTABLE : BLOB_ASHMEM_IMMUTABLE);
Jeff Brown5707dbf2011-09-23 21:17:56 -07001567 if (!status) {
Jeff Brown93ff1f92011-11-04 19:01:44 -07001568 status = writeFileDescriptor(fd, true /*takeOwnership*/);
Jeff Brown5707dbf2011-09-23 21:17:56 -07001569 if (!status) {
Jeff Brown13b16042014-11-11 16:44:25 -08001570 outBlob->init(fd, ptr, len, mutableCopy);
Jeff Brown5707dbf2011-09-23 21:17:56 -07001571 return NO_ERROR;
1572 }
1573 }
1574 }
1575 }
1576 ::munmap(ptr, len);
1577 }
1578 ::close(fd);
1579 return status;
1580}
1581
Jeff Brown13b16042014-11-11 16:44:25 -08001582status_t Parcel::writeDupImmutableBlobFileDescriptor(int fd)
1583{
1584 // Must match up with what's done in writeBlob.
1585 if (!mAllowFds) return FDS_NOT_ALLOWED;
1586 status_t status = writeInt32(BLOB_ASHMEM_IMMUTABLE);
1587 if (status) return status;
1588 return writeDupFileDescriptor(fd);
1589}
1590
Mathias Agopiane1424282013-07-29 21:24:40 -07001591status_t Parcel::write(const FlattenableHelperInterface& val)
Mathias Agopian98e71dd2010-02-11 17:30:52 -08001592{
1593 status_t err;
1594
1595 // size if needed
Mathias Agopiane1424282013-07-29 21:24:40 -07001596 const size_t len = val.getFlattenedSize();
1597 const size_t fd_count = val.getFdCount();
Mathias Agopian98e71dd2010-02-11 17:30:52 -08001598
Andrei Homescu1519b982022-06-09 02:04:44 +00001599 if ((len > INT32_MAX) || (fd_count > kMaxFds)) {
Nick Kralevichb6b14232015-04-02 09:36:02 -07001600 // don't accept size_t values which may have come from an
1601 // inadvertent conversion from a negative int.
1602 return BAD_VALUE;
1603 }
1604
Mathias Agopian98e71dd2010-02-11 17:30:52 -08001605 err = this->writeInt32(len);
1606 if (err) return err;
1607
1608 err = this->writeInt32(fd_count);
1609 if (err) return err;
1610
1611 // payload
Martijn Coenenf8542382018-04-04 11:46:56 +02001612 void* const buf = this->writeInplace(len);
Yi Kong91635562018-06-07 14:38:36 -07001613 if (buf == nullptr)
Mathias Agopian98e71dd2010-02-11 17:30:52 -08001614 return BAD_VALUE;
1615
Yi Kong91635562018-06-07 14:38:36 -07001616 int* fds = nullptr;
Mathias Agopian98e71dd2010-02-11 17:30:52 -08001617 if (fd_count) {
Christopher Tatee4e0ae82016-03-24 16:03:44 -07001618 fds = new (std::nothrow) int[fd_count];
1619 if (fds == nullptr) {
1620 ALOGE("write: failed to allocate requested %zu fds", fd_count);
1621 return BAD_VALUE;
1622 }
Mathias Agopian98e71dd2010-02-11 17:30:52 -08001623 }
1624
1625 err = val.flatten(buf, len, fds, fd_count);
1626 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
1627 err = this->writeDupFileDescriptor( fds[i] );
1628 }
1629
1630 if (fd_count) {
1631 delete [] fds;
1632 }
1633
1634 return err;
1635}
1636
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001637status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
1638{
Frederick Mayled3c595a2022-05-09 23:02:54 +00001639 auto* kernelFields = maybeKernelFields();
1640 LOG_ALWAYS_FATAL_IF(kernelFields == nullptr, "Can't write flat_binder_object to RPC Parcel");
1641
Andrei Homescua9cca9c2022-05-03 04:48:01 +00001642#ifdef BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001643 const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
Frederick Mayled3c595a2022-05-09 23:02:54 +00001644 const bool enoughObjects = kernelFields->mObjectsSize < kernelFields->mObjectsCapacity;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001645 if (enoughData && enoughObjects) {
1646restart_write:
1647 *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07001648
Christopher Tate98e67d32015-06-03 18:44:15 -07001649 // remember if it's a file descriptor
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -07001650 if (val.hdr.type == BINDER_TYPE_FD) {
Christopher Tate98e67d32015-06-03 18:44:15 -07001651 if (!mAllowFds) {
1652 // fail before modifying our object index
1653 return FDS_NOT_ALLOWED;
1654 }
Frederick Mayled3c595a2022-05-09 23:02:54 +00001655 kernelFields->mHasFds = kernelFields->mFdsKnown = true;
Christopher Tate98e67d32015-06-03 18:44:15 -07001656 }
1657
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001658 // Need to write meta-data?
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08001659 if (nullMetaData || val.binder != 0) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00001660 kernelFields->mObjects[kernelFields->mObjectsSize] = mDataPos;
Steven Morelandc673f1f2021-10-07 18:23:35 -07001661 acquire_object(ProcessState::self(), val, this);
Frederick Mayled3c595a2022-05-09 23:02:54 +00001662 kernelFields->mObjectsSize++;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001663 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07001664
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001665 return finishWrite(sizeof(flat_binder_object));
1666 }
1667
1668 if (!enoughData) {
1669 const status_t err = growData(sizeof(val));
1670 if (err != NO_ERROR) return err;
1671 }
1672 if (!enoughObjects) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00001673 if (kernelFields->mObjectsSize > SIZE_MAX - 2) return NO_MEMORY; // overflow
1674 if ((kernelFields->mObjectsSize + 2) > SIZE_MAX / 3) return NO_MEMORY; // overflow
1675 size_t newSize = ((kernelFields->mObjectsSize + 2) * 3) / 2;
Martijn Coenen93fe5182020-01-22 10:46:25 +01001676 if (newSize > SIZE_MAX / sizeof(binder_size_t)) return NO_MEMORY; // overflow
Frederick Mayled3c595a2022-05-09 23:02:54 +00001677 binder_size_t* objects =
1678 (binder_size_t*)realloc(kernelFields->mObjects, newSize * sizeof(binder_size_t));
Yi Kong91635562018-06-07 14:38:36 -07001679 if (objects == nullptr) return NO_MEMORY;
Frederick Mayled3c595a2022-05-09 23:02:54 +00001680 kernelFields->mObjects = objects;
1681 kernelFields->mObjectsCapacity = newSize;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001682 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07001683
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001684 goto restart_write;
Andrei Homescua9cca9c2022-05-03 04:48:01 +00001685#else // BINDER_WITH_KERNEL_IPC
1686 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
1687 (void)val;
1688 (void)nullMetaData;
1689 return INVALID_OPERATION;
1690#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001691}
1692
Brad Fitzpatrick837a0d02010-07-13 15:33:35 -07001693status_t Parcel::writeNoException()
1694{
Christopher Wiley09eb7492015-11-09 15:06:15 -08001695 binder::Status status;
1696 return status.writeToParcel(this);
Brad Fitzpatrick837a0d02010-07-13 15:33:35 -07001697}
1698
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001699status_t Parcel::validateReadData(size_t upperBound) const
1700{
Frederick Mayled3c595a2022-05-09 23:02:54 +00001701 const auto* kernelFields = maybeKernelFields();
1702 if (kernelFields == nullptr) {
1703 // Can't validate RPC Parcel reads because the location of binder
1704 // objects is unknown.
1705 return OK;
1706 }
1707
Andrei Homescua9cca9c2022-05-03 04:48:01 +00001708#ifdef BINDER_WITH_KERNEL_IPC
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001709 // Don't allow non-object reads on object data
Frederick Mayled3c595a2022-05-09 23:02:54 +00001710 if (kernelFields->mObjectsSorted || kernelFields->mObjectsSize <= 1) {
1711 data_sorted:
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001712 // Expect to check only against the next object
Frederick Mayled3c595a2022-05-09 23:02:54 +00001713 if (kernelFields->mNextObjectHint < kernelFields->mObjectsSize &&
1714 upperBound > kernelFields->mObjects[kernelFields->mNextObjectHint]) {
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001715 // For some reason the current read position is greater than the next object
1716 // hint. Iterate until we find the right object
Frederick Mayled3c595a2022-05-09 23:02:54 +00001717 size_t nextObject = kernelFields->mNextObjectHint;
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001718 do {
Frederick Mayled3c595a2022-05-09 23:02:54 +00001719 if (mDataPos < kernelFields->mObjects[nextObject] + sizeof(flat_binder_object)) {
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001720 // Requested info overlaps with an object
1721 ALOGE("Attempt to read from protected data in Parcel %p", this);
1722 return PERMISSION_DENIED;
1723 }
1724 nextObject++;
Frederick Mayled3c595a2022-05-09 23:02:54 +00001725 } while (nextObject < kernelFields->mObjectsSize &&
1726 upperBound > kernelFields->mObjects[nextObject]);
1727 kernelFields->mNextObjectHint = nextObject;
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001728 }
1729 return NO_ERROR;
1730 }
1731 // Quickly determine if mObjects is sorted.
Frederick Mayled3c595a2022-05-09 23:02:54 +00001732 binder_size_t* currObj = kernelFields->mObjects + kernelFields->mObjectsSize - 1;
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001733 binder_size_t* prevObj = currObj;
Frederick Mayled3c595a2022-05-09 23:02:54 +00001734 while (currObj > kernelFields->mObjects) {
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001735 prevObj--;
1736 if(*prevObj > *currObj) {
1737 goto data_unsorted;
1738 }
1739 currObj--;
1740 }
Frederick Mayled3c595a2022-05-09 23:02:54 +00001741 kernelFields->mObjectsSorted = true;
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001742 goto data_sorted;
1743
1744data_unsorted:
1745 // Insertion Sort mObjects
1746 // Great for mostly sorted lists. If randomly sorted or reverse ordered mObjects become common,
1747 // switch to std::sort(mObjects, mObjects + mObjectsSize);
Frederick Mayled3c595a2022-05-09 23:02:54 +00001748 for (binder_size_t* iter0 = kernelFields->mObjects + 1;
1749 iter0 < kernelFields->mObjects + kernelFields->mObjectsSize; iter0++) {
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001750 binder_size_t temp = *iter0;
1751 binder_size_t* iter1 = iter0 - 1;
Frederick Mayled3c595a2022-05-09 23:02:54 +00001752 while (iter1 >= kernelFields->mObjects && *iter1 > temp) {
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001753 *(iter1 + 1) = *iter1;
1754 iter1--;
1755 }
1756 *(iter1 + 1) = temp;
1757 }
Frederick Mayled3c595a2022-05-09 23:02:54 +00001758 kernelFields->mNextObjectHint = 0;
1759 kernelFields->mObjectsSorted = true;
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001760 goto data_sorted;
Andrei Homescua9cca9c2022-05-03 04:48:01 +00001761#else // BINDER_WITH_KERNEL_IPC
1762 (void)upperBound;
1763 return NO_ERROR;
1764#endif // BINDER_WITH_KERNEL_IPC
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001765}
1766
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001767status_t Parcel::read(void* outData, size_t len) const
1768{
Nick Kralevichb6b14232015-04-02 09:36:02 -07001769 if (len > INT32_MAX) {
1770 // don't accept size_t values which may have come from an
1771 // inadvertent conversion from a negative int.
1772 return BAD_VALUE;
1773 }
1774
1775 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1776 && len <= pad_size(len)) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00001777 const auto* kernelFields = maybeKernelFields();
1778 if (kernelFields != nullptr && kernelFields->mObjectsSize > 0) {
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001779 status_t err = validateReadData(mDataPos + pad_size(len));
Michael Wachenschwanza17f0222018-04-17 16:52:40 -07001780 if(err != NO_ERROR) {
1781 // Still increment the data position by the expected length
1782 mDataPos += pad_size(len);
1783 ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
1784 return err;
1785 }
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001786 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001787 memcpy(outData, mData+mDataPos, len);
Nick Kralevichb6b14232015-04-02 09:36:02 -07001788 mDataPos += pad_size(len);
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07001789 ALOGV("read Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001790 return NO_ERROR;
1791 }
1792 return NOT_ENOUGH_DATA;
1793}
1794
1795const void* Parcel::readInplace(size_t len) const
1796{
Nick Kralevichb6b14232015-04-02 09:36:02 -07001797 if (len > INT32_MAX) {
1798 // don't accept size_t values which may have come from an
1799 // inadvertent conversion from a negative int.
Yi Kong91635562018-06-07 14:38:36 -07001800 return nullptr;
Nick Kralevichb6b14232015-04-02 09:36:02 -07001801 }
1802
1803 if ((mDataPos+pad_size(len)) >= mDataPos && (mDataPos+pad_size(len)) <= mDataSize
1804 && len <= pad_size(len)) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00001805 const auto* kernelFields = maybeKernelFields();
1806 if (kernelFields != nullptr && kernelFields->mObjectsSize > 0) {
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001807 status_t err = validateReadData(mDataPos + pad_size(len));
Michael Wachenschwanza17f0222018-04-17 16:52:40 -07001808 if(err != NO_ERROR) {
1809 // Still increment the data position by the expected length
1810 mDataPos += pad_size(len);
1811 ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
Yi Kong91635562018-06-07 14:38:36 -07001812 return nullptr;
Michael Wachenschwanza17f0222018-04-17 16:52:40 -07001813 }
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001814 }
1815
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001816 const void* data = mData+mDataPos;
Nick Kralevichb6b14232015-04-02 09:36:02 -07001817 mDataPos += pad_size(len);
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07001818 ALOGV("readInplace Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001819 return data;
1820 }
Yi Kong91635562018-06-07 14:38:36 -07001821 return nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001822}
1823
Steven Morelandd4f73fb2021-05-14 19:50:52 +00001824status_t Parcel::readOutVectorSizeWithCheck(size_t elmSize, int32_t* size) const {
1825 if (status_t status = readInt32(size); status != OK) return status;
1826 if (*size < 0) return OK; // may be null, client to handle
1827
1828 LOG_ALWAYS_FATAL_IF(elmSize > INT32_MAX, "Cannot have element as big as %zu", elmSize);
1829
1830 // approximation, can't know max element size (e.g. if it makes heap
1831 // allocations)
1832 static_assert(sizeof(int) == sizeof(int32_t), "Android is LP64");
1833 int32_t allocationSize;
1834 if (__builtin_smul_overflow(elmSize, *size, &allocationSize)) return NO_MEMORY;
1835
1836 // High limit of 1MB since something this big could never be returned. Could
1837 // probably scope this down, but might impact very specific usecases.
1838 constexpr int32_t kMaxAllocationSize = 1 * 1000 * 1000;
1839
1840 if (allocationSize >= kMaxAllocationSize) {
1841 return NO_MEMORY;
1842 }
1843
1844 return OK;
1845}
1846
Andreas Huber84a6d042009-08-17 13:33:27 -07001847template<class T>
1848status_t Parcel::readAligned(T *pArg) const {
Elliott Hughes42a9b942020-08-17 15:53:31 -07001849 static_assert(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
Andrei Homescue33238e2022-03-29 22:50:00 +00001850 static_assert(std::is_trivially_copyable_v<T>);
Andreas Huber84a6d042009-08-17 13:33:27 -07001851
1852 if ((mDataPos+sizeof(T)) <= mDataSize) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00001853 const auto* kernelFields = maybeKernelFields();
1854 if (kernelFields != nullptr && kernelFields->mObjectsSize > 0) {
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001855 status_t err = validateReadData(mDataPos + sizeof(T));
Michael Wachenschwanza17f0222018-04-17 16:52:40 -07001856 if(err != NO_ERROR) {
1857 // Still increment the data position by the expected length
1858 mDataPos += sizeof(T);
1859 return err;
1860 }
Michael Wachenschwanzc5176812017-11-17 18:25:05 -08001861 }
1862
Andrei Homescue33238e2022-03-29 22:50:00 +00001863 memcpy(pArg, mData + mDataPos, sizeof(T));
Andreas Huber84a6d042009-08-17 13:33:27 -07001864 mDataPos += sizeof(T);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001865 return NO_ERROR;
1866 } else {
1867 return NOT_ENOUGH_DATA;
1868 }
1869}
1870
Andreas Huber84a6d042009-08-17 13:33:27 -07001871template<class T>
1872T Parcel::readAligned() const {
1873 T result;
1874 if (readAligned(&result) != NO_ERROR) {
1875 result = 0;
1876 }
1877
1878 return result;
1879}
1880
1881template<class T>
1882status_t Parcel::writeAligned(T val) {
Elliott Hughes42a9b942020-08-17 15:53:31 -07001883 static_assert(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
Andrei Homescue33238e2022-03-29 22:50:00 +00001884 static_assert(std::is_trivially_copyable_v<T>);
Andreas Huber84a6d042009-08-17 13:33:27 -07001885
1886 if ((mDataPos+sizeof(val)) <= mDataCapacity) {
1887restart_write:
Andrei Homescue33238e2022-03-29 22:50:00 +00001888 memcpy(mData + mDataPos, &val, sizeof(val));
Andreas Huber84a6d042009-08-17 13:33:27 -07001889 return finishWrite(sizeof(val));
1890 }
1891
1892 status_t err = growData(sizeof(val));
1893 if (err == NO_ERROR) goto restart_write;
1894 return err;
1895}
1896
1897status_t Parcel::readInt32(int32_t *pArg) const
1898{
1899 return readAligned(pArg);
1900}
1901
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001902int32_t Parcel::readInt32() const
1903{
Andreas Huber84a6d042009-08-17 13:33:27 -07001904 return readAligned<int32_t>();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001905}
1906
Dan Stoza41a0f2f2014-12-01 10:01:10 -08001907status_t Parcel::readUint32(uint32_t *pArg) const
1908{
1909 return readAligned(pArg);
1910}
1911
1912uint32_t Parcel::readUint32() const
1913{
1914 return readAligned<uint32_t>();
1915}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001916
1917status_t Parcel::readInt64(int64_t *pArg) const
1918{
Andreas Huber84a6d042009-08-17 13:33:27 -07001919 return readAligned(pArg);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001920}
1921
1922
1923int64_t Parcel::readInt64() const
1924{
Andreas Huber84a6d042009-08-17 13:33:27 -07001925 return readAligned<int64_t>();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001926}
1927
Ronghua Wu2d13afd2015-03-16 11:11:07 -07001928status_t Parcel::readUint64(uint64_t *pArg) const
1929{
1930 return readAligned(pArg);
1931}
1932
1933uint64_t Parcel::readUint64() const
1934{
1935 return readAligned<uint64_t>();
1936}
1937
Serban Constantinescuf683e012013-11-05 16:53:55 +00001938status_t Parcel::readPointer(uintptr_t *pArg) const
1939{
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08001940 status_t ret;
1941 binder_uintptr_t ptr;
1942 ret = readAligned(&ptr);
1943 if (!ret)
1944 *pArg = ptr;
1945 return ret;
Serban Constantinescuf683e012013-11-05 16:53:55 +00001946}
1947
1948uintptr_t Parcel::readPointer() const
1949{
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08001950 return readAligned<binder_uintptr_t>();
Serban Constantinescuf683e012013-11-05 16:53:55 +00001951}
1952
1953
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001954status_t Parcel::readFloat(float *pArg) const
1955{
Andreas Huber84a6d042009-08-17 13:33:27 -07001956 return readAligned(pArg);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001957}
1958
1959
1960float Parcel::readFloat() const
1961{
Andreas Huber84a6d042009-08-17 13:33:27 -07001962 return readAligned<float>();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001963}
1964
Douglas Leungcc1a4bb2013-01-11 15:00:55 -08001965#if defined(__mips__) && defined(__mips_hard_float)
1966
1967status_t Parcel::readDouble(double *pArg) const
1968{
1969 union {
1970 double d;
1971 unsigned long long ll;
1972 } u;
Narayan Kamath2c68d382014-06-04 15:04:29 +01001973 u.d = 0;
Douglas Leungcc1a4bb2013-01-11 15:00:55 -08001974 status_t status;
1975 status = readAligned(&u.ll);
1976 *pArg = u.d;
1977 return status;
1978}
1979
1980double Parcel::readDouble() const
1981{
1982 union {
1983 double d;
1984 unsigned long long ll;
1985 } u;
1986 u.ll = readAligned<unsigned long long>();
1987 return u.d;
1988}
1989
1990#else
1991
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001992status_t Parcel::readDouble(double *pArg) const
1993{
Andreas Huber84a6d042009-08-17 13:33:27 -07001994 return readAligned(pArg);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001995}
1996
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001997double Parcel::readDouble() const
1998{
Andreas Huber84a6d042009-08-17 13:33:27 -07001999 return readAligned<double>();
2000}
2001
Douglas Leungcc1a4bb2013-01-11 15:00:55 -08002002#endif
2003
Casey Dahlind6848f52015-10-15 15:44:59 -07002004status_t Parcel::readBool(bool *pArg) const
2005{
Manoj Gupta6eb62052017-07-12 10:29:15 -07002006 int32_t tmp = 0;
Casey Dahlind6848f52015-10-15 15:44:59 -07002007 status_t ret = readInt32(&tmp);
2008 *pArg = (tmp != 0);
2009 return ret;
2010}
2011
2012bool Parcel::readBool() const
2013{
2014 return readInt32() != 0;
2015}
2016
2017status_t Parcel::readChar(char16_t *pArg) const
2018{
Manoj Gupta6eb62052017-07-12 10:29:15 -07002019 int32_t tmp = 0;
Casey Dahlind6848f52015-10-15 15:44:59 -07002020 status_t ret = readInt32(&tmp);
2021 *pArg = char16_t(tmp);
2022 return ret;
2023}
2024
2025char16_t Parcel::readChar() const
2026{
2027 return char16_t(readInt32());
2028}
2029
2030status_t Parcel::readByte(int8_t *pArg) const
2031{
Manoj Gupta6eb62052017-07-12 10:29:15 -07002032 int32_t tmp = 0;
Casey Dahlind6848f52015-10-15 15:44:59 -07002033 status_t ret = readInt32(&tmp);
2034 *pArg = int8_t(tmp);
2035 return ret;
2036}
2037
2038int8_t Parcel::readByte() const
2039{
2040 return int8_t(readInt32());
2041}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002042
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08002043status_t Parcel::readUtf8FromUtf16(std::string* str) const {
2044 size_t utf16Size = 0;
2045 const char16_t* src = readString16Inplace(&utf16Size);
2046 if (!src) {
2047 return UNEXPECTED_NULL;
2048 }
2049
2050 // Save ourselves the trouble, we're done.
2051 if (utf16Size == 0u) {
2052 str->clear();
2053 return NO_ERROR;
2054 }
2055
Sergio Giro9b39ebe2016-06-28 18:19:33 +01002056 // Allow for closing '\0'
2057 ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1;
2058 if (utf8Size < 1) {
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08002059 return BAD_VALUE;
2060 }
2061 // Note that while it is probably safe to assume string::resize keeps a
Sergio Giro9b39ebe2016-06-28 18:19:33 +01002062 // spare byte around for the trailing null, we still pass the size including the trailing null
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08002063 str->resize(utf8Size);
Sergio Giro9b39ebe2016-06-28 18:19:33 +01002064 utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size);
2065 str->resize(utf8Size - 1);
Christopher Wiley9a5e32f2016-01-28 16:56:53 -08002066 return NO_ERROR;
2067}
2068
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002069const char* Parcel::readCString() const
2070{
Steven Morelandd0d4b582019-05-17 13:14:06 -07002071 if (mDataPos < mDataSize) {
2072 const size_t avail = mDataSize-mDataPos;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002073 const char* str = reinterpret_cast<const char*>(mData+mDataPos);
2074 // is the string's trailing NUL within the parcel's valid bounds?
2075 const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail));
2076 if (eos) {
2077 const size_t len = eos - str;
Nick Kralevichb6b14232015-04-02 09:36:02 -07002078 mDataPos += pad_size(len+1);
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002079 ALOGV("readCString Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002080 return str;
2081 }
2082 }
Yi Kong91635562018-06-07 14:38:36 -07002083 return nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002084}
2085
2086String8 Parcel::readString8() const
2087{
Jeff Sharkey2f8bdb52020-04-19 21:41:26 -06002088 size_t len;
2089 const char* str = readString8Inplace(&len);
2090 if (str) return String8(str, len);
2091 ALOGE("Reading a NULL string not supported here.");
2092 return String8();
Roshan Pius87b64d22016-07-18 12:51:02 -07002093}
2094
2095status_t Parcel::readString8(String8* pArg) const
2096{
Jeff Sharkey2f8bdb52020-04-19 21:41:26 -06002097 size_t len;
2098 const char* str = readString8Inplace(&len);
2099 if (str) {
2100 pArg->setTo(str, len);
2101 return 0;
2102 } else {
Roshan Pius87b64d22016-07-18 12:51:02 -07002103 *pArg = String8();
Jeff Sharkey2f8bdb52020-04-19 21:41:26 -06002104 return UNEXPECTED_NULL;
Roshan Pius87b64d22016-07-18 12:51:02 -07002105 }
Jeff Sharkey2f8bdb52020-04-19 21:41:26 -06002106}
2107
2108const char* Parcel::readString8Inplace(size_t* outLen) const
2109{
2110 int32_t size = readInt32();
2111 // watch for potential int overflow from size+1
2112 if (size >= 0 && size < INT32_MAX) {
2113 *outLen = size;
2114 const char* str = (const char*)readInplace(size+1);
Steven Moreland61d0f842020-12-04 21:13:03 +00002115 if (str != nullptr) {
2116 if (str[size] == '\0') {
2117 return str;
2118 }
2119 android_errorWriteLog(0x534e4554, "172655291");
Jeff Sharkey2f8bdb52020-04-19 21:41:26 -06002120 }
Roshan Pius87b64d22016-07-18 12:51:02 -07002121 }
Jeff Sharkey2f8bdb52020-04-19 21:41:26 -06002122 *outLen = 0;
2123 return nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002124}
2125
2126String16 Parcel::readString16() const
2127{
2128 size_t len;
2129 const char16_t* str = readString16Inplace(&len);
2130 if (str) return String16(str, len);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002131 ALOGE("Reading a NULL string not supported here.");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002132 return String16();
2133}
2134
Casey Dahlinb9872622015-11-25 15:09:45 -08002135
Casey Dahlin451ff582015-10-19 18:12:18 -07002136status_t Parcel::readString16(String16* pArg) const
2137{
2138 size_t len;
2139 const char16_t* str = readString16Inplace(&len);
2140 if (str) {
Casey Dahlin1515ea12015-10-20 16:26:23 -07002141 pArg->setTo(str, len);
Casey Dahlin451ff582015-10-19 18:12:18 -07002142 return 0;
2143 } else {
2144 *pArg = String16();
Christopher Wiley4db672d2015-11-10 09:44:30 -08002145 return UNEXPECTED_NULL;
Casey Dahlin451ff582015-10-19 18:12:18 -07002146 }
2147}
2148
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002149const char16_t* Parcel::readString16Inplace(size_t* outLen) const
2150{
2151 int32_t size = readInt32();
2152 // watch for potential int overflow from size+1
2153 if (size >= 0 && size < INT32_MAX) {
2154 *outLen = size;
2155 const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t));
Steven Moreland61d0f842020-12-04 21:13:03 +00002156 if (str != nullptr) {
2157 if (str[size] == u'\0') {
2158 return str;
2159 }
2160 android_errorWriteLog(0x534e4554, "172655291");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002161 }
2162 }
2163 *outLen = 0;
Yi Kong91635562018-06-07 14:38:36 -07002164 return nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002165}
2166
Casey Dahlinf0c13772015-10-27 18:33:56 -07002167status_t Parcel::readStrongBinder(sp<IBinder>* val) const
2168{
Christopher Wiley35d77ca2016-03-08 10:49:51 -08002169 status_t status = readNullableStrongBinder(val);
2170 if (status == OK && !val->get()) {
Steven Morelanddce98242022-03-11 00:26:10 +00002171 ALOGW("Expecting binder but got null!");
Christopher Wiley35d77ca2016-03-08 10:49:51 -08002172 status = UNEXPECTED_NULL;
2173 }
2174 return status;
2175}
2176
2177status_t Parcel::readNullableStrongBinder(sp<IBinder>* val) const
2178{
Steven Morelanda86a3562019-08-01 23:28:34 +00002179 return unflattenBinder(val);
Casey Dahlinf0c13772015-10-27 18:33:56 -07002180}
2181
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002182sp<IBinder> Parcel::readStrongBinder() const
2183{
2184 sp<IBinder> val;
Christopher Wiley35d77ca2016-03-08 10:49:51 -08002185 // Note that a lot of code in Android reads binders by hand with this
2186 // method, and that code has historically been ok with getting nullptr
2187 // back (while ignoring error codes).
2188 readNullableStrongBinder(&val);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002189 return val;
2190}
2191
Brad Fitzpatrick837a0d02010-07-13 15:33:35 -07002192int32_t Parcel::readExceptionCode() const
2193{
Christopher Wiley09eb7492015-11-09 15:06:15 -08002194 binder::Status status;
2195 status.readFromParcel(*this);
2196 return status.exceptionCode();
Brad Fitzpatrick837a0d02010-07-13 15:33:35 -07002197}
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002198
Mathias Agopiana47f02a2009-05-21 16:29:38 -07002199native_handle* Parcel::readNativeHandle() const
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002200{
2201 int numFds, numInts;
2202 status_t err;
2203 err = readInt32(&numFds);
Yi Kong91635562018-06-07 14:38:36 -07002204 if (err != NO_ERROR) return nullptr;
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002205 err = readInt32(&numInts);
Yi Kong91635562018-06-07 14:38:36 -07002206 if (err != NO_ERROR) return nullptr;
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002207
Mathias Agopiana47f02a2009-05-21 16:29:38 -07002208 native_handle* h = native_handle_create(numFds, numInts);
Adam Lesinskieaac99a2015-05-12 17:35:48 -07002209 if (!h) {
Yi Kong91635562018-06-07 14:38:36 -07002210 return nullptr;
Adam Lesinskieaac99a2015-05-12 17:35:48 -07002211 }
2212
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002213 for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
Nick Kralevichec9ec7d2016-12-17 19:47:27 -08002214 h->data[i] = fcntl(readFileDescriptor(), F_DUPFD_CLOEXEC, 0);
Marco Nelissen1de79662016-04-26 08:44:09 -07002215 if (h->data[i] < 0) {
2216 for (int j = 0; j < i; j++) {
2217 close(h->data[j]);
2218 }
2219 native_handle_delete(h);
Yi Kong91635562018-06-07 14:38:36 -07002220 return nullptr;
Marco Nelissen1de79662016-04-26 08:44:09 -07002221 }
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002222 }
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002223 err = read(h->data + numFds, sizeof(int)*numInts);
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002224 if (err != NO_ERROR) {
Mathias Agopiana47f02a2009-05-21 16:29:38 -07002225 native_handle_close(h);
2226 native_handle_delete(h);
Yi Kong91635562018-06-07 14:38:36 -07002227 h = nullptr;
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002228 }
2229 return h;
2230}
2231
Frederick Mayle69a0c992022-05-26 20:38:39 +00002232int Parcel::readFileDescriptor() const {
2233 if (const auto* rpcFields = maybeRpcFields()) {
2234 if (!std::binary_search(rpcFields->mObjectPositions.begin(),
2235 rpcFields->mObjectPositions.end(), mDataPos)) {
2236 ALOGW("Attempt to read file descriptor from Parcel %p at offset %zu that is not in the "
2237 "object list",
2238 this, mDataPos);
2239 return BAD_TYPE;
2240 }
2241
2242 int32_t objectType = readInt32();
2243 if (objectType != RpcFields::TYPE_NATIVE_FILE_DESCRIPTOR) {
2244 return BAD_TYPE;
2245 }
2246
2247 int32_t fdIndex = readInt32();
2248 if (rpcFields->mFds == nullptr || fdIndex < 0 ||
2249 static_cast<size_t>(fdIndex) >= rpcFields->mFds->size()) {
2250 ALOGE("RPC Parcel contains invalid file descriptor index. index=%d fd_count=%zu",
2251 fdIndex, rpcFields->mFds ? rpcFields->mFds->size() : 0);
2252 return BAD_VALUE;
2253 }
2254 return toRawFd(rpcFields->mFds->at(fdIndex));
2255 }
2256
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002257#ifdef BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002258 const flat_binder_object* flat = readObject(true);
Casey Dahlin06673e32015-11-23 13:24:23 -08002259
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -07002260 if (flat && flat->hdr.type == BINDER_TYPE_FD) {
Casey Dahlin06673e32015-11-23 13:24:23 -08002261 return flat->handle;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002262 }
Casey Dahlin06673e32015-11-23 13:24:23 -08002263
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002264 return BAD_TYPE;
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002265#else // BINDER_WITH_KERNEL_IPC
2266 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
2267 return INVALID_OPERATION;
2268#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002269}
2270
Frederick Mayle69a0c992022-05-26 20:38:39 +00002271int Parcel::readParcelFileDescriptor() const {
Dianne Hackborn1941a402016-08-29 12:30:43 -07002272 int32_t hasComm = readInt32();
2273 int fd = readFileDescriptor();
2274 if (hasComm != 0) {
Steven Morelandb73806a2018-11-12 19:35:47 -08002275 // detach (owned by the binder driver)
2276 int comm = readFileDescriptor();
2277
2278 // warning: this must be kept in sync with:
2279 // frameworks/base/core/java/android/os/ParcelFileDescriptor.java
2280 enum ParcelFileDescriptorStatus {
2281 DETACHED = 2,
2282 };
2283
2284#if BYTE_ORDER == BIG_ENDIAN
2285 const int32_t message = ParcelFileDescriptorStatus::DETACHED;
2286#endif
2287#if BYTE_ORDER == LITTLE_ENDIAN
2288 const int32_t message = __builtin_bswap32(ParcelFileDescriptorStatus::DETACHED);
2289#endif
2290
2291 ssize_t written = TEMP_FAILURE_RETRY(
2292 ::write(comm, &message, sizeof(message)));
2293
Krzysztof Kosińskia8406892021-02-02 17:59:43 -08002294 if (written != sizeof(message)) {
Steven Morelandb73806a2018-11-12 19:35:47 -08002295 ALOGW("Failed to detach ParcelFileDescriptor written: %zd err: %s",
2296 written, strerror(errno));
2297 return BAD_TYPE;
2298 }
Dianne Hackborn1941a402016-08-29 12:30:43 -07002299 }
2300 return fd;
2301}
2302
Christopher Wiley2cf19952016-04-11 11:09:37 -07002303status_t Parcel::readUniqueFileDescriptor(base::unique_fd* val) const
Casey Dahlin06673e32015-11-23 13:24:23 -08002304{
2305 int got = readFileDescriptor();
2306
2307 if (got == BAD_TYPE) {
2308 return BAD_TYPE;
2309 }
2310
Andrei Homescu24ad36e2022-08-04 01:33:33 +00002311 int dupFd;
2312 if (status_t err = dupFileDescriptor(got, &dupFd); err != OK) {
2313 return BAD_VALUE;
2314 }
2315
2316 val->reset(dupFd);
Casey Dahlin06673e32015-11-23 13:24:23 -08002317
2318 if (val->get() < 0) {
2319 return BAD_VALUE;
2320 }
2321
2322 return OK;
2323}
2324
Ryo Hashimotobf551892018-05-31 16:58:35 +09002325status_t Parcel::readUniqueParcelFileDescriptor(base::unique_fd* val) const
2326{
2327 int got = readParcelFileDescriptor();
2328
2329 if (got == BAD_TYPE) {
2330 return BAD_TYPE;
2331 }
2332
Andrei Homescu24ad36e2022-08-04 01:33:33 +00002333 int dupFd;
2334 if (status_t err = dupFileDescriptor(got, &dupFd); err != OK) {
2335 return BAD_VALUE;
2336 }
2337
2338 val->reset(dupFd);
Ryo Hashimotobf551892018-05-31 16:58:35 +09002339
2340 if (val->get() < 0) {
2341 return BAD_VALUE;
2342 }
2343
2344 return OK;
2345}
Casey Dahlin06673e32015-11-23 13:24:23 -08002346
Jeff Brown5707dbf2011-09-23 21:17:56 -07002347status_t Parcel::readBlob(size_t len, ReadableBlob* outBlob) const
2348{
Jeff Brown13b16042014-11-11 16:44:25 -08002349 int32_t blobType;
2350 status_t status = readInt32(&blobType);
Jeff Brown5707dbf2011-09-23 21:17:56 -07002351 if (status) return status;
2352
Jeff Brown13b16042014-11-11 16:44:25 -08002353 if (blobType == BLOB_INPLACE) {
Steve Block6807e592011-10-20 11:56:00 +01002354 ALOGV("readBlob: read in place");
Jeff Brown5707dbf2011-09-23 21:17:56 -07002355 const void* ptr = readInplace(len);
2356 if (!ptr) return BAD_VALUE;
2357
Jeff Brown13b16042014-11-11 16:44:25 -08002358 outBlob->init(-1, const_cast<void*>(ptr), len, false);
Jeff Brown5707dbf2011-09-23 21:17:56 -07002359 return NO_ERROR;
2360 }
2361
Steve Block6807e592011-10-20 11:56:00 +01002362 ALOGV("readBlob: read from ashmem");
Jeff Brown13b16042014-11-11 16:44:25 -08002363 bool isMutable = (blobType == BLOB_ASHMEM_MUTABLE);
Jeff Brown5707dbf2011-09-23 21:17:56 -07002364 int fd = readFileDescriptor();
2365 if (fd == int(BAD_TYPE)) return BAD_VALUE;
2366
Jorim Jaggi150b4ef2018-07-13 11:18:30 +00002367 if (!ashmem_valid(fd)) {
2368 ALOGE("invalid fd");
2369 return BAD_VALUE;
2370 }
Marco Nelissen7a96ec42018-06-06 07:37:46 -07002371 int size = ashmem_get_size_region(fd);
2372 if (size < 0 || size_t(size) < len) {
Jorim Jaggi150b4ef2018-07-13 11:18:30 +00002373 ALOGE("request size %zu does not match fd size %d", len, size);
Marco Nelissen7a96ec42018-06-06 07:37:46 -07002374 return BAD_VALUE;
2375 }
Yi Kong91635562018-06-07 14:38:36 -07002376 void* ptr = ::mmap(nullptr, len, isMutable ? PROT_READ | PROT_WRITE : PROT_READ,
Jeff Brown13b16042014-11-11 16:44:25 -08002377 MAP_SHARED, fd, 0);
Narayan Kamath9ea09752014-10-08 17:35:45 +01002378 if (ptr == MAP_FAILED) return NO_MEMORY;
Jeff Brown5707dbf2011-09-23 21:17:56 -07002379
Jeff Brown13b16042014-11-11 16:44:25 -08002380 outBlob->init(fd, ptr, len, isMutable);
Jeff Brown5707dbf2011-09-23 21:17:56 -07002381 return NO_ERROR;
2382}
2383
Mathias Agopiane1424282013-07-29 21:24:40 -07002384status_t Parcel::read(FlattenableHelperInterface& val) const
Mathias Agopian98e71dd2010-02-11 17:30:52 -08002385{
2386 // size
2387 const size_t len = this->readInt32();
2388 const size_t fd_count = this->readInt32();
2389
Andrei Homescu1519b982022-06-09 02:04:44 +00002390 if ((len > INT32_MAX) || (fd_count > kMaxFds)) {
Nick Kralevichb6b14232015-04-02 09:36:02 -07002391 // don't accept size_t values which may have come from an
2392 // inadvertent conversion from a negative int.
2393 return BAD_VALUE;
2394 }
2395
Mathias Agopian98e71dd2010-02-11 17:30:52 -08002396 // payload
Nick Kralevichb6b14232015-04-02 09:36:02 -07002397 void const* const buf = this->readInplace(pad_size(len));
Yi Kong91635562018-06-07 14:38:36 -07002398 if (buf == nullptr)
Mathias Agopian98e71dd2010-02-11 17:30:52 -08002399 return BAD_VALUE;
2400
Yi Kong91635562018-06-07 14:38:36 -07002401 int* fds = nullptr;
Mathias Agopian98e71dd2010-02-11 17:30:52 -08002402 if (fd_count) {
Christopher Tatee4e0ae82016-03-24 16:03:44 -07002403 fds = new (std::nothrow) int[fd_count];
2404 if (fds == nullptr) {
2405 ALOGE("read: failed to allocate requested %zu fds", fd_count);
2406 return BAD_VALUE;
2407 }
Mathias Agopian98e71dd2010-02-11 17:30:52 -08002408 }
2409
2410 status_t err = NO_ERROR;
2411 for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) {
Fabien Sanglardd84ff312016-10-21 10:58:26 -07002412 int fd = this->readFileDescriptor();
Nick Kralevichec9ec7d2016-12-17 19:47:27 -08002413 if (fd < 0 || ((fds[i] = fcntl(fd, F_DUPFD_CLOEXEC, 0)) < 0)) {
Jun Jiangabf8a2c2014-04-29 14:22:10 +08002414 err = BAD_VALUE;
Nick Kralevichec9ec7d2016-12-17 19:47:27 -08002415 ALOGE("fcntl(F_DUPFD_CLOEXEC) failed in Parcel::read, i is %zu, fds[i] is %d, fd_count is %zu, error: %s",
Fabien Sanglardd84ff312016-10-21 10:58:26 -07002416 i, fds[i], fd_count, strerror(fd < 0 ? -fd : errno));
2417 // Close all the file descriptors that were dup-ed.
2418 for (size_t j=0; j<i ;j++) {
2419 close(fds[j]);
2420 }
Jun Jiangabf8a2c2014-04-29 14:22:10 +08002421 }
Mathias Agopian98e71dd2010-02-11 17:30:52 -08002422 }
2423
2424 if (err == NO_ERROR) {
2425 err = val.unflatten(buf, len, fds, fd_count);
2426 }
2427
2428 if (fd_count) {
2429 delete [] fds;
2430 }
2431
2432 return err;
2433}
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002434
2435#ifdef BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002436const flat_binder_object* Parcel::readObject(bool nullMetaData) const
2437{
Frederick Mayled3c595a2022-05-09 23:02:54 +00002438 const auto* kernelFields = maybeKernelFields();
2439 if (kernelFields == nullptr) {
2440 return nullptr;
2441 }
2442
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002443 const size_t DPOS = mDataPos;
2444 if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) {
2445 const flat_binder_object* obj
2446 = reinterpret_cast<const flat_binder_object*>(mData+DPOS);
2447 mDataPos = DPOS + sizeof(flat_binder_object);
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08002448 if (!nullMetaData && (obj->cookie == 0 && obj->binder == 0)) {
The Android Open Source Project5f78a482009-01-20 14:03:58 -08002449 // When transferring a NULL object, we don't write it into
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002450 // the object list, so we don't want to check for it when
2451 // reading.
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002452 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002453 return obj;
2454 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002455
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002456 // Ensure that this object is valid...
Frederick Mayled3c595a2022-05-09 23:02:54 +00002457 binder_size_t* const OBJS = kernelFields->mObjects;
2458 const size_t N = kernelFields->mObjectsSize;
2459 size_t opos = kernelFields->mNextObjectHint;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002460
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002461 if (N > 0) {
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002462 ALOGV("Parcel %p looking for obj at %zu, hint=%zu",
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002463 this, DPOS, opos);
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002464
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002465 // Start at the current hint position, looking for an object at
2466 // the current data position.
2467 if (opos < N) {
2468 while (opos < (N-1) && OBJS[opos] < DPOS) {
2469 opos++;
2470 }
2471 } else {
2472 opos = N-1;
2473 }
2474 if (OBJS[opos] == DPOS) {
2475 // Found it!
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002476 ALOGV("Parcel %p found obj %zu at index %zu with forward search",
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002477 this, DPOS, opos);
Frederick Mayled3c595a2022-05-09 23:02:54 +00002478 kernelFields->mNextObjectHint = opos + 1;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002479 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002480 return obj;
2481 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002482
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002483 // Look backwards for it...
2484 while (opos > 0 && OBJS[opos] > DPOS) {
2485 opos--;
2486 }
2487 if (OBJS[opos] == DPOS) {
2488 // Found it!
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002489 ALOGV("Parcel %p found obj %zu at index %zu with backward search",
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002490 this, DPOS, opos);
Frederick Mayled3c595a2022-05-09 23:02:54 +00002491 kernelFields->mNextObjectHint = opos + 1;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002492 ALOGV("readObject Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002493 return obj;
2494 }
2495 }
Colin Cross6f4f3ab2014-02-05 17:42:44 -08002496 ALOGW("Attempt to read object from Parcel %p at offset %zu that is not in the object list",
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002497 this, DPOS);
2498 }
Yi Kong91635562018-06-07 14:38:36 -07002499 return nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002500}
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002501#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002502
Frederick Mayled3c595a2022-05-09 23:02:54 +00002503void Parcel::closeFileDescriptors() {
Frederick Mayle69a0c992022-05-26 20:38:39 +00002504 if (auto* kernelFields = maybeKernelFields()) {
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002505#ifdef BINDER_WITH_KERNEL_IPC
Frederick Mayle69a0c992022-05-26 20:38:39 +00002506 size_t i = kernelFields->mObjectsSize;
2507 if (i > 0) {
2508 // ALOGI("Closing file descriptors for %zu objects...", i);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002509 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00002510 while (i > 0) {
2511 i--;
2512 const flat_binder_object* flat =
2513 reinterpret_cast<flat_binder_object*>(mData + kernelFields->mObjects[i]);
2514 if (flat->hdr.type == BINDER_TYPE_FD) {
2515 // ALOGI("Closing fd: %ld", flat->handle);
2516 close(flat->handle);
2517 }
2518 }
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002519#else // BINDER_WITH_KERNEL_IPC
2520 LOG_ALWAYS_FATAL("Binder kernel driver disabled at build time");
2521#endif // BINDER_WITH_KERNEL_IPC
Frederick Mayle69a0c992022-05-26 20:38:39 +00002522 } else if (auto* rpcFields = maybeRpcFields()) {
2523 rpcFields->mFds.reset();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002524 }
2525}
2526
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08002527uintptr_t Parcel::ipcData() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002528{
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08002529 return reinterpret_cast<uintptr_t>(mData);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002530}
2531
2532size_t Parcel::ipcDataSize() const
2533{
2534 return (mDataSize > mDataPos ? mDataSize : mDataPos);
2535}
2536
Arve Hjønnevåg84e625a2014-01-28 20:12:59 -08002537uintptr_t Parcel::ipcObjects() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002538{
Frederick Mayled3c595a2022-05-09 23:02:54 +00002539 if (const auto* kernelFields = maybeKernelFields()) {
2540 return reinterpret_cast<uintptr_t>(kernelFields->mObjects);
2541 }
2542 return 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002543}
2544
2545size_t Parcel::ipcObjectsCount() const
2546{
Frederick Mayled3c595a2022-05-09 23:02:54 +00002547 if (const auto* kernelFields = maybeKernelFields()) {
2548 return kernelFields->mObjectsSize;
2549 }
2550 return 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002551}
2552
Frederick Mayled3c595a2022-05-09 23:02:54 +00002553void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
2554 size_t objectsCount, release_func relFunc) {
Steven Moreland438cce82021-04-02 18:04:08 +00002555 // this code uses 'mOwner == nullptr' to understand whether it owns memory
2556 LOG_ALWAYS_FATAL_IF(relFunc == nullptr, "must provide cleanup function");
2557
Steven Morelandceed9bb2020-12-17 01:01:06 +00002558 freeData();
2559
Frederick Mayled3c595a2022-05-09 23:02:54 +00002560 auto* kernelFields = maybeKernelFields();
2561 LOG_ALWAYS_FATAL_IF(kernelFields == nullptr); // guaranteed by freeData.
2562
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002563 mData = const_cast<uint8_t*>(data);
2564 mDataSize = mDataCapacity = dataSize;
Frederick Mayled3c595a2022-05-09 23:02:54 +00002565 kernelFields->mObjects = const_cast<binder_size_t*>(objects);
2566 kernelFields->mObjectsSize = kernelFields->mObjectsCapacity = objectsCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002567 mOwner = relFunc;
Steven Morelandceed9bb2020-12-17 01:01:06 +00002568
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002569#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandceed9bb2020-12-17 01:01:06 +00002570 binder_size_t minOffset = 0;
Frederick Mayled3c595a2022-05-09 23:02:54 +00002571 for (size_t i = 0; i < kernelFields->mObjectsSize; i++) {
2572 binder_size_t offset = kernelFields->mObjects[i];
Arve Hjønnevågf50b9ea2014-02-13 19:22:08 -08002573 if (offset < minOffset) {
Dan Albert3bdc5b82014-11-20 11:50:23 -08002574 ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
Arve Hjønnevåg6f286112014-02-19 20:42:13 -08002575 __func__, (uint64_t)offset, (uint64_t)minOffset);
Frederick Mayled3c595a2022-05-09 23:02:54 +00002576 kernelFields->mObjectsSize = 0;
Arve Hjønnevågf50b9ea2014-02-13 19:22:08 -08002577 break;
2578 }
Martijn Coenen82c75312019-07-24 15:18:30 +02002579 const flat_binder_object* flat
2580 = reinterpret_cast<const flat_binder_object*>(mData + offset);
2581 uint32_t type = flat->hdr.type;
2582 if (!(type == BINDER_TYPE_BINDER || type == BINDER_TYPE_HANDLE ||
2583 type == BINDER_TYPE_FD)) {
2584 // We should never receive other types (eg BINDER_TYPE_FDA) as long as we don't support
2585 // them in libbinder. If we do receive them, it probably means a kernel bug; try to
Steven Morelandf2e0a952021-11-01 18:17:23 -07002586 // recover gracefully by clearing out the objects.
Martijn Coenen82c75312019-07-24 15:18:30 +02002587 android_errorWriteLog(0x534e4554, "135930648");
Steven Morelandf2e0a952021-11-01 18:17:23 -07002588 android_errorWriteLog(0x534e4554, "203847542");
Martijn Coenen82c75312019-07-24 15:18:30 +02002589 ALOGE("%s: unsupported type object (%" PRIu32 ") at offset %" PRIu64 "\n",
2590 __func__, type, (uint64_t)offset);
Steven Morelandf2e0a952021-11-01 18:17:23 -07002591
2592 // WARNING: callers of ipcSetDataReference need to make sure they
2593 // don't rely on mObjectsSize in their release_func.
Frederick Mayled3c595a2022-05-09 23:02:54 +00002594 kernelFields->mObjectsSize = 0;
Martijn Coenen82c75312019-07-24 15:18:30 +02002595 break;
2596 }
Arve Hjønnevågf50b9ea2014-02-13 19:22:08 -08002597 minOffset = offset + sizeof(flat_binder_object);
2598 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002599 scanForFds();
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002600#else // BINDER_WITH_KERNEL_IPC
2601 LOG_ALWAYS_FATAL_IF(objectsCount != 0,
2602 "Non-zero objects count passed to Parcel with kernel driver disabled");
2603#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002604}
2605
Frederick Mayleffe9ac22022-06-30 02:07:36 +00002606status_t Parcel::rpcSetDataReference(
2607 const sp<RpcSession>& session, const uint8_t* data, size_t dataSize,
2608 const uint32_t* objectTable, size_t objectTableSize,
2609 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds,
2610 release_func relFunc) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00002611 // this code uses 'mOwner == nullptr' to understand whether it owns memory
2612 LOG_ALWAYS_FATAL_IF(relFunc == nullptr, "must provide cleanup function");
2613
2614 LOG_ALWAYS_FATAL_IF(session == nullptr);
2615
Frederick Mayle694e9732022-07-15 00:24:58 +00002616 if (objectTableSize != ancillaryFds.size()) {
2617 ALOGE("objectTableSize=%zu ancillaryFds.size=%zu", objectTableSize, ancillaryFds.size());
2618 relFunc(data, dataSize, nullptr, 0);
2619 return BAD_VALUE;
2620 }
2621 for (size_t i = 0; i < objectTableSize; i++) {
2622 uint32_t minObjectEnd;
2623 if (__builtin_add_overflow(objectTable[i], sizeof(RpcFields::ObjectType), &minObjectEnd) ||
2624 minObjectEnd >= dataSize) {
2625 ALOGE("received out of range object position: %" PRIu32 " (parcel size is %zu)",
2626 objectTable[i], dataSize);
2627 relFunc(data, dataSize, nullptr, 0);
2628 return BAD_VALUE;
2629 }
2630 }
2631
Frederick Mayled3c595a2022-05-09 23:02:54 +00002632 freeData();
2633 markForRpc(session);
2634
Frederick Mayle69a0c992022-05-26 20:38:39 +00002635 auto* rpcFields = maybeRpcFields();
2636 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr); // guaranteed by markForRpc.
2637
Frederick Mayled3c595a2022-05-09 23:02:54 +00002638 mData = const_cast<uint8_t*>(data);
2639 mDataSize = mDataCapacity = dataSize;
2640 mOwner = relFunc;
Frederick Mayle69a0c992022-05-26 20:38:39 +00002641
Frederick Mayle69a0c992022-05-26 20:38:39 +00002642 rpcFields->mObjectPositions.reserve(objectTableSize);
2643 for (size_t i = 0; i < objectTableSize; i++) {
2644 rpcFields->mObjectPositions.push_back(objectTable[i]);
2645 }
2646 if (!ancillaryFds.empty()) {
2647 rpcFields->mFds = std::make_unique<decltype(rpcFields->mFds)::element_type>();
Frederick Mayleffe9ac22022-06-30 02:07:36 +00002648 *rpcFields->mFds = std::move(ancillaryFds);
Frederick Mayle69a0c992022-05-26 20:38:39 +00002649 }
2650
2651 return OK;
Frederick Mayled3c595a2022-05-09 23:02:54 +00002652}
2653
Pawan Wagh7063b522022-09-28 18:52:26 +00002654void Parcel::print(std::ostream& to, uint32_t /*flags*/) const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002655 to << "Parcel(";
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002656
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002657 if (errorCheck() != NO_ERROR) {
2658 const status_t err = errorCheck();
Colin Cross6f4f3ab2014-02-05 17:42:44 -08002659 to << "Error: " << (void*)(intptr_t)err << " \"" << strerror(-err) << "\"";
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002660 } else if (dataSize() > 0) {
2661 const uint8_t* DATA = data();
Pawan Wagh7063b522022-09-28 18:52:26 +00002662 to << "\t" << HexDump(DATA, dataSize());
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002663#ifdef BINDER_WITH_KERNEL_IPC
Frederick Mayled3c595a2022-05-09 23:02:54 +00002664 if (const auto* kernelFields = maybeKernelFields()) {
2665 const binder_size_t* OBJS = kernelFields->mObjects;
2666 const size_t N = objectsCount();
2667 for (size_t i = 0; i < N; i++) {
2668 const flat_binder_object* flat =
2669 reinterpret_cast<const flat_binder_object*>(DATA + OBJS[i]);
Pawan Wagh7063b522022-09-28 18:52:26 +00002670 to << "Object #" << i << " @ " << (void*)OBJS[i] << ": "
Frederick Mayled3c595a2022-05-09 23:02:54 +00002671 << TypeCode(flat->hdr.type & 0x7f7f7f00) << " = " << flat->binder;
2672 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002673 }
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002674#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002675 } else {
2676 to << "NULL";
2677 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002678
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002679 to << ")";
2680}
2681
2682void Parcel::releaseObjects()
2683{
Frederick Mayled3c595a2022-05-09 23:02:54 +00002684 auto* kernelFields = maybeKernelFields();
2685 if (kernelFields == nullptr) {
2686 return;
2687 }
2688
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002689#ifdef BINDER_WITH_KERNEL_IPC
Frederick Mayled3c595a2022-05-09 23:02:54 +00002690 size_t i = kernelFields->mObjectsSize;
Martijn Coenen69390d42018-10-22 15:18:10 +02002691 if (i == 0) {
2692 return;
2693 }
2694 sp<ProcessState> proc(ProcessState::self());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002695 uint8_t* const data = mData;
Frederick Mayled3c595a2022-05-09 23:02:54 +00002696 binder_size_t* const objects = kernelFields->mObjects;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002697 while (i > 0) {
2698 i--;
Frederick Mayled3c595a2022-05-09 23:02:54 +00002699 const flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(data + objects[i]);
Steven Morelandc673f1f2021-10-07 18:23:35 -07002700 release_object(proc, *flat, this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002701 }
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002702#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002703}
2704
2705void Parcel::acquireObjects()
2706{
Frederick Mayled3c595a2022-05-09 23:02:54 +00002707 auto* kernelFields = maybeKernelFields();
2708 if (kernelFields == nullptr) {
2709 return;
2710 }
2711
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002712#ifdef BINDER_WITH_KERNEL_IPC
Frederick Mayled3c595a2022-05-09 23:02:54 +00002713 size_t i = kernelFields->mObjectsSize;
Martijn Coenen69390d42018-10-22 15:18:10 +02002714 if (i == 0) {
2715 return;
2716 }
2717 const sp<ProcessState> proc(ProcessState::self());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002718 uint8_t* const data = mData;
Frederick Mayled3c595a2022-05-09 23:02:54 +00002719 binder_size_t* const objects = kernelFields->mObjects;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002720 while (i > 0) {
2721 i--;
Frederick Mayled3c595a2022-05-09 23:02:54 +00002722 const flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(data + objects[i]);
Steven Morelandc673f1f2021-10-07 18:23:35 -07002723 acquire_object(proc, *flat, this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002724 }
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002725#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002726}
2727
2728void Parcel::freeData()
2729{
2730 freeDataNoInit();
2731 initState();
2732}
2733
2734void Parcel::freeDataNoInit()
2735{
2736 if (mOwner) {
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002737 LOG_ALLOC("Parcel %p: freeing other owner data", this);
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002738 //ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
Frederick Mayled3c595a2022-05-09 23:02:54 +00002739 auto* kernelFields = maybeKernelFields();
Frederick Mayle53b6ffe2022-07-15 20:14:01 +00002740 // Close FDs before freeing, otherwise they will leak for kernel binder.
2741 closeFileDescriptors();
2742 mOwner(mData, mDataSize, kernelFields ? kernelFields->mObjects : nullptr,
Frederick Mayled3c595a2022-05-09 23:02:54 +00002743 kernelFields ? kernelFields->mObjectsSize : 0);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002744 } else {
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002745 LOG_ALLOC("Parcel %p: freeing allocated data", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002746 releaseObjects();
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002747 if (mData) {
2748 LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
Jeff Sharkey8994c182020-09-11 12:07:10 -06002749 gParcelGlobalAllocSize -= mDataCapacity;
2750 gParcelGlobalAllocCount--;
Steven Morelandf183fdd2020-10-27 00:12:12 +00002751 if (mDeallocZero) {
2752 zeroMemory(mData, mDataSize);
2753 }
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002754 free(mData);
2755 }
Frederick Mayled3c595a2022-05-09 23:02:54 +00002756 auto* kernelFields = maybeKernelFields();
2757 if (kernelFields && kernelFields->mObjects) free(kernelFields->mObjects);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002758 }
2759}
2760
2761status_t Parcel::growData(size_t len)
2762{
Nick Kralevichb6b14232015-04-02 09:36:02 -07002763 if (len > INT32_MAX) {
2764 // don't accept size_t values which may have come from an
2765 // inadvertent conversion from a negative int.
2766 return BAD_VALUE;
2767 }
2768
Martijn Coenen93fe5182020-01-22 10:46:25 +01002769 if (len > SIZE_MAX - mDataSize) return NO_MEMORY; // overflow
2770 if (mDataSize + len > SIZE_MAX / 3) return NO_MEMORY; // overflow
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002771 size_t newSize = ((mDataSize+len)*3)/2;
2772 return (newSize <= mDataSize)
2773 ? (status_t) NO_MEMORY
Steven Moreland042ae822020-05-27 17:45:17 +00002774 : continueWrite(std::max(newSize, (size_t) 128));
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002775}
2776
Steven Morelandf183fdd2020-10-27 00:12:12 +00002777static uint8_t* reallocZeroFree(uint8_t* data, size_t oldCapacity, size_t newCapacity, bool zero) {
2778 if (!zero) {
2779 return (uint8_t*)realloc(data, newCapacity);
2780 }
2781 uint8_t* newData = (uint8_t*)malloc(newCapacity);
2782 if (!newData) {
2783 return nullptr;
2784 }
2785
2786 memcpy(newData, data, std::min(oldCapacity, newCapacity));
2787 zeroMemory(data, oldCapacity);
2788 free(data);
2789 return newData;
2790}
2791
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002792status_t Parcel::restartWrite(size_t desired)
2793{
Nick Kralevichb6b14232015-04-02 09:36:02 -07002794 if (desired > INT32_MAX) {
2795 // don't accept size_t values which may have come from an
2796 // inadvertent conversion from a negative int.
2797 return BAD_VALUE;
2798 }
2799
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002800 if (mOwner) {
2801 freeData();
2802 return continueWrite(desired);
2803 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002804
Steven Morelandf183fdd2020-10-27 00:12:12 +00002805 uint8_t* data = reallocZeroFree(mData, mDataCapacity, desired, mDeallocZero);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002806 if (!data && desired > mDataCapacity) {
2807 mError = NO_MEMORY;
2808 return NO_MEMORY;
2809 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002810
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002811 releaseObjects();
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002812
Devin Moore4a0a55e2020-06-04 13:23:10 -07002813 if (data || desired == 0) {
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002814 LOG_ALLOC("Parcel %p: restart from %zu to %zu capacity", this, mDataCapacity, desired);
Jeff Sharkey8994c182020-09-11 12:07:10 -06002815 if (mDataCapacity > desired) {
2816 gParcelGlobalAllocSize -= (mDataCapacity - desired);
2817 } else {
2818 gParcelGlobalAllocSize += (desired - mDataCapacity);
2819 }
2820
Colin Cross83ec65e2015-12-08 17:15:50 -08002821 if (!mData) {
2822 gParcelGlobalAllocCount++;
2823 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002824 mData = data;
2825 mDataCapacity = desired;
2826 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002827
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002828 mDataSize = mDataPos = 0;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002829 ALOGV("restartWrite Setting data size of %p to %zu", this, mDataSize);
2830 ALOGV("restartWrite Setting data pos of %p to %zu", this, mDataPos);
2831
Frederick Mayled3c595a2022-05-09 23:02:54 +00002832 if (auto* kernelFields = maybeKernelFields()) {
2833 free(kernelFields->mObjects);
2834 kernelFields->mObjects = nullptr;
2835 kernelFields->mObjectsSize = kernelFields->mObjectsCapacity = 0;
2836 kernelFields->mNextObjectHint = 0;
2837 kernelFields->mObjectsSorted = false;
2838 kernelFields->mHasFds = false;
2839 kernelFields->mFdsKnown = true;
Frederick Mayle69a0c992022-05-26 20:38:39 +00002840 } else if (auto* rpcFields = maybeRpcFields()) {
2841 rpcFields->mObjectPositions.clear();
2842 rpcFields->mFds.reset();
Frederick Mayled3c595a2022-05-09 23:02:54 +00002843 }
Dianne Hackborn8938ed22011-09-28 23:19:47 -04002844 mAllowFds = true;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002845
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002846 return NO_ERROR;
2847}
2848
2849status_t Parcel::continueWrite(size_t desired)
2850{
Nick Kralevichb6b14232015-04-02 09:36:02 -07002851 if (desired > INT32_MAX) {
2852 // don't accept size_t values which may have come from an
2853 // inadvertent conversion from a negative int.
2854 return BAD_VALUE;
2855 }
2856
Frederick Mayled3c595a2022-05-09 23:02:54 +00002857 auto* kernelFields = maybeKernelFields();
Frederick Mayle69a0c992022-05-26 20:38:39 +00002858 auto* rpcFields = maybeRpcFields();
Frederick Mayled3c595a2022-05-09 23:02:54 +00002859
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002860 // If shrinking, first adjust for any objects that appear
2861 // after the new data size.
Frederick Mayle69a0c992022-05-26 20:38:39 +00002862 size_t objectsSize =
2863 kernelFields ? kernelFields->mObjectsSize : rpcFields->mObjectPositions.size();
2864 if (desired < mDataSize) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002865 if (desired == 0) {
2866 objectsSize = 0;
2867 } else {
Frederick Mayle69a0c992022-05-26 20:38:39 +00002868 if (kernelFields) {
2869 while (objectsSize > 0) {
2870 if (kernelFields->mObjects[objectsSize - 1] < desired) break;
2871 objectsSize--;
2872 }
2873 } else {
2874 while (objectsSize > 0) {
2875 if (rpcFields->mObjectPositions[objectsSize - 1] < desired) break;
2876 objectsSize--;
2877 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002878 }
2879 }
2880 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002881
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002882 if (mOwner) {
2883 // If the size is going to zero, just release the owner's data.
2884 if (desired == 0) {
2885 freeData();
2886 return NO_ERROR;
2887 }
2888
2889 // If there is a different owner, we need to take
2890 // posession.
2891 uint8_t* data = (uint8_t*)malloc(desired);
2892 if (!data) {
2893 mError = NO_MEMORY;
2894 return NO_MEMORY;
2895 }
Yi Kong91635562018-06-07 14:38:36 -07002896 binder_size_t* objects = nullptr;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002897
Frederick Mayle69a0c992022-05-26 20:38:39 +00002898 if (kernelFields && objectsSize) {
Nick Kraleviche9881a32015-04-28 16:21:30 -07002899 objects = (binder_size_t*)calloc(objectsSize, sizeof(binder_size_t));
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002900 if (!objects) {
Hyejin Kim3f727c02013-03-09 11:28:54 +09002901 free(data);
2902
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002903 mError = NO_MEMORY;
2904 return NO_MEMORY;
2905 }
2906
2907 // Little hack to only acquire references on objects
2908 // we will be keeping.
Frederick Mayled3c595a2022-05-09 23:02:54 +00002909 size_t oldObjectsSize = kernelFields->mObjectsSize;
2910 kernelFields->mObjectsSize = objectsSize;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002911 acquireObjects();
Frederick Mayled3c595a2022-05-09 23:02:54 +00002912 kernelFields->mObjectsSize = oldObjectsSize;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002913 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00002914 if (rpcFields) {
2915 if (status_t status = truncateRpcObjects(objectsSize); status != OK) {
2916 free(data);
2917 return status;
2918 }
2919 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002920
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002921 if (mData) {
2922 memcpy(data, mData, mDataSize < desired ? mDataSize : desired);
2923 }
Frederick Mayled3c595a2022-05-09 23:02:54 +00002924 if (objects && kernelFields && kernelFields->mObjects) {
2925 memcpy(objects, kernelFields->mObjects, objectsSize * sizeof(binder_size_t));
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002926 }
Frederick Mayle53b6ffe2022-07-15 20:14:01 +00002927 // ALOGI("Freeing data ref of %p (pid=%d)", this, getpid());
2928 if (kernelFields) {
2929 // TODO(b/239222407): This seems wrong. We should only free FDs when
2930 // they are in a truncated section of the parcel.
2931 closeFileDescriptors();
2932 }
2933 mOwner(mData, mDataSize, kernelFields ? kernelFields->mObjects : nullptr,
Frederick Mayled3c595a2022-05-09 23:02:54 +00002934 kernelFields ? kernelFields->mObjectsSize : 0);
Yi Kong91635562018-06-07 14:38:36 -07002935 mOwner = nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002936
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002937 LOG_ALLOC("Parcel %p: taking ownership of %zu capacity", this, desired);
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002938 gParcelGlobalAllocSize += desired;
2939 gParcelGlobalAllocCount++;
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002940
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002941 mData = data;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002942 mDataSize = (mDataSize < desired) ? mDataSize : desired;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07002943 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002944 mDataCapacity = desired;
Frederick Mayled3c595a2022-05-09 23:02:54 +00002945 if (kernelFields) {
2946 kernelFields->mObjects = objects;
2947 kernelFields->mObjectsSize = kernelFields->mObjectsCapacity = objectsSize;
2948 kernelFields->mNextObjectHint = 0;
2949 kernelFields->mObjectsSorted = false;
2950 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002951
2952 } else if (mData) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00002953 if (kernelFields && objectsSize < kernelFields->mObjectsSize) {
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002954#ifdef BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002955 // Need to release refs on any objects we are dropping.
2956 const sp<ProcessState> proc(ProcessState::self());
Frederick Mayled3c595a2022-05-09 23:02:54 +00002957 for (size_t i = objectsSize; i < kernelFields->mObjectsSize; i++) {
2958 const flat_binder_object* flat =
2959 reinterpret_cast<flat_binder_object*>(mData + kernelFields->mObjects[i]);
Christopher Ferrisdbaa22a2017-07-27 10:38:45 -07002960 if (flat->hdr.type == BINDER_TYPE_FD) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002961 // will need to rescan because we may have lopped off the only FDs
Frederick Mayled3c595a2022-05-09 23:02:54 +00002962 kernelFields->mFdsKnown = false;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002963 }
Steven Morelandc673f1f2021-10-07 18:23:35 -07002964 release_object(proc, *flat, this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002965 }
Michael Wachenschwanz6af27a82019-06-03 17:24:51 -07002966
2967 if (objectsSize == 0) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00002968 free(kernelFields->mObjects);
2969 kernelFields->mObjects = nullptr;
2970 kernelFields->mObjectsCapacity = 0;
Michael Wachenschwanz6af27a82019-06-03 17:24:51 -07002971 } else {
2972 binder_size_t* objects =
Frederick Mayled3c595a2022-05-09 23:02:54 +00002973 (binder_size_t*)realloc(kernelFields->mObjects,
2974 objectsSize * sizeof(binder_size_t));
Michael Wachenschwanz6af27a82019-06-03 17:24:51 -07002975 if (objects) {
Frederick Mayled3c595a2022-05-09 23:02:54 +00002976 kernelFields->mObjects = objects;
2977 kernelFields->mObjectsCapacity = objectsSize;
Michael Wachenschwanz6af27a82019-06-03 17:24:51 -07002978 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002979 }
Frederick Mayled3c595a2022-05-09 23:02:54 +00002980 kernelFields->mObjectsSize = objectsSize;
2981 kernelFields->mNextObjectHint = 0;
2982 kernelFields->mObjectsSorted = false;
Andrei Homescua9cca9c2022-05-03 04:48:01 +00002983#else // BINDER_WITH_KERNEL_IPC
2984 LOG_ALWAYS_FATAL("Non-zero numObjects for RPC Parcel");
2985#endif // BINDER_WITH_KERNEL_IPC
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002986 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00002987 if (rpcFields) {
2988 if (status_t status = truncateRpcObjects(objectsSize); status != OK) {
2989 return status;
2990 }
2991 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002992
2993 // We own the data, so we can just do a realloc().
2994 if (desired > mDataCapacity) {
Steven Morelandf183fdd2020-10-27 00:12:12 +00002995 uint8_t* data = reallocZeroFree(mData, mDataCapacity, desired, mDeallocZero);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002996 if (data) {
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002997 LOG_ALLOC("Parcel %p: continue from %zu to %zu capacity", this, mDataCapacity,
2998 desired);
Dianne Hackborn7e790af2014-11-11 12:22:53 -08002999 gParcelGlobalAllocSize += desired;
3000 gParcelGlobalAllocSize -= mDataCapacity;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003001 mData = data;
3002 mDataCapacity = desired;
Ganesh Mahendranade89892017-09-28 16:56:03 +08003003 } else {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003004 mError = NO_MEMORY;
3005 return NO_MEMORY;
3006 }
3007 } else {
Dianne Hackborn97e2bcd2011-04-13 18:15:56 -07003008 if (mDataSize > desired) {
3009 mDataSize = desired;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07003010 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
Dianne Hackborn97e2bcd2011-04-13 18:15:56 -07003011 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003012 if (mDataPos > desired) {
3013 mDataPos = desired;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07003014 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003015 }
3016 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07003017
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003018 } else {
3019 // This is the first data. Easy!
3020 uint8_t* data = (uint8_t*)malloc(desired);
3021 if (!data) {
3022 mError = NO_MEMORY;
3023 return NO_MEMORY;
3024 }
Hyejin Kim3f727c02013-03-09 11:28:54 +09003025
Frederick Mayled3c595a2022-05-09 23:02:54 +00003026 if (!(mDataCapacity == 0 &&
3027 (kernelFields == nullptr ||
3028 (kernelFields->mObjects == nullptr && kernelFields->mObjectsCapacity == 0)))) {
3029 ALOGE("continueWrite: %zu/%p/%zu/%zu", mDataCapacity,
3030 kernelFields ? kernelFields->mObjects : nullptr,
3031 kernelFields ? kernelFields->mObjectsCapacity : 0, desired);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003032 }
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07003033
Dianne Hackborn7e790af2014-11-11 12:22:53 -08003034 LOG_ALLOC("Parcel %p: allocating with %zu capacity", this, desired);
Dianne Hackborn7e790af2014-11-11 12:22:53 -08003035 gParcelGlobalAllocSize += desired;
3036 gParcelGlobalAllocCount++;
Dianne Hackborn7e790af2014-11-11 12:22:53 -08003037
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003038 mData = data;
3039 mDataSize = mDataPos = 0;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07003040 ALOGV("continueWrite Setting data size of %p to %zu", this, mDataSize);
3041 ALOGV("continueWrite Setting data pos of %p to %zu", this, mDataPos);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003042 mDataCapacity = desired;
3043 }
3044
3045 return NO_ERROR;
3046}
3047
Frederick Mayle69a0c992022-05-26 20:38:39 +00003048status_t Parcel::truncateRpcObjects(size_t newObjectsSize) {
3049 auto* rpcFields = maybeRpcFields();
3050 if (newObjectsSize == 0) {
3051 rpcFields->mObjectPositions.clear();
3052 if (rpcFields->mFds) {
3053 rpcFields->mFds->clear();
3054 }
3055 return OK;
3056 }
3057 while (rpcFields->mObjectPositions.size() > newObjectsSize) {
3058 uint32_t pos = rpcFields->mObjectPositions.back();
3059 rpcFields->mObjectPositions.pop_back();
3060 const auto type = *reinterpret_cast<const RpcFields::ObjectType*>(mData + pos);
3061 if (type == RpcFields::TYPE_NATIVE_FILE_DESCRIPTOR) {
3062 const auto fdIndex =
3063 *reinterpret_cast<const int32_t*>(mData + pos + sizeof(RpcFields::ObjectType));
3064 if (rpcFields->mFds == nullptr || fdIndex < 0 ||
3065 static_cast<size_t>(fdIndex) >= rpcFields->mFds->size()) {
3066 ALOGE("RPC Parcel contains invalid file descriptor index. index=%d fd_count=%zu",
3067 fdIndex, rpcFields->mFds ? rpcFields->mFds->size() : 0);
3068 return BAD_VALUE;
3069 }
3070 // In practice, this always removes the last element.
3071 rpcFields->mFds->erase(rpcFields->mFds->begin() + fdIndex);
3072 }
3073 }
3074 return OK;
3075}
3076
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003077void Parcel::initState()
3078{
Dianne Hackborn7e790af2014-11-11 12:22:53 -08003079 LOG_ALLOC("Parcel %p: initState", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003080 mError = NO_ERROR;
Yi Kong91635562018-06-07 14:38:36 -07003081 mData = nullptr;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003082 mDataSize = 0;
3083 mDataCapacity = 0;
3084 mDataPos = 0;
Mark Salyzynd4ecccf2014-05-30 16:35:57 -07003085 ALOGV("initState Setting data size of %p to %zu", this, mDataSize);
3086 ALOGV("initState Setting data pos of %p to %zu", this, mDataPos);
Frederick Mayled3c595a2022-05-09 23:02:54 +00003087 mVariantFields.emplace<KernelFields>();
Steven Moreland6e5a7752019-08-05 20:30:14 -07003088 mAllowFds = true;
Steven Morelandf183fdd2020-10-27 00:12:12 +00003089 mDeallocZero = false;
Yi Kong91635562018-06-07 14:38:36 -07003090 mOwner = nullptr;
Pawan Wagh104654a2022-11-15 21:18:42 +00003091 mEnforceNoDataAvail = true;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003092}
3093
Bernardo Rufinobbbd88d2021-10-15 14:54:30 +01003094void Parcel::scanForFds() const {
Frederick Mayled3c595a2022-05-09 23:02:54 +00003095 auto* kernelFields = maybeKernelFields();
3096 if (kernelFields == nullptr) {
3097 return;
3098 }
3099 status_t status = hasFileDescriptorsInRange(0, dataSize(), &kernelFields->mHasFds);
Bernardo Rufinobbbd88d2021-10-15 14:54:30 +01003100 ALOGE_IF(status != NO_ERROR, "Error %d calling hasFileDescriptorsInRange()", status);
Frederick Mayled3c595a2022-05-09 23:02:54 +00003101 kernelFields->mFdsKnown = true;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003102}
3103
Andrei Homescua9cca9c2022-05-03 04:48:01 +00003104#ifdef BINDER_WITH_KERNEL_IPC
Dan Sandleraa5c2342015-04-10 10:08:45 -04003105size_t Parcel::getBlobAshmemSize() const
3106{
Adrian Roos6bb31142015-10-22 16:46:12 -07003107 // This used to return the size of all blobs that were written to ashmem, now we're returning
3108 // the ashmem currently referenced by this Parcel, which should be equivalent.
Steven Morelandc673f1f2021-10-07 18:23:35 -07003109 // TODO(b/202029388): Remove method once ABI can be changed.
3110 return getOpenAshmemSize();
Dan Sandleraa5c2342015-04-10 10:08:45 -04003111}
3112
Adrian Rooscbf37262015-10-22 16:12:53 -07003113size_t Parcel::getOpenAshmemSize() const
3114{
Frederick Mayled3c595a2022-05-09 23:02:54 +00003115 auto* kernelFields = maybeKernelFields();
3116 if (kernelFields == nullptr) {
3117 return 0;
3118 }
3119
Steven Morelandc673f1f2021-10-07 18:23:35 -07003120 size_t openAshmemSize = 0;
Frederick Mayled3c595a2022-05-09 23:02:54 +00003121 for (size_t i = 0; i < kernelFields->mObjectsSize; i++) {
Steven Morelandc673f1f2021-10-07 18:23:35 -07003122 const flat_binder_object* flat =
Frederick Mayled3c595a2022-05-09 23:02:54 +00003123 reinterpret_cast<const flat_binder_object*>(mData + kernelFields->mObjects[i]);
Steven Morelandc673f1f2021-10-07 18:23:35 -07003124
3125 // cookie is compared against zero for historical reasons
3126 // > obj.cookie = takeOwnership ? 1 : 0;
3127 if (flat->hdr.type == BINDER_TYPE_FD && flat->cookie != 0 && ashmem_valid(flat->handle)) {
3128 int size = ashmem_get_size_region(flat->handle);
3129 if (__builtin_add_overflow(openAshmemSize, size, &openAshmemSize)) {
3130 ALOGE("Overflow when computing ashmem size.");
3131 return SIZE_MAX;
3132 }
3133 }
3134 }
3135 return openAshmemSize;
Jeff Brown5707dbf2011-09-23 21:17:56 -07003136}
Andrei Homescua9cca9c2022-05-03 04:48:01 +00003137#endif // BINDER_WITH_KERNEL_IPC
Jeff Brown5707dbf2011-09-23 21:17:56 -07003138
3139// --- Parcel::Blob ---
3140
3141Parcel::Blob::Blob() :
Yi Kong91635562018-06-07 14:38:36 -07003142 mFd(-1), mData(nullptr), mSize(0), mMutable(false) {
Jeff Brown5707dbf2011-09-23 21:17:56 -07003143}
3144
3145Parcel::Blob::~Blob() {
3146 release();
3147}
3148
3149void Parcel::Blob::release() {
Jeff Brown13b16042014-11-11 16:44:25 -08003150 if (mFd != -1 && mData) {
Jeff Brown5707dbf2011-09-23 21:17:56 -07003151 ::munmap(mData, mSize);
3152 }
3153 clear();
3154}
3155
Jeff Brown13b16042014-11-11 16:44:25 -08003156void Parcel::Blob::init(int fd, void* data, size_t size, bool isMutable) {
3157 mFd = fd;
Jeff Brown5707dbf2011-09-23 21:17:56 -07003158 mData = data;
3159 mSize = size;
Jeff Brown13b16042014-11-11 16:44:25 -08003160 mMutable = isMutable;
Jeff Brown5707dbf2011-09-23 21:17:56 -07003161}
3162
3163void Parcel::Blob::clear() {
Jeff Brown13b16042014-11-11 16:44:25 -08003164 mFd = -1;
Yi Kong91635562018-06-07 14:38:36 -07003165 mData = nullptr;
Jeff Brown5707dbf2011-09-23 21:17:56 -07003166 mSize = 0;
Jeff Brown13b16042014-11-11 16:44:25 -08003167 mMutable = false;
Jeff Brown5707dbf2011-09-23 21:17:56 -07003168}
3169
Steven Moreland61ff8492019-09-26 16:05:45 -07003170} // namespace android