1 /*
2 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* IOData.m created by rsulack on Thu 25-Sep-1997 */
29
30 #include <string.h>
31
32 #include <vm/vm_kern.h>
33
34 #define IOKIT_ENABLE_SHARED_PTR
35
36 #include <libkern/c++/OSData.h>
37 #include <libkern/c++/OSSerialize.h>
38 #include <libkern/c++/OSLib.h>
39 #include <libkern/c++/OSString.h>
40 #include <IOKit/IOLib.h>
41
42 #define super OSObject
43
44 OSDefineMetaClassAndStructorsWithZone(OSData, OSObject, ZC_ZFREE_CLEARMEM)
45 OSMetaClassDefineReservedUsedX86(OSData, 0); // setDeallocFunction
46 OSMetaClassDefineReservedUnused(OSData, 1);
47 OSMetaClassDefineReservedUnused(OSData, 2);
48 OSMetaClassDefineReservedUnused(OSData, 3);
49 OSMetaClassDefineReservedUnused(OSData, 4);
50 OSMetaClassDefineReservedUnused(OSData, 5);
51 OSMetaClassDefineReservedUnused(OSData, 6);
52 OSMetaClassDefineReservedUnused(OSData, 7);
53
54 #define EXTERNAL ((unsigned int) -1)
55
56 bool
initWithCapacity(unsigned int inCapacity)57 OSData::initWithCapacity(unsigned int inCapacity)
58 {
59 struct kalloc_result kr;
60 bool success = true;
61
62 if (!super::init()) {
63 return false;
64 }
65
66 /*
67 * OSData use of Z_MAY_COPYINMAP serves 2 purpposes:
68 *
69 * - It makes sure than when it goes to the VM, it uses its own object
70 * rather than the kernel object so that vm_map_copyin() can be used.
71 *
72 * - On Intel, it goes to the VM for any size >= PAGE_SIZE to maintain
73 * old (inefficient) ABI. On arm64 it will use kalloc_data() instead
74 * until the vm_map_copy_t msg_ool_size_small threshold for copies.
75 */
76
77 if (inCapacity == 0) {
78 if (capacity) {
79 OSCONTAINER_ACCUMSIZE(-(size_t)capacity);
80 /* can't use kfree() as we need to pass Z_MAY_COPYINMAP */
81 __kheap_realloc(KHEAP_DATA_BUFFERS, data, capacity, 0,
82 Z_VM_TAG_BT(Z_WAITOK_ZERO | Z_MAY_COPYINMAP,
83 VM_KERN_MEMORY_LIBKERN), (void *)&this->data);
84 data = nullptr;
85 capacity = 0;
86 }
87 } else if (inCapacity <= capacity) {
88 /*
89 * Nothing to change
90 */
91 } else {
92 if (inCapacity >= PAGE_SIZE) {
93 inCapacity = (uint32_t)round_page(inCapacity);
94 }
95 kr = kalloc_ext(KHEAP_DATA_BUFFERS, inCapacity,
96 Z_VM_TAG_BT(Z_WAITOK_ZERO | Z_MAY_COPYINMAP,
97 VM_KERN_MEMORY_LIBKERN), (void *)&this->data);
98
99 if (kr.addr) {
100 size_t delta = 0;
101
102 data = kr.addr;
103 delta -= capacity;
104 capacity = (uint32_t)MIN(kr.size, UINT32_MAX);
105 delta += capacity;
106 OSCONTAINER_ACCUMSIZE(delta);
107 } else {
108 success = false;
109 }
110 }
111
112 length = 0;
113 capacityIncrement = MAX(16, inCapacity);
114
115 return success;
116 }
117
118 bool
initWithBytes(const void * bytes,unsigned int inLength)119 OSData::initWithBytes(const void *bytes, unsigned int inLength)
120 {
121 if ((inLength && !bytes) || !initWithCapacity(inLength)) {
122 return false;
123 }
124
125 if (bytes != data) {
126 bcopy(bytes, data, inLength);
127 }
128 length = inLength;
129
130 return true;
131 }
132
133 bool
initWithBytesNoCopy(void * bytes,unsigned int inLength)134 OSData::initWithBytesNoCopy(void *bytes, unsigned int inLength)
135 {
136 if (!super::init()) {
137 return false;
138 }
139
140 length = inLength;
141 capacity = EXTERNAL;
142 data = bytes;
143
144 return true;
145 }
146
147 bool
initWithData(const OSData * inData)148 OSData::initWithData(const OSData *inData)
149 {
150 return initWithBytes(inData->data, inData->length);
151 }
152
153 bool
initWithData(const OSData * inData,unsigned int start,unsigned int inLength)154 OSData::initWithData(const OSData *inData,
155 unsigned int start, unsigned int inLength)
156 {
157 const void *localData = inData->getBytesNoCopy(start, inLength);
158
159 if (localData) {
160 return initWithBytes(localData, inLength);
161 } else {
162 return false;
163 }
164 }
165
166 OSSharedPtr<OSData>
withCapacity(unsigned int inCapacity)167 OSData::withCapacity(unsigned int inCapacity)
168 {
169 OSSharedPtr<OSData> me = OSMakeShared<OSData>();
170
171 if (me && !me->initWithCapacity(inCapacity)) {
172 return nullptr;
173 }
174
175 return me;
176 }
177
178 OSSharedPtr<OSData>
withBytes(const void * bytes,unsigned int inLength)179 OSData::withBytes(const void *bytes, unsigned int inLength)
180 {
181 OSSharedPtr<OSData> me = OSMakeShared<OSData>();
182
183 if (me && !me->initWithBytes(bytes, inLength)) {
184 return nullptr;
185 }
186 return me;
187 }
188
189 OSSharedPtr<OSData>
withBytesNoCopy(void * bytes,unsigned int inLength)190 OSData::withBytesNoCopy(void *bytes, unsigned int inLength)
191 {
192 OSSharedPtr<OSData> me = OSMakeShared<OSData>();
193
194 if (me && !me->initWithBytesNoCopy(bytes, inLength)) {
195 return nullptr;
196 }
197
198 return me;
199 }
200
201 OSSharedPtr<OSData>
withData(const OSData * inData)202 OSData::withData(const OSData *inData)
203 {
204 OSSharedPtr<OSData> me = OSMakeShared<OSData>();
205
206 if (me && !me->initWithData(inData)) {
207 return nullptr;
208 }
209
210 return me;
211 }
212
213 OSSharedPtr<OSData>
withData(const OSData * inData,unsigned int start,unsigned int inLength)214 OSData::withData(const OSData *inData,
215 unsigned int start, unsigned int inLength)
216 {
217 OSSharedPtr<OSData> me = OSMakeShared<OSData>();
218
219 if (me && !me->initWithData(inData, start, inLength)) {
220 return nullptr;
221 }
222
223 return me;
224 }
225
226 void
free()227 OSData::free()
228 {
229 if ((capacity != EXTERNAL) && data && capacity) {
230 /* can't use kfree() as we need to pass Z_MAY_COPYINMAP */
231 __kheap_realloc(KHEAP_DATA_BUFFERS, data, capacity, 0,
232 Z_VM_TAG_BT(Z_WAITOK_ZERO | Z_FULLSIZE | Z_MAY_COPYINMAP,
233 VM_KERN_MEMORY_LIBKERN), (void *)&this->data);
234 OSCONTAINER_ACCUMSIZE( -((size_t)capacity));
235 } else if (capacity == EXTERNAL) {
236 DeallocFunction freemem = reserved ? reserved->deallocFunction : NULL;
237 if (freemem && data && length) {
238 freemem(data, length);
239 }
240 }
241 if (reserved) {
242 kfree_type(ExpansionData, reserved);
243 }
244 super::free();
245 }
246
247 unsigned int
getLength() const248 OSData::getLength() const
249 {
250 return length;
251 }
252 unsigned int
getCapacity() const253 OSData::getCapacity() const
254 {
255 return capacity;
256 }
257
258 unsigned int
getCapacityIncrement() const259 OSData::getCapacityIncrement() const
260 {
261 return capacityIncrement;
262 }
263
264 unsigned int
setCapacityIncrement(unsigned increment)265 OSData::setCapacityIncrement(unsigned increment)
266 {
267 return capacityIncrement = increment;
268 }
269
270 // xx-review: does not check for capacity == EXTERNAL
271
272 unsigned int
ensureCapacity(unsigned int newCapacity)273 OSData::ensureCapacity(unsigned int newCapacity)
274 {
275 struct kalloc_result kr;
276 unsigned int finalCapacity;
277
278 if (newCapacity <= capacity) {
279 return capacity;
280 }
281
282 finalCapacity = (((newCapacity - 1) / capacityIncrement) + 1)
283 * capacityIncrement;
284
285 // integer overflow check
286 if (finalCapacity < newCapacity) {
287 return capacity;
288 }
289
290 if (finalCapacity >= PAGE_SIZE) {
291 finalCapacity = (uint32_t)round_page(finalCapacity);
292 }
293 kr = krealloc_ext((void *)KHEAP_DATA_BUFFERS, data, capacity, finalCapacity,
294 Z_VM_TAG_BT(Z_WAITOK_ZERO | Z_MAY_COPYINMAP,
295 VM_KERN_MEMORY_LIBKERN), (void *)&this->data);
296
297 if (kr.addr) {
298 size_t delta = 0;
299
300 data = kr.addr;
301 delta -= capacity;
302 capacity = (uint32_t)MIN(kr.size, UINT32_MAX);
303 delta += capacity;
304 OSCONTAINER_ACCUMSIZE(delta);
305 }
306
307 return capacity;
308 }
309
310 bool
clipForCopyout()311 OSData::clipForCopyout()
312 {
313 unsigned int newCapacity = (uint32_t)round_page(length);
314 __assert_only struct kalloc_result kr;
315
316 /*
317 * OSData allocations are atomic, which means that if copyoutkdata()
318 * is used on them, and that there are fully unused pages at the end
319 * of the OSData buffer, then vm_map_copyin() will try to clip the VM
320 * entry which will panic.
321 *
322 * In order to avoid this, trim down the unused pages.
323 *
324 * We know this operation never fails and keeps the allocation
325 * address stable.
326 */
327 if (length >= msg_ool_size_small && newCapacity < capacity) {
328 kr = krealloc_ext((void *)KHEAP_DATA_BUFFERS,
329 data, capacity, newCapacity,
330 Z_VM_TAG_BT(Z_WAITOK_ZERO | Z_FULLSIZE | Z_MAY_COPYINMAP,
331 VM_KERN_MEMORY_LIBKERN), (void *)&this->data);
332 assert(kr.addr == data);
333 OSCONTAINER_ACCUMSIZE(((size_t)newCapacity) - ((size_t)capacity));
334 capacity = newCapacity;
335 }
336 return true;
337 }
338
339 bool
appendBytes(const void * bytes,unsigned int inLength)340 OSData::appendBytes(const void *bytes, unsigned int inLength)
341 {
342 unsigned int newSize;
343
344 if (!inLength) {
345 return true;
346 }
347
348 if (capacity == EXTERNAL) {
349 return false;
350 }
351
352 if (os_add_overflow(length, inLength, &newSize)) {
353 return false;
354 }
355
356 if ((newSize > capacity) && newSize > ensureCapacity(newSize)) {
357 return false;
358 }
359
360 if (bytes) {
361 bcopy(bytes, &((unsigned char *)data)[length], inLength);
362 } else {
363 bzero(&((unsigned char *)data)[length], inLength);
364 }
365
366 length = newSize;
367
368 return true;
369 }
370
371 bool
appendByte(unsigned char byte,unsigned int inLength)372 OSData::appendByte(unsigned char byte, unsigned int inLength)
373 {
374 unsigned int newSize;
375
376 if (!inLength) {
377 return true;
378 }
379
380 if (capacity == EXTERNAL) {
381 return false;
382 }
383
384 if (os_add_overflow(length, inLength, &newSize)) {
385 return false;
386 }
387
388 if ((newSize > capacity) && newSize > ensureCapacity(newSize)) {
389 return false;
390 }
391
392 memset(&((unsigned char *)data)[length], byte, inLength);
393 length = newSize;
394
395 return true;
396 }
397
398 bool
appendBytes(const OSData * other)399 OSData::appendBytes(const OSData *other)
400 {
401 return appendBytes(other->data, other->length);
402 }
403
404 const void *
getBytesNoCopy() const405 OSData::getBytesNoCopy() const
406 {
407 if (!length) {
408 return NULL;
409 } else {
410 return data;
411 }
412 }
413
414 const void *
getBytesNoCopy(unsigned int start,unsigned int inLength) const415 OSData::getBytesNoCopy(unsigned int start,
416 unsigned int inLength) const
417 {
418 const void *outData = NULL;
419
420 if (length
421 && start < length
422 && (start + inLength) >= inLength // overflow check
423 && (start + inLength) <= length) {
424 outData = (const void *) ((char *) data + start);
425 }
426
427 return outData;
428 }
429
430 bool
isEqualTo(const OSData * aData) const431 OSData::isEqualTo(const OSData *aData) const
432 {
433 unsigned int len;
434
435 len = aData->length;
436 if (length != len) {
437 return false;
438 }
439
440 return isEqualTo(aData->data, len);
441 }
442
443 bool
isEqualTo(const void * someData,unsigned int inLength) const444 OSData::isEqualTo(const void *someData, unsigned int inLength) const
445 {
446 return (length >= inLength) && (bcmp(data, someData, inLength) == 0);
447 }
448
449 bool
isEqualTo(const OSMetaClassBase * obj) const450 OSData::isEqualTo(const OSMetaClassBase *obj) const
451 {
452 OSData * otherData;
453 OSString * str;
454
455 if ((otherData = OSDynamicCast(OSData, obj))) {
456 return isEqualTo(otherData);
457 } else if ((str = OSDynamicCast(OSString, obj))) {
458 return isEqualTo(str);
459 } else {
460 return false;
461 }
462 }
463
464 bool
isEqualTo(const OSString * obj) const465 OSData::isEqualTo(const OSString *obj) const
466 {
467 const char * aCString;
468 char * dataPtr;
469 unsigned int checkLen = length;
470 unsigned int stringLen;
471
472 if (!obj) {
473 return false;
474 }
475
476 stringLen = obj->getLength();
477
478 dataPtr = (char *)data;
479
480 if (stringLen != checkLen) {
481 // check for the fact that OSData may be a buffer that
482 // that includes a termination byte and will thus have
483 // a length of the actual string length PLUS 1. In this
484 // case we verify that the additional byte is a terminator
485 // and if so count the two lengths as being the same.
486
487 if ((checkLen - stringLen) == 1) {
488 if (dataPtr[checkLen - 1] != 0) { // non-zero means not a terminator and thus not likely the same
489 return false;
490 }
491 checkLen--;
492 } else {
493 return false;
494 }
495 }
496
497 aCString = obj->getCStringNoCopy();
498
499 for (unsigned int i = 0; i < checkLen; i++) {
500 if (*dataPtr++ != aCString[i]) {
501 return false;
502 }
503 }
504
505 return true;
506 }
507
508 //this was taken from CFPropertyList.c
509 static const char __CFPLDataEncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
510
511 bool
serialize(OSSerialize * s) const512 OSData::serialize(OSSerialize *s) const
513 {
514 unsigned int i;
515 const unsigned char *p;
516 unsigned char c;
517 unsigned int serializeLength;
518
519 if (s->previouslySerialized(this)) {
520 return true;
521 }
522
523 if (!s->addXMLStartTag(this, "data")) {
524 return false;
525 }
526
527 serializeLength = length;
528 if (reserved && reserved->disableSerialization) {
529 serializeLength = 0;
530 }
531
532 for (i = 0, p = (unsigned char *)data; i < serializeLength; i++, p++) {
533 /* 3 bytes are encoded as 4 */
534 switch (i % 3) {
535 case 0:
536 c = __CFPLDataEncodeTable[((p[0] >> 2) & 0x3f)];
537 if (!s->addChar(c)) {
538 return false;
539 }
540 break;
541 case 1:
542 c = __CFPLDataEncodeTable[((((p[-1] << 8) | p[0]) >> 4) & 0x3f)];
543 if (!s->addChar(c)) {
544 return false;
545 }
546 break;
547 case 2:
548 c = __CFPLDataEncodeTable[((((p[-1] << 8) | p[0]) >> 6) & 0x3f)];
549 if (!s->addChar(c)) {
550 return false;
551 }
552 c = __CFPLDataEncodeTable[(p[0] & 0x3f)];
553 if (!s->addChar(c)) {
554 return false;
555 }
556 break;
557 }
558 }
559 switch (i % 3) {
560 case 0:
561 break;
562 case 1:
563 c = __CFPLDataEncodeTable[((p[-1] << 4) & 0x30)];
564 if (!s->addChar(c)) {
565 return false;
566 }
567 if (!s->addChar('=')) {
568 return false;
569 }
570 if (!s->addChar('=')) {
571 return false;
572 }
573 break;
574 case 2:
575 c = __CFPLDataEncodeTable[((p[-1] << 2) & 0x3c)];
576 if (!s->addChar(c)) {
577 return false;
578 }
579 if (!s->addChar('=')) {
580 return false;
581 }
582 break;
583 }
584
585 return s->addXMLEndTag("data");
586 }
587
588 void
setDeallocFunction(DeallocFunction func)589 OSData::setDeallocFunction(DeallocFunction func)
590 {
591 if (!reserved) {
592 reserved = (typeof(reserved))kalloc_type(ExpansionData, (zalloc_flags_t)(Z_WAITOK | Z_ZERO));
593 if (!reserved) {
594 return;
595 }
596 }
597 reserved->deallocFunction = func;
598 }
599
600 void
setSerializable(bool serializable)601 OSData::setSerializable(bool serializable)
602 {
603 if (!reserved) {
604 reserved = (typeof(reserved))kalloc_type(ExpansionData, (zalloc_flags_t)(Z_WAITOK | Z_ZERO));
605 if (!reserved) {
606 return;
607 }
608 }
609 reserved->disableSerialization = (!serializable);
610 }
611
612 bool
isSerializable(void)613 OSData::isSerializable(void)
614 {
615 return !reserved || !reserved->disableSerialization;
616 }
617