Blame gl/vsnprintf.c

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