@@ -195,6 +195,15 @@ static int parse_win_cmdline(const char *cmd, char out[][256], int max_args) {
195195 char * o = out [argc ];
196196 size_t oi = 0 ;
197197 bool in_quotes = false;
198+ /* Guard every write: each out[] row is 256 bytes; test args stay well under
199+ * that, but cap defensively so a future longer arg fails a length assertion
200+ * rather than smashing the stack. */
201+ #define PUTO (ch ) \
202+ do { \
203+ if (oi < 255) { \
204+ o[oi++] = (ch); \
205+ } \
206+ } while (0)
198207 for (;;) {
199208 size_t nbs = 0 ;
200209 while (* p == '\\' ) {
@@ -203,24 +212,26 @@ static int parse_win_cmdline(const char *cmd, char out[][256], int max_args) {
203212 }
204213 if (* p == '"' ) {
205214 for (size_t k = 0 ; k < nbs / 2 ; k ++ ) {
206- o [ oi ++ ] = '\\' ;
215+ PUTO ( '\\' ) ;
207216 }
208217 if (nbs % 2 ) {
209- o [ oi ++ ] = '"' ; /* odd run → the quote is an escaped literal */
218+ PUTO ( '"' ) ; /* odd run → the quote is an escaped literal */
210219 } else {
211220 in_quotes = !in_quotes ; /* even run → the quote is a delimiter */
212221 }
213222 p ++ ;
214223 } else {
215224 for (size_t k = 0 ; k < nbs ; k ++ ) {
216- o [ oi ++ ] = '\\' ;
225+ PUTO ( '\\' ) ;
217226 }
218227 if (* p == '\0' || (!in_quotes && (* p == ' ' || * p == '\t' ))) {
219228 break ;
220229 }
221- o [oi ++ ] = * p ++ ;
230+ PUTO (* p );
231+ p ++ ;
222232 }
223233 }
234+ #undef PUTO
224235 o [oi ] = '\0' ;
225236 argc ++ ;
226237 }
@@ -293,6 +304,18 @@ TEST(win_cmdline_overflow_rejected) {
293304 PASS ();
294305}
295306
307+ /* Reproduce-first guard for the overflow CONTRACT (subprocess.h): on overflow buf
308+ * must be left a valid (empty) string. RED on the pre-fix code — the overflow path
309+ * returned without terminating buf, so buf[0] held the first quoted byte ('"') —
310+ * and GREEN once the overflow path sets buf[0] = '\0'. */
311+ TEST (win_cmdline_overflow_leaves_empty_string ) {
312+ char buf [8 ];
313+ const char * const argv [] = {"averylongprogramname" , "x" , NULL };
314+ ASSERT_FALSE (cbm_build_win_cmdline (buf , sizeof (buf ), argv )); /* overflows cap */
315+ ASSERT_EQ (buf [0 ], '\0' ); /* pre-fix: buf[0] == '"' (a partial byte), not NUL */
316+ PASS ();
317+ }
318+
296319SUITE (subprocess ) {
297320 RUN_TEST (subprocess_classify_clean );
298321 RUN_TEST (subprocess_classify_exit_nonzero );
@@ -310,4 +333,5 @@ SUITE(subprocess) {
310333 RUN_TEST (win_cmdline_index_worker_json );
311334 RUN_TEST (win_cmdline_roundtrip_battery );
312335 RUN_TEST (win_cmdline_overflow_rejected );
336+ RUN_TEST (win_cmdline_overflow_leaves_empty_string );
313337}
0 commit comments