xref: /haiku/src/tests/system/boot/loader/Handle.cpp (revision e1c4049fed1047bdb957b0529e1921e97ef94770)
1 /*
2  * Copyright 2003-2005, Axel Dörfler, axeld@pinc-software.de. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include "Handle.h"
8 
9 #include <SupportDefs.h>
10 #include <boot/platform.h>
11 
12 #include <stdio.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <errno.h>
18 
19 
20 #ifndef HAVE_READ_POS
21 #	define read_pos(fd, pos, buffer, size) pread(fd, buffer, size, pos)
22 #	define write_pos(fd, pos, buffer, size) pwrite(fd, buffer, size, pos)
23 #endif
24 
25 
26 Handle::Handle(int handle, bool takeOwnership)
27 	:
28 	fHandle(handle),
29 	fOwnHandle(takeOwnership),
30 	fPath(NULL)
31 {
32 }
33 
34 
35 Handle::Handle(const char *path)
36 	:
37 	fOwnHandle(true),
38 	fPath(NULL)
39 {
40 	fHandle = open(path, O_RDONLY);
41 	if (fHandle < B_OK) {
42 		fHandle = errno;
43 		return;
44 	}
45 
46 	fPath = strdup(path);
47 }
48 
49 
50 Handle::Handle(void)
51 	:
52 	fHandle(0)
53 {
54 }
55 
56 
57 Handle::~Handle()
58 {
59 	if (fOwnHandle)
60 		close(fHandle);
61 
62 	free(fPath);
63 }
64 
65 
66 status_t
67 Handle::InitCheck()
68 {
69 	return fHandle < B_OK ? fHandle : B_OK;
70 }
71 
72 
73 void
74 Handle::SetTo(int handle, bool takeOwnership)
75 {
76 	if (fHandle && fOwnHandle)
77 		close(fHandle);
78 
79 	fHandle = handle;
80 	fOwnHandle = takeOwnership;
81 }
82 
83 
84 ssize_t
85 Handle::ReadAt(void *cookie, off_t pos, void *buffer, size_t bufferSize)
86 {
87 	//printf("Handle::ReadAt(pos = %lld, buffer = %p, size = %lu)\n", pos, buffer, bufferSize);
88 	return read_pos(fHandle, pos, buffer, bufferSize);
89 }
90 
91 
92 ssize_t
93 Handle::WriteAt(void *cookie, off_t pos, const void *buffer, size_t bufferSize)
94 {
95 	return write_pos(fHandle, pos, buffer, bufferSize);
96 }
97 
98 
99 status_t
100 Handle::GetName(char *nameBuffer, size_t bufferSize) const
101 {
102 	if (fPath == NULL)
103 		return B_ERROR;
104 
105 	strncpy(nameBuffer, fPath, bufferSize - 1);
106 	nameBuffer[bufferSize - 1] = '\0';
107 	return B_OK;
108 }
109 
110 
111 off_t
112 Handle::Size() const
113 {
114 	struct stat stat;
115 	if (fstat(fHandle, &stat) == B_OK) {
116 		if (stat.st_size == 0) {
117 			// ToDo: fix this!
118 			return 1024LL * 1024 * 1024 * 1024;
119 				// 1024 GB
120 		}
121 		return stat.st_size;
122 	}
123 
124 	return 0LL;
125 }
126 
127