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