1 // support.cc
2 // Non-class support functions for gdisk program.
3 // Primarily by Rod Smith, February 2009, but with a few functions
4 // copied from other sources (see attributions below).
5
6 /* This program is copyright (c) 2009-2018 by Roderick W. Smith. It is distributed
7 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
9 #define __STDC_LIMIT_MACROS
10 #ifndef __STDC_CONSTANT_MACROS
11 #define __STDC_CONSTANT_MACROS
12 #endif
13
14 #include <stdio.h>
15 #include <stdint.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <string.h>
19 #include <sys/stat.h>
20 #include <string>
21 #include <iostream>
22 #include <inttypes.h>
23 #include <sstream>
24 #include "support.h"
25
26 #include <sys/types.h>
27
28 // As of 1/2010, BLKPBSZGET is very new, so I'm explicitly defining it if
29 // it's not already defined. This should become unnecessary in the future.
30 // Note that this is a Linux-only ioctl....
31 #ifndef BLKPBSZGET
32 #define BLKPBSZGET _IO(0x12,123)
33 #endif
34
35 using namespace std;
36
37 // Reads a string from stdin, returning it as a C++-style string.
38 // Note that the returned string will NOT include the carriage return
39 // entered by the user.
40 #ifdef EFI
41 extern int __sscanf( const char * str , const char * format , ... ) ;
ReadString(void)42 string ReadString(void) {
43 string inString;
44 char efiString[256];
45 int stringLength;
46
47 if (fgets(efiString, 255, stdin) != NULL) {
48 stringLength = strlen(efiString);
49 if ((stringLength > 0) && (efiString[stringLength - 1] == '\n'))
50 efiString[stringLength - 1] = '\0';
51 inString = efiString;
52 } else {
53 inString = "";
54 }
55 return inString;
56 } // ReadString()
57 #else
ReadString(void)58 string ReadString(void) {
59 string inString;
60
61 cout << flush;
62 getline(cin, inString);
63 if (!cin.good())
64 exit(5);
65 return inString;
66 } // ReadString()
67 #endif
68
69 // Get a numeric value from the user, between low and high (inclusive).
70 // Keeps looping until the user enters a value within that range.
71 // If user provides no input, def (default value) is returned.
72 // (If def is outside of the low-high range, an explicit response
73 // is required.)
GetNumber(uint64_t low,uint64_t high,uint64_t def,const string & prompt)74 uint64_t GetNumber(uint64_t low, uint64_t high, uint64_t def, const string & prompt) {
75 uint64_t response, num;
76 char line[255];
77
78 if (low != high) { // bother only if low and high differ...
79 do {
80 cout << prompt << flush;
81 cin.getline(line, 255);
82 if (!cin.good())
83 exit(5);
84 num = sscanf(line, "%" SCNu64, &response);
85 if (num == 1) { // user provided a response
86 if ((response < low) || (response > high))
87 cout << "Value out of range\n";
88 } else { // user hit enter; return default
89 response = def;
90 } // if/else
91 } while ((response < low) || (response > high));
92 } else { // low == high, so return this value
93 cout << "Using " << low << "\n";
94 response = low;
95 } // else
96 return (response);
97 } // GetNumber()
98
99 // Gets a Y/N response (and converts lowercase to uppercase)
GetYN(void)100 char GetYN(void) {
101 char response;
102 string line;
103 bool again = 0 ;
104
105 do {
106 if ( again ) { cout << "Your option? " ; }
107 again = 1 ;
108 cout << "(Y/N): " << flush;
109 line = ReadString();
110 response = toupper(line[0]);
111 } while ((response != 'Y') && (response != 'N'));
112 return response;
113 } // GetYN(void)
114
115 // Obtains a sector number, between low and high, from the
116 // user, accepting values prefixed by "+" to add sectors to low,
117 // or the same with "K", "M", "G", "T", or "P" as suffixes to add
118 // kilobytes, megabytes, gigabytes, terabytes, or petabytes,
119 // respectively. If a "-" prefix is used, use the high value minus
120 // the user-specified number of sectors (or KiB, MiB, etc.). Use the
121 // def value as the default if the user just hits Enter. The sSize is
122 // the sector size of the device.
GetSectorNum(uint64_t low,uint64_t high,uint64_t def,uint64_t sSize,const string & prompt)123 uint64_t GetSectorNum(uint64_t low, uint64_t high, uint64_t def, uint64_t sSize,
124 const string & prompt) {
125 uint64_t response;
126 char line[255];
127
128 do {
129 cout << prompt;
130 cin.getline(line, 255);
131 if (!cin.good())
132 exit(5);
133 response = IeeeToInt(line, sSize, low, high, def);
134 } while ((response < low) || (response > high));
135 return response;
136 } // GetSectorNum()
137
138 // Convert an IEEE-1541-2002 value (K, M, G, T, P, or E) to its equivalent in
139 // number of sectors. If no units are appended, interprets as the number
140 // of sectors; otherwise, interprets as number of specified units and
141 // converts to sectors. For instance, with 512-byte sectors, "1K" converts
142 // to 2. If value includes a "+", adds low and subtracts 1; if SIValue
143 // inclues a "-", subtracts from high. If IeeeValue is empty, returns def.
144 // Returns final sector value. In case inValue is invalid, returns 0 (a
145 // sector value that's always in use on GPT and therefore invalid); and if
146 // inValue works out to something outside the range low-high, returns the
147 // computed value; the calling function is responsible for checking the
148 // validity of this value.
149 // NOTE: There's a difference in how GCC and VC++ treat oversized values
150 // (say, "999999999999999999999") read via the ">>" operator; GCC turns
151 // them into the maximum value for the type, whereas VC++ turns them into
152 // 0 values. The result is that IeeeToInt() returns UINT64_MAX when
153 // compiled with GCC (and so the value is rejected), whereas when VC++
154 // is used, the default value is returned.
IeeeToInt(string inValue,uint64_t sSize,uint64_t low,uint64_t high,uint64_t def)155 uint64_t IeeeToInt(string inValue, uint64_t sSize, uint64_t low, uint64_t high, uint64_t def) {
156 uint64_t response = def, bytesPerUnit = 1, mult = 1, divide = 1;
157 size_t foundAt = 0;
158 char suffix = ' ', plusFlag = ' ';
159 string suffixes = "KMGTPE";
160 int badInput = 0; // flag bad input; once this goes to 1, other values are irrelevant
161
162 if (sSize == 0) {
163 sSize = SECTOR_SIZE;
164 cerr << "Bug: Sector size invalid in IeeeToInt()!\n";
165 } // if
166
167 // Remove leading spaces, if present
168 while (inValue[0] == ' ')
169 inValue.erase(0, 1);
170
171 // If present, flag and remove leading plus or minus sign
172 if ((inValue[0] == '+') || (inValue[0] == '-')) {
173 plusFlag = inValue[0];
174 inValue.erase(0, 1);
175 } // if
176
177 // Extract numeric response and, if present, suffix
178 istringstream inString(inValue);
179 if (((inString.peek() < '0') || (inString.peek() > '9')) && (inString.peek() != -1))
180 badInput = 1;
181 inString >> response >> suffix;
182 suffix = toupper(suffix);
183
184 // If no response, or if response == 0, use default (def)
185 if ((inValue.length() == 0) || (response == 0)) {
186 response = def;
187 suffix = ' ';
188 plusFlag = ' ';
189 } // if
190
191 // Find multiplication and division factors for the suffix
192 foundAt = suffixes.find(suffix);
193 if (foundAt != string::npos) {
194 bytesPerUnit = UINT64_C(1) << (10 * (foundAt + 1));
195 mult = bytesPerUnit / sSize;
196 divide = sSize / bytesPerUnit;
197 } // if
198
199 // Adjust response based on multiplier and plus flag, if present
200 if (mult > 1) {
201 if (response > (UINT64_MAX / mult))
202 badInput = 1;
203 else
204 response *= mult;
205 } else if (divide > 1) {
206 response /= divide;
207 } // if/elseif
208
209 if (plusFlag == '+') {
210 // Recompute response based on low part of range (if default == high
211 // value, which should be the case when prompting for the end of a
212 // range) or the defaut value (if default != high, which should be
213 // the case for the first sector of a partition).
214 if (def == high) {
215 if (response > 0)
216 response--;
217 if (response > (UINT64_MAX - low))
218 badInput = 1;
219 else
220 response = response + low;
221 } else {
222 if (response > (UINT64_MAX - def))
223 badInput = 1;
224 else
225 response = response + def;
226 } // if/else
227 } else if (plusFlag == '-') {
228 if (response > high)
229 badInput = 1;
230 else
231 response = high - response;
232 } // if
233
234 if (badInput)
235 response = UINT64_C(0);
236
237 return response;
238 } // IeeeToInt()
239
240 // Takes a size and converts this to a size in IEEE-1541-2002 units (KiB, MiB,
241 // GiB, TiB, PiB, or EiB), returned in C++ string form. The size is either in
242 // units of the sector size or, if that parameter is omitted, in bytes.
243 // (sectorSize defaults to 1). Note that this function uses peculiar
244 // manual computation of decimal value rather than simply setting
245 // theValue.precision() because this isn't possible using the available
246 // EFI library.
BytesToIeee(uint64_t size,uint32_t sectorSize)247 string BytesToIeee(uint64_t size, uint32_t sectorSize) {
248 uint64_t sizeInIeee;
249 uint64_t previousIeee;
250 float decimalIeee;
251 uint64_t index = 0;
252 string units, prefixes = " KMGTPEZ";
253 ostringstream theValue;
254
255 sizeInIeee = previousIeee = size * (uint64_t) sectorSize;
256 while ((sizeInIeee > 1024) && (index < (prefixes.length() - 1))) {
257 index++;
258 previousIeee = sizeInIeee;
259 sizeInIeee /= 1024;
260 } // while
261 if (prefixes[index] == ' ') {
262 theValue << sizeInIeee << " bytes";
263 } else {
264 units = " iB";
265 units[1] = prefixes[index];
266 decimalIeee = ((float) previousIeee -
267 ((float) sizeInIeee * 1024.0) + 51.2) / 102.4;
268 if (decimalIeee >= 10.0) {
269 decimalIeee = 0.0;
270 sizeInIeee++;
271 }
272 theValue << sizeInIeee << "." << (uint32_t) decimalIeee << units;
273 } // if/else
274 return theValue.str();
275 } // BytesToIeee()
276
277 // Converts two consecutive characters in the input string into a
278 // number, interpreting the string as a hexadecimal number, starting
279 // at the specified position.
StrToHex(const string & input,unsigned int position)280 unsigned char StrToHex(const string & input, unsigned int position) {
281 unsigned char retval = 0x00;
282 unsigned int temp;
283
284 if (input.length() > position) {
285 sscanf(input.substr(position, 2).c_str(), "%x", &temp);
286 retval = (unsigned char) temp;
287 } // if
288 return retval;
289 } // StrToHex()
290
291 // Returns 1 if input can be interpreted as a hexadecimal number --
292 // all characters must be spaces, digits, or letters A-F (upper- or
293 // lower-case), with at least one valid hexadecimal digit; with the
294 // exception of the first two characters, which may be "0x"; otherwise
295 // returns 0.
IsHex(string input)296 int IsHex(string input) {
297 int isHex = 1, foundHex = 0, i;
298
299 if (input.substr(0, 2) == "0x")
300 input.erase(0, 2);
301 for (i = 0; i < (int) input.length(); i++) {
302 if ((input[i] < '0') || (input[i] > '9')) {
303 if ((input[i] < 'A') || (input[i] > 'F')) {
304 if ((input[i] < 'a') || (input[i] > 'f')) {
305 if ((input[i] != ' ') && (input[i] != '\n')) {
306 isHex = 0;
307 }
308 } else foundHex = 1;
309 } else foundHex = 1;
310 } else foundHex = 1;
311 } // for
312 if (!foundHex)
313 isHex = 0;
314 return isHex;
315 } // IsHex()
316
317 // Return 1 if the CPU architecture is little endian, 0 if it's big endian....
IsLittleEndian(void)318 int IsLittleEndian(void) {
319 int littleE = 1; // assume little-endian (Intel-style)
320 union {
321 uint32_t num;
322 unsigned char uc[sizeof(uint32_t)];
323 } endian;
324
325 endian.num = 1;
326 if (endian.uc[0] != (unsigned char) 1) {
327 littleE = 0;
328 } // if
329 return (littleE);
330 } // IsLittleEndian()
331
332 // Reverse the byte order of theValue; numBytes is number of bytes
ReverseBytes(void * theValue,int numBytes)333 void ReverseBytes(void* theValue, int numBytes) {
334 char* tempValue = NULL;
335 int i;
336
337 tempValue = new char [numBytes];
338 if (tempValue != NULL) {
339 memcpy(tempValue, theValue, numBytes);
340 for (i = 0; i < numBytes; i++)
341 ((char*) theValue)[i] = tempValue[numBytes - i - 1];
342 delete[] tempValue;
343 } else {
344 cerr << "Could not allocate memory in ReverseBytes()! Terminating\n";
345 exit(1);
346 } // if/else
347 } // ReverseBytes()
348
349 // On Windows, display a warning and ask whether to continue. If the user elects
350 // not to continue, exit immediately.
WinWarning(void)351 void WinWarning(void) {
352 #ifdef _WIN32
353 cout << "\a************************************************************************\n"
354 << "Most versions of Windows cannot boot from a GPT disk except on a UEFI-based\n"
355 << "computer, and most varieties prior to Vista cannot read GPT disks. Therefore,\n"
356 << "you should exit now unless you understand the implications of converting MBR\n"
357 << "to GPT or creating a new GPT disk layout!\n"
358 << "************************************************************************\n\n";
359 cout << "Are you SURE you want to continue? ";
360 if (GetYN() != 'Y')
361 exit(0);
362 #endif
363 } // WinWarning()
364