• 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-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 #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 // Obtains a sector number, between low and high, from the
121 // user, accepting values prefixed by "+" to add sectors to low,
122 // or the same with "K", "M", "G", "T", or "P" as suffixes to add
123 // kilobytes, megabytes, gigabytes, terabytes, or petabytes,
124 // respectively. If a "-" prefix is used, use the high value minus
125 // the user-specified number of sectors (or KiB, MiB, etc.). Use the
126 // def value as the default if the user just hits Enter. The sSize is
127 // the sector size of the device.
GetSectorNum(uint64_t low,uint64_t high,uint64_t def,uint64_t sSize,const string & prompt)128 uint64_t GetSectorNum(uint64_t low, uint64_t high, uint64_t def, uint64_t sSize,
129                       const string & prompt) {
130    uint64_t response;
131    char line[255];
132 
133    do {
134       cout << prompt;
135       cin.getline(line, 255);
136       if (!cin.good())
137          exit(5);
138       response = IeeeToInt(line, sSize, low, high, def);
139    } while ((response < low) || (response > high));
140    return response;
141 } // GetSectorNum()
142 
143 // Convert an IEEE-1541-2002 value (K, M, G, T, P, or E) to its equivalent in
144 // number of sectors. If no units are appended, interprets as the number
145 // of sectors; otherwise, interprets as number of specified units and
146 // converts to sectors. For instance, with 512-byte sectors, "1K" converts
147 // to 2. If value includes a "+", adds low and subtracts 1; if SIValue
148 // inclues a "-", subtracts from high. If IeeeValue is empty, returns def.
149 // Returns final sector value. In case inValue is invalid, returns 0 (a
150 // sector value that's always in use on GPT and therefore invalid); and if
151 // inValue works out to something outside the range low-high, returns the
152 // computed value; the calling function is responsible for checking the
153 // validity of this value.
154 // NOTE: There's a difference in how GCC and VC++ treat oversized values
155 // (say, "999999999999999999999") read via the ">>" operator; GCC turns
156 // them into the maximum value for the type, whereas VC++ turns them into
157 // 0 values. The result is that IeeeToInt() returns UINT64_MAX when
158 // compiled with GCC (and so the value is rejected), whereas when VC++
159 // is used, the default value is returned.
IeeeToInt(string inValue,uint64_t sSize,uint64_t low,uint64_t high,uint64_t def)160 uint64_t IeeeToInt(string inValue, uint64_t sSize, uint64_t low, uint64_t high, uint64_t def) {
161    uint64_t response = def, bytesPerUnit = 1, mult = 1, divide = 1;
162    size_t foundAt = 0;
163    char suffix = ' ', plusFlag = ' ';
164    string suffixes = "KMGTPE";
165    int badInput = 0; // flag bad input; once this goes to 1, other values are irrelevant
166 
167    if (sSize == 0) {
168       sSize = SECTOR_SIZE;
169       cerr << "Bug: Sector size invalid in IeeeToInt()!\n";
170    } // if
171 
172    // Remove leading spaces, if present
173    while (inValue[0] == ' ')
174       inValue.erase(0, 1);
175 
176    // If present, flag and remove leading plus or minus sign
177    if ((inValue[0] == '+') || (inValue[0] == '-')) {
178       plusFlag = inValue[0];
179       inValue.erase(0, 1);
180    } // if
181 
182    // Extract numeric response and, if present, suffix
183    istringstream inString(inValue);
184    if (((inString.peek() < '0') || (inString.peek() > '9')) && (inString.peek() != -1))
185       badInput = 1;
186    inString >> response >> suffix;
187    suffix = toupper(suffix);
188 
189    // If no response, or if response == 0, use default (def)
190    if ((inValue.length() == 0) || (response == 0)) {
191       response = def;
192       suffix = ' ';
193       plusFlag = ' ';
194    } // if
195 
196    // Find multiplication and division factors for the suffix
197    foundAt = suffixes.find(suffix);
198    if (foundAt != string::npos) {
199       bytesPerUnit = UINT64_C(1) << (10 * (foundAt + 1));
200       mult = bytesPerUnit / sSize;
201       divide = sSize / bytesPerUnit;
202    } // if
203 
204    // Adjust response based on multiplier and plus flag, if present
205    if (mult > 1) {
206       if (response > (UINT64_MAX / mult))
207          badInput = 1;
208       else
209          response *= mult;
210    } else if (divide > 1) {
211          response /= divide;
212    } // if/elseif
213 
214    if (plusFlag == '+') {
215       // Recompute response based on low part of range (if default == high
216       // value, which should be the case when prompting for the end of a
217       // range) or the defaut value (if default != high, which should be
218       // the case for the first sector of a partition).
219       if (def == high) {
220          if (response > 0)
221             response--;
222          if (response > (UINT64_MAX - low))
223             badInput = 1;
224          else
225             response = response + low;
226       } else {
227          if (response > (UINT64_MAX - def))
228             badInput = 1;
229          else
230             response = response + def;
231       } // if/else
232    } else if (plusFlag == '-') {
233       if (response > high)
234          badInput = 1;
235       else
236          response = high - response;
237    } // if
238 
239    if (badInput)
240       response = UINT64_C(0);
241 
242    return response;
243 } // IeeeToInt()
244 
245 // Takes a size and converts this to a size in IEEE-1541-2002 units (KiB, MiB,
246 // GiB, TiB, PiB, or EiB), returned in C++ string form. The size is either in
247 // units of the sector size or, if that parameter is omitted, in bytes.
248 // (sectorSize defaults to 1). Note that this function uses peculiar
249 // manual computation of decimal value rather than simply setting
250 // theValue.precision() because this isn't possible using the available
251 // EFI library.
BytesToIeee(uint64_t size,uint32_t sectorSize)252 string BytesToIeee(uint64_t size, uint32_t sectorSize) {
253    uint64_t sizeInIeee;
254    uint64_t previousIeee;
255    float decimalIeee;
256    uint64_t index = 0;
257    string units, prefixes = " KMGTPEZ";
258    ostringstream theValue;
259 
260    sizeInIeee = previousIeee = size * (uint64_t) sectorSize;
261    while ((sizeInIeee > 1024) && (index < (prefixes.length() - 1))) {
262       index++;
263       previousIeee = sizeInIeee;
264       sizeInIeee /= 1024;
265    } // while
266    if (prefixes[index] == ' ') {
267       theValue << sizeInIeee << " bytes";
268    } else {
269       units = "  iB";
270       units[1] = prefixes[index];
271       decimalIeee = ((float) previousIeee -
272                      ((float) sizeInIeee * 1024.0) + 51.2) / 102.4;
273       if (decimalIeee >= 10.0) {
274          decimalIeee = 0.0;
275          sizeInIeee++;
276       }
277       theValue << sizeInIeee << "." << (uint32_t) decimalIeee << units;
278    } // if/else
279    return theValue.str();
280 } // BytesToIeee()
281 
282 // Converts two consecutive characters in the input string into a
283 // number, interpreting the string as a hexadecimal number, starting
284 // at the specified position.
StrToHex(const string & input,unsigned int position)285 unsigned char StrToHex(const string & input, unsigned int position) {
286    unsigned char retval = 0x00;
287    unsigned int temp;
288 
289    if (input.length() > position) {
290       sscanf(input.substr(position, 2).c_str(), "%x", &temp);
291       retval = (unsigned char) temp;
292    } // if
293    return retval;
294 } // StrToHex()
295 
296 // Returns 1 if input can be interpreted as a hexadecimal number --
297 // all characters must be spaces, digits, or letters A-F (upper- or
298 // lower-case), with at least one valid hexadecimal digit; with the
299 // exception of the first two characters, which may be "0x"; otherwise
300 // returns 0.
IsHex(string input)301 int IsHex(string input) {
302    int isHex = 1, foundHex = 0, i;
303 
304    if (input.substr(0, 2) == "0x")
305       input.erase(0, 2);
306    for (i = 0; i < (int) input.length(); i++) {
307       if ((input[i] < '0') || (input[i] > '9')) {
308          if ((input[i] < 'A') || (input[i] > 'F')) {
309             if ((input[i] < 'a') || (input[i] > 'f')) {
310                if ((input[i] != ' ') && (input[i] != '\n')) {
311                   isHex = 0;
312                }
313             } else foundHex = 1;
314          } else foundHex = 1;
315       } else foundHex = 1;
316    } // for
317    if (!foundHex)
318       isHex = 0;
319    return isHex;
320 } // IsHex()
321 
322 // Return 1 if the CPU architecture is little endian, 0 if it's big endian....
IsLittleEndian(void)323 int IsLittleEndian(void) {
324    int littleE = 1; // assume little-endian (Intel-style)
325    union {
326       uint32_t num;
327       unsigned char uc[sizeof(uint32_t)];
328    } endian;
329 
330    endian.num = 1;
331    if (endian.uc[0] != (unsigned char) 1) {
332       littleE = 0;
333    } // if
334    return (littleE);
335 } // IsLittleEndian()
336 
337 // Reverse the byte order of theValue; numBytes is number of bytes
ReverseBytes(void * theValue,int numBytes)338 void ReverseBytes(void* theValue, int numBytes) {
339    char* tempValue = NULL;
340    int i;
341 
342    tempValue = new char [numBytes];
343    if (tempValue != NULL) {
344       memcpy(tempValue, theValue, numBytes);
345       for (i = 0; i < numBytes; i++)
346          ((char*) theValue)[i] = tempValue[numBytes - i - 1];
347       delete[] tempValue;
348    } else {
349       cerr << "Could not allocate memory in ReverseBytes()! Terminating\n";
350       exit(1);
351    } // if/else
352 } // ReverseBytes()
353 
354 // On Windows, display a warning and ask whether to continue. If the user elects
355 // not to continue, exit immediately.
WinWarning(void)356 void WinWarning(void) {
357    #ifdef _WIN32
358    cout << "\a************************************************************************\n"
359         << "Most versions of Windows cannot boot from a GPT disk except on a UEFI-based\n"
360         << "computer, and most varieties prior to Vista cannot read GPT disks. Therefore,\n"
361         << "you should exit now unless you understand the implications of converting MBR\n"
362         << "to GPT or creating a new GPT disk layout!\n"
363         << "************************************************************************\n\n";
364    cout << "Are you SURE you want to continue? ";
365    if (GetYN() != 'Y')
366       exit(0);
367    #endif
368 } // WinWarning()
369 
370 // Returns the input string in lower case
ToLower(const string & input)371 string ToLower(const string& input) {
372    string lower = input; // allocate correct size through copy
373 
374    transform(input.begin(), input.end(), lower.begin(), ::tolower);
375    return lower;
376 } // ToLower()
377