Coverage Report

Created: 2026-09-28 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/util-linux/lib/mbsalign.c
Line
Count
Source
1
/*
2
 * SPDX-License-Identifier: LGPL-2.1-or-later
3
 *
4
 * Align/Truncate a string in a given screen width
5
 * Copyright (C) 2009-2010 Free Software Foundation, Inc.
6
 *
7
 * This program is free software: you can redistribute it and/or modify it
8
 * under the terms of the GNU Lesser General Public License as published by the
9
 * Free Software Foundation, either version 2.1 of the License, or (at your
10
 * option) any later version.
11
 *
12
 * Written by Pádraig Brady.
13
 */
14
#include <stdlib.h>
15
#include <string.h>
16
#include <stdio.h>
17
#include <stdbool.h>
18
#include <limits.h>
19
#include <ctype.h>
20
21
#include "c.h"
22
#include "mbsalign.h"
23
#include "strutils.h"
24
#include "widechar.h"
25
26
/*
27
 * Counts number of cells in multibyte string. All control and
28
 * non-printable chars are ignored.
29
 *
30
 * Returns: number of cells.
31
 */
32
size_t mbs_nwidth(const char *buf, size_t bufsz)
33
0
{
34
0
  const char *p = buf, *last = buf;
35
0
  size_t width = 0;
36
37
0
#ifdef HAVE_WIDECHAR
38
0
  mbstate_t st;
39
0
  memset(&st, 0, sizeof(st));
40
0
#endif
41
0
  if (p && *p && bufsz)
42
0
    last = p + (bufsz - 1);
43
44
0
  while (p && *p && p <= last) {
45
0
    if (*p == '\033') {
46
0
      p++;
47
48
      /* try detect a CSI sequence "\e[" and skip on success;
49
       * it is parameter bytes (0x30-0x3f), then intermediate
50
       * bytes (0x20-0x2f), terminated by a final byte
51
       * (0x40-0x7e). None of them occupies a cell. */
52
0
      if (*p == '[') {
53
0
        const char *e = p + 1;
54
55
0
        while (e <= last && (unsigned char) *e >= 0x30
56
0
             && (unsigned char) *e <= 0x3f)
57
0
          e++;
58
0
        while (e <= last && (unsigned char) *e >= 0x20
59
0
             && (unsigned char) *e <= 0x2f)
60
0
          e++;
61
0
        if (e <= last && (unsigned char) *e >= 0x40
62
0
                 && (unsigned char) *e <= 0x7e)
63
0
          p = e + 1;
64
0
      }
65
      /* try detect SCS sequences "\e(X", "\e)X", "\e*X", "\e+X" and skip on success */
66
0
      else if (p < last && (*p == '(' || *p == ')' || *p == '*' || *p == '+'))
67
0
        p += 2;  /* skip the SCS sequence */
68
0
      continue;
69
0
    }
70
0
    if (iscntrl((unsigned char) *p)) {
71
0
      p++;
72
0
      continue;
73
0
    }
74
0
#ifdef HAVE_WIDECHAR
75
0
    wchar_t wc;
76
0
    size_t len = mbrtowc(&wc, p, MB_CUR_MAX, &st);
77
78
0
    if (len == 0)
79
0
      break;
80
0
    if (len > 0 && iswprint(wc)) {
81
0
      int x = wcwidth(wc);
82
0
      if (x > 0)
83
0
        width += x;
84
0
    } else if (len == (size_t) -1 || len == (size_t) -2)
85
0
      len = 1;
86
0
    p += len;
87
#else
88
    if (isprint((unsigned char) *p))
89
      width++;
90
    p++;
91
#endif
92
0
  }
93
94
0
  return width;
95
0
}
96
97
size_t mbs_width(const char *s)
98
0
{
99
0
  if (!s || !*s)
100
0
    return 0;
101
0
  return mbs_nwidth(s, strlen(s));
102
0
}
103
104
/*
105
 * Counts number of cells in multibyte string. For all control and
106
 * non-printable chars is the result width enlarged to store \x?? hex
107
 * sequence. See mbs_safe_encode().
108
 *
109
 * Returns: number of cells, @sz returns number of bytes.
110
 */
111
size_t mbs_safe_nwidth(const char *buf, size_t bufsz, size_t *sz)
112
0
{
113
0
  const char *p = buf, *last = buf;
114
0
  size_t width = 0, bytes = 0;
115
116
0
#ifdef HAVE_WIDECHAR
117
0
  mbstate_t st;
118
0
  memset(&st, 0, sizeof(st));
119
0
#endif
120
0
  if (p && *p && bufsz)
121
0
    last = p + (bufsz - 1);
122
123
0
  while (p && *p && p <= last) {
124
0
    if ((p < last && *p == '\\' && *(p + 1) == 'x')
125
0
        || iscntrl((unsigned char) *p)) {
126
0
      width += 4, bytes += 4;   /* *p encoded to \x?? */
127
0
      p++;
128
0
    }
129
0
#ifdef HAVE_WIDECHAR
130
0
    else {
131
0
      wchar_t wc;
132
0
      size_t len = mbrtowc(&wc, p, MB_CUR_MAX, &st);
133
134
0
      if (len == 0)
135
0
        break;
136
137
0
      if (len == (size_t) -1 || len == (size_t) -2) {
138
0
        len = 1;
139
0
        if (isprint((unsigned char) *p))
140
0
          width += 1, bytes += 1;
141
0
        else
142
0
          width += 4, bytes += 4;
143
144
0
      } else if (!iswprint(wc)) {
145
0
        width += len * 4; /* hex encode whole sequence */
146
0
        bytes += len * 4;
147
0
      } else {
148
0
        width += wcwidth(wc); /* number of cells */
149
0
        bytes += len;   /* number of bytes */
150
0
      }
151
0
      p += len;
152
0
    }
153
#else
154
    else if (!isprint((unsigned char) *p)) {
155
      width += 4, bytes += 4;   /* *p encoded to \x?? */
156
      p++;
157
    } else {
158
      width++, bytes++;
159
      p++;
160
    }
161
#endif
162
0
  }
163
164
0
  if (sz)
165
0
    *sz = bytes;
166
0
  return width;
167
0
}
168
169
size_t mbs_safe_width(const char *s)
170
0
{
171
0
  if (!s || !*s)
172
0
    return 0;
173
0
  return mbs_safe_nwidth(s, strlen(s), NULL);
174
0
}
175
176
/*
177
 * Copy @s to @buf and replace control and non-printable chars with
178
 * \x?? hex sequence. The @width returns number of cells. The @safechars
179
 * are not encoded.
180
 *
181
 * The @buf has to be big enough to store mbs_safe_encode_size(strlen(s)))
182
 * bytes.
183
 */
184
char *mbs_safe_encode_to_buffer(const char *s, size_t *width, char *buf, size_t bufsiz, const char *safechars)
185
0
{
186
0
  const char *p = s;
187
0
  char *r;
188
0
  int rsz;
189
0
  size_t sz = s ? strlen(s) : 0;
190
191
0
#ifdef HAVE_WIDECHAR
192
0
  mbstate_t st;
193
0
  memset(&st, 0, sizeof(st));
194
0
#endif
195
0
  if (!sz || !buf || !bufsiz)
196
0
    return NULL;
197
198
0
  r = buf;
199
0
  rsz = (int) bufsiz;
200
0
  *width = 0;
201
202
0
  while (p && *p) {
203
0
    if (safechars && strchr(safechars, *p)) {
204
0
      if (rsz < 2)
205
0
        break;
206
0
      *r++ = *p++;
207
0
      rsz--;
208
0
      continue;
209
0
    }
210
211
0
    if ((*p == '\\' && *(p + 1) == 'x')
212
0
        || iscntrl((unsigned char) *p)) {
213
0
      if (rsz < 5)
214
0
        break;
215
0
      snprintf(r, rsz, "\\x%02x", (unsigned char) *p);
216
0
      r += 4;
217
0
      rsz -= 4;
218
0
      *width += 4;
219
0
      p++;
220
0
    }
221
0
#ifdef HAVE_WIDECHAR
222
0
    else {
223
0
      wchar_t wc;
224
0
      size_t len = mbrtowc(&wc, p, MB_CUR_MAX, &st);
225
226
0
      if (len == 0)
227
0
        break;   /* end of string */
228
229
0
      if (len == (size_t) -1 || len == (size_t) -2) {
230
0
        len = 1;
231
        /*
232
         * Not valid multibyte sequence -- maybe it's
233
         * printable char according to the current locales.
234
         */
235
0
        if (!isprint((unsigned char) *p)) {
236
0
          if (rsz < 5)
237
0
            break;
238
0
          snprintf(r, rsz, "\\x%02x", (unsigned char) *p);
239
0
          r += 4;
240
0
          rsz -= 4;
241
0
          *width += 4;
242
0
        } else {
243
0
          if (rsz < 2)
244
0
            break;
245
0
          (*width)++;
246
0
          *r++ = *p;
247
0
          rsz--;
248
0
        }
249
0
      } else if (!iswprint(wc)) {
250
0
        size_t i;
251
0
        for (i = 0; i < len; i++) {
252
0
          if (rsz < 5)
253
0
            break;
254
0
          snprintf(r, rsz, "\\x%02x", (unsigned char) p[i]);
255
0
          r += 4;
256
0
          rsz -= 4;
257
0
          *width += 4;
258
0
        }
259
0
        if (i < len)
260
0
          break;
261
0
      } else {
262
0
        if (rsz < (int)len + 1)
263
0
          break;
264
0
        memcpy(r, p, len);
265
0
        r += len;
266
0
        rsz -= len;
267
0
        *width += wcwidth(wc);
268
0
      }
269
0
      p += len;
270
0
    }
271
#else
272
    else if (!isprint((unsigned char) *p)) {
273
      if (rsz < 5)
274
        break;
275
      snprintf(r, rsz, "\\x%02x", (unsigned char) *p);
276
      p++;
277
      r += 4;
278
      rsz -= 4;
279
      *width += 4;
280
    } else {
281
      if (rsz < 2)
282
        break;
283
      *r++ = *p++;
284
      rsz--;
285
      (*width)++;
286
    }
287
#endif
288
0
  }
289
290
0
  *r = '\0';
291
0
  return buf;
292
0
}
293
294
/*
295
 * Copy @s to @buf and replace broken sequences to \x?? hex sequence. The
296
 * @width returns number of cells. The @safechars are not encoded.
297
 *
298
 * The @buf has to be big enough to store mbs_safe_encode_size(strlen(s)))
299
 * bytes.
300
 */
301
char *mbs_invalid_encode_to_buffer(const char *s, size_t *width, char *buf, size_t bufsiz)
302
0
{
303
0
  const char *p = s;
304
0
  char *r;
305
0
  int rsz;
306
0
  size_t sz = s ? strlen(s) : 0;
307
308
0
#ifdef HAVE_WIDECHAR
309
0
  mbstate_t st;
310
0
  memset(&st, 0, sizeof(st));
311
0
#endif
312
0
  if (!sz || !buf || !bufsiz)
313
0
    return NULL;
314
315
0
  r = buf;
316
0
  rsz = (int) bufsiz;
317
0
  *width = 0;
318
319
0
  while (p && *p) {
320
0
#ifdef HAVE_WIDECHAR
321
0
    wchar_t wc;
322
0
    size_t len = mbrtowc(&wc, p, MB_CUR_MAX, &st);
323
#else
324
    size_t len = 1;
325
#endif
326
327
0
    if (len == 0)
328
0
      break;   /* end of string */
329
330
0
    if (len == (size_t) -1 || len == (size_t) -2) {
331
0
      len = 1;
332
      /*
333
       * Not valid multibyte sequence -- maybe it's
334
       * printable char according to the current locales.
335
       */
336
0
      if (!isprint((unsigned char) *p)) {
337
0
        if (rsz < 5)
338
0
          break;
339
0
        snprintf(r, rsz, "\\x%02x", (unsigned char) *p);
340
0
        r += 4;
341
0
        rsz -= 4;
342
0
        *width += 4;
343
0
      } else {
344
0
        if (rsz < 2)
345
0
          break;
346
0
        (*width)++;
347
0
        *r++ = *p;
348
0
        rsz--;
349
0
      }
350
0
    } else if (*p == '\\' && *(p + 1) == 'x') {
351
0
      if (rsz < 5)
352
0
        break;
353
0
      snprintf(r, rsz, "\\x%02x", (unsigned char) *p);
354
0
      r += 4;
355
0
      rsz -= 4;
356
0
      *width += 4;
357
0
    } else {
358
0
      if (rsz < (int)len + 1)
359
0
        break;
360
0
      r = mempcpy(r, p, len);
361
0
      rsz -= len;
362
0
      *width += wcwidth(wc);
363
0
    }
364
0
    p += len;
365
0
  }
366
367
0
  *r = '\0';
368
0
  return buf;
369
0
}
370
371
/*
372
 * Guess size
373
 */
374
size_t mbs_safe_encode_size(size_t bytes)
375
0
{
376
0
  return (bytes * 4) + 1;
377
0
}
378
379
/*
380
 * Count size of the original string in bytes (count \x?? as one byte)
381
 */
382
size_t mbs_safe_decode_size(const char *p)
383
0
{
384
0
  size_t bytes = 0;
385
386
0
  while (p && *p) {
387
0
    if (*p == '\\' && *(p + 1) == 'x' &&
388
0
        isxdigit(*(p + 2)) && isxdigit(*(p + 3)))
389
0
      p += 4;
390
0
    else
391
0
      p++;
392
0
    bytes++;
393
0
  }
394
0
  return bytes;
395
0
}
396
397
/*
398
 * Returns allocated string where all control and non-printable chars are
399
 * replaced with \x?? hex sequence.
400
 */
401
char *mbs_safe_encode(const char *s, size_t *width)
402
0
{
403
0
  size_t sz = s ? strlen(s) : 0;
404
0
  size_t bufsz;
405
0
  char *buf, *ret = NULL;
406
407
0
  if (!sz)
408
0
    return NULL;
409
0
  bufsz = mbs_safe_encode_size(sz);
410
0
  buf = malloc(bufsz);
411
0
  if (buf)
412
0
    ret = mbs_safe_encode_to_buffer(s, width, buf, bufsz, NULL);
413
0
  if (!ret)
414
0
    free(buf);
415
0
  return ret;
416
0
}
417
418
/*
419
 * Returns allocated string where all broken widechars chars are
420
 * replaced with \x?? hex sequence.
421
 */
422
char *mbs_invalid_encode(const char *s, size_t *width)
423
0
{
424
0
  size_t sz = s ? strlen(s) : 0;
425
0
  size_t bufsz;
426
0
  char *buf, *ret = NULL;
427
428
0
  if (!sz)
429
0
    return NULL;
430
0
  bufsz = mbs_safe_encode_size(sz);
431
0
  buf = malloc(bufsz);
432
0
  if (buf)
433
0
    ret = mbs_invalid_encode_to_buffer(s, width, buf, bufsz);
434
0
  if (!ret)
435
0
    free(buf);
436
0
  return ret;
437
0
}
438
439
#ifdef HAVE_WIDECHAR
440
441
static bool
442
wc_ensure_printable (wchar_t *wchars)
443
0
{
444
0
  bool replaced = false;
445
0
  wchar_t *wc = wchars;
446
0
  while (*wc)
447
0
    {
448
0
      if (!iswprint ((wint_t) *wc))
449
0
        {
450
0
          *wc = 0xFFFD; /* L'\uFFFD' (replacement char) */
451
0
          replaced = true;
452
0
        }
453
0
      wc++;
454
0
    }
455
0
  return replaced;
456
0
}
457
458
/* Truncate wchar string to width cells.
459
 * Returns number of cells used.  */
460
461
static size_t
462
wc_truncate (wchar_t *wc, size_t width)
463
0
{
464
0
  size_t cells = 0;
465
0
  int next_cells = 0;
466
467
0
  while (*wc)
468
0
    {
469
0
      next_cells = wcwidth (*wc);
470
0
      if (next_cells == -1) /* non printable */
471
0
        {
472
0
          *wc = 0xFFFD; /* L'\uFFFD' (replacement char) */
473
0
          next_cells = 1;
474
0
        }
475
0
      if (cells + next_cells > width)
476
0
        break;
477
478
0
      cells += next_cells;
479
0
      wc++;
480
0
    }
481
0
  *wc = L'\0';
482
0
  return cells;
483
0
}
484
485
static int
486
rpl_wcswidth (const wchar_t *s, size_t n)
487
0
{
488
0
  int ret = 0;
489
490
0
  while (n-- > 0 && *s != L'\0')
491
0
    {
492
0
      int nwidth = wcwidth (*s++);
493
0
      if (nwidth == -1)             /* non printable */
494
0
        return -1;
495
0
      if (ret > (INT_MAX - nwidth)) /* overflow */
496
0
        return -1;
497
0
      ret += nwidth;
498
0
    }
499
500
0
  return ret;
501
0
}
502
#endif /* HAVE_WIDECHAR */
503
504
/* Truncate multi-byte string to @width and returns number of
505
 * bytes of the new string @str, and in @width returns number
506
 * of cells.
507
 */
508
size_t
509
mbs_truncate(char *str, size_t *width)
510
0
{
511
0
  ssize_t bytes = strlen(str);
512
0
#ifdef HAVE_WIDECHAR
513
0
  ssize_t sz = mbstowcs(NULL, str, 0);
514
0
  wchar_t *wcs = NULL;
515
516
0
  if (sz == (ssize_t) -1)
517
0
    goto done;
518
519
0
  wcs = calloc(1, (sz + 1) * sizeof(wchar_t));
520
0
  if (!wcs)
521
0
    goto done;
522
523
0
  if (!mbstowcs(wcs, str, sz))
524
0
    goto done;
525
0
  *width = wc_truncate(wcs, *width);
526
0
  bytes = wcstombs(str, wcs, bytes);
527
0
done:
528
0
  free(wcs);
529
#else
530
  if (bytes >= 0 && *width < (size_t) bytes)
531
    bytes = *width;
532
#endif
533
0
  if (bytes >= 0)
534
0
    str[bytes] = '\0';
535
0
  return bytes;
536
0
}
537
538
/* Write N_SPACES space characters to DEST while ensuring
539
   nothing is written beyond DEST_END. A terminating NUL
540
   is always added to DEST.
541
   A pointer to the terminating NUL is returned.  */
542
543
static char*
544
mbs_align_pad (char *dest, const char* dest_end, size_t n_spaces, int padchar)
545
0
{
546
0
  for (/* nothing */; n_spaces && (dest < dest_end); n_spaces--)
547
0
    *dest++ = padchar;
548
0
  *dest = '\0';
549
0
  return dest;
550
0
}
551
552
size_t
553
mbsalign (const char *src, char *dest, size_t dest_size,
554
          size_t *width, mbs_align_t align, int flags)
555
0
{
556
0
  return mbsalign_with_padding(src, dest, dest_size, width, align, flags, ' ');
557
0
}
558
559
/* Align a string, SRC, in a field of *WIDTH columns, handling multi-byte
560
   characters; write the result into the DEST_SIZE-byte buffer, DEST.
561
   ALIGNMENT specifies whether to left- or right-justify or to center.
562
   If SRC requires more than *WIDTH columns, truncate it to fit.
563
   When centering, the number of trailing spaces may be one less than the
564
   number of leading spaces. The FLAGS parameter is unused at present.
565
   Return the length in bytes required for the final result, not counting
566
   the trailing NUL.  A return value of DEST_SIZE or larger means there
567
   wasn't enough space.  DEST will be NUL terminated in any case.
568
   Return (size_t) -1 upon error (invalid multi-byte sequence in SRC,
569
   or malloc failure), unless MBA_UNIBYTE_FALLBACK is specified.
570
   Update *WIDTH to indicate how many columns were used before padding.  */
571
572
size_t
573
mbsalign_with_padding (const char *src, char *dest, size_t dest_size,
574
                 size_t *width, mbs_align_t align,
575
#ifdef HAVE_WIDECHAR
576
           int flags,
577
#else
578
           int flags __attribute__((__unused__)),
579
#endif
580
           int padchar)
581
0
{
582
0
  size_t ret = -1;
583
0
  size_t src_size = strlen (src) + 1;
584
0
  char *newstr = NULL;
585
0
  wchar_t *str_wc = NULL;
586
0
  const char *str_to_print = src;
587
0
  size_t n_cols = src_size - 1;
588
0
  size_t n_used_bytes = n_cols; /* Not including NUL */
589
0
  size_t n_spaces = 0, space_left;
590
591
0
#ifdef HAVE_WIDECHAR
592
0
  bool conversion = false;
593
0
  bool wc_enabled = false;
594
595
  /* In multi-byte locales convert to wide characters
596
     to allow easy truncation. Also determine number
597
     of screen columns used.  */
598
0
  if (MB_CUR_MAX > 1)
599
0
    {
600
0
      size_t src_chars = mbstowcs (NULL, src, 0);
601
0
      if (src_chars == (size_t) -1)
602
0
        {
603
0
          if (flags & MBA_UNIBYTE_FALLBACK)
604
0
            goto mbsalign_unibyte;
605
0
          else
606
0
            goto mbsalign_cleanup;
607
0
        }
608
0
      src_chars += 1; /* make space for NUL */
609
0
      str_wc = malloc (src_chars * sizeof (wchar_t));
610
0
      if (str_wc == NULL)
611
0
        {
612
0
          if (flags & MBA_UNIBYTE_FALLBACK)
613
0
            goto mbsalign_unibyte;
614
0
          else
615
0
            goto mbsalign_cleanup;
616
0
        }
617
0
      if (mbstowcs (str_wc, src, src_chars) != 0)
618
0
        {
619
0
          str_wc[src_chars - 1] = L'\0';
620
0
          wc_enabled = true;
621
0
          conversion = wc_ensure_printable (str_wc);
622
0
          n_cols = rpl_wcswidth (str_wc, src_chars);
623
0
        }
624
0
    }
625
626
  /* If we transformed or need to truncate the source string
627
     then create a modified copy of it.  */
628
0
  if (wc_enabled && (conversion || (n_cols > *width)))
629
0
    {
630
0
        if (conversion)
631
0
          {
632
             /* May have increased the size by converting
633
                \t to \uFFFD for example.  */
634
0
            src_size = wcstombs(NULL, str_wc, 0) + 1;
635
0
          }
636
0
        newstr = malloc (src_size);
637
0
        if (newstr == NULL)
638
0
        {
639
0
          if (flags & MBA_UNIBYTE_FALLBACK)
640
0
            goto mbsalign_unibyte;
641
0
          else
642
0
            goto mbsalign_cleanup;
643
0
        }
644
0
        str_to_print = newstr;
645
0
        n_cols = wc_truncate (str_wc, *width);
646
0
        n_used_bytes = wcstombs (newstr, str_wc, src_size);
647
0
    }
648
649
0
mbsalign_unibyte:
650
0
#endif
651
652
0
  if (n_cols > *width) /* Unibyte truncation required.  */
653
0
    {
654
0
      n_cols = *width;
655
0
      n_used_bytes = n_cols;
656
0
    }
657
658
0
  if (*width > n_cols) /* Padding required.  */
659
0
    n_spaces = *width - n_cols;
660
661
  /* indicate to caller how many cells needed (not including padding).  */
662
0
  *width = n_cols;
663
664
  /* indicate to caller how many bytes needed (not including NUL).  */
665
0
  ret = n_used_bytes + (n_spaces * 1);
666
667
  /* Write as much NUL terminated output to DEST as possible.  */
668
0
  if (dest_size != 0)
669
0
    {
670
0
      char *dest_end = dest + dest_size - 1;
671
0
      size_t start_spaces;
672
0
      size_t end_spaces;
673
674
0
      switch (align)
675
0
        {
676
0
        case MBS_ALIGN_CENTER:
677
0
          start_spaces = n_spaces / 2 + n_spaces % 2;
678
0
          end_spaces = n_spaces / 2;
679
0
          break;
680
0
        case MBS_ALIGN_LEFT:
681
0
          start_spaces = 0;
682
0
          end_spaces = n_spaces;
683
0
          break;
684
0
        case MBS_ALIGN_RIGHT:
685
0
          start_spaces = n_spaces;
686
0
          end_spaces = 0;
687
0
          break;
688
0
  default:
689
0
    abort();
690
0
        }
691
692
0
      dest = mbs_align_pad (dest, dest_end, start_spaces, padchar);
693
0
      space_left = dest_end - dest;
694
0
      dest = mempcpy (dest, str_to_print, min (n_used_bytes, space_left));
695
0
      mbs_align_pad (dest, dest_end, end_spaces, padchar);
696
0
    }
697
0
#ifdef HAVE_WIDECHAR
698
0
mbsalign_cleanup:
699
0
#endif
700
0
  free (str_wc);
701
0
  free (newstr);
702
703
0
  return ret;
704
0
}