From fd5d477b12eecd6880d06bca40801c5e9dae1ec4 Mon Sep 17 00:00:00 2001
From: Elliott Hughes <enh@google.com>
Date: Tue, 31 Jan 2023 08:24:15 -0800
Subject: [PATCH] vi: don't call open() with O_CREAT but no mode.

This was invisible before because we were calling xopen(), which
always passes mode 0 to open(). Now we're calling open() directly,
bionic's _FORTIFY_SOURCE spots this.

Rather than create with 0600 and then chmod() later as the code
used to do, move the stat() before the creation so we can supply
the final permissions from the beginning.

Also rewrite the default permissions in octal, in keeping with
toybox style.
---
 toys/pending/vi.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/toys/pending/vi.c b/toys/pending/vi.c
index e12713da..22a08690 100644
--- a/toys/pending/vi.c
+++ b/toys/pending/vi.c
@@ -570,9 +570,11 @@ static int write_file(char *filename)
     return -1;
   }
 
+  if (stat(filename, &st) == -1) st.st_mode = 0644;
+
   sprintf(toybuf, "%s.swp", filename);
 
-  if ((fd = open(toybuf, O_WRONLY | O_CREAT | O_TRUNC)) == -1) {
+  if ((fd = open(toybuf, O_WRONLY | O_CREAT | O_TRUNC, st.st_mode)) == -1) {
     show_error("Couldn't open \"%s\" for writing: %s", toybuf, strerror(errno));
     return -1;
   }
@@ -587,8 +589,6 @@ static int write_file(char *filename)
   linelist_unload();
 
   xclose(fd);
-  if (!stat(filename, &st)) chmod(toybuf, st.st_mode);
-  else chmod(toybuf, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
   xrename(toybuf, filename);
   linelist_load(filename, 0);
   return 0;
-- 
2.39.1.456.gfc5497dd1b-goog

