improve previous: do the size check up front to avoid leaking memory
authorschwarze <schwarze@openbsd.org>
Sun, 28 Dec 2014 14:16:07 +0000 (14:16 +0000)
committerschwarze <schwarze@openbsd.org>
Sun, 28 Dec 2014 14:16:07 +0000 (14:16 +0000)
usr.bin/mandoc/roff.c

index 7d6a02e..65b4394 100644 (file)
@@ -1,4 +1,4 @@
-/*     $OpenBSD: roff.c,v 1.117 2014/12/25 17:18:40 schwarze Exp $ */
+/*     $OpenBSD: roff.c,v 1.118 2014/12/28 14:16:07 schwarze Exp $ */
 /*
  * Copyright (c) 2010, 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
  * Copyright (c) 2010-2014 Ingo Schwarze <schwarze@openbsd.org>
@@ -649,6 +649,10 @@ roff_res(struct roff *r, struct buf *buf, int ln, int pos)
                            r->parse, ln, (int)(stesc - buf->buf),
                            "%.*s", (int)naml, stnam);
                        res = "";
+               } else if (buf->sz + strlen(res) > SHRT_MAX) {
+                       mandoc_msg(MANDOCERR_ROFFLOOP, r->parse,
+                           ln, (int)(stesc - buf->buf), NULL);
+                       return(ROFF_IGN);
                }
 
                /* Replace the escape sequence by the string. */
@@ -657,12 +661,6 @@ roff_res(struct roff *r, struct buf *buf, int ln, int pos)
                buf->sz = mandoc_asprintf(&nbuf, "%s%s%s",
                    buf->buf, res, cp) + 1;
 
-               if (buf->sz > SHRT_MAX) {
-                       mandoc_msg(MANDOCERR_ROFFLOOP, r->parse,
-                           ln, (int)(stesc - buf->buf), NULL);
-                       return(ROFF_IGN);
-               }
-
                /* Prepare for the next replacement. */
 
                start = nbuf + pos;