1 /*
2 * Copyright (C) 2017 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 "AHardwareBuffer"
18
19 #include <android/hardware_buffer.h>
20 #include <android/hardware_buffer_aidl.h>
21 #include <android/binder_libbinder.h>
22 #include <vndk/hardware_buffer.h>
23
24 #include <errno.h>
25 #include <sys/socket.h>
26 #include <memory>
27
28 #include <cutils/native_handle.h>
29 #include <log/log.h>
30 #include <utils/StrongPointer.h>
31 #include <ui/GraphicBuffer.h>
32 #include <system/graphics.h>
33
34 #include <private/android/AHardwareBufferHelpers.h>
35 #include <android/hardware/graphics/common/1.1/types.h>
36 #include <aidl/android/hardware/graphics/common/PixelFormat.h>
37
38 static constexpr int kFdBufferSize = 128 * sizeof(int); // 128 ints
39
40 using namespace android;
41
42 // ----------------------------------------------------------------------------
43 // Validate hardware_buffer.h and PixelFormat.aidl agree
44 // ----------------------------------------------------------------------------
45
46 static_assert(HAL_PIXEL_FORMAT_RGBA_8888 == AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
47 "HAL and AHardwareBuffer pixel format don't match");
48 static_assert(HAL_PIXEL_FORMAT_RGBX_8888 == AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM,
49 "HAL and AHardwareBuffer pixel format don't match");
50 static_assert(HAL_PIXEL_FORMAT_RGB_565 == AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM,
51 "HAL and AHardwareBuffer pixel format don't match");
52 static_assert(HAL_PIXEL_FORMAT_RGB_888 == AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM,
53 "HAL and AHardwareBuffer pixel format don't match");
54 static_assert(HAL_PIXEL_FORMAT_RGBA_FP16 == AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT,
55 "HAL and AHardwareBuffer pixel format don't match");
56 static_assert(HAL_PIXEL_FORMAT_RGBA_1010102 == AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM,
57 "HAL and AHardwareBuffer pixel format don't match");
58 static_assert(HAL_PIXEL_FORMAT_BLOB == AHARDWAREBUFFER_FORMAT_BLOB,
59 "HAL and AHardwareBuffer pixel format don't match");
60 static_assert(HAL_PIXEL_FORMAT_DEPTH_16 == AHARDWAREBUFFER_FORMAT_D16_UNORM,
61 "HAL and AHardwareBuffer pixel format don't match");
62 static_assert(HAL_PIXEL_FORMAT_DEPTH_24 == AHARDWAREBUFFER_FORMAT_D24_UNORM,
63 "HAL and AHardwareBuffer pixel format don't match");
64 static_assert(HAL_PIXEL_FORMAT_DEPTH_24_STENCIL_8 == AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT,
65 "HAL and AHardwareBuffer pixel format don't match");
66 static_assert(HAL_PIXEL_FORMAT_DEPTH_32F == AHARDWAREBUFFER_FORMAT_D32_FLOAT,
67 "HAL and AHardwareBuffer pixel format don't match");
68 static_assert(HAL_PIXEL_FORMAT_DEPTH_32F_STENCIL_8 == AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT,
69 "HAL and AHardwareBuffer pixel format don't match");
70 static_assert(HAL_PIXEL_FORMAT_STENCIL_8 == AHARDWAREBUFFER_FORMAT_S8_UINT,
71 "HAL and AHardwareBuffer pixel format don't match");
72 static_assert(HAL_PIXEL_FORMAT_BGRA_8888 == AHARDWAREBUFFER_FORMAT_B8G8R8A8_UNORM,
73 "HAL and AHardwareBuffer pixel format don't match");
74 static_assert(HAL_PIXEL_FORMAT_YV12 == AHARDWAREBUFFER_FORMAT_YV12,
75 "HAL and AHardwareBuffer pixel format don't match");
76 static_assert(HAL_PIXEL_FORMAT_Y8 == AHARDWAREBUFFER_FORMAT_Y8,
77 "HAL and AHardwareBuffer pixel format don't match");
78 static_assert(HAL_PIXEL_FORMAT_Y16 == AHARDWAREBUFFER_FORMAT_Y16,
79 "HAL and AHardwareBuffer pixel format don't match");
80 static_assert(HAL_PIXEL_FORMAT_RAW16 == AHARDWAREBUFFER_FORMAT_RAW16,
81 "HAL and AHardwareBuffer pixel format don't match");
82 static_assert(HAL_PIXEL_FORMAT_RAW10 == AHARDWAREBUFFER_FORMAT_RAW10,
83 "HAL and AHardwareBuffer pixel format don't match");
84 static_assert(HAL_PIXEL_FORMAT_RAW12 == AHARDWAREBUFFER_FORMAT_RAW12,
85 "HAL and AHardwareBuffer pixel format don't match");
86 static_assert(HAL_PIXEL_FORMAT_RAW_OPAQUE == AHARDWAREBUFFER_FORMAT_RAW_OPAQUE,
87 "HAL and AHardwareBuffer pixel format don't match");
88 static_assert(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED ==
89 AHARDWAREBUFFER_FORMAT_IMPLEMENTATION_DEFINED,
90 "HAL and AHardwareBuffer pixel format don't match");
91 static_assert(HAL_PIXEL_FORMAT_YCBCR_420_888 == AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420,
92 "HAL and AHardwareBuffer pixel format don't match");
93 static_assert(HAL_PIXEL_FORMAT_YCBCR_422_SP == AHARDWAREBUFFER_FORMAT_YCbCr_422_SP,
94 "HAL and AHardwareBuffer pixel format don't match");
95 static_assert(HAL_PIXEL_FORMAT_YCRCB_420_SP == AHARDWAREBUFFER_FORMAT_YCrCb_420_SP,
96 "HAL and AHardwareBuffer pixel format don't match");
97 static_assert(HAL_PIXEL_FORMAT_YCBCR_422_I == AHARDWAREBUFFER_FORMAT_YCbCr_422_I,
98 "HAL and AHardwareBuffer pixel format don't match");
99 static_assert(HAL_PIXEL_FORMAT_YCBCR_P010 == AHARDWAREBUFFER_FORMAT_YCbCr_P010,
100 "HAL and AHardwareBuffer pixel format don't match");
101 static_assert(static_cast<int>(aidl::android::hardware::graphics::common::PixelFormat::R_8) ==
102 AHARDWAREBUFFER_FORMAT_R8_UNORM,
103 "HAL and AHardwareBuffer pixel format don't match");
104 static_assert(static_cast<int>(aidl::android::hardware::graphics::common::PixelFormat::R_16_UINT) ==
105 AHARDWAREBUFFER_FORMAT_R16_UINT,
106 "HAL and AHardwareBuffer pixel format don't match");
107 static_assert(
108 static_cast<int>(aidl::android::hardware::graphics::common::PixelFormat::RG_1616_UINT) ==
109 AHARDWAREBUFFER_FORMAT_R16G16_UINT,
110 "HAL and AHardwareBuffer pixel format don't match");
111 static_assert(
112 static_cast<int>(aidl::android::hardware::graphics::common::PixelFormat::RGBA_10101010) ==
113 AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM,
114 "HAL and AHardwareBuffer pixel format don't match");
115
filterStatus(status_t status)116 static enum AHardwareBufferStatus filterStatus(status_t status) {
117 switch (status) {
118 case STATUS_OK:
119 return AHARDWAREBUFFER_STATUS_OK;
120 case STATUS_NO_MEMORY:
121 return AHARDWAREBUFFER_STATUS_NO_MEMORY;
122 case STATUS_BAD_VALUE:
123 return AHARDWAREBUFFER_STATUS_BAD_VALUE;
124 case STATUS_UNKNOWN_TRANSACTION:
125 case STATUS_INVALID_OPERATION:
126 return AHARDWAREBUFFER_STATUS_UNSUPPORTED;
127 default:
128 return AHARDWAREBUFFER_STATUS_UNKNOWN_ERROR;
129 }
130 }
131
132 // ----------------------------------------------------------------------------
133 // Public functions
134 // ----------------------------------------------------------------------------
135
AHardwareBuffer_allocate(const AHardwareBuffer_Desc * desc,AHardwareBuffer ** outBuffer)136 int AHardwareBuffer_allocate(const AHardwareBuffer_Desc* desc, AHardwareBuffer** outBuffer) {
137 if (!outBuffer || !desc) return BAD_VALUE;
138 if (!AHardwareBuffer_isValidDescription(desc, /*log=*/true)) return BAD_VALUE;
139
140 int format = AHardwareBuffer_convertToPixelFormat(desc->format);
141 uint64_t usage = AHardwareBuffer_convertToGrallocUsageBits(desc->usage);
142 sp<GraphicBuffer> gbuffer(new GraphicBuffer(
143 desc->width, desc->height, format, desc->layers, usage,
144 std::string("AHardwareBuffer pid [") + std::to_string(getpid()) + "]"));
145
146 status_t err = gbuffer->initCheck();
147 if (err != 0 || gbuffer->handle == nullptr) {
148 if (err == NO_MEMORY) {
149 GraphicBuffer::dumpAllocationsToSystemLog();
150 }
151 ALOGE("GraphicBuffer(w=%u, h=%u, lc=%u) failed (%s), handle=%p",
152 desc->width, desc->height, desc->layers, strerror(-err), gbuffer->handle);
153 return err == 0 ? UNKNOWN_ERROR : err;
154 }
155
156 *outBuffer = AHardwareBuffer_from_GraphicBuffer(gbuffer.get());
157
158 // Ensure the buffer doesn't get destroyed when the sp<> goes away.
159 AHardwareBuffer_acquire(*outBuffer);
160 return NO_ERROR;
161 }
162
AHardwareBuffer_acquire(AHardwareBuffer * buffer)163 void AHardwareBuffer_acquire(AHardwareBuffer* buffer) {
164 // incStrong/decStrong token must be the same, doesn't matter what it is
165 AHardwareBuffer_to_GraphicBuffer(buffer)->incStrong((void*)AHardwareBuffer_acquire);
166 }
167
AHardwareBuffer_release(AHardwareBuffer * buffer)168 void AHardwareBuffer_release(AHardwareBuffer* buffer) {
169 // incStrong/decStrong token must be the same, doesn't matter what it is
170 AHardwareBuffer_to_GraphicBuffer(buffer)->decStrong((void*)AHardwareBuffer_acquire);
171 }
172
AHardwareBuffer_describe(const AHardwareBuffer * buffer,AHardwareBuffer_Desc * outDesc)173 void AHardwareBuffer_describe(const AHardwareBuffer* buffer,
174 AHardwareBuffer_Desc* outDesc) {
175 if (!buffer || !outDesc) return;
176
177 const GraphicBuffer* gbuffer = AHardwareBuffer_to_GraphicBuffer(buffer);
178
179 outDesc->width = gbuffer->getWidth();
180 outDesc->height = gbuffer->getHeight();
181 outDesc->layers = gbuffer->getLayerCount();
182 outDesc->format = AHardwareBuffer_convertFromPixelFormat(uint32_t(gbuffer->getPixelFormat()));
183 outDesc->usage = AHardwareBuffer_convertFromGrallocUsageBits(gbuffer->getUsage());
184 outDesc->stride = gbuffer->getStride();
185 outDesc->rfu0 = 0;
186 outDesc->rfu1 = 0;
187 }
188
AHardwareBuffer_lockAndGetInfo(AHardwareBuffer * buffer,uint64_t usage,int32_t fence,const ARect * rect,void ** outVirtualAddress,int32_t * outBytesPerPixel,int32_t * outBytesPerStride)189 int AHardwareBuffer_lockAndGetInfo(AHardwareBuffer* buffer, uint64_t usage,
190 int32_t fence, const ARect* rect, void** outVirtualAddress,
191 int32_t* outBytesPerPixel, int32_t* outBytesPerStride) {
192 if (outBytesPerPixel) *outBytesPerPixel = -1;
193 if (outBytesPerStride) *outBytesPerStride = -1;
194
195 if (!buffer) {
196 return BAD_VALUE;
197 }
198
199 if (usage & ~(AHARDWAREBUFFER_USAGE_CPU_READ_MASK |
200 AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK)) {
201 ALOGE("Invalid usage flags passed to AHardwareBuffer_lock; only "
202 "AHARDWAREBUFFER_USAGE_CPU_* flags are allowed");
203 return BAD_VALUE;
204 }
205
206 usage = AHardwareBuffer_convertToGrallocUsageBits(usage);
207 GraphicBuffer* gbuffer = AHardwareBuffer_to_GraphicBuffer(buffer);
208
209 //Mapper implementations before 3.0 will not return bytes per pixel or
210 //bytes per stride information.
211 if (gbuffer->getBufferMapperVersion() == GraphicBufferMapper::Version::GRALLOC_2) {
212 ALOGE("Mapper versions before 3.0 cannot retrieve bytes per pixel and bytes per stride info");
213 return INVALID_OPERATION;
214 }
215
216 if (gbuffer->getLayerCount() > 1) {
217 ALOGE("Buffer with multiple layers passed to AHardwareBuffer_lock; "
218 "only buffers with one layer are allowed");
219 return INVALID_OPERATION;
220 }
221
222 Rect bounds;
223 if (!rect) {
224 bounds.set(Rect(gbuffer->getWidth(), gbuffer->getHeight()));
225 } else {
226 bounds.set(Rect(rect->left, rect->top, rect->right, rect->bottom));
227 }
228 int32_t bytesPerPixel;
229 int32_t bytesPerStride;
230 int result = gbuffer->lockAsync(usage, usage, bounds, outVirtualAddress, fence, &bytesPerPixel, &bytesPerStride);
231
232 // if hardware returns -1 for bytes per pixel or bytes per stride, we fail
233 // and unlock the buffer
234 if (bytesPerPixel == -1 || bytesPerStride == -1) {
235 gbuffer->unlock();
236 return INVALID_OPERATION;
237 }
238
239 if (outBytesPerPixel) *outBytesPerPixel = bytesPerPixel;
240 if (outBytesPerStride) *outBytesPerStride = bytesPerStride;
241 return result;
242 }
243
AHardwareBuffer_lock(AHardwareBuffer * buffer,uint64_t usage,int32_t fence,const ARect * rect,void ** outVirtualAddress)244 int AHardwareBuffer_lock(AHardwareBuffer* buffer, uint64_t usage,
245 int32_t fence, const ARect* rect, void** outVirtualAddress) {
246 int32_t bytesPerPixel;
247 int32_t bytesPerStride;
248
249 if (!buffer) return BAD_VALUE;
250
251 if (usage & ~(AHARDWAREBUFFER_USAGE_CPU_READ_MASK |
252 AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK)) {
253 ALOGE("Invalid usage flags passed to AHardwareBuffer_lock; only "
254 "AHARDWAREBUFFER_USAGE_CPU_* flags are allowed");
255 return BAD_VALUE;
256 }
257
258 usage = AHardwareBuffer_convertToGrallocUsageBits(usage);
259 GraphicBuffer* gbuffer = AHardwareBuffer_to_GraphicBuffer(buffer);
260
261 if (gbuffer->getLayerCount() > 1) {
262 ALOGE("Buffer with multiple layers passed to AHardwareBuffer_lock; "
263 "only buffers with one layer are allowed");
264 return INVALID_OPERATION;
265 }
266
267 Rect bounds;
268 if (!rect) {
269 bounds.set(Rect(gbuffer->getWidth(), gbuffer->getHeight()));
270 } else {
271 bounds.set(Rect(rect->left, rect->top, rect->right, rect->bottom));
272 }
273 return gbuffer->lockAsync(usage, usage, bounds, outVirtualAddress, fence, &bytesPerPixel, &bytesPerStride);
274 }
275
AHardwareBuffer_lockPlanes(AHardwareBuffer * buffer,uint64_t usage,int32_t fence,const ARect * rect,AHardwareBuffer_Planes * outPlanes)276 int AHardwareBuffer_lockPlanes(AHardwareBuffer* buffer, uint64_t usage,
277 int32_t fence, const ARect* rect, AHardwareBuffer_Planes* outPlanes) {
278 if (!buffer || !outPlanes) return BAD_VALUE;
279
280 if (usage & ~(AHARDWAREBUFFER_USAGE_CPU_READ_MASK |
281 AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK)) {
282 ALOGE("Invalid usage flags passed to AHardwareBuffer_lock; only "
283 " AHARDWAREBUFFER_USAGE_CPU_* flags are allowed");
284 return BAD_VALUE;
285 }
286
287 usage = AHardwareBuffer_convertToGrallocUsageBits(usage);
288 GraphicBuffer* gBuffer = AHardwareBuffer_to_GraphicBuffer(buffer);
289 Rect bounds;
290 if (!rect) {
291 bounds.set(Rect(gBuffer->getWidth(), gBuffer->getHeight()));
292 } else {
293 bounds.set(Rect(rect->left, rect->top, rect->right, rect->bottom));
294 }
295 int format = AHardwareBuffer_convertFromPixelFormat(uint32_t(gBuffer->getPixelFormat()));
296 memset(outPlanes->planes, 0, sizeof(outPlanes->planes));
297 if (AHardwareBuffer_formatIsYuv(format)) {
298 android_ycbcr yuvData;
299 int result = gBuffer->lockAsyncYCbCr(usage, bounds, &yuvData, fence);
300 if (result == 0) {
301 outPlanes->planeCount = 3;
302 outPlanes->planes[0].data = yuvData.y;
303 // P010 is word-aligned 10-bit semiplaner, and YCbCr_422_I is a single interleaved plane
304 if (format == AHARDWAREBUFFER_FORMAT_YCbCr_P010 ||
305 format == AHARDWAREBUFFER_FORMAT_YCbCr_422_I) {
306 outPlanes->planes[0].pixelStride = 2;
307 } else {
308 outPlanes->planes[0].pixelStride = 1;
309 }
310 outPlanes->planes[0].rowStride = yuvData.ystride;
311 outPlanes->planes[1].data = yuvData.cb;
312 outPlanes->planes[1].pixelStride = yuvData.chroma_step;
313 outPlanes->planes[1].rowStride = yuvData.cstride;
314 outPlanes->planes[2].data = yuvData.cr;
315 outPlanes->planes[2].pixelStride = yuvData.chroma_step;
316 outPlanes->planes[2].rowStride = yuvData.cstride;
317 } else {
318 outPlanes->planeCount = 0;
319 }
320 return result;
321 } else {
322 int32_t bytesPerPixel;
323 int32_t bytesPerStride;
324 int result = gBuffer->lockAsync(usage, usage, bounds, &outPlanes->planes[0].data, fence,
325 &bytesPerPixel, &bytesPerStride);
326 outPlanes->planeCount = 1;
327 outPlanes->planes[0].pixelStride = bytesPerPixel;
328 outPlanes->planes[0].rowStride = bytesPerStride;
329 return result;
330 }
331 }
332
AHardwareBuffer_unlock(AHardwareBuffer * buffer,int32_t * fence)333 int AHardwareBuffer_unlock(AHardwareBuffer* buffer, int32_t* fence) {
334 if (!buffer) return BAD_VALUE;
335
336 GraphicBuffer* gBuffer = AHardwareBuffer_to_GraphicBuffer(buffer);
337 if (fence == nullptr)
338 return gBuffer->unlock();
339 else
340 return gBuffer->unlockAsync(fence);
341 }
342
AHardwareBuffer_sendHandleToUnixSocket(const AHardwareBuffer * buffer,int socketFd)343 int AHardwareBuffer_sendHandleToUnixSocket(const AHardwareBuffer* buffer, int socketFd) {
344 if (!buffer) return BAD_VALUE;
345 const GraphicBuffer* gBuffer = AHardwareBuffer_to_GraphicBuffer(buffer);
346
347 size_t flattenedSize = gBuffer->getFlattenedSize();
348 size_t fdCount = gBuffer->getFdCount();
349
350 std::unique_ptr<uint8_t[]> data(new uint8_t[flattenedSize]);
351 std::unique_ptr<int[]> fds(new int[fdCount]);
352
353 // Make copies of needed items since flatten modifies them, and we don't
354 // want to send anything if there's an error during flatten.
355 size_t flattenedSizeCopy = flattenedSize;
356 size_t fdCountCopy = fdCount;
357 void* dataStart = data.get();
358 int* fdsStart = fds.get();
359 status_t err = gBuffer->flatten(dataStart, flattenedSizeCopy, fdsStart,
360 fdCountCopy);
361 if (err != NO_ERROR) {
362 return err;
363 }
364
365 struct iovec iov[1];
366 iov[0].iov_base = data.get();
367 iov[0].iov_len = flattenedSize;
368
369 char buf[CMSG_SPACE(kFdBufferSize)];
370 struct msghdr msg = {
371 .msg_iov = &iov[0],
372 .msg_iovlen = 1,
373 .msg_control = buf,
374 .msg_controllen = sizeof(buf),
375 };
376
377 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
378 cmsg->cmsg_level = SOL_SOCKET;
379 cmsg->cmsg_type = SCM_RIGHTS;
380 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * fdCount);
381 int* fdData = reinterpret_cast<int*>(CMSG_DATA(cmsg));
382 memcpy(fdData, fds.get(), sizeof(int) * fdCount);
383 msg.msg_controllen = cmsg->cmsg_len;
384
385 int result;
386 do {
387 result = sendmsg(socketFd, &msg, 0);
388 } while (result == -1 && errno == EINTR);
389 if (result == -1) {
390 result = errno;
391 ALOGE("Error writing AHardwareBuffer to socket: error %#x (%s)",
392 result, strerror(result));
393 return -result;
394 }
395
396 return NO_ERROR;
397 }
398
AHardwareBuffer_recvHandleFromUnixSocket(int socketFd,AHardwareBuffer ** outBuffer)399 int AHardwareBuffer_recvHandleFromUnixSocket(int socketFd, AHardwareBuffer** outBuffer) {
400 if (!outBuffer) return BAD_VALUE;
401
402 static constexpr int kMessageBufferSize = 4096 * sizeof(int);
403
404 std::unique_ptr<char[]> dataBuf(new char[kMessageBufferSize]);
405 char fdBuf[CMSG_SPACE(kFdBufferSize)];
406 struct iovec iov[1];
407 iov[0].iov_base = dataBuf.get();
408 iov[0].iov_len = kMessageBufferSize;
409
410 struct msghdr msg = {
411 .msg_iov = &iov[0],
412 .msg_iovlen = 1,
413 .msg_control = fdBuf,
414 .msg_controllen = sizeof(fdBuf),
415 };
416
417 int result;
418 do {
419 result = recvmsg(socketFd, &msg, 0);
420 } while (result == -1 && errno == EINTR);
421 if (result == -1) {
422 result = errno;
423 ALOGE("Error reading AHardwareBuffer from socket: error %#x (%s)",
424 result, strerror(result));
425 return -result;
426 }
427
428 if (msg.msg_iovlen != 1) {
429 ALOGE("Error reading AHardwareBuffer from socket: bad data length");
430 return INVALID_OPERATION;
431 }
432
433 if (msg.msg_controllen % sizeof(int) != 0) {
434 ALOGE("Error reading AHardwareBuffer from socket: bad fd length");
435 return INVALID_OPERATION;
436 }
437
438 size_t dataLen = msg.msg_iov[0].iov_len;
439 const void* data = static_cast<const void*>(msg.msg_iov[0].iov_base);
440 if (!data) {
441 ALOGE("Error reading AHardwareBuffer from socket: no buffer data");
442 return INVALID_OPERATION;
443 }
444
445 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
446 if (!cmsg) {
447 ALOGE("Error reading AHardwareBuffer from socket: no fd header");
448 return INVALID_OPERATION;
449 }
450
451 size_t fdCount = msg.msg_controllen >> 2;
452 const int* fdData = reinterpret_cast<const int*>(CMSG_DATA(cmsg));
453 if (!fdData) {
454 ALOGE("Error reading AHardwareBuffer from socket: no fd data");
455 return INVALID_OPERATION;
456 }
457
458 sp<GraphicBuffer> gBuffer(new GraphicBuffer());
459 status_t err = gBuffer->unflatten(data, dataLen, fdData, fdCount);
460 if (err != NO_ERROR) {
461 return err;
462 }
463 *outBuffer = AHardwareBuffer_from_GraphicBuffer(gBuffer.get());
464 // Ensure the buffer has a positive ref-count.
465 AHardwareBuffer_acquire(*outBuffer);
466
467 return NO_ERROR;
468 }
469
AHardwareBuffer_isSupported(const AHardwareBuffer_Desc * desc)470 int AHardwareBuffer_isSupported(const AHardwareBuffer_Desc* desc) {
471 if (!desc) return 0;
472 if (!AHardwareBuffer_isValidDescription(desc, /*log=*/false)) return 0;
473
474 bool supported = false;
475 sp<GraphicBuffer> gBuffer(new GraphicBuffer());
476 status_t err = gBuffer->isSupported(desc->width, desc->height, desc->format, desc->layers,
477 desc->usage, &supported);
478
479 if (err == NO_ERROR) {
480 return supported;
481 }
482
483 // function isSupported is not implemented on device or an error occurred during HAL
484 // query. Make a trial allocation.
485 AHardwareBuffer_Desc trialDesc = *desc;
486 trialDesc.width = 4;
487 trialDesc.height = desc->format == AHARDWAREBUFFER_FORMAT_BLOB ? 1 : 4;
488 if (desc->usage & AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP) {
489 trialDesc.layers = desc->layers == 6 ? 6 : 12;
490 } else {
491 trialDesc.layers = desc->layers == 1 ? 1 : 2;
492 }
493 AHardwareBuffer* trialBuffer = nullptr;
494 int result = AHardwareBuffer_allocate(&trialDesc, &trialBuffer);
495 if (result == NO_ERROR) {
496 AHardwareBuffer_release(trialBuffer);
497 return 1;
498 }
499 return 0;
500 }
501
AHardwareBuffer_getId(const AHardwareBuffer * buffer,uint64_t * outId)502 int AHardwareBuffer_getId(const AHardwareBuffer* buffer, uint64_t* outId) {
503 if (!buffer || !outId) return BAD_VALUE;
504
505 const GraphicBuffer* gb = AHardwareBuffer_to_GraphicBuffer(buffer);
506 if (!gb) return BAD_VALUE;
507
508 *outId = gb->getId();
509
510 return OK;
511 }
512
AHardwareBuffer_readFromParcel(const AParcel * _Nonnull parcel,AHardwareBuffer * _Nullable * _Nonnull outBuffer)513 binder_status_t AHardwareBuffer_readFromParcel(const AParcel* _Nonnull parcel,
514 AHardwareBuffer* _Nullable* _Nonnull outBuffer) {
515 if (!parcel || !outBuffer) return STATUS_BAD_VALUE;
516 auto buffer = sp<GraphicBuffer>::make();
517 status_t status = AParcel_viewPlatformParcel(parcel)->read(*buffer);
518 if (status != STATUS_OK) return status;
519 *outBuffer = AHardwareBuffer_from_GraphicBuffer(buffer.get());
520 AHardwareBuffer_acquire(*outBuffer);
521 return STATUS_OK;
522 }
523
AHardwareBuffer_writeToParcel(const AHardwareBuffer * _Nonnull buffer,AParcel * _Nonnull parcel)524 binder_status_t AHardwareBuffer_writeToParcel(const AHardwareBuffer* _Nonnull buffer,
525 AParcel* _Nonnull parcel) {
526 const GraphicBuffer* gb = AHardwareBuffer_to_GraphicBuffer(buffer);
527 if (!gb) return STATUS_BAD_VALUE;
528 if (!parcel) return STATUS_BAD_VALUE;
529 return AParcel_viewPlatformParcel(parcel)->write(*gb);
530 }
531
AHardwareBuffer_getDataSpace(const AHardwareBuffer * _Nonnull buffer)532 ADataSpace AHardwareBuffer_getDataSpace(const AHardwareBuffer* _Nonnull buffer) {
533 const GraphicBuffer* gb = AHardwareBuffer_to_GraphicBuffer(buffer);
534 if (!gb) return ADATASPACE_UNKNOWN;
535 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
536 status_t status = gb->getDataspace(&dataspace);
537 if (status != OK) {
538 return ADATASPACE_UNKNOWN;
539 }
540 return static_cast<ADataSpace>(dataspace);
541 }
542
AHardwareBuffer_setDataSpace(AHardwareBuffer * buffer,ADataSpace dataspace)543 enum AHardwareBufferStatus AHardwareBuffer_setDataSpace(AHardwareBuffer* buffer,
544 ADataSpace dataspace) {
545 GraphicBuffer* gb = AHardwareBuffer_to_GraphicBuffer(buffer);
546 auto& mapper = GraphicBufferMapper::get();
547 return filterStatus(mapper.setDataspace(gb->handle, static_cast<ui::Dataspace>(dataspace)));
548 }
549
550 // ----------------------------------------------------------------------------
551 // VNDK functions
552 // ----------------------------------------------------------------------------
553
AHardwareBuffer_getNativeHandle(const AHardwareBuffer * buffer)554 const native_handle_t* AHardwareBuffer_getNativeHandle(
555 const AHardwareBuffer* buffer) {
556 if (!buffer) return nullptr;
557 const GraphicBuffer* gbuffer = AHardwareBuffer_to_GraphicBuffer(buffer);
558 return gbuffer->handle;
559 }
560
AHardwareBuffer_createFromHandle(const AHardwareBuffer_Desc * desc,const native_handle_t * handle,int32_t method,AHardwareBuffer ** outBuffer)561 int AHardwareBuffer_createFromHandle(const AHardwareBuffer_Desc* desc,
562 const native_handle_t* handle, int32_t method,
563 AHardwareBuffer** outBuffer) {
564 static_assert(static_cast<int32_t>(AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_REGISTER) ==
565 static_cast<int32_t>(GraphicBuffer::TAKE_UNREGISTERED_HANDLE));
566 static_assert(static_cast<int32_t>(AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE) ==
567 static_cast<int32_t>(GraphicBuffer::CLONE_HANDLE));
568
569 if (!desc || !handle || !outBuffer) return BAD_VALUE;
570 if (!(method == AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_REGISTER ||
571 method == AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE))
572 return BAD_VALUE;
573 if (desc->rfu0 != 0 || desc->rfu1 != 0) return BAD_VALUE;
574 if (desc->format == AHARDWAREBUFFER_FORMAT_BLOB && desc->height != 1) return BAD_VALUE;
575
576 const int format = AHardwareBuffer_convertToPixelFormat(desc->format);
577 const uint64_t usage = AHardwareBuffer_convertToGrallocUsageBits(desc->usage);
578 const auto wrapMethod = static_cast<GraphicBuffer::HandleWrapMethod>(method);
579 sp<GraphicBuffer> gbuffer(new GraphicBuffer(handle, wrapMethod, desc->width, desc->height,
580 format, desc->layers, usage, desc->stride));
581 status_t err = gbuffer->initCheck();
582 if (err != 0 || gbuffer->handle == 0) return err;
583
584 *outBuffer = AHardwareBuffer_from_GraphicBuffer(gbuffer.get());
585 // Ensure the buffer doesn't get destroyed when the sp<> goes away.
586 AHardwareBuffer_acquire(*outBuffer);
587
588 return NO_ERROR;
589 }
590
AHardwareBuffer_allocateWithOptions(const AHardwareBuffer_Desc * desc,const AHardwareBufferLongOptions * additionalOptions,size_t additionalOptionsSize,AHardwareBuffer ** outBuffer)591 enum AHardwareBufferStatus AHardwareBuffer_allocateWithOptions(
592 const AHardwareBuffer_Desc* desc, const AHardwareBufferLongOptions* additionalOptions,
593 size_t additionalOptionsSize, AHardwareBuffer** outBuffer) {
594 (void)additionalOptions;
595 (void)additionalOptionsSize;
596 if (!outBuffer || !desc) return AHARDWAREBUFFER_STATUS_BAD_VALUE;
597 if (!AHardwareBuffer_isValidDescription(desc, /*log=*/true)) {
598 return AHARDWAREBUFFER_STATUS_BAD_VALUE;
599 }
600
601 int format = AHardwareBuffer_convertToPixelFormat(desc->format);
602 uint64_t usage = AHardwareBuffer_convertToGrallocUsageBits(desc->usage);
603
604 std::vector<GraphicBufferAllocator::AdditionalOptions> extras;
605 extras.reserve(additionalOptionsSize);
606 for (size_t i = 0; i < additionalOptionsSize; i++) {
607 extras.push_back(GraphicBufferAllocator::AdditionalOptions{additionalOptions[i].name,
608 additionalOptions[i].value});
609 }
610
611 const auto extrasCount = extras.size();
612 auto gbuffer = sp<GraphicBuffer>::make(GraphicBufferAllocator::AllocationRequest{
613 .importBuffer = true,
614 .width = desc->width,
615 .height = desc->height,
616 .format = format,
617 .layerCount = desc->layers,
618 .usage = usage,
619 .requestorName = std::string("AHardwareBuffer pid [") + std::to_string(getpid()) + "]",
620 .extras = std::move(extras),
621 });
622
623 status_t err = gbuffer->initCheck();
624 if (err != 0 || gbuffer->handle == nullptr) {
625 if (err == NO_MEMORY) {
626 GraphicBuffer::dumpAllocationsToSystemLog();
627 }
628 ALOGE("GraphicBuffer(w=%u, h=%u, lc=%u, extrasCount=%zd) failed (%s), handle=%p",
629 desc->width, desc->height, desc->layers, extrasCount, strerror(-err),
630 gbuffer->handle);
631 return filterStatus(err == 0 ? UNKNOWN_ERROR : err);
632 }
633
634 *outBuffer = AHardwareBuffer_from_GraphicBuffer(gbuffer.get());
635
636 // Ensure the buffer doesn't get destroyed when the sp<> goes away.
637 AHardwareBuffer_acquire(*outBuffer);
638 return AHARDWAREBUFFER_STATUS_OK;
639 }
640
641 // ----------------------------------------------------------------------------
642 // Helpers implementation
643 // ----------------------------------------------------------------------------
644
645 namespace android {
646
AHardwareBuffer_isValidDescription(const AHardwareBuffer_Desc * desc,bool log)647 bool AHardwareBuffer_isValidDescription(const AHardwareBuffer_Desc* desc, bool log) {
648 if (desc->width == 0 || desc->height == 0 || desc->layers == 0) {
649 ALOGE_IF(log, "Width, height and layers must all be nonzero");
650 return false;
651 }
652
653 if (desc->rfu0 != 0 || desc->rfu1 != 0) {
654 ALOGE_IF(log, "AHardwareBuffer_Desc::rfu fields must be 0");
655 return false;
656 }
657
658 if (desc->format == AHARDWAREBUFFER_FORMAT_BLOB) {
659 if (desc->height != 1 || desc->layers != 1) {
660 ALOGE_IF(log, "Height and layers must be 1 for AHARDWAREBUFFER_FORMAT_BLOB");
661 return false;
662 }
663 const uint64_t blobInvalidGpuMask =
664 AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
665 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER |
666 AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE |
667 AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP;
668 if (desc->usage & blobInvalidGpuMask) {
669 ALOGE_IF(log, "Invalid GPU usage flag for AHARDWAREBUFFER_FORMAT_BLOB; "
670 "only AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER is allowed");
671 return false;
672 }
673 if (desc->usage & AHARDWAREBUFFER_USAGE_VIDEO_ENCODE) {
674 ALOGE_IF(log, "AHARDWAREBUFFER_FORMAT_BLOB cannot be encoded as video");
675 return false;
676 }
677 } else if (AHardwareBuffer_formatIsYuv(desc->format)) {
678 if (desc->layers != 1) {
679 ALOGE_IF(log, "Layers must be 1 for YUV formats.");
680 return false;
681 }
682 const uint64_t yuvInvalidGpuMask =
683 AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE |
684 AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP;
685 if (desc->usage & yuvInvalidGpuMask) {
686 ALOGE_IF(log, "Invalid usage flags specified for YUV format; "
687 "mip-mapping and cube-mapping are not allowed.");
688 return false;
689 }
690 } else {
691 if (desc->usage & AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA) {
692 ALOGE_IF(log, "AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA requires AHARDWAREBUFFER_FORMAT_BLOB");
693 return false;
694 }
695 }
696
697 if ((desc->usage & (AHARDWAREBUFFER_USAGE_CPU_READ_MASK | AHARDWAREBUFFER_USAGE_CPU_WRITE_MASK)) &&
698 (desc->usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT)) {
699 ALOGE_IF(log, "AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT requires AHARDWAREBUFFER_USAGE_CPU_READ_NEVER "
700 "and AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER");
701 return false;
702 }
703
704 if (desc->usage & AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP) {
705 if (desc->width != desc->height) {
706 ALOGE_IF(log, "Cube maps must be square");
707 return false;
708 }
709 if (desc->layers % 6 != 0) {
710 ALOGE_IF(log, "Cube map layers must be a multiple of 6");
711 return false;
712 }
713 }
714 return true;
715 }
716
AHardwareBuffer_formatIsYuv(uint32_t format)717 bool AHardwareBuffer_formatIsYuv(uint32_t format) {
718 switch (format) {
719 case AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420:
720 case AHARDWAREBUFFER_FORMAT_YV12:
721 case AHARDWAREBUFFER_FORMAT_Y8:
722 case AHARDWAREBUFFER_FORMAT_Y16:
723 case AHARDWAREBUFFER_FORMAT_YCbCr_422_SP:
724 case AHARDWAREBUFFER_FORMAT_YCrCb_420_SP:
725 case AHARDWAREBUFFER_FORMAT_YCbCr_422_I:
726 case AHARDWAREBUFFER_FORMAT_YCbCr_P010:
727 return true;
728 default:
729 return false;
730 }
731 }
732
AHardwareBuffer_convertFromPixelFormat(uint32_t hal_format)733 uint32_t AHardwareBuffer_convertFromPixelFormat(uint32_t hal_format) {
734 return hal_format;
735 }
736
AHardwareBuffer_convertToPixelFormat(uint32_t ahardwarebuffer_format)737 uint32_t AHardwareBuffer_convertToPixelFormat(uint32_t ahardwarebuffer_format) {
738 return ahardwarebuffer_format;
739 }
740
741 // TODO: Remove, this is just to make an overly aggressive ABI checker happy
AHardwareBuffer_getDataSpace(AHardwareBuffer * buffer)742 int32_t AHardwareBuffer_getDataSpace(AHardwareBuffer* buffer) {
743 return ::AHardwareBuffer_getDataSpace(buffer);
744 }
745
AHardwareBuffer_convertToGrallocUsageBits(uint64_t usage)746 uint64_t AHardwareBuffer_convertToGrallocUsageBits(uint64_t usage) {
747 using android::hardware::graphics::common::V1_1::BufferUsage;
748 static_assert(AHARDWAREBUFFER_USAGE_CPU_READ_NEVER == (uint64_t)BufferUsage::CPU_READ_NEVER,
749 "gralloc and AHardwareBuffer flags don't match");
750 static_assert(AHARDWAREBUFFER_USAGE_CPU_READ_RARELY == (uint64_t)BufferUsage::CPU_READ_RARELY,
751 "gralloc and AHardwareBuffer flags don't match");
752 static_assert(AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN == (uint64_t)BufferUsage::CPU_READ_OFTEN,
753 "gralloc and AHardwareBuffer flags don't match");
754 static_assert(AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER == (uint64_t)BufferUsage::CPU_WRITE_NEVER,
755 "gralloc and AHardwareBuffer flags don't match");
756 static_assert(AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY == (uint64_t)BufferUsage::CPU_WRITE_RARELY,
757 "gralloc and AHardwareBuffer flags don't match");
758 static_assert(AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN == (uint64_t)BufferUsage::CPU_WRITE_OFTEN,
759 "gralloc and AHardwareBuffer flags don't match");
760 static_assert(AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE == (uint64_t)BufferUsage::GPU_TEXTURE,
761 "gralloc and AHardwareBuffer flags don't match");
762 static_assert(AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER == (uint64_t)BufferUsage::GPU_RENDER_TARGET,
763 "gralloc and AHardwareBuffer flags don't match");
764 static_assert(AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT == (uint64_t)BufferUsage::PROTECTED,
765 "gralloc and AHardwareBuffer flags don't match");
766 static_assert(AHARDWAREBUFFER_USAGE_VIDEO_ENCODE == (uint64_t)BufferUsage::VIDEO_ENCODER,
767 "gralloc and AHardwareBuffer flags don't match");
768 static_assert(AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER == (uint64_t)BufferUsage::GPU_DATA_BUFFER,
769 "gralloc and AHardwareBuffer flags don't match");
770 static_assert(AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA == (uint64_t)BufferUsage::SENSOR_DIRECT_DATA,
771 "gralloc and AHardwareBuffer flags don't match");
772 static_assert(AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP == (uint64_t)BufferUsage::GPU_CUBE_MAP,
773 "gralloc and AHardwareBuffer flags don't match");
774 static_assert(AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE == (uint64_t)BufferUsage::GPU_MIPMAP_COMPLETE,
775 "gralloc and AHardwareBuffer flags don't match");
776 static_assert(AHARDWAREBUFFER_USAGE_CAMERA_WRITE == (uint64_t)BufferUsage::CAMERA_OUTPUT,
777 "gralloc and AHardwareBuffer flags don't match");
778 static_assert(AHARDWAREBUFFER_USAGE_CAMERA_READ == (uint64_t)BufferUsage::CAMERA_INPUT,
779 "gralloc and AHardwareBuffer flags don't match");
780 return usage;
781 }
782
AHardwareBuffer_convertFromGrallocUsageBits(uint64_t usage)783 uint64_t AHardwareBuffer_convertFromGrallocUsageBits(uint64_t usage) {
784 return usage;
785 }
786
AHardwareBuffer_to_GraphicBuffer(const AHardwareBuffer * buffer)787 const GraphicBuffer* AHardwareBuffer_to_GraphicBuffer(const AHardwareBuffer* buffer) {
788 return GraphicBuffer::fromAHardwareBuffer(buffer);
789 }
790
AHardwareBuffer_to_GraphicBuffer(AHardwareBuffer * buffer)791 GraphicBuffer* AHardwareBuffer_to_GraphicBuffer(AHardwareBuffer* buffer) {
792 return GraphicBuffer::fromAHardwareBuffer(buffer);
793 }
794
AHardwareBuffer_to_ANativeWindowBuffer(const AHardwareBuffer * buffer)795 const ANativeWindowBuffer* AHardwareBuffer_to_ANativeWindowBuffer(const AHardwareBuffer* buffer) {
796 return AHardwareBuffer_to_GraphicBuffer(buffer)->getNativeBuffer();
797 }
798
AHardwareBuffer_to_ANativeWindowBuffer(AHardwareBuffer * buffer)799 ANativeWindowBuffer* AHardwareBuffer_to_ANativeWindowBuffer(AHardwareBuffer* buffer) {
800 return AHardwareBuffer_to_GraphicBuffer(buffer)->getNativeBuffer();
801 }
802
AHardwareBuffer_from_GraphicBuffer(GraphicBuffer * buffer)803 AHardwareBuffer* AHardwareBuffer_from_GraphicBuffer(GraphicBuffer* buffer) {
804 return buffer->toAHardwareBuffer();
805 }
806
807 } // namespace android
808