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