smartmontools SVN Rev 5474
Utility to control and monitor storage systems with "S.M.A.R.T."
utility.cpp
Go to the documentation of this file.
1/*
2 * utility.cpp
3 *
4 * Home page of code is: https://www.smartmontools.org
5 *
6 * Copyright (C) 2002-12 Bruce Allen
7 * Copyright (C) 2008-23 Christian Franke
8 * Copyright (C) 2000 Michael Cornwell <cornwell@acm.org>
9 *
10 * SPDX-License-Identifier: GPL-2.0-or-later
11 */
12
13// THIS FILE IS INTENDED FOR UTILITY ROUTINES THAT ARE APPLICABLE TO
14// BOTH SCSI AND ATA DEVICES, AND THAT MAY BE USED IN SMARTD,
15// SMARTCTL, OR BOTH.
16
17#include "config.h"
18#define __STDC_FORMAT_MACROS 1 // enable PRI* for C++
19
20#include <inttypes.h>
21#include <stdio.h>
22#include <string.h>
23#include <time.h>
24#include <errno.h>
25#include <stdlib.h>
26#include <ctype.h>
27#include <stdarg.h>
28#include <sys/stat.h>
29#ifdef HAVE_LOCALE_H
30#include <locale.h>
31#endif
32#ifdef _WIN32
33#include <mbstring.h> // _mbsinc()
34#endif
35
36#include <stdexcept>
37
38#include "svnversion.h"
39#include "utility.h"
40
41#include "atacmds.h"
42#include "dev_interface.h"
43#include "sg_unaligned.h"
44
45#ifndef USE_CLOCK_MONOTONIC
46#ifdef __MINGW32__
47// If MinGW-w64 < 9.0.0 or Windows < 8, GetSystemTimeAsFileTime() is used for
48// std::chrono::high_resolution_clock. This provides only 1/64s (>15ms) resolution.
49// CLOCK_MONOTONIC uses QueryPerformanceCounter() which provides <1us resolution.
50#define USE_CLOCK_MONOTONIC 1
51#else
52// Use std::chrono::high_resolution_clock.
53#include <chrono>
54#define USE_CLOCK_MONOTONIC 0
55#endif
56#endif // USE_CLOCK_MONOTONIC
57
58const char * utility_cpp_cvsid = "$Id: utility.cpp 5438 2023-01-23 17:57:02Z chrfranke $"
60
61const char * packet_types[] = {
62 "Direct-access (disk)",
63 "Sequential-access (tape)",
64 "Printer",
65 "Processor",
66 "Write-once (optical disk)",
67 "CD/DVD",
68 "Scanner",
69 "Optical memory (optical disk)",
70 "Medium changer",
71 "Communications",
72 "Graphic arts pre-press (10)",
73 "Graphic arts pre-press (11)",
74 "Array controller",
75 "Enclosure services",
76 "Reduced block command (simplified disk)",
77 "Optical card reader/writer"
78};
79
80// BUILD_INFO can be provided by package maintainers
81#ifndef BUILD_INFO
82#define BUILD_INFO "(local build)"
83#endif
84
85// Make version information string
86std::string format_version_info(const char * prog_name, bool full /*= false*/)
87{
88 std::string info = strprintf(
89 "%s "
90#ifndef SMARTMONTOOLS_RELEASE_DATE
91 "pre-"
92#endif
93 PACKAGE_VERSION " "
94#ifdef SMARTMONTOOLS_SVN_REV
95 SMARTMONTOOLS_SVN_DATE " r" SMARTMONTOOLS_SVN_REV
96#else
97 "(build date " __DATE__ ")" // checkout without expansion of Id keywords
98#endif
99 " [%s] " BUILD_INFO "\n"
100 "Copyright (C) 2002-23, Bruce Allen, Christian Franke, www.smartmontools.org\n",
101 prog_name, smi()->get_os_version_str().c_str()
102 );
103 if (!full)
104 return info;
105
106 info += "\n";
107 info += prog_name;
108 info += " comes with ABSOLUTELY NO WARRANTY. This is free\n"
109 "software, and you are welcome to redistribute it under\n"
110 "the terms of the GNU General Public License; either\n"
111 "version 2, or (at your option) any later version.\n"
112 "See https://www.gnu.org for further details.\n"
113 "\n"
114#ifndef SMARTMONTOOLS_RELEASE_DATE
115 "smartmontools pre-release " PACKAGE_VERSION "\n"
116#else
117 "smartmontools release " PACKAGE_VERSION
118 " dated " SMARTMONTOOLS_RELEASE_DATE " at " SMARTMONTOOLS_RELEASE_TIME "\n"
119#endif
120#ifdef SMARTMONTOOLS_SVN_REV
121 "smartmontools SVN rev " SMARTMONTOOLS_SVN_REV
122 " dated " SMARTMONTOOLS_SVN_DATE " at " SMARTMONTOOLS_SVN_TIME "\n"
123#else
124 "smartmontools SVN rev is unknown\n"
125#endif
126 "smartmontools build host: " SMARTMONTOOLS_BUILD_HOST "\n"
127 "smartmontools build with: "
128
129#define N2S_(s) #s
130#define N2S(s) N2S_(s)
131#if __cplusplus == 202002
132 "C++20"
133#elif __cplusplus == 201703
134 "C++17"
135#elif __cplusplus == 201402
136 "C++14"
137#elif __cplusplus == 201103
138 "C++11"
139#else
140 "C++(" N2S(__cplusplus) ")"
141#endif
142#undef N2S
143#undef N2S_
144
145#if defined(__GNUC__) && defined(__VERSION__) // works also with CLang
146 ", GCC " __VERSION__
147#endif
148#ifdef __MINGW64_VERSION_STR
149 ", MinGW-w64 " __MINGW64_VERSION_STR
150#endif
151 "\n"
152 "smartmontools configure arguments:"
153#ifdef SOURCE_DATE_EPOCH
154 " [hidden in reproducible builds]\n"
155 "reproducible build SOURCE_DATE_EPOCH: "
156#endif
157 ;
158#ifdef SOURCE_DATE_EPOCH
159 char ts[32]; struct tm tmbuf;
160 strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M:%S", time_to_tm_local(&tmbuf, SOURCE_DATE_EPOCH));
161 info += strprintf("%u (%s)", (unsigned)SOURCE_DATE_EPOCH, ts);
162#else
163 info += (sizeof(SMARTMONTOOLS_CONFIGURE_ARGS) > 1 ?
164 SMARTMONTOOLS_CONFIGURE_ARGS : " [no arguments given]");
165#endif
166 info += '\n';
167
168 return info;
169}
170
171// Solaris only: Get site-default timezone. This is called from
172// UpdateTimezone() when TZ environment variable is unset at startup.
173#if defined (__SVR4) && defined (__sun)
174static const char *TIMEZONE_FILE = "/etc/TIMEZONE";
175
176static char *ReadSiteDefaultTimezone(){
177 FILE *fp;
178 char buf[512], *tz;
179 int n;
180
181 tz = NULL;
182 fp = fopen(TIMEZONE_FILE, "r");
183 if(fp == NULL) return NULL;
184 while(fgets(buf, sizeof(buf), fp)) {
185 if (strncmp(buf, "TZ=", 3)) // searches last "TZ=" line
186 continue;
187 n = strlen(buf) - 1;
188 if (buf[n] == '\n') buf[n] = 0;
189 if (tz) free(tz);
190 tz = strdup(buf);
191 }
192 fclose(fp);
193 return tz;
194}
195#endif
196
197// Make sure that this executable is aware if the user has changed the
198// time-zone since the last time we polled devices. The canonical
199// example is a user who starts smartd on a laptop, then flies across
200// time-zones with a laptop, and then changes the timezone, WITHOUT
201// restarting smartd. This is a work-around for a bug in
202// GLIBC. Yuk. See bug number 48184 at http://bugs.debian.org and
203// thanks to Ian Redfern for posting a workaround.
204
205// Please refer to the smartd manual page, in the section labeled LOG
206// TIMESTAMP TIMEZONE.
208#if __GLIBC__
209 if (!getenv("TZ")) {
210 putenv((char *)"TZ=GMT"); // POSIX prototype is 'int putenv(char *)'
211 tzset();
212 putenv((char *)"TZ");
213 tzset();
214 }
215#elif _WIN32
216 if (!getenv("TZ")) {
217 putenv("TZ=GMT");
218 tzset();
219 putenv("TZ="); // empty value removes TZ, putenv("TZ") does nothing
220 tzset();
221 }
222#elif defined (__SVR4) && defined (__sun)
223 // In Solaris, putenv("TZ=") sets null string and invalid timezone.
224 // putenv("TZ") does nothing. With invalid TZ, tzset() do as if
225 // TZ=GMT. With TZ unset, /etc/TIMEZONE will be read only _once_ at
226 // first tzset() call. Conclusion: Unlike glibc, dynamic
227 // configuration of timezone can be done only by changing actual
228 // value of TZ environment value.
229 enum tzstate { NOT_CALLED_YET, USER_TIMEZONE, TRACK_TIMEZONE };
230 static enum tzstate state = NOT_CALLED_YET;
231
232 static struct stat prev_stat;
233 static char *prev_tz;
234 struct stat curr_stat;
235 char *curr_tz;
236
237 if(state == NOT_CALLED_YET) {
238 if(getenv("TZ")) {
239 state = USER_TIMEZONE; // use supplied timezone
240 } else {
241 state = TRACK_TIMEZONE;
242 if(stat(TIMEZONE_FILE, &prev_stat)) {
243 state = USER_TIMEZONE; // no TZ, no timezone file; use GMT forever
244 } else {
245 prev_tz = ReadSiteDefaultTimezone(); // track timezone file change
246 if(prev_tz) putenv(prev_tz);
247 }
248 }
249 tzset();
250 } else if(state == TRACK_TIMEZONE) {
251 if(stat(TIMEZONE_FILE, &curr_stat) == 0
252 && (curr_stat.st_ctime != prev_stat.st_ctime
253 || curr_stat.st_mtime != prev_stat.st_mtime)) {
254 // timezone file changed
255 curr_tz = ReadSiteDefaultTimezone();
256 if(curr_tz) {
257 putenv(curr_tz);
258 if(prev_tz) free(prev_tz);
259 prev_tz = curr_tz; prev_stat = curr_stat;
260 }
261 }
262 tzset();
263 }
264#endif
265 // OTHER OS/LIBRARY FIXES SHOULD GO HERE, IF DESIRED. PLEASE TRY TO
266 // KEEP THEM INDEPENDENT.
267 return;
268}
269
270#ifdef _WIN32
271// Fix strings in tzname[] to avoid long names with non-ascii characters.
272// If TZ is not set, tzset() in the MSVC runtime sets tzname[] to the
273// national language timezone names returned by GetTimezoneInformation().
274static char * fixtzname(char * dest, int destsize, const char * src)
275{
276 int i = 0, j = 0;
277 while (src[i] && j < destsize-1) {
278 int i2 = (const char *)_mbsinc((const unsigned char *)src+i) - src;
279 if (i2 > i+1)
280 i = i2; // Ignore multibyte chars
281 else {
282 if ('A' <= src[i] && src[i] <= 'Z')
283 dest[j++] = src[i]; // "Pacific Standard Time" => "PST"
284 i++;
285 }
286 }
287 if (j < 2)
288 j = 0;
289 dest[j] = 0;
290 return dest;
291}
292#endif // _WIN32
293
294// This value follows the peripheral device type value as defined in
295// SCSI Primary Commands, ANSI INCITS 301:1997. It is also used in
296// the ATA standard for packet devices to define the device type.
297const char *packetdevicetype(int type){
298 if (type<0x10)
299 return packet_types[type];
300
301 if (type<0x20)
302 return "Reserved";
303
304 return "Unknown";
305}
306
307// Convert time to broken-down local time, throw on error.
308struct tm * time_to_tm_local(struct tm * tp, time_t t)
309{
310#ifndef _WIN32
311 // POSIX (missing in MSVRCT, C and C++)
312 if (!localtime_r(&t, tp))
313 throw std::runtime_error("localtime_r() failed");
314#else
315 // MSVCRT (missing in POSIX, C11 variant differs)
316 if (localtime_s(tp, &t))
317 throw std::runtime_error("localtime_s() failed");
318#endif
319 return tp;
320}
321
322// Utility function prints date and time and timezone into a character
323// buffer of length 64. All the fuss is needed to get the right
324// timezone info (sigh).
325void dateandtimezoneepoch(char (& buffer)[DATEANDEPOCHLEN], time_t tval)
326{
328
329 // Get the time structure. We need this to determine if we are in
330 // daylight savings time or not.
331 struct tm tmbuf, * tmval = time_to_tm_local(&tmbuf, tval);
332
333 // Convert to an ASCII string, put in datebuffer.
334 // Same as: strftime(datebuffer, sizeof(datebuffer), "%a %b %e %H:%M:%S %Y\n"),
335 // but always in "C" locale.
336 char datebuffer[32];
337 STATIC_ASSERT(sizeof(datebuffer) >= 26); // assumed by asctime_r()
338#ifndef _WIN32
339 // POSIX (missing in MSVRCT, C and C++)
340 if (!asctime_r(tmval, datebuffer))
341 throw std::runtime_error("asctime_r() failed");
342#else
343 // MSVCRT, C11 (missing in POSIX)
344 if (asctime_s(datebuffer, sizeof(datebuffer), tmval))
345 throw std::runtime_error("asctime_s() failed");
346#endif
347
348 // Remove newline
349 int lenm1 = strlen(datebuffer) - 1;
350 datebuffer[lenm1>=0?lenm1:0]='\0';
351
352#if defined(_WIN32) && defined(_MSC_VER)
353 // tzname is missing in MSVC14
354 #define tzname _tzname
355#endif
356
357 // correct timezone name
358 const char * timezonename;
359 if (tmval->tm_isdst==0)
360 // standard time zone
361 timezonename=tzname[0];
362 else if (tmval->tm_isdst>0)
363 // daylight savings in effect
364 timezonename=tzname[1];
365 else
366 // unable to determine if daylight savings in effect
367 timezonename="";
368
369#ifdef _WIN32
370 // Fix long non-ascii timezone names
371 // cppcheck-suppress variableScope
372 char tzfixbuf[6+1] = "";
373 if (!getenv("TZ"))
374 timezonename=fixtzname(tzfixbuf, sizeof(tzfixbuf), timezonename);
375#endif
376
377 // Finally put the information into the buffer as needed.
378 snprintf(buffer, DATEANDEPOCHLEN, "%s %s", datebuffer, timezonename);
379
380 return;
381}
382
383// A replacement for perror() that sends output to our choice of
384// printing. If errno not set then just print message.
385void syserror(const char *message){
386
387 if (errno) {
388 // Get the correct system error message:
389 const char *errormessage=strerror(errno);
390
391 // Check that caller has handed a sensible string, and provide
392 // appropriate output. See perror(3) man page to understand better.
393 if (message && *message)
394 pout("%s: %s\n",message, errormessage);
395 else
396 pout("%s\n",errormessage);
397 }
398 else if (message && *message)
399 pout("%s\n",message);
400
401 return;
402}
403
404// Check regular expression for non-portable features.
405//
406// POSIX extended regular expressions interpret unmatched ')' ordinary:
407// "The close-parenthesis shall be considered special in this context
408// only if matched with a preceding open-parenthesis."
409//
410// GNU libc and BSD libc support unmatched ')', Cygwin reports an error.
411//
412// POSIX extended regular expressions do not define empty subexpressions:
413// "A vertical-line appearing first or last in an ERE, or immediately following
414// a vertical-line or a left-parenthesis, or immediately preceding a
415// right-parenthesis, produces undefined results."
416//
417// GNU libc and Cygwin support empty subexpressions, BSD libc reports an error.
418//
419static const char * check_regex(const char * pattern)
420{
421 int level = 0;
422 char c;
423
424 for (int i = 0; (c = pattern[i]); i++) {
425 // Skip "\x"
426 if (c == '\\') {
427 if (!pattern[++i])
428 break;
429 continue;
430 }
431
432 // Skip "[...]"
433 if (c == '[') {
434 if (pattern[++i] == '^')
435 i++;
436 if (!pattern[i++])
437 break;
438 while ((c = pattern[i]) && c != ']')
439 i++;
440 if (!c)
441 break;
442 continue;
443 }
444
445 // Check "(...)" nesting
446 if (c == '(')
447 level++;
448 else if (c == ')' && --level < 0)
449 return "Unmatched ')'";
450
451 // Check for leading/trailing '|' or "||", "|)", "|$", "(|", "^|"
452 char c1;
453 if ( (c == '|' && ( i == 0 || !(c1 = pattern[i+1])
454 || c1 == '|' || c1 == ')' || c1 == '$'))
455 || ((c == '(' || c == '^') && pattern[i+1] == '|') )
456 return "Empty '|' subexpression";
457 }
458
459 return (const char *)0;
460}
461
462// Wrapper class for POSIX regex(3) or std::regex
463
464#ifndef WITH_CXX11_REGEX
465
467{
468 memset(&m_regex_buf, 0, sizeof(m_regex_buf));
469}
470
472{
473 free_buf();
474}
475
477: m_pattern(x.m_pattern),
478 m_errmsg(x.m_errmsg)
479{
480 memset(&m_regex_buf, 0, sizeof(m_regex_buf));
481 copy_buf(x);
482}
483
485{
487 m_errmsg = x.m_errmsg;
488 free_buf();
489 copy_buf(x);
490 return *this;
491}
492
494{
495 if (nonempty(&m_regex_buf, sizeof(m_regex_buf))) {
496 regfree(&m_regex_buf);
497 memset(&m_regex_buf, 0, sizeof(m_regex_buf));
498 }
499}
500
502{
503 if (nonempty(&x.m_regex_buf, sizeof(x.m_regex_buf))) {
504 // There is no POSIX compiled-regex-copy command.
505 if (!compile())
506 throw std::runtime_error(strprintf(
507 "Unable to recompile regular expression \"%s\": %s",
508 m_pattern.c_str(), m_errmsg.c_str()));
509 }
510}
511
512#endif // !WITH_CXX11_REGEX
513
515: m_pattern(pattern)
516{
517 if (!compile())
518 throw std::runtime_error(strprintf(
519 "error in regular expression \"%s\": %s",
520 m_pattern.c_str(), m_errmsg.c_str()));
521}
522
523bool regular_expression::compile(const char * pattern)
524{
525#ifndef WITH_CXX11_REGEX
526 free_buf();
527#endif
528 m_pattern = pattern;
529 return compile();
530}
531
533{
534#ifdef WITH_CXX11_REGEX
535 try {
536 m_regex.assign(m_pattern, std::regex_constants::extended);
537 }
538 catch (std::regex_error & ex) {
539 m_errmsg = ex.what();
540 return false;
541 }
542
543#else
544 int errcode = regcomp(&m_regex_buf, m_pattern.c_str(), REG_EXTENDED);
545 if (errcode) {
546 char errmsg[512];
547 regerror(errcode, &m_regex_buf, errmsg, sizeof(errmsg));
548 m_errmsg = errmsg;
549 free_buf();
550 return false;
551 }
552#endif
553
554 const char * errmsg = check_regex(m_pattern.c_str());
555 if (errmsg) {
556 m_errmsg = errmsg;
557#ifdef WITH_CXX11_REGEX
558 m_regex = std::regex();
559#else
560 free_buf();
561#endif
562 return false;
563 }
564
565 m_errmsg.clear();
566 return true;
567}
568
569bool regular_expression::full_match(const char * str) const
570{
571#ifdef WITH_CXX11_REGEX
572 return std::regex_match(str, m_regex);
573#else
574 match_range range;
575 return ( !regexec(&m_regex_buf, str, 1, &range, 0)
576 && range.rm_so == 0 && range.rm_eo == (int)strlen(str));
577#endif
578}
579
580bool regular_expression::execute(const char * str, unsigned nmatch, match_range * pmatch) const
581{
582#ifdef WITH_CXX11_REGEX
583 std::cmatch m;
584 if (!std::regex_search(str, m, m_regex))
585 return false;
586 unsigned sz = m.size();
587 for (unsigned i = 0; i < nmatch; i++) {
588 if (i < sz && *m[i].first) {
589 pmatch[i].rm_so = m[i].first - str;
590 pmatch[i].rm_eo = m[i].second - str;
591 }
592 else
593 pmatch[i].rm_so = pmatch[i].rm_eo = -1;
594 }
595 return true;
596
597#else
598 return !regexec(&m_regex_buf, str, nmatch, pmatch, 0);
599#endif
600}
601
602// Splits an argument to the -t option that is assumed to be of the form
603// "selective,%lld-%lld" (prefixes of "0" (for octal) and "0x"/"0X" (for hex)
604// are allowed). The first long long int is assigned to *start and the second
605// to *stop. Returns zero if successful and non-zero otherwise.
606int split_selective_arg(char *s, uint64_t *start,
607 uint64_t *stop, int *mode)
608{
609 char *tailptr;
610 if (!(s = strchr(s, ',')))
611 return 1;
612 bool add = false;
613 if (!isdigit((int)(*++s))) {
614 *start = *stop = 0;
615 if (!strncmp(s, "redo", 4))
616 *mode = SEL_REDO;
617 else if (!strncmp(s, "next", 4))
618 *mode = SEL_NEXT;
619 else if (!strncmp(s, "cont", 4))
620 *mode = SEL_CONT;
621 else
622 return 1;
623 s += 4;
624 if (!*s)
625 return 0;
626 if (*s != '+')
627 return 1;
628 }
629 else {
630 *mode = SEL_RANGE;
631 errno = 0;
632 // Last argument to strtoull (the base) is 0 meaning that decimal is assumed
633 // unless prefixes of "0" (for octal) or "0x"/"0X" (for hex) are used.
634 *start = strtoull(s, &tailptr, 0);
635 s = tailptr;
636 add = (*s == '+');
637 if (!(!errno && (add || *s == '-')))
638 return 1;
639 if (!strcmp(s, "-max")) {
640 *stop = ~(uint64_t)0; // replaced by max LBA later
641 return 0;
642 }
643 }
644
645 errno = 0;
646 *stop = strtoull(s+1, &tailptr, 0);
647 if (errno || *tailptr != '\0')
648 return 1;
649 if (add) {
650 if (*stop > 0)
651 (*stop)--;
652 *stop += *start; // -t select,N+M => -t select,N,(N+M-1)
653 }
654 return 0;
655}
656
657// Returns true if region of memory contains non-zero entries
658bool nonempty(const void * data, int size)
659{
660 for (int i = 0; i < size; i++)
661 if (((const unsigned char *)data)[i])
662 return true;
663 return false;
664}
665
666// Copy not null terminated char array to null terminated string.
667// Replace non-ascii characters. Remove leading and trailing blanks.
668const char * format_char_array(char * str, int strsize, const char * chr, int chrsize)
669{
670 int b = 0;
671 while (b < chrsize && chr[b] == ' ')
672 b++;
673 int n = 0;
674 while (b+n < chrsize && chr[b+n])
675 n++;
676 while (n > 0 && chr[b+n-1] == ' ')
677 n--;
678
679 if (n >= strsize)
680 n = strsize-1;
681
682 for (int i = 0; i < n; i++) {
683 char c = chr[b+i];
684 str[i] = (' ' <= c && c <= '~' ? c : '?');
685 }
686
687 str[n] = 0;
688 return str;
689}
690
691// Format integer with thousands separator
692const char * format_with_thousands_sep(char * str, int strsize, uint64_t val,
693 const char * thousands_sep /* = 0 */)
694{
695 if (!thousands_sep) {
696 thousands_sep = ",";
697#ifdef HAVE_LOCALE_H
698 setlocale(LC_ALL, "");
699 const struct lconv * currentlocale = localeconv();
700 if (*(currentlocale->thousands_sep))
701 thousands_sep = currentlocale->thousands_sep;
702#endif
703 }
704
705 char num[64];
706 snprintf(num, sizeof(num), "%" PRIu64, val);
707 int numlen = strlen(num);
708
709 int i = 0, j = 0;
710 do
711 str[j++] = num[i++];
712 while (i < numlen && (numlen - i) % 3 != 0 && j < strsize-1);
713 str[j] = 0;
714
715 while (i < numlen && j < strsize-1) {
716 j += snprintf(str+j, strsize-j, "%s%.3s", thousands_sep, num+i);
717 i += 3;
718 }
719
720 return str;
721}
722
723// Format capacity with SI prefixes
724const char * format_capacity(char * str, int strsize, uint64_t val,
725 const char * decimal_point /* = 0 */)
726{
727 if (!decimal_point) {
728 decimal_point = ".";
729#ifdef HAVE_LOCALE_H
730 setlocale(LC_ALL, "");
731 const struct lconv * currentlocale = localeconv();
732 if (*(currentlocale->decimal_point))
733 decimal_point = currentlocale->decimal_point;
734#endif
735 }
736
737 const unsigned factor = 1000; // 1024 for KiB,MiB,...
738 static const char prefixes[] = " KMGTP";
739
740 // Find d with val in [d, d*factor)
741 unsigned i = 0;
742 uint64_t d = 1;
743 for (uint64_t d2 = d * factor; val >= d2; d2 *= factor) {
744 d = d2;
745 if (++i >= sizeof(prefixes)-2)
746 break;
747 }
748
749 // Print 3 digits
750 uint64_t n = val / d;
751 if (i == 0)
752 snprintf(str, strsize, "%u B", (unsigned)n);
753 else if (n >= 100) // "123 xB"
754 snprintf(str, strsize, "%" PRIu64 " %cB", n, prefixes[i]);
755 else if (n >= 10) // "12.3 xB"
756 snprintf(str, strsize, "%" PRIu64 "%s%u %cB", n, decimal_point,
757 (unsigned)(((val % d) * 10) / d), prefixes[i]);
758 else // "1.23 xB"
759 snprintf(str, strsize, "%" PRIu64 "%s%02u %cB", n, decimal_point,
760 (unsigned)(((val % d) * 100) / d), prefixes[i]);
761
762 return str;
763}
764
765// return (v)sprintf() formatted std::string
767std::string vstrprintf(const char * fmt, va_list ap)
768{
769 char buf[512];
770 vsnprintf(buf, sizeof(buf), fmt, ap);
771 buf[sizeof(buf)-1] = 0;
772 return buf;
773}
774
775std::string strprintf(const char * fmt, ...)
776{
777 va_list ap; va_start(ap, fmt);
778 std::string str = vstrprintf(fmt, ap);
779 va_end(ap);
780 return str;
781}
782
783#if defined(HAVE___INT128)
784// Compiler supports '__int128'.
785
786// Recursive 128-bit to string conversion function
787static int snprint_uint128(char * str, int strsize, unsigned __int128 value)
788{
789 if (strsize <= 0)
790 return -1;
791
792 if (value <= 0xffffffffffffffffULL) {
793 // Print leading digits as 64-bit value
794 return snprintf(str, (size_t)strsize, "%" PRIu64, (uint64_t)value);
795 }
796 else {
797 // Recurse to print leading digits
798 const uint64_t e19 = 10000000000000000000ULL; // 2^63 < 10^19 < 2^64
799 int len1 = snprint_uint128(str, strsize, value / e19);
800 if (len1 < 0)
801 return -1;
802
803 // Print 19 digits remainder as 64-bit value
804 int len2 = snprintf(str + (len1 < strsize ? len1 : strsize - 1),
805 (size_t)(len1 < strsize ? strsize - len1 : 1),
806 "%019" PRIu64, (uint64_t)(value % e19) );
807 if (len2 < 0)
808 return -1;
809 return len1 + len2;
810 }
811}
812
813// Convert 128-bit unsigned integer provided as two 64-bit halves to a string.
814const char * uint128_hilo_to_str(char * str, int strsize, uint64_t value_hi, uint64_t value_lo)
815{
816 snprint_uint128(str, strsize, ((unsigned __int128)value_hi << 64) | value_lo);
817 return str;
818}
819
820#elif defined(HAVE_LONG_DOUBLE_WIDER_PRINTF)
821// Compiler and *printf() support 'long double' which is wider than 'double'.
822
823const char * uint128_hilo_to_str(char * str, int strsize, uint64_t value_hi, uint64_t value_lo)
824{
825 snprintf(str, strsize, "%.0Lf", value_hi * (0xffffffffffffffffULL + 1.0L) + value_lo);
826 return str;
827}
828
829#else // !HAVE_LONG_DOUBLE_WIDER_PRINTF
830// No '__int128' or 'long double' support, use 'double'.
831
832const char * uint128_hilo_to_str(char * str, int strsize, uint64_t value_hi, uint64_t value_lo)
833{
834 snprintf(str, strsize, "%.0f", value_hi * (0xffffffffffffffffULL + 1.0) + value_lo);
835 return str;
836}
837
838#endif // HAVE___INT128
839
840// Get microseconds since some unspecified starting point.
841long long get_timer_usec()
842{
843#if USE_CLOCK_MONOTONIC
844 struct timespec ts;
845 if (clock_gettime(CLOCK_MONOTONIC, &ts))
846 return -1;
847 return ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
848#else
849 return std::chrono::duration_cast<std::chrono::microseconds>(
850 std::chrono::high_resolution_clock::now().time_since_epoch()
851 ).count();
852#endif
853}
854
855// Runtime check of byte ordering, throws on error.
856static void check_endianness()
857{
858 const union {
859 // Force compile error if int type is not 32bit.
860 unsigned char c[sizeof(int) == 4 ? 8 : -1];
861 uint64_t i;
862 } x = {{1, 2, 3, 4, 5, 6, 7, 8}};
863 const uint64_t le = 0x0807060504030201ULL;
864 const uint64_t be = 0x0102030405060708ULL;
865
866 if (!( x.i == (isbigendian() ? be : le)
867 && sg_get_unaligned_le16(x.c) == (uint16_t)le
868 && sg_get_unaligned_be16(x.c+6) == (uint16_t)be
869 && sg_get_unaligned_le32(x.c) == (uint32_t)le
870 && sg_get_unaligned_be32(x.c+4) == (uint32_t)be
871 && sg_get_unaligned_le64(x.c) == le
872 && sg_get_unaligned_be64(x.c) == be ))
873 throw std::logic_error("CPU endianness does not match compile time test");
874}
875
876#if defined(__GNUC__) && (__GNUC__ >= 7)
877
878// G++ 7+: Assume sane implementation and avoid -Wformat-truncation warning
879static void check_snprintf() {}
880
881#else
882
883static void check_snprintf()
884{
885 char buf[] = "ABCDEFGHI";
886 int n1 = snprintf(buf, 8, "123456789");
887 int n2 = snprintf(buf, 0, "X");
888 if (!(!strcmp(buf, "1234567") && n1 == 9 && n2 == 1))
889 throw std::logic_error("Function snprintf() does not conform to C99");
890}
891
892#endif
893
894// Runtime check of ./configure result, throws on error.
896{
899}
@ SEL_REDO
Definition: atacmds.h:607
@ SEL_RANGE
Definition: atacmds.h:606
@ SEL_NEXT
Definition: atacmds.h:608
@ SEL_CONT
Definition: atacmds.h:609
Wrapper class for POSIX regex(3) or std::regex Supports copy & assignment and is compatible with STL ...
Definition: utility.h:221
regex_t m_regex_buf
Definition: utility.h:274
bool full_match(const char *str) const
Return true if full string matches pattern.
Definition: utility.cpp:569
std::string m_pattern
Definition: utility.h:268
regular_expression & operator=(const regular_expression &x)
Definition: utility.cpp:484
regmatch_t match_range
Definition: utility.h:261
std::string m_errmsg
Definition: utility.h:269
void copy_buf(const regular_expression &x)
Definition: utility.cpp:501
bool execute(const char *str, unsigned nmatch, match_range *pmatch) const
Return true if substring matches pattern, fill match_range array.
Definition: utility.cpp:580
smart_interface * smi()
Global access to the (usually singleton) smart_interface.
u8 b[12]
Definition: megaraid.h:17
ptr_t buffer
Definition: megaraid.h:3
u16 s[6]
Definition: megaraid.h:18
ptr_t data
Definition: megaraid.h:15
u32 size
Definition: megaraid.h:0
static uint64_t sg_get_unaligned_le64(const void *p)
Definition: sg_unaligned.h:303
static uint32_t sg_get_unaligned_le32(const void *p)
Definition: sg_unaligned.h:297
static uint64_t sg_get_unaligned_be64(const void *p)
Definition: sg_unaligned.h:267
static uint16_t sg_get_unaligned_be16(const void *p)
Definition: sg_unaligned.h:256
static uint16_t sg_get_unaligned_le16(const void *p)
Definition: sg_unaligned.h:292
static uint32_t sg_get_unaligned_be32(const void *p)
Definition: sg_unaligned.h:261
const char const char * fmt
Definition: smartctl.cpp:1322
const char const char va_list ap
Definition: smartctl.cpp:1323
vsnprintf(buf, sizeof(buf), fmt, ap)
void pout(const char *fmt,...)
Definition: smartd.cpp:1336
#define STATIC_ASSERT(x)
Definition: static_assert.h:24
void FixGlibcTimeZoneBug()
Definition: utility.cpp:207
const char * format_char_array(char *str, int strsize, const char *chr, int chrsize)
Definition: utility.cpp:668
void dateandtimezoneepoch(char(&buffer)[DATEANDEPOCHLEN], time_t tval)
Definition: utility.cpp:325
long long get_timer_usec()
Get microseconds since some unspecified starting point.
Definition: utility.cpp:841
const char * packet_types[]
Definition: utility.cpp:61
const char * format_capacity(char *str, int strsize, uint64_t val, const char *decimal_point)
Definition: utility.cpp:724
const char * format_with_thousands_sep(char *str, int strsize, uint64_t val, const char *thousands_sep)
Definition: utility.cpp:692
void syserror(const char *message)
Definition: utility.cpp:385
std::string strprintf(const char *fmt,...)
Definition: utility.cpp:775
#define N2S(s)
const char * utility_cpp_cvsid
Definition: utility.cpp:58
static const char * check_regex(const char *pattern)
Definition: utility.cpp:419
bool nonempty(const void *data, int size)
Definition: utility.cpp:658
static void check_endianness()
Definition: utility.cpp:856
int split_selective_arg(char *s, uint64_t *start, uint64_t *stop, int *mode)
Definition: utility.cpp:606
const char * uint128_hilo_to_str(char *str, int strsize, uint64_t value_hi, uint64_t value_lo)
Definition: utility.cpp:832
void check_config()
Definition: utility.cpp:895
const char * packetdevicetype(int type)
Definition: utility.cpp:297
#define BUILD_INFO
Definition: utility.cpp:82
struct tm * time_to_tm_local(struct tm *tp, time_t t)
Definition: utility.cpp:308
static void check_snprintf()
Definition: utility.cpp:883
std::string format_version_info(const char *prog_name, bool full)
Definition: utility.cpp:86
std::string std::string vstrprintf(const char *fmt, va_list ap)
#define UTILITY_H_CVSID
Definition: utility.h:16
#define DATEANDEPOCHLEN
Definition: utility.h:63
bool isbigendian()
Definition: utility.h:81
std::string strprintf(const char *fmt,...) __attribute_format_printf(1
bool nonempty(const void *data, int size)
Definition: utility.cpp:658
#define __attribute_format_printf(x, y)
Definition: utility.h:34