blob: 47f695062fd1ff9a9d438ea00661c462bdc87577 [file] [log] [blame]
Mathias Agopian1d3faaf2009-04-10 14:24:31 -07001/*
2 * Copyright (C) 2007 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 "Gralloc"
18
19#include <stdint.h>
20#include <errno.h>
21#include <string.h>
22#include <stdlib.h>
23#include <unistd.h>
24
25#include <cutils/log.h>
26#include <cutils/native_handle.h>
27
28native_handle* native_handle_create(int numFds, int numInts)
29{
30 native_handle* h = malloc(
31 sizeof(native_handle) + sizeof(int)*(numFds+numInts));
32
33 h->version = sizeof(native_handle);
34 h->numFds = numFds;
35 h->numInts = numInts;
36 return h;
37}
38
39int native_handle_delete(native_handle* h)
40{
41 if (h) {
42 if (h->version != sizeof(native_handle))
43 return -EINVAL;
44 free(h);
45 }
46 return 0;
47}
48
49int native_handle_dup(native_handle* lhs, native_handle const* rhs)
50{
51 if (rhs->version != sizeof(native_handle))
52 return -EINVAL;
53
54 if (lhs->version != sizeof(native_handle))
55 return -EINVAL;
56
57 const int numFds = rhs->numFds;
58 const int numInts = rhs->numInts;
59
60 if (lhs->numFds == 0 && lhs->numInts == 0) {
61 lhs->numFds = numFds;
62 lhs->numInts = numInts;
63 return 0;
64 }
65
66 if (lhs->numFds != numFds)
67 return -EINVAL;
68
69 if (lhs->numInts != numInts)
70 return -EINVAL;
71
72 int i;
73 for (i=0 ; i<numFds ; i++) {
74 lhs->data[i] = dup( rhs->data[i] );
75 }
76 memcpy(&lhs->data[i], &rhs->data[i], numInts*sizeof(int));
77 return 0;
78}
79
80int native_handle_close(const native_handle* h)
81{
82 if (h->version != sizeof(native_handle))
83 return -EINVAL;
84
85 const int numFds = h->numFds;
86 int i;
87 for (i=0 ; i<numFds ; i++) {
88 close(h->data[i]);
89 }
90 return 0;
91}
92
93native_handle* native_handle_copy(const native_handle* rhs)
94{
95 if (rhs == 0)
96 return 0;
97
98 native_handle* lhs = native_handle_create(rhs->numFds, rhs->numInts);
99 if (native_handle_dup(lhs, rhs) < 0) {
100 native_handle_delete(lhs);
101 lhs = 0;
102 }
103 return lhs;
104}