- if (found) {
- env_copy[index] = fds_env;
- } else {
- /* If the process removed ENV_NAME_FDS from the environment, re-add
- * it. */
- env_copy[count-1] = fds_env;
- env_copy[count] = NULL;
+ int found = 0;
+ char **x_copy = env_copy;
+
+ /* Copy the environment manually; allows skipping elements. */
+ x = env;
+ while ((*x_copy = *x)) {
+ /* Remove ENV_NAME_FDS if we've already used its value. The new
+ * program must use the updated list from ENV_NAME_PRIVATE_FDS. */
+ if (used_fds_set_by_user
+ && !strncmp(*x, ENV_NAME_FDS "=", strlen(ENV_NAME_FDS) + 1)) {
+ x++;
+ continue;
+ /* Update ENV_NAME_PRIVATE_FDS. */
+ } else if (!strncmp(*x, ENV_NAME_PRIVATE_FDS "=",
+ strlen(ENV_NAME_PRIVATE_FDS) + 1)) {
+ *x_copy = fds_env;
+ found = 1;
+ }
+
+ x++;
+ x_copy++;
+ }
+ /* The loop "condition" NULL-terminates env_copy. */
+
+ if (!found) {
+ /* If the process removed ENV_NAME_PRIVATE_FDS from the environment,
+ * re-add it. */
+ *x_copy++ = fds_env;
+ *x_copy++ = NULL;