Blame lib/vsnprintf.c

Packit 8f70b4
/* Formatted output to strings.
Packit 8f70b4
   Copyright (C) 2004, 2006-2018 Free Software Foundation, Inc.
Packit 8f70b4
   Written by Simon Josefsson and Yoann Vandoorselaere <yoann@prelude-ids.org>.
Packit 8f70b4
Packit 8f70b4
   This program is free software; you can redistribute it and/or modify
Packit 8f70b4
   it under the terms of the GNU General Public License as published by
Packit 8f70b4
   the Free Software Foundation; either version 3, or (at your option)
Packit 8f70b4
   any later version.
Packit 8f70b4
Packit 8f70b4
   This program is distributed in the hope that it will be useful,
Packit 8f70b4
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 8f70b4
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 8f70b4
   GNU General Public License for more details.
Packit 8f70b4
Packit 8f70b4
   You should have received a copy of the GNU General Public License along
Packit 8f70b4
   with this program; if not, see <https://www.gnu.org/licenses/>.  */
Packit 8f70b4
Packit 8f70b4
#ifdef HAVE_CONFIG_H
Packit 8f70b4
# include <config.h>
Packit 8f70b4
#endif
Packit 8f70b4
Packit 8f70b4
/* Specification.  */
Packit 8f70b4
#include <stdio.h>
Packit 8f70b4
Packit 8f70b4
#include <errno.h>
Packit 8f70b4
#include <limits.h>
Packit 8f70b4
#include <stdarg.h>
Packit 8f70b4
#include <stdlib.h>
Packit 8f70b4
#include <string.h>
Packit 8f70b4
Packit 8f70b4
#include "vasnprintf.h"
Packit 8f70b4
Packit 8f70b4
/* Print formatted output to string STR.  Similar to vsprintf, but
Packit 8f70b4
   additional length SIZE limit how much is written into STR.  Returns
Packit 8f70b4
   string length of formatted string (which may be larger than SIZE).
Packit 8f70b4
   STR may be NULL, in which case nothing will be written.  On error,
Packit 8f70b4
   return a negative value.  */
Packit 8f70b4
int
Packit 8f70b4
vsnprintf (char *str, size_t size, const char *format, va_list args)
Packit 8f70b4
{
Packit 8f70b4
  char *output;
Packit 8f70b4
  size_t len;
Packit 8f70b4
  size_t lenbuf = size;
Packit 8f70b4
Packit 8f70b4
  output = vasnprintf (str, &lenbuf, format, args);
Packit 8f70b4
  len = lenbuf;
Packit 8f70b4
Packit 8f70b4
  if (!output)
Packit 8f70b4
    return -1;
Packit 8f70b4
Packit 8f70b4
  if (output != str)
Packit 8f70b4
    {
Packit 8f70b4
      if (size)
Packit 8f70b4
        {
Packit 8f70b4
          size_t pruned_len = (len < size ? len : size - 1);
Packit 8f70b4
          memcpy (str, output, pruned_len);
Packit 8f70b4
          str[pruned_len] = '\0';
Packit 8f70b4
        }
Packit 8f70b4
Packit 8f70b4
      free (output);
Packit 8f70b4
    }
Packit 8f70b4
Packit 8f70b4
  if (len > INT_MAX)
Packit 8f70b4
    {
Packit 8f70b4
      errno = EOVERFLOW;
Packit 8f70b4
      return -1;
Packit 8f70b4
    }
Packit 8f70b4
Packit 8f70b4
  return len;
Packit 8f70b4
}