safec  2.1
Safe C Library - ISO TR24731 Bounds Checking Interface
sprintf_s.c
Go to the documentation of this file.
1 /* Need restrict */
2 #include "config.h"
3 #include "safe_str_lib.h"
4 #include "safe_str_constraint.h"
5 #include <stdarg.h>
6 
7 /* TODO: error when fmt contains %n, or encoding errors occur.
8  */
9 
49 int sprintf_s(char * restrict dest, rsize_t dmax, const char * restrict fmt, ...)
50 {
51  va_list ap;
52  int ret = -1;
53  if (dmax > RSIZE_MAX_STR) {
54  invoke_safe_str_constraint_handler("sprintf_s: dmax exceeds max",
55  NULL, ESLEMAX);
56  return RCNEGATE(ESLEMAX);
57  }
58 
59  if (dest == NULL) {
60  invoke_safe_str_constraint_handler("sprintf_s: dest is null",
61  NULL, ESNULLP);
62  return RCNEGATE(ESNULLP);
63  }
64 
65  if (fmt == NULL) {
66  invoke_safe_str_constraint_handler("sprintf_s: fmt is null",
67  NULL, ESNULLP);
68  return RCNEGATE(ESNULLP);
69  }
70 
71  if (dmax == 0) {
72  invoke_safe_str_constraint_handler("sprintf_s: dmax is 0",
73  NULL, ESZEROL);
74  return RCNEGATE(ESZEROL);
75  }
76 
77  va_start(ap, fmt);
78 
79  ret = vsnprintf(dest, (size_t)dmax, fmt, ap);
80 
81  if (ret >= (int)dmax) {
82  invoke_safe_str_constraint_handler("sprintf_s: len exceeds dmax",
83  NULL, ESNOSPC);
84  *dest = 0;
85  ret = RCNEGATE(ESNOSPC);
86  }
87 
88  va_end(ap);
89 
90  return ret;
91 }
void invoke_safe_str_constraint_handler(const char *msg, void *ptr, errno_t error)
Invokes the currently set constraint handler or the default.
int sprintf_s(char *restrict dest, rsize_t dmax, const char *restrict fmt,...)
The sprintf_s function composes a string with same test that would be printed if format was used on p...
Definition: sprintf_s.c:49