LCOV - code coverage report
Current view: top level - cmdline - support.c (source / functions) Hit Total Coverage
Test: lcov.info Lines: 441 550 80.2 %
Date: 2016-11-21 Functions: 60 62 96.8 %

          Line data    Source code
       1             : /*
       2             :  * Copyright (C) 2011 Andrea Mazzoleni
       3             :  *
       4             :  * This program is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 3 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * This program is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "portable.h"
      19             : 
      20             : #include "support.h"
      21             : 
      22             : /****************************************************************************/
      23             : /* lock */
      24             : 
      25             : /**
      26             :  * Locks used externally.
      27             :  */
      28             : #if HAVE_PTHREAD
      29             : static pthread_mutex_t msg_lock;
      30             : static pthread_mutex_t memory_lock;
      31             : #endif
      32             : 
      33     3887334 : void lock_msg(void)
      34             : {
      35             : #if HAVE_PTHREAD
      36     3887334 :         thread_mutex_lock(&msg_lock);
      37             : #endif
      38     3887334 : }
      39             : 
      40     3887334 : void unlock_msg(void)
      41             : {
      42             : #if HAVE_PTHREAD
      43     3887334 :         thread_mutex_unlock(&msg_lock);
      44             : #endif
      45     3887334 : }
      46             : 
      47    20173887 : void lock_memory(void)
      48             : {
      49             : #if HAVE_PTHREAD
      50    20173887 :         thread_mutex_lock(&memory_lock);
      51             : #endif
      52    20173887 : }
      53             : 
      54    20173887 : void unlock_memory(void)
      55             : {
      56             : #if HAVE_PTHREAD
      57    20173887 :         thread_mutex_unlock(&memory_lock);
      58             : #endif
      59    20173887 : }
      60             : 
      61         299 : void lock_init(void)
      62             : {
      63             : #if HAVE_PTHREAD
      64             :         /* initialize the locks as first operation as log_fatal depends on them */
      65         299 :         thread_mutex_init(&msg_lock, 0);
      66         299 :         thread_mutex_init(&memory_lock, 0);
      67             : #endif
      68         299 : }
      69             : 
      70         264 : void lock_done(void)
      71             : {
      72             : #if HAVE_PTHREAD
      73         264 :         thread_mutex_destroy(&msg_lock);
      74         264 :         thread_mutex_destroy(&memory_lock);
      75             : #endif
      76         264 : }
      77             : 
      78             : /****************************************************************************/
      79             : /* print */
      80             : 
      81             : int msg_level = 0;
      82             : 
      83             : /*
      84             :  * Note that in the following functions we always flush both
      85             :  * stdout and stderr, because we want to ensure that they mixes
      86             :  * well when redirected to files
      87             :  *
      88             :  * The buffering is similar at the "line buffered" one, that
      89             :  * is not available on Windows, so we emulate it in this way.
      90             :  *
      91             :  * For stdlog flushing is limited. To ensure flushing the
      92             :  * caller should use log_flush().
      93             :  */
      94             : 
      95         809 : void log_fatal(const char* format, ...)
      96             : {
      97             :         va_list ap;
      98             : 
      99         809 :         lock_msg();
     100             : 
     101         809 :         if (stdlog) {
     102          95 :                 va_start(ap, format);
     103          95 :                 fprintf(stdlog, "msg:fatal: ");
     104          95 :                 vfprintf(stdlog, format, ap);
     105          95 :                 fflush(stdlog);
     106          95 :                 va_end(ap);
     107             :         }
     108             : 
     109         809 :         va_start(ap, format);
     110         809 :         vfprintf(stderr, format, ap);
     111         809 :         fflush(stderr);
     112         809 :         va_end(ap);
     113             : 
     114         809 :         unlock_msg();
     115         809 : }
     116             : 
     117      536048 : void log_error(const char* format, ...)
     118             : {
     119             :         va_list ap;
     120             : 
     121      536048 :         lock_msg();
     122             : 
     123      536048 :         if (stdlog) {
     124      534168 :                 va_start(ap, format);
     125      534168 :                 fprintf(stdlog, "msg:error: ");
     126      534168 :                 vfprintf(stdlog, format, ap);
     127      534168 :                 fflush(stdlog);
     128      534168 :                 va_end(ap);
     129             :         } else {
     130        1880 :                 va_start(ap, format);
     131        1880 :                 vfprintf(stderr, format, ap);
     132        1880 :                 fflush(stderr);
     133        1880 :                 va_end(ap);
     134             :         }
     135             : 
     136      536048 :         unlock_msg();
     137      536048 : }
     138             : 
     139       11259 : void log_expected(const char* format, ...)
     140             : {
     141             :         va_list ap;
     142             : 
     143       11259 :         lock_msg();
     144             : 
     145       11259 :         if (stdlog) {
     146       11259 :                 va_start(ap, format);
     147       11259 :                 fprintf(stdlog, "msg:expected: ");
     148       11259 :                 vfprintf(stdlog, format, ap);
     149       11259 :                 fflush(stdlog);
     150       11259 :                 va_end(ap);
     151             :         }
     152             : 
     153       11259 :         unlock_msg();
     154       11259 : }
     155             : 
     156     2907727 : void log_tag(const char* format, ...)
     157             : {
     158             :         va_list ap;
     159             : 
     160     2907727 :         lock_msg();
     161             : 
     162     2907727 :         if (stdlog) {
     163     2571717 :                 va_start(ap, format);
     164     2571717 :                 vfprintf(stdlog, format, ap);
     165             :                 /* here we intentionally don't flush */
     166             :                 /* to make the output faster */
     167     2571717 :                 va_end(ap);
     168             :         }
     169             : 
     170     2907727 :         unlock_msg();
     171     2907727 : }
     172             : 
     173        1200 : void log_flush(void)
     174             : {
     175        1200 :         lock_msg();
     176             : 
     177        1200 :         if (stdlog)
     178         339 :                 fflush(stdlog);
     179        1200 :         fflush(stdout);
     180        1200 :         fflush(stderr);
     181             : 
     182        1200 :         unlock_msg();
     183        1200 : }
     184             : 
     185         625 : void msg_status(const char* format, ...)
     186             : {
     187             :         va_list ap;
     188             : 
     189         625 :         lock_msg();
     190             : 
     191         625 :         if (stdlog) {
     192         275 :                 va_start(ap, format);
     193         275 :                 fprintf(stdlog, "msg:status: ");
     194         275 :                 vfprintf(stdlog, format, ap);
     195         275 :                 fflush(stdlog);
     196         275 :                 va_end(ap);
     197             :         }
     198             : 
     199         625 :         if (msg_level >= MSG_STATUS) {
     200         625 :                 va_start(ap, format);
     201         625 :                 vfprintf(stdout, format, ap);
     202         625 :                 fflush(stdout);
     203         625 :                 va_end(ap);
     204             :         }
     205             : 
     206         625 :         unlock_msg();
     207         625 : }
     208             : 
     209      295689 : void msg_info(const char* format, ...)
     210             : {
     211             :         va_list ap;
     212             : 
     213      295689 :         lock_msg();
     214             : 
     215             :         /* don't output in stdlog as these messages */
     216             :         /* are always paired with a msg_tag() call */
     217             : 
     218      295689 :         if (msg_level >= MSG_INFO) {
     219       28811 :                 va_start(ap, format);
     220       28811 :                 vfprintf(stdout, format, ap);
     221       28811 :                 fflush(stdout);
     222       28811 :                 va_end(ap);
     223             :         }
     224             : 
     225      295689 :         unlock_msg();
     226      295689 : }
     227             : 
     228        4449 : void msg_progress(const char* format, ...)
     229             : {
     230             :         va_list ap;
     231             : 
     232        4449 :         lock_msg();
     233             : 
     234        4449 :         if (stdlog) {
     235         819 :                 va_start(ap, format);
     236         819 :                 fprintf(stdlog, "msg:progress: ");
     237         819 :                 vfprintf(stdlog, format, ap);
     238         819 :                 fflush(stdlog);
     239         819 :                 va_end(ap);
     240             :         }
     241             : 
     242        4449 :         if (msg_level >= MSG_PROGRESS) {
     243         161 :                 va_start(ap, format);
     244         161 :                 vfprintf(stdout, format, ap);
     245         161 :                 fflush(stdout);
     246         161 :                 va_end(ap);
     247             :         }
     248             : 
     249        4449 :         unlock_msg();
     250        4449 : }
     251             : 
     252        1958 : void msg_bar(const char* format, ...)
     253             : {
     254             :         va_list ap;
     255             : 
     256        1958 :         lock_msg();
     257             : 
     258             :         /* don't output in stdlog as these messages */
     259             :         /* are intended for screen only */
     260             :         /* also don't flush stdout as they are intended to be partial messages */
     261             : 
     262        1958 :         if (msg_level >= MSG_BAR) {
     263           0 :                 va_start(ap, format);
     264           0 :                 vfprintf(stdout, format, ap);
     265           0 :                 va_end(ap);
     266             :         }
     267             : 
     268        1958 :         unlock_msg();
     269        1958 : }
     270             : 
     271      126943 : void msg_verbose(const char* format, ...)
     272             : {
     273             :         va_list ap;
     274             : 
     275      126943 :         lock_msg();
     276             : 
     277      126943 :         if (stdlog) {
     278      125077 :                 va_start(ap, format);
     279      125077 :                 fprintf(stdlog, "msg:verbose: ");
     280      125077 :                 vfprintf(stdlog, format, ap);
     281      125077 :                 fflush(stdlog);
     282      125077 :                 va_end(ap);
     283             :         }
     284             : 
     285      126943 :         if (msg_level >= MSG_VERBOSE) {
     286          91 :                 va_start(ap, format);
     287          91 :                 vfprintf(stdout, format, ap);
     288          91 :                 fflush(stdout);
     289          91 :                 va_end(ap);
     290             :         }
     291             : 
     292      126943 :         unlock_msg();
     293      126943 : }
     294             : 
     295         627 : void msg_flush(void)
     296             : {
     297         627 :         lock_msg();
     298             : 
     299         627 :         fflush(stdout);
     300         627 :         fflush(stderr);
     301             : 
     302         627 :         unlock_msg();
     303         627 : }
     304             : 
     305         106 : void printc(char c, size_t pad)
     306             : {
     307         304 :         while (pad) {
     308             :                 /* group writes in long pieces */
     309             :                 char buf[128];
     310          92 :                 size_t len = pad;
     311             : 
     312          92 :                 if (len >= sizeof(buf))
     313           0 :                         len = sizeof(buf) - 1;
     314             : 
     315          92 :                 memset(buf, c, len);
     316          92 :                 buf[len] = 0;
     317             : 
     318          92 :                 fputs(buf, stdout);
     319             : 
     320          92 :                 pad -= len;
     321             :         }
     322         106 : }
     323             : 
     324          34 : void printr(const char* str, size_t pad)
     325             : {
     326             :         size_t len;
     327             : 
     328          34 :         len = strlen(str);
     329             : 
     330          34 :         if (len < pad)
     331          34 :                 printc(' ', pad - len);
     332             : 
     333          34 :         fputs(str, stdout);
     334          34 : }
     335             : 
     336          52 : void printl(const char* str, size_t pad)
     337             : {
     338             :         size_t len;
     339             : 
     340          52 :         fputs(str, stdout);
     341             : 
     342          52 :         len = strlen(str);
     343             : 
     344          52 :         if (len < pad)
     345          29 :                 printc(' ', pad - len);
     346          52 : }
     347             : 
     348          18 : void printp(double v, size_t pad)
     349             : {
     350             :         char buf[64];
     351          18 :         const char* s = "%";
     352             : 
     353          18 :         if (v > 0.1)
     354           4 :                 snprintf(buf, sizeof(buf), "%5.2f%s", v, s);
     355          14 :         else if (v > 0.01)
     356           2 :                 snprintf(buf, sizeof(buf), "%6.3f%s", v, s);
     357          12 :         else if (v > 0.001)
     358           3 :                 snprintf(buf, sizeof(buf), "%7.4f%s", v, s);
     359           9 :         else if (v > 0.0001)
     360           2 :                 snprintf(buf, sizeof(buf), "%8.5f%s", v, s);
     361           7 :         else if (v > 0.00001)
     362           2 :                 snprintf(buf, sizeof(buf), "%9.6f%s", v, s);
     363           5 :         else if (v > 0.000001)
     364           1 :                 snprintf(buf, sizeof(buf), "%10.7f%s", v, s);
     365           4 :         else if (v > 0.0000001)
     366           1 :                 snprintf(buf, sizeof(buf), "%11.8f%s", v, s);
     367           3 :         else if (v > 0.00000001)
     368           1 :                 snprintf(buf, sizeof(buf), "%12.9f%s", v, s);
     369           2 :         else if (v > 0.000000001)
     370           1 :                 snprintf(buf, sizeof(buf), "%13.10f%s", v, s);
     371           1 :         else if (v > 0.0000000001)
     372           0 :                 snprintf(buf, sizeof(buf), "%14.11f%s", v, s);
     373           1 :         else if (v > 0.00000000001)
     374           1 :                 snprintf(buf, sizeof(buf), "%15.12f%s", v, s);
     375           0 :         else if (v > 0.000000000001)
     376           0 :                 snprintf(buf, sizeof(buf), "%16.13f%s", v, s);
     377             :         else
     378           0 :                 snprintf(buf, sizeof(buf), "%17.14f%s", v, s);
     379          18 :         printl(buf, pad);
     380          18 : }
     381             : 
     382             : #define ESCAPE(from,escape,to) \
     383             :         case from : \
     384             :                 if (p == end) \
     385             :                         goto bail; \
     386             :                 *p++ = escape; \
     387             :                 if (p == end) \
     388             :                         goto bail; \
     389             :                 *p++ = to; \
     390             :                 break
     391             : 
     392     2428312 : const char* esc_tag(const char* str, char* buffer)
     393             : {
     394     2428312 :         char* begin = buffer;
     395     2428312 :         char* end = begin + ESC_MAX;
     396     2428312 :         char* p = begin;
     397             : 
     398             :         /* copy string with escaping */
     399    36387237 :         while (*str) {
     400    31530613 :                 char c = *str;
     401             : 
     402    31530613 :                 switch (c) {
     403             : 
     404           0 :                 ESCAPE('\n', '\\', 'n');
     405           0 :                 ESCAPE('\r', '\\', 'r');
     406           0 :                 ESCAPE(':', '\\', 'd');
     407           0 :                 ESCAPE('\\', '\\', '\\');
     408             : 
     409             :                 default:
     410    31530613 :                         if (p == end)
     411           0 :                                 goto bail;
     412    31530613 :                         *p++ = c;
     413    31530613 :                         break;
     414             :                 }
     415             : 
     416    31530613 :                 ++str;
     417             :         }
     418             : 
     419             :         /* put final 0 */
     420     2428312 :         if (p == end)
     421           0 :                 goto bail;
     422     2428312 :         *p = 0;
     423             : 
     424     4856624 :         return begin;
     425             : 
     426             : bail:
     427             :         /* LCOV_EXCL_START */
     428             :         log_fatal("Escape for log too long\n");
     429             :         exit(EXIT_FAILURE);
     430             :         /* LCOV_EXCL_STOP */
     431             : }
     432             : 
     433      355914 : const char* esc_shell_multi(const char** str_map, unsigned str_max, char* buffer)
     434             : {
     435      355914 :         char* begin = buffer;
     436      355914 :         char* end = begin + ESC_MAX;
     437      355914 :         char* p = begin;
     438             :         unsigned str_mac;
     439             :         const char* str;
     440             : 
     441             : #ifdef _WIN32
     442             :         int has_quote = 0;
     443             : 
     444             :         for (str_mac = 0; str_mac < str_max; ++str_mac) {
     445             :                 str = str_map[str_mac];
     446             :                 if (strchr(str, ' ') != 0)
     447             :                         has_quote = 1;
     448             :         }
     449             : 
     450             :         if (has_quote) {
     451             :                 if (p == end)
     452             :                         goto bail;
     453             :                 *p++ = '"';
     454             :         }
     455             : #endif
     456             : 
     457             :         /* copy string with escaping */
     458      355914 :         str_mac = 0;
     459      355914 :         str = str_map[str_mac];
     460             :         while (1) {
     461             :                 /* get the next char */
     462     5122618 :                 char c = *str;
     463             : 
     464             :                 /* if one string is finished, go to the next */
     465    10281326 :                 while (c == 0 && str_mac + 1 < str_max) {
     466       36090 :                         ++str_mac;
     467       36090 :                         str = str_map[str_mac];
     468       36090 :                         c = *str;
     469             :                 }
     470             : 
     471             :                 /* if we read all the strings, stop */
     472     5122618 :                 if (!c)
     473      355914 :                         break;
     474             : 
     475     4766704 :                 switch (c) {
     476             : #ifdef _WIN32
     477             :                 /*
     478             :                  * Windows shell escape
     479             :                  *
     480             :                  * The Windows NT Command Shell
     481             :                  * https://technet.microsoft.com/en-us/library/cc723564.aspx
     482             :                  */
     483             :                 case '"' :
     484             :                         /* double quote, it needs to be quoted with \ */
     485             :                         if (has_quote) {
     486             :                                 /* " -> "\"" -> (close quote)(quoted with \ ")(reopen quote) */
     487             :                                 if (p == end)
     488             :                                         goto bail;
     489             :                                 *p++ = '"';
     490             :                                 if (p == end)
     491             :                                         goto bail;
     492             :                                 *p++ = '\\';
     493             :                                 if (p == end)
     494             :                                         goto bail;
     495             :                                 *p++ = '"';
     496             :                                 if (p == end)
     497             :                                         goto bail;
     498             :                                 *p++ = '"';
     499             :                         } else {
     500             :                                 /* " -> \" */
     501             :                                 if (p == end)
     502             :                                         goto bail;
     503             :                                 *p++ = '\\';
     504             :                                 if (p == end)
     505             :                                         goto bail;
     506             :                                 *p++ = '"';
     507             :                         }
     508             :                         break;
     509             :                 case '&' :
     510             :                 case '|' :
     511             :                 case '(' :
     512             :                 case ')' :
     513             :                 case '<' :
     514             :                 case '>' :
     515             :                 case '^' :
     516             :                         /* reserved chars, they need to be quoted with ^ */
     517             :                         if (has_quote) {
     518             :                                 if (p == end)
     519             :                                         goto bail;
     520             :                                 *p++ = c;
     521             :                         } else {
     522             :                                 if (p == end)
     523             :                                         goto bail;
     524             :                                 *p++ = '^';
     525             :                                 if (p == end)
     526             :                                         goto bail;
     527             :                                 *p++ = c;
     528             :                         }
     529             :                         break;
     530             :                 default :
     531             :                         /* unquoted */
     532             :                         if (p == end)
     533             :                                 goto bail;
     534             :                         *p++ = c;
     535             :                         break;
     536             : #else
     537             :                 case 'a' ... 'z' :
     538             :                 case 'A' ... 'Z' :
     539             :                 case '0' ... '9' :
     540             :                 case ',' :
     541             :                 case '.' :
     542             :                 case '_' :
     543             :                 case '+' :
     544             :                 case ':' :
     545             :                 case '@' :
     546             :                 case '%' :
     547             :                 case '/' :
     548             :                 case '-' :
     549             :                         /* safe chars for all shells, unquoted */
     550     4687726 :                         if (p == end)
     551           0 :                                 goto bail;
     552     4687726 :                         *p++ = c;
     553     4687726 :                         break;
     554             :                 default :
     555             :                         /* all the others are quoted with \ */
     556       78978 :                         if (p == end)
     557           0 :                                 goto bail;
     558       78978 :                         *p++ = '\\';
     559       78978 :                         if (p == end)
     560           0 :                                 goto bail;
     561       78978 :                         *p++ = c;
     562       78978 :                         break;
     563             : #endif
     564             :                 }
     565             : 
     566     4766704 :                 ++str;
     567     4766704 :         }
     568             : 
     569             : #ifdef _WIN32
     570             :         if (has_quote) {
     571             :                 if (p == end)
     572             :                         goto bail;
     573             :                 *p++ = '"';
     574             :         }
     575             : #endif
     576             : 
     577             :         /* put final 0 */
     578      355914 :         if (p == end)
     579           0 :                 goto bail;
     580      355914 :         *p = 0;
     581             : 
     582      711828 :         return begin;
     583             : 
     584             : bail:
     585             :         /* LCOV_EXCL_START */
     586             :         log_fatal("Escape for shell too long\n");
     587             :         exit(EXIT_FAILURE);
     588             :         /* LCOV_EXCL_STOP */
     589             : }
     590             : 
     591           0 : char* strpolish(char* s)
     592             : {
     593           0 :         char* i = s;
     594             : 
     595           0 :         while (*i) {
     596           0 :                 if (isspace(*i) || !isprint(*i))
     597           0 :                         *i = ' ';
     598           0 :                 ++i;
     599             :         }
     600             : 
     601           0 :         return s;
     602             : }
     603             : 
     604        1472 : unsigned strsplit(char** split_map, unsigned split_max, char* str, const char* delimiters)
     605             : {
     606        1472 :         unsigned mac = 0;
     607             : 
     608             :         /* skip initial delimiters */
     609        1472 :         str += strspn(str, delimiters);
     610             : 
     611        8932 :         while (*str != 0 || mac == split_max) {
     612             :                 /* start of the token */
     613        5988 :                 split_map[mac] = str;
     614        5988 :                 ++mac;
     615             : 
     616             :                 /* find the first delimiter or the end of the string */
     617        5988 :                 str += strcspn(str, delimiters);
     618             : 
     619             :                 /* put the final terminator if missing */
     620        5988 :                 if (*str != 0)
     621        4616 :                         *str++ = 0;
     622             : 
     623             :                 /* skip trailing delimiters */
     624        5988 :                 str += strspn(str, delimiters);
     625             :         }
     626             : 
     627        1472 :         return mac;
     628             : }
     629             : 
     630             : /****************************************************************************/
     631             : /* path */
     632             : 
     633     7892123 : void pathcpy(char* dst, size_t size, const char* src)
     634             : {
     635     7892123 :         size_t len = strlen(src);
     636             : 
     637     7892123 :         if (len + 1 > size) {
     638             :                 /* LCOV_EXCL_START */
     639             :                 log_fatal("Path too long '%s'\n", src);
     640             :                 os_abort();
     641             :                 /* LCOV_EXCL_STOP */
     642             :         }
     643             : 
     644     7892123 :         memcpy(dst, src, len + 1);
     645     7892123 : }
     646             : 
     647         267 : void pathcat(char* dst, size_t size, const char* src)
     648             : {
     649         267 :         size_t dst_len = strlen(dst);
     650         267 :         size_t src_len = strlen(src);
     651             : 
     652         267 :         if (dst_len + src_len + 1 > size) {
     653             :                 /* LCOV_EXCL_START */
     654             :                 log_fatal("Path too long '%s%s'\n", dst, src);
     655             :                 os_abort();
     656             :                 /* LCOV_EXCL_STOP */
     657             :         }
     658             : 
     659         267 :         memcpy(dst + dst_len, src, src_len + 1);
     660         267 : }
     661             : 
     662         788 : void pathcatc(char* dst, size_t size, char c)
     663             : {
     664         788 :         size_t dst_len = strlen(dst);
     665             : 
     666         788 :         if (dst_len + 2 > size) {
     667             :                 /* LCOV_EXCL_START */
     668             :                 log_fatal("Path too long '%s%c'\n", dst, c);
     669             :                 os_abort();
     670             :                 /* LCOV_EXCL_STOP */
     671             :         }
     672             : 
     673         788 :         dst[dst_len] = c;
     674         788 :         dst[dst_len + 1] = 0;
     675         788 : }
     676             : 
     677       16572 : void pathimport(char* dst, size_t size, const char* src)
     678             : {
     679       16572 :         pathcpy(dst, size, src);
     680             : 
     681             : #ifdef _WIN32
     682             :         /* convert the  Windows dir separator '\' to C '/', */
     683             :         /* and the Windows escaping  char '^' to the fnmatch '\' */
     684             :         while (*dst) {
     685             :                 switch (*dst) {
     686             :                 case '\\' :
     687             :                         *dst = '/';
     688             :                         break;
     689             :                 case '^' :
     690             :                         *dst = '\\';
     691             :                         break;
     692             :                 }
     693             :                 ++dst;
     694             :         }
     695             : #endif
     696       16572 : }
     697             : 
     698       17589 : void pathexport(char* dst, size_t size, const char* src)
     699             : {
     700       17589 :         pathcpy(dst, size, src);
     701             : 
     702             : #ifdef _WIN32
     703             :         /* invert the import */
     704             :         while (*dst) {
     705             :                 switch (*dst) {
     706             :                 case '/' :
     707             :                         *dst = '\\';
     708             :                         break;
     709             :                 case '\\' :
     710             :                         *dst = '^';
     711             :                         break;
     712             :                 }
     713             :                 ++dst;
     714             :         }
     715             : #endif
     716       17589 : }
     717             : 
     718    51564160 : void pathprint(char* dst, size_t size, const char* format, ...)
     719             : {
     720             :         size_t len;
     721             :         va_list ap;
     722             : 
     723    51564160 :         va_start(ap, format);
     724    51564160 :         len = vsnprintf(dst, size, format, ap);
     725    51564160 :         va_end(ap);
     726             : 
     727    51564160 :         if (len >= size) {
     728             :                 /* LCOV_EXCL_START */
     729             :                 if (size > 0) {
     730             :                         dst[size - 1] = 0;
     731             :                         log_fatal("Path too long '%s...'\n", dst);
     732             :                 } else {
     733             :                         log_fatal("Path too long for empty size'\n");
     734             :                 }
     735             :                 os_abort();
     736             :                 /* LCOV_EXCL_STOP */
     737             :         }
     738    51564160 : }
     739             : 
     740        7705 : void pathslash(char* dst, size_t size)
     741             : {
     742        7705 :         size_t len = strlen(dst);
     743             : 
     744        7705 :         if (len > 0 && dst[len - 1] != '/') {
     745        6114 :                 if (len + 2 >= size) {
     746             :                         /* LCOV_EXCL_START */
     747             :                         log_fatal("Path too long '%s/'\n", dst);
     748             :                         os_abort();
     749             :                         /* LCOV_EXCL_STOP */
     750             :                 }
     751             : 
     752        6114 :                 dst[len] = '/';
     753        6114 :                 dst[len + 1] = 0;
     754             :         }
     755        7705 : }
     756             : 
     757         100 : void pathcut(char* dst)
     758             : {
     759         100 :         char* slash = strrchr(dst, '/');
     760             : 
     761         100 :         if (slash)
     762         100 :                 slash[1] = 0;
     763             :         else
     764           0 :                 dst[0] = 0;
     765         100 : }
     766             : 
     767    51890261 : int pathcmp(const char* a, const char* b)
     768             : {
     769             : #ifdef _WIN32
     770             :         char ai[PATH_MAX];
     771             :         char bi[PATH_MAX];
     772             : 
     773             :         /* import to convert \ to / */
     774             :         pathimport(ai, sizeof(ai), a);
     775             :         pathimport(bi, sizeof(bi), b);
     776             : 
     777             :         /* case insensitive compare in Windows */
     778             :         return stricmp(ai, bi);
     779             : #else
     780    51890261 :         return strcmp(a, b);
     781             : #endif
     782             : }
     783             : 
     784             : /****************************************************************************/
     785             : /* file-system */
     786             : 
     787      793073 : int mkancestor(const char* file)
     788             : {
     789             :         char dir[PATH_MAX];
     790             :         struct stat st;
     791             :         char* c;
     792             : 
     793      793073 :         pathcpy(dir, sizeof(dir), file);
     794             : 
     795      793073 :         c = strrchr(dir, '/');
     796      793073 :         if (!c) {
     797             :                 /* no ancestor */
     798           0 :                 return 0;
     799             :         }
     800             : 
     801             :         /* clear the file */
     802      793073 :         *c = 0;
     803             : 
     804             :         /* if it's the root dir */
     805      793073 :         if (*dir == 0) {
     806             :                 /* nothing more to do */
     807           0 :                 return 0;
     808             :         }
     809             : 
     810             : #ifdef _WIN32
     811             :         /* if it's a drive specificaion like "C:" */
     812             :         if (isalpha(dir[0]) && dir[1] == ':' && dir[2] == 0) {
     813             :                 /* nothing more to do */
     814             :                 return 0;
     815             :         }
     816             : #endif
     817             : 
     818             :         /*
     819             :          * Check if the dir already exists using lstat().
     820             :          *
     821             :          * Note that in Windows when dealing with read-only media
     822             :          * you cannot try to create the directory, and expecting
     823             :          * the EEXIST error because the call will fail with ERROR_WRITE_PROTECTED.
     824             :          *
     825             :          * Also in Windows it's better to use lstat() than stat() because it
     826             :          * doesn't need to open the dir with CreateFile().
     827             :          */
     828      793073 :         if (lstat(dir, &st) == 0) {
     829             :                 /* it already exists */
     830      792993 :                 return 0;
     831             :         }
     832             : 
     833             :         /* recursively create them all */
     834          80 :         if (mkancestor(dir) != 0) {
     835             :                 /* LCOV_EXCL_START */
     836             :                 return -1;
     837             :                 /* LCOV_EXCL_STOP */
     838             :         }
     839             : 
     840             :         /* create it */
     841          80 :         if (mkdir(dir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
     842             :                 /* LCOV_EXCL_START */
     843             :                 log_fatal("Error creating directory '%s'. %s.\n", dir, strerror(errno));
     844             :                 return -1;
     845             :                 /* LCOV_EXCL_STOP */
     846             :         }
     847             : 
     848          80 :         return 0;
     849             : }
     850             : 
     851      119580 : int fmtime(int f, int64_t mtime_sec, int mtime_nsec)
     852             : {
     853             : #if HAVE_FUTIMENS
     854             :         struct timespec tv[2];
     855             : #else
     856             :         struct timeval tv[2];
     857             : #endif
     858             :         int ret;
     859             : 
     860             : #if HAVE_FUTIMENS /* futimens() is preferred because it gives nanosecond precision */
     861      119580 :         tv[0].tv_sec = mtime_sec;
     862      119580 :         if (mtime_nsec != STAT_NSEC_INVALID)
     863      119580 :                 tv[0].tv_nsec = mtime_nsec;
     864             :         else
     865           0 :                 tv[0].tv_nsec = 0;
     866      119580 :         tv[1].tv_sec = tv[0].tv_sec;
     867      119580 :         tv[1].tv_nsec = tv[0].tv_nsec;
     868             : 
     869      119580 :         ret = futimens(f, tv);
     870             : #elif HAVE_FUTIMES /* fallback to futimes() if nanosecond precision is not available */
     871             :         tv[0].tv_sec = mtime_sec;
     872             :         if (mtime_nsec != STAT_NSEC_INVALID)
     873             :                 tv[0].tv_usec = mtime_nsec / 1000;
     874             :         else
     875             :                 tv[0].tv_usec = 0;
     876             :         tv[1].tv_sec = tv[0].tv_sec;
     877             :         tv[1].tv_usec = tv[0].tv_usec;
     878             : 
     879             :         ret = futimes(f, tv);
     880             : #elif HAVE_FUTIMESAT /* fallback to futimesat() for Solaris, it only has futimesat() */
     881             :         tv[0].tv_sec = mtime_sec;
     882             :         if (mtime_nsec != STAT_NSEC_INVALID)
     883             :                 tv[0].tv_usec = mtime_nsec / 1000;
     884             :         else
     885             :                 tv[0].tv_usec = 0;
     886             :         tv[1].tv_sec = tv[0].tv_sec;
     887             :         tv[1].tv_usec = tv[0].tv_usec;
     888             : 
     889             :         ret = futimesat(f, 0, tv);
     890             : #else
     891             : #error No function available to set file timestamps with sub-second precision
     892             : #endif
     893             : 
     894      119580 :         return ret;
     895             : }
     896             : 
     897             : /****************************************************************************/
     898             : /* advise */
     899             : 
     900     2494910 : void advise_init(struct advise_struct* advise, int mode)
     901             : {
     902     2494910 :         advise->mode = mode;
     903     2494910 :         advise->dirty_begin = 0;
     904     2494910 :         advise->dirty_end = 0;
     905     2494910 : }
     906             : 
     907     2494965 : int advise_flags(struct advise_struct* advise)
     908             : {
     909     2494965 :         int flags = 0;
     910             : 
     911     2494965 :         if (advise->mode == ADVISE_SEQUENTIAL
     912     2483621 :                 || advise->mode == ADVISE_FLUSH
     913       34020 :                 || advise->mode == ADVISE_FLUSH_WINDOW
     914       22682 :                 || advise->mode == ADVISE_DISCARD
     915       22682 :                 || advise->mode == ADVISE_DISCARD_WINDOW
     916             :         )
     917     2483614 :                 flags |= O_SEQUENTIAL;
     918             : 
     919             : #if HAVE_DIRECT_IO
     920     2494965 :         if (advise->mode == ADVISE_DIRECT)
     921           0 :                 flags |= O_DIRECT;
     922             : #endif
     923             : 
     924     2494965 :         return flags;
     925             : }
     926             : 
     927     2416366 : int advise_open(struct advise_struct* advise, int f)
     928             : {
     929             :         (void)advise;
     930             :         (void)f;
     931             : 
     932             : #if HAVE_POSIX_FADVISE
     933     2416366 :         if (advise->mode == ADVISE_SEQUENTIAL
     934     2405026 :                 || advise->mode == ADVISE_FLUSH
     935       34021 :                 || advise->mode == ADVISE_FLUSH_WINDOW
     936       22682 :                 || advise->mode == ADVISE_DISCARD
     937       22682 :                 || advise->mode == ADVISE_DISCARD_WINDOW
     938             :         ) {
     939             :                 int ret;
     940             : 
     941             :                 /* advise sequential access */
     942     2405029 :                 ret = posix_fadvise(f, 0, 0, POSIX_FADV_SEQUENTIAL);
     943     2405059 :                 if (ret == ENOSYS) {
     944             :                         /* call is not supported, like in armhf, see posix_fadvise manpage */
     945           0 :                         ret = 0;
     946             :                 }
     947     2405059 :                 if (ret != 0) {
     948             :                         /* LCOV_EXCL_START */
     949             :                         errno = ret; /* posix_fadvise return the error code */
     950             :                         return -1;
     951             :                         /* LCOV_EXCL_STOP */
     952             :                 }
     953             :         }
     954             : #endif
     955             : 
     956     2416396 :         return 0;
     957             : }
     958             : 
     959      900358 : int advise_write(struct advise_struct* advise, int f, data_off_t offset, data_off_t size)
     960             : {
     961             :         data_off_t flush_offset;
     962             :         data_off_t flush_size;
     963             :         data_off_t discard_offset;
     964             :         data_off_t discard_size;
     965             : 
     966             :         (void)f;
     967             :         (void)flush_offset;
     968             :         (void)flush_size;
     969             :         (void)discard_offset;
     970             :         (void)discard_size;
     971             : 
     972      900358 :         flush_offset = 0;
     973      900358 :         flush_size = 0;
     974      900358 :         discard_offset = 0;
     975      900358 :         discard_size = 0;
     976             : 
     977             :         /*
     978             :          * Follow Linus recommendations about fast writes.
     979             :          *
     980             :          * Linus "Unexpected splice "always copy" behavior observed"
     981             :          * http://thread.gmane.org/gmane.linux.kernel/987247/focus=988070
     982             :          * ---
     983             :          * I have had _very_ good experiences with even a rather trivial
     984             :          * file writer that basically used (iirc) 8MB windows, and the logic was very
     985             :          * trivial:
     986             :          *
     987             :          *  - before writing a new 8M window, do "start writeback"
     988             :          *    (SYNC_FILE_RANGE_WRITE) on the previous window, and do
     989             :          *    a wait (SYNC_FILE_RANGE_WAIT_AFTER) on the window before that.
     990             :          *
     991             :          * in fact, in its simplest form, you can do it like this (this is from my
     992             :          * "overwrite disk images" program that I use on old disks):
     993             :          *
     994             :          * for (index = 0; index < max_index ;index++) {
     995             :          *   if (write(fd, buffer, BUFSIZE) != BUFSIZE)
     996             :          *     break;
     997             :          *   // This won't block, but will start writeout asynchronously
     998             :          *   sync_file_range(fd, index*BUFSIZE, BUFSIZE, SYNC_FILE_RANGE_WRITE);
     999             :          *   // This does a blocking write-and-wait on any old ranges
    1000             :          *   if (index)
    1001             :          *     sync_file_range(fd, (index-1)*BUFSIZE, BUFSIZE, SYNC_FILE_RANGE_WAIT_BEFORE|SYNC_FILE_RANGE_WRITE|SYNC_FILE_RANGE_WAIT_AFTER);
    1002             :          * }
    1003             :          *
    1004             :          * and even if you don't actually do a discard (maybe we should add a
    1005             :          * SYNC_FILE_RANGE_DISCARD bit, right now you'd need to do a separate
    1006             :          * fadvise(FADV_DONTNEED) to throw it out) the system behavior is pretty
    1007             :          * nice, because the heavy writer gets good IO performance _and_ leaves only
    1008             :          * easy-to-free pages around after itself.
    1009             :          * ---
    1010             :          *
    1011             :          * Linus "Unexpected splice "always copy" behavior observed"
    1012             :          * http://thread.gmane.org/gmane.linux.kernel/987247/focus=988176
    1013             :          * ---
    1014             :          * The behavior for dirty page writeback is _not_ well defined, and
    1015             :          * if you do POSIX_FADV_DONTNEED, I would suggest you do it as part of that
    1016             :          * writeback logic, ie you do it only on ranges that you have just waited on.
    1017             :          *
    1018             :          * IOW, in my example, you'd couple the
    1019             :          *
    1020             :          *   sync_file_range(fd, (index-1)*BUFSIZE, BUFSIZE, SYNC_FILE_RANGE_WAIT_BEFORE|SYNC_FILE_RANGE_WRITE|SYNC_FILE_RANGE_WAIT_AFTER);
    1021             :          *
    1022             :          * with a
    1023             :          *
    1024             :          *   posix_fadvise(fd, (index-1)*BUFSIZE, BUFSIZE, POSIX_FADV_DONTNEED);
    1025             :          *
    1026             :          * afterwards to throw out the pages that you just waited for.
    1027             :          * ---
    1028             :          */
    1029             : 
    1030      900358 :         switch (advise->mode) {
    1031             :         case ADVISE_FLUSH :
    1032      881613 :                 flush_offset = offset;
    1033      881613 :                 flush_size = size;
    1034      881613 :                 break;
    1035             :         case ADVISE_DISCARD :
    1036           0 :                 discard_offset = offset;
    1037           0 :                 discard_size = size;
    1038           0 :                 break;
    1039             :         case ADVISE_FLUSH_WINDOW :
    1040             :                 /* if the dirty range can be extended */
    1041        4687 :                 if (advise->dirty_end == offset) {
    1042             :                         /* extent the dirty range */
    1043        4687 :                         advise->dirty_end += size;
    1044             : 
    1045             :                         /* if we reached the window size */
    1046        4687 :                         if (advise->dirty_end - advise->dirty_begin >= ADVISE_WINDOW_SIZE) {
    1047             :                                 /* flush the window  */
    1048           0 :                                 flush_offset = advise->dirty_begin;
    1049           0 :                                 flush_size = ADVISE_WINDOW_SIZE;
    1050             : 
    1051             :                                 /* remove it from the dirty range */
    1052           0 :                                 advise->dirty_begin += ADVISE_WINDOW_SIZE;
    1053             :                         }
    1054             :                 } else {
    1055             :                         /* otherwise flush the existing dirty */
    1056           0 :                         flush_offset = advise->dirty_begin;
    1057           0 :                         flush_size = advise->dirty_end - advise->dirty_begin;
    1058             : 
    1059             :                         /* and set the new range as dirty */
    1060           0 :                         advise->dirty_begin = offset;
    1061           0 :                         advise->dirty_end = offset + size;
    1062             :                 }
    1063        4687 :                 break;
    1064             :         case ADVISE_DISCARD_WINDOW :
    1065             :                 /* if the dirty range can be extended */
    1066        4687 :                 if (advise->dirty_end == offset) {
    1067             :                         /* extent the dirty range */
    1068        4687 :                         advise->dirty_end += size;
    1069             : 
    1070             :                         /* if we reached the double window size */
    1071        4687 :                         if (advise->dirty_end - advise->dirty_begin >= 2 * ADVISE_WINDOW_SIZE) {
    1072             :                                 /* discard the first window */
    1073           0 :                                 discard_offset = advise->dirty_begin;
    1074           0 :                                 discard_size = ADVISE_WINDOW_SIZE;
    1075             : 
    1076             :                                 /* remove it from the dirty range */
    1077           0 :                                 advise->dirty_begin += ADVISE_WINDOW_SIZE;
    1078             : 
    1079             :                                 /* flush the second window */
    1080           0 :                                 flush_offset = advise->dirty_begin;
    1081           0 :                                 flush_size = ADVISE_WINDOW_SIZE;
    1082             :                         }
    1083             :                 } else {
    1084             :                         /* otherwise discard the existing dirty */
    1085           0 :                         discard_offset = advise->dirty_begin;
    1086           0 :                         discard_size = advise->dirty_end - advise->dirty_begin;
    1087             : 
    1088             :                         /* and set the new range as dirty */
    1089           0 :                         advise->dirty_begin = offset;
    1090           0 :                         advise->dirty_end = offset + size;
    1091             :                 }
    1092        4687 :                 break;
    1093             :         }
    1094             : 
    1095             : #if HAVE_SYNC_FILE_RANGE
    1096      900358 :         if (flush_size != 0) {
    1097             :                 int ret;
    1098             : 
    1099             :                 /* start writing immediately */
    1100      881612 :                 ret = sync_file_range(f, flush_offset, flush_size, SYNC_FILE_RANGE_WRITE);
    1101      881612 :                 if (ret != 0) {
    1102             :                         /* LCOV_EXCL_START */
    1103             :                         return -1;
    1104             :                         /* LCOV_EXCL_STOP */
    1105             :                 }
    1106             :         }
    1107             : #endif
    1108             : 
    1109             : #if HAVE_SYNC_FILE_RANGE && HAVE_POSIX_FADVISE
    1110      900358 :         if (discard_size != 0) {
    1111             :                 int ret;
    1112             : 
    1113             :                 /* send the data to the disk and wait until it's written */
    1114           0 :                 ret = sync_file_range(f, discard_offset, discard_size, SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE | SYNC_FILE_RANGE_WAIT_AFTER);
    1115           0 :                 if (ret != 0) {
    1116             :                         /* LCOV_EXCL_START */
    1117             :                         return -1;
    1118             :                         /* LCOV_EXCL_STOP */
    1119             :                 }
    1120             : 
    1121             :                 /* flush the data from the cache */
    1122           0 :                 ret = posix_fadvise(f, discard_offset, discard_size, POSIX_FADV_DONTNEED);
    1123             :                 /* for POSIX_FADV_DONTNEED we don't allow failure with ENOSYS */
    1124           0 :                 if (ret != 0) {
    1125             :                         /* LCOV_EXCL_START */
    1126             :                         errno = ret; /* posix_fadvise return the error code */
    1127             :                         return -1;
    1128             :                         /* LCOV_EXCL_STOP */
    1129             :                 }
    1130             :         }
    1131             : #endif
    1132             : 
    1133      900358 :         return 0;
    1134             : }
    1135             : 
    1136     8903631 : int advise_read(struct advise_struct* advise, int f, data_off_t offset, data_off_t size)
    1137             : {
    1138             :         (void)advise;
    1139             :         (void)f;
    1140             :         (void)offset;
    1141             :         (void)size;
    1142             : 
    1143             : #if HAVE_POSIX_FADVISE
    1144     8903631 :         if (advise->mode == ADVISE_DISCARD
    1145     8903983 :                 || advise->mode == ADVISE_DISCARD_WINDOW
    1146             :         ) {
    1147             :                 int ret;
    1148             : 
    1149             :                 /* flush the data from the cache */
    1150       27482 :                 ret = posix_fadvise(f, offset, size, POSIX_FADV_DONTNEED);
    1151             :                 /* for POSIX_FADV_DONTNEED we don't allow failure with ENOSYS */
    1152       27825 :                 if (ret != 0) {
    1153             :                         /* LCOV_EXCL_START */
    1154             :                         errno = ret; /* posix_fadvise return the error code */
    1155             :                         return -1;
    1156             :                         /* LCOV_EXCL_STOP */
    1157             :                 }
    1158             :         }
    1159             : #endif
    1160             : 
    1161             :         /*
    1162             :          * Here we cannot call posix_fadvise(..., POSIX_FADV_WILLNEED) for the next block
    1163             :          * because it may be blocking.
    1164             :          *
    1165             :          * Ted Ts'o "posix_fadvise(POSIX_FADV_WILLNEED) waits before returning?"
    1166             :          * https://lkml.org/lkml/2010/12/6/122
    1167             :          * ---
    1168             :          * readahead and posix_fadvise(POSIX_FADV_WILLNEED) work exactly the same
    1169             :          * way, and in fact share mostly the same code path (see
    1170             :          * force_page_cache_readahead() in mm/readahead.c).
    1171             :          *
    1172             :          * They are asynchronous in that there is no guarantee the pages will be
    1173             :          * in the page cache by the time they return.  But at the same time, they
    1174             :          * are not guaranteed to be non-blocking.  That is, the work of doing the
    1175             :          * readahead does not take place in a kernel thread.  So if you try to
    1176             :          * request I/O than will fit in the request queue, the system call will
    1177             :          * block until some I/O is completed so that more I/O requested cam be
    1178             :          * loaded onto the request queue.
    1179             :          *
    1180             :          * The only way to fix this would be to either put the work on a kernel
    1181             :          * thread (i.e., some kind of workqueue) or in a userspace thread.  For
    1182             :          * ion programmer wondering what to do today, I'd suggest the
    1183             :          * latter since it will be more portable across various kernel versions.
    1184             :          *
    1185             :          * This does leave the question about whether we should change the kernel
    1186             :          * to allow readahead() and posix_fadvise(POSIX_FADV_WILLNEED) to be
    1187             :          * non-blocking and do this work in a workqueue (or via some kind of
    1188             :          * callback/continuation scheme).  My worry is just doing this if a user
    1189             :          * application does something crazy, like request gigabytes and gigabytes
    1190             :          * of readahead, and then repents of their craziness, there should be a
    1191             :          * way of cancelling the readahead request.  Today, the user can just
    1192             :          * kill the application.  But if we simply shove the work to a kernel
    1193             :          * thread, it becomes a lot harder to cancel the readahead request.  We'd
    1194             :          * have to invent a new API, and then have a way to know whether the user
    1195             :          * has access to kill a particular readahead request, etc.
    1196             :          * ---
    1197             :          */
    1198             : 
    1199     8903974 :         return 0;
    1200             : }
    1201             : 
    1202             : /****************************************************************************/
    1203             : /* memory */
    1204             : 
    1205             : /**
    1206             :  * Total amount of memory allocated.
    1207             :  */
    1208             : static size_t mcounter;
    1209             : 
    1210         476 : size_t malloc_counter_get(void)
    1211             : {
    1212             :         size_t ret;
    1213             : 
    1214         476 :         lock_memory();
    1215             : 
    1216         476 :         ret = mcounter;
    1217             : 
    1218         476 :         unlock_memory();
    1219             : 
    1220         476 :         return ret;
    1221             : }
    1222             : 
    1223    20173411 : void malloc_counter_inc(size_t inc)
    1224             : {
    1225    20173411 :         lock_memory();
    1226             : 
    1227    20173411 :         mcounter += inc;
    1228             : 
    1229    20173411 :         unlock_memory();
    1230    20173411 : }
    1231             : 
    1232             : /* LCOV_EXCL_START */
    1233             : static ssize_t malloc_print(int f, const char* str)
    1234             : {
    1235             :         ssize_t len = 0;
    1236             : 
    1237             :         while (str[len])
    1238             :                 ++len;
    1239             :         return write(f, str, len);
    1240             : }
    1241             : /* LCOV_EXCL_STOP */
    1242             : 
    1243             : /* LCOV_EXCL_START */
    1244             : static ssize_t malloc_printn(int f, size_t value)
    1245             : {
    1246             :         char buf[32];
    1247             :         int i;
    1248             : 
    1249             :         if (!value)
    1250             :                 return write(f, "0", 1);
    1251             : 
    1252             :         i = sizeof(buf);
    1253             :         while (value) {
    1254             :                 buf[--i] = (value % 10) + '0';
    1255             :                 value /= 10;
    1256             :         }
    1257             : 
    1258             :         return write(f, buf + i, sizeof(buf) - i);
    1259             : }
    1260             : /* LCOV_EXCL_STOP */
    1261             : 
    1262             : /* LCOV_EXCL_START */
    1263             : void malloc_fail(size_t size)
    1264             : {
    1265             :         /* don't use printf to avoid any possible extra allocation */
    1266             :         int f = 2; /* stderr */
    1267             : 
    1268             :         malloc_print(f, "Failed for Low Memory!\n");
    1269             :         malloc_print(f, "Allocating ");
    1270             :         malloc_printn(f, size);
    1271             :         malloc_print(f, " bytes.\n");
    1272             :         malloc_print(f, "Already allocated ");
    1273             :         malloc_printn(f, malloc_counter_get());
    1274             :         malloc_print(f, " bytes.\n");
    1275             :         if (sizeof(void*) == 4) {
    1276             :                 malloc_print(f, "You are currently using a 32 bits executable.\n");
    1277             :                 malloc_print(f, "If you have more than 4GB of memory, please upgrade to a 64 bits one.\n");
    1278             :         }
    1279             : }
    1280             : /* LCOV_EXCL_STOP */
    1281             : 
    1282    14363921 : void* malloc_nofail(size_t size)
    1283             : {
    1284    14363921 :         void* ptr = malloc(size);
    1285             : 
    1286    14363921 :         if (!ptr) {
    1287             :                 /* LCOV_EXCL_START */
    1288             :                 malloc_fail(size);
    1289             :                 exit(EXIT_FAILURE);
    1290             :                 /* LCOV_EXCL_STOP */
    1291             :         }
    1292             : 
    1293             : #ifndef CHECKER /* Don't preinitialize when running for valgrind */
    1294             :         /* Here we preinitialize the memory to ensure that the OS is really allocating it */
    1295             :         /* and not only reserving the addressable space. */
    1296             :         /* Otherwise we are risking that the OOM (Out Of Memory) killer in Linux will kill the process. */
    1297             :         /* Filling the memory doesn't ensure to disable OOM, but it increase a lot the chances to */
    1298             :         /* get a real error from malloc() instead than a process killed. */
    1299             :         /* Note that calloc() doesn't have the same effect. */
    1300    14363921 :         memset(ptr, 0xA5, size);
    1301             : #endif
    1302             : 
    1303    14363921 :         malloc_counter_inc(size);
    1304             : 
    1305    14363921 :         return ptr;
    1306             : }
    1307             : 
    1308       10089 : void* calloc_nofail(size_t count, size_t size)
    1309             : {
    1310             :         void* ptr;
    1311             : 
    1312       10089 :         size *= count;
    1313             : 
    1314             :         /* see the note in malloc_nofail() of why we don't use calloc() */
    1315       10089 :         ptr = malloc(size);
    1316             : 
    1317       10089 :         if (!ptr) {
    1318             :                 /* LCOV_EXCL_START */
    1319             :                 malloc_fail(size);
    1320             :                 exit(EXIT_FAILURE);
    1321             :                 /* LCOV_EXCL_STOP */
    1322             :         }
    1323             : 
    1324       10089 :         memset(ptr, 0, size);
    1325             : 
    1326       10089 :         malloc_counter_inc(size);
    1327             : 
    1328       10089 :         return ptr;
    1329             : }
    1330             : 
    1331     5799401 : char* strdup_nofail(const char* str)
    1332             : {
    1333             :         size_t size;
    1334             :         char* ptr;
    1335             : 
    1336     5799401 :         size = strlen(str) + 1;
    1337             : 
    1338     5799401 :         ptr = malloc(size);
    1339             : 
    1340     5799401 :         if (!ptr) {
    1341             :                 /* LCOV_EXCL_START */
    1342             :                 malloc_fail(size);
    1343             :                 exit(EXIT_FAILURE);
    1344             :                 /* LCOV_EXCL_STOP */
    1345             :         }
    1346             : 
    1347     5799401 :         memcpy(ptr, str, size);
    1348             : 
    1349     5799401 :         malloc_counter_inc(size);
    1350             : 
    1351     5799401 :         return ptr;
    1352             : }
    1353             : 
    1354             : /****************************************************************************/
    1355             : /* smartctl */
    1356             : 
    1357             : /**
    1358             :  * Match a string with the specified pattern.
    1359             :  * Like sscanf() a space match any sequence of spaces.
    1360             :  * Return 0 if it matches.
    1361             :  */
    1362           0 : static int smatch(const char* str, const char* pattern)
    1363             : {
    1364           0 :         while (*pattern) {
    1365           0 :                 if (isspace(*pattern)) {
    1366           0 :                         ++pattern;
    1367           0 :                         while (isspace(*str))
    1368           0 :                                 ++str;
    1369           0 :                 } else if (*pattern == *str) {
    1370           0 :                         ++pattern;
    1371           0 :                         ++str;
    1372             :                 } else
    1373           0 :                         return -1;
    1374             :         }
    1375             : 
    1376           0 :         return 0;
    1377             : }
    1378             : 
    1379          43 : int smartctl_attribute(FILE* f, const char* file, const char* name, uint64_t* smart, char* serial, char* vendor, char* model)
    1380             : {
    1381             :         unsigned i;
    1382             :         int inside;
    1383             : 
    1384             :         /* preclear attribute */
    1385          43 :         *serial = 0;
    1386       11223 :         for (i = 0; i < SMART_COUNT; ++i)
    1387       11180 :                 smart[i] = SMART_UNASSIGNED;
    1388             : 
    1389             :         /* read the file */
    1390          43 :         inside = 0;
    1391             :         while (1) {
    1392             :                 char buf[256];
    1393             :                 unsigned id;
    1394             :                 uint64_t raw;
    1395             :                 char* s;
    1396             : 
    1397          43 :                 s = fgets(buf, sizeof(buf), f);
    1398          43 :                 if (s == 0)
    1399          43 :                         break;
    1400             : 
    1401             :                 /* remove extraneous chars */
    1402           0 :                 s = strpolish(buf);
    1403             : 
    1404           0 :                 log_tag("smartctl:%s:%s:out: %s\n", file, name, s);
    1405             : 
    1406             :                 /* skip initial spaces */
    1407           0 :                 while (isspace(*s))
    1408           0 :                         ++s;
    1409             : 
    1410           0 :                 if (*s == 0) {
    1411           0 :                         inside = 0;
    1412             :                 /* common */
    1413           0 :                 } else if (smatch(s, "Rotation Rate: Solid State") == 0) {
    1414           0 :                         smart[SMART_ROTATION_RATE] = 0;
    1415           0 :                 } else if (sscanf(s, "Rotation Rate: %" SCNu64, &smart[SMART_ROTATION_RATE]) == 1) {
    1416           0 :                 } else if (smatch(s, "User Capacity:") == 0) {
    1417           0 :                         char* begin = strchr(s, ':');
    1418           0 :                         char* end = strstr(s, "bytes");
    1419           0 :                         if (begin != 0 && end != 0 && begin < end) {
    1420             :                                 char* p;
    1421           0 :                                 smart[SMART_SIZE] = 0;
    1422           0 :                                 for (p = begin; p != end; ++p) {
    1423           0 :                                         if (isdigit(*p)) {
    1424           0 :                                                 smart[SMART_SIZE] *= 10;
    1425           0 :                                                 smart[SMART_SIZE] += *p - '0';
    1426             :                                         }
    1427             :                                 }
    1428             :                         }
    1429           0 :                 } else if (sscanf(s, "Device Model: %63s %63s", vendor, model) == 2) {
    1430           0 :                 } else if (sscanf(s, "Device Model: %63s", model) == 1) {
    1431             :                 /* SCSI */
    1432           0 :                 } else if (sscanf(s, "Serial number: %63s", serial) == 1) { /* note "n" of "number" lower case */
    1433           0 :                 } else if (sscanf(s, "Elements in grown defect list: %" SCNu64, &smart[SMART_REALLOCATED_SECTOR_COUNT]) == 1) {
    1434           0 :                 } else if (sscanf(s, "Current Drive Temperature: %" SCNu64, &smart[SMART_TEMPERATURE_CELSIUS]) == 1) {
    1435           0 :                 } else if (sscanf(s, "Drive Trip Temperature: %" SCNu64, &smart[SMART_AIRFLOW_TEMPERATURE_CELSIUS]) == 1) {
    1436           0 :                 } else if (sscanf(s, "Accumulated start-stop cycles: %" SCNu64, &smart[SMART_START_STOP_COUNT]) == 1) {
    1437           0 :                 } else if (sscanf(s, "Accumulated load-unload cycles: %" SCNu64, &smart[SMART_LOAD_CYCLE_COUNT]) == 1) {
    1438           0 :                 } else if (sscanf(s, "  number of hours powered up = %" SCNu64, &smart[SMART_POWER_ON_HOURS]) == 1) {
    1439             :                 /* ATA */
    1440           0 :                 } else if (sscanf(s, "Serial Number: %63s", serial) == 1) {
    1441           0 :                 } else if (smatch(s, "ID#") == 0) {
    1442           0 :                         inside = 1;
    1443           0 :                 } else if (smatch(s, "No Errors Logged") == 0) {
    1444           0 :                         smart[SMART_ERROR] = 0;
    1445           0 :                 } else if (sscanf(s, "ATA Error Count: %" SCNu64, &raw) == 1) {
    1446           0 :                         smart[SMART_ERROR] = raw;
    1447           0 :                 } else if (inside) {
    1448           0 :                         if (sscanf(s, "%u %*s %*s %*s %*s %*s %*s %*s %*s %" SCNu64, &id, &raw) != 2) {
    1449             :                                 /* LCOV_EXCL_START */
    1450             :                                 log_fatal("Invalid smartctl line '%s'.\n", s);
    1451             :                                 return -1;
    1452             :                                 /* LCOV_EXCL_STOP */
    1453             :                         }
    1454             : 
    1455           0 :                         if (id >= 256) {
    1456             :                                 /* LCOV_EXCL_START */
    1457             :                                 log_fatal("Invalid SMART id '%u'.\n", id);
    1458             :                                 return -1;
    1459             :                                 /* LCOV_EXCL_STOP */
    1460             :                         }
    1461             : 
    1462           0 :                         smart[id] = raw;
    1463             :                 }
    1464           0 :         }
    1465             : 
    1466          43 :         return 0;
    1467             : }
    1468             : 
    1469           5 : int smartctl_flush(FILE* f, const char* file, const char* name)
    1470             : {
    1471             :         /* read the file */
    1472             :         while (1) {
    1473             :                 char buf[256];
    1474             :                 char* s;
    1475             : 
    1476           5 :                 s = fgets(buf, sizeof(buf), f);
    1477           5 :                 if (s == 0)
    1478           5 :                         break;
    1479             : 
    1480             :                 /* remove extraneous chars */
    1481           0 :                 s = strpolish(buf);
    1482             : 
    1483           0 :                 log_tag("smartctl:%s:%s:out: %s\n", file, name, s);
    1484           0 :         }
    1485             : 
    1486          10 :         return 0;
    1487             : }
    1488             : 
    1489             : /****************************************************************************/
    1490             : /* thread */
    1491             : 
    1492             : #if HAVE_PTHREAD
    1493        2284 : void thread_mutex_init(pthread_mutex_t* mutex, pthread_mutexattr_t* attr)
    1494             : {
    1495        2284 :         if (pthread_mutex_init(mutex, attr) != 0) {
    1496             :                 /* LCOV_EXCL_START */
    1497             :                 log_fatal("Failed call to pthread_mutex_init().\n");
    1498             :                 os_abort();
    1499             :                 /* LCOV_EXCL_STOP */
    1500             :         }
    1501        2284 : }
    1502             : 
    1503        2082 : void thread_mutex_destroy(pthread_mutex_t* mutex)
    1504             : {
    1505        2082 :         if (pthread_mutex_destroy(mutex) != 0) {
    1506             :                 /* LCOV_EXCL_START */
    1507             :                 log_fatal("Failed call to pthread_mutex_destroy().\n");
    1508             :                 os_abort();
    1509             :                 /* LCOV_EXCL_STOP */
    1510             :         }
    1511        2082 : }
    1512             : 
    1513    80857668 : void thread_mutex_lock(pthread_mutex_t* mutex)
    1514             : {
    1515    80857668 :         if (pthread_mutex_lock(mutex) != 0) {
    1516             :                 /* LCOV_EXCL_START */
    1517             :                 log_fatal("Failed call to pthread_mutex_lock().\n");
    1518             :                 os_abort();
    1519             :                 /* LCOV_EXCL_STOP */
    1520             :         }
    1521    80860507 : }
    1522             : 
    1523    80858701 : void thread_mutex_unlock(pthread_mutex_t* mutex)
    1524             : {
    1525    80858701 :         if (pthread_mutex_unlock(mutex) != 0) {
    1526             :                 /* LCOV_EXCL_START */
    1527             :                 log_fatal("Failed call to pthread_mutex_unlock().\n");
    1528             :                 os_abort();
    1529             :                 /* LCOV_EXCL_STOP */
    1530             :         }
    1531    80861909 : }
    1532             : 
    1533         380 : void thread_cond_init(pthread_cond_t* cond, pthread_condattr_t* attr)
    1534             : {
    1535         380 :         if (pthread_cond_init(cond, attr) != 0) {
    1536             :                 /* LCOV_EXCL_START */
    1537             :                 log_fatal("Failed call to pthread_cond_init().\n");
    1538             :                 os_abort();
    1539             :                 /* LCOV_EXCL_STOP */
    1540             :         }
    1541         380 : }
    1542             : 
    1543         380 : void thread_cond_destroy(pthread_cond_t* cond)
    1544             : {
    1545         380 :         if (pthread_cond_destroy(cond) != 0) {
    1546             :                 /* LCOV_EXCL_START */
    1547             :                 log_fatal("Failed call to pthread_cond_destroy().\n");
    1548             :                 os_abort();
    1549             :                 /* LCOV_EXCL_STOP */
    1550             :         }
    1551         380 : }
    1552             : 
    1553       85887 : void thread_cond_signal(pthread_cond_t* cond)
    1554             : {
    1555       85887 :         if (pthread_cond_signal(cond) != 0) {
    1556             :                 /* LCOV_EXCL_START */
    1557             :                 log_fatal("Failed call to pthread_cond_signal().\n");
    1558             :                 os_abort();
    1559             :                 /* LCOV_EXCL_STOP */
    1560             :         }
    1561       85887 : }
    1562             : 
    1563      255503 : void thread_cond_broadcast(pthread_cond_t* cond)
    1564             : {
    1565      255503 :         if (pthread_cond_broadcast(cond) != 0) {
    1566             :                 /* LCOV_EXCL_START */
    1567             :                 log_fatal("Failed call to pthread_cond_broadcast().\n");
    1568             :                 os_abort();
    1569             :                 /* LCOV_EXCL_STOP */
    1570             :         }
    1571      255503 : }
    1572             : 
    1573     1037153 : void thread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex)
    1574             : {
    1575     1037153 :         if (pthread_cond_wait(cond, mutex) != 0) {
    1576             :                 /* LCOV_EXCL_START */
    1577             :                 log_fatal("Failed call to pthread_cond_wait().\n");
    1578             :                 os_abort();
    1579             :                 /* LCOV_EXCL_STOP */
    1580             :         }
    1581     1037153 : }
    1582             : 
    1583             : /**
    1584             :  * Implementation note about conditional variables.
    1585             :  *
    1586             :  * The conditional variables can be signaled inside or ouside the mutex,
    1587             :  * what is better it's debatable but in general doing that ouside the mutex,
    1588             :  * reduces the number of context switches.
    1589             :  *
    1590             :  * But when when testing with helgrind and drd, this disallows such tools to
    1591             :  * to see the dependency between the signal and the wait.
    1592             :  *
    1593             :  * To avoid it we signal everything inside the mutex. And we do this in both
    1594             :  * test mode (with CHERCKER defined) and release mode (CHECKER not defined),
    1595             :  * to be on the safe side and avoid any difference in beaviour between test and
    1596             :  * release.
    1597             :  *
    1598             :  * Here some interesting discussion:
    1599             :  *
    1600             :  * Condvars: signal with mutex locked or not?
    1601             :  * http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/
    1602             :  *
    1603             :  * Calling pthread_cond_signal without locking mutex
    1604             :  * http://stackoverflow.com/questions/4544234/calling-pthread-cond-signal-without-locking-mutex/4544494#4544494
    1605             :  */
    1606             : 
    1607             : /**
    1608             :  * Control when to signal the condition variables.
    1609             :  */
    1610             : int thread_cond_signal_outside = 0;
    1611             : 
    1612       85887 : void thread_cond_signal_and_unlock(pthread_cond_t* cond, pthread_mutex_t* mutex)
    1613             : {
    1614       85887 :         if (thread_cond_signal_outside) {
    1615             :                 /* without the thread checker unlock before signaling, */
    1616             :                 /* this reduces the number of context switches */
    1617           0 :                 thread_mutex_unlock(mutex);
    1618             :         }
    1619             : 
    1620       85887 :         thread_cond_signal(cond);
    1621             : 
    1622       85887 :         if (!thread_cond_signal_outside) {
    1623             :                 /* with the thread checker unlock after signaling */
    1624             :                 /* to make explicit the condition and mutex relation */
    1625       85887 :                 thread_mutex_unlock(mutex);
    1626             :         }
    1627       85887 : }
    1628             : 
    1629      255313 : void thread_cond_broadcast_and_unlock(pthread_cond_t* cond, pthread_mutex_t* mutex)
    1630             : {
    1631      255313 :         if (thread_cond_signal_outside) {
    1632             :                 /* without the thread checker unlock before signaling, */
    1633             :                 /* this reduces the number of context switches */
    1634           0 :                 thread_mutex_unlock(mutex);
    1635             :         }
    1636             : 
    1637      255313 :         thread_cond_broadcast(cond);
    1638             : 
    1639      255313 :         if (!thread_cond_signal_outside) {
    1640             :                 /* with the thread checker unlock after signaling */
    1641             :                 /* to make explicit the condition and mutex relation */
    1642      255313 :                 thread_mutex_unlock(mutex);
    1643             :         }
    1644      255313 : }
    1645             : 
    1646        2200 : void thread_create(pthread_t* thread, pthread_attr_t* attr, void *(* func)(void *), void *arg)
    1647             : {
    1648        2200 :         if (pthread_create(thread, attr, func, arg) != 0) {
    1649             :                 /* LCOV_EXCL_START */
    1650             :                 log_fatal("Failed call to pthread_create().\n");
    1651             :                 os_abort();
    1652             :                 /* LCOV_EXCL_STOP */
    1653             :         }
    1654        2200 : }
    1655             : 
    1656        2200 : void thread_join(pthread_t thread, void** retval)
    1657             : {
    1658        2200 :         if (pthread_join(thread, retval) != 0) {
    1659             :                 /* LCOV_EXCL_START */
    1660             :                 log_fatal("Failed call to pthread_join().\n");
    1661             :                 os_abort();
    1662             :                 /* LCOV_EXCL_STOP */
    1663             :         }
    1664        2200 : }
    1665             : 
    1666             : #endif
    1667             : 

Generated by: LCOV version 1.10