+2015-04-14 Jerry DeLisle <jvdelisle@gcc.gnu.org>
+
+ PR libgfortran/65089
+ * io/format.h (free_format): New function to free memory
+ allocated for building format error messages.
+ * io/format.c (format_error): Add checks before freeing memory
+ to avoid potential segfaults and free formatting data when
+ needed on error conditions. Always allocate and NULL terminate
+ the string.
+ * io/transfer.c (st_read_done, st_write_done): Use new
+ free_format function to clean up memory allocations when done.
+
2015-03-28 Jerry DeLisle <jvdelisle@gcc.gnu.org>
PR libgfortran/65596
}
+/* free_format()-- Free allocated format string. */
+void
+free_format (st_parameter_dt *dtp)
+{
+ if ((dtp->common.flags & IOPARM_DT_HAS_FORMAT) && dtp->format)
+ {
+ free (dtp->format);
+ dtp->format = NULL;
+ }
+}
+
+
/* free_format_data()-- Free all allocated format data. */
void
p = strchr (buffer, '\0');
- memcpy (p, dtp->format, width);
+ if (dtp->format)
+ memcpy (p, dtp->format, width);
p += width;
*p++ = '\n';
*p++ = '^';
*p = '\0';
+ /* Cleanup any left over memory allocations before calling generate
+ error. */
+ if (is_internal_unit (dtp))
+ {
+ if (dtp->format != NULL)
+ {
+ free (dtp->format);
+ dtp->format = NULL;
+ }
+
+ /* Leave these alone if IOSTAT was given because execution will
+ return from generate error in those cases. */
+ if (!(dtp->common.flags & IOPARM_HAS_IOSTAT))
+ {
+ free (dtp->u.p.fmt);
+ free_format_hash_table (dtp->u.p.current_unit);
+ free_internal_unit (dtp);
+ }
+ }
+
generate_error (&dtp->common, LIBERROR_FORMAT, buffer);
}
/* Not found so proceed as follows. */
- if (format_cache_ok)
- {
- char *fmt_string = xmalloc (dtp->format_len + 1);
- memcpy (fmt_string, dtp->format, dtp->format_len);
- dtp->format = fmt_string;
- dtp->format[dtp->format_len] = '\0';
- }
+ char *fmt_string = fc_strdup_notrim (dtp->format, dtp->format_len);
+ dtp->format = fmt_string;
dtp->u.p.fmt = fmt = xmalloc (sizeof (format_data));
fmt->format_string = dtp->format;
else
fmt->error = "Missing initial left parenthesis in format";
- if (fmt->error)
- {
- format_error (dtp, NULL, fmt->error);
- if (format_cache_ok)
- free (dtp->format);
- free_format_hash_table (dtp->u.p.current_unit);
- return;
- }
-
if (format_cache_ok)
save_parsed_format (dtp);
else
dtp->u.p.format_not_saved = 1;
+
+ if (fmt->error)
+ format_error (dtp, NULL, fmt->error);
}
st_read_done (st_parameter_dt *dtp)
{
finalize_transfer (dtp);
+
if (is_internal_unit (dtp) || dtp->u.p.format_not_saved)
- free_format_data (dtp->u.p.fmt);
+ {
+ free_format_data (dtp->u.p.fmt);
+ free_format (dtp);
+ }
+
free_ionml (dtp);
+
if (dtp->u.p.current_unit != NULL)
unlock_unit (dtp->u.p.current_unit);
}
if (is_internal_unit (dtp) || dtp->u.p.format_not_saved)
- free_format_data (dtp->u.p.fmt);
+ {
+ free_format_data (dtp->u.p.fmt);
+ free_format (dtp);
+ }
+
free_ionml (dtp);
+
if (dtp->u.p.current_unit != NULL)
unlock_unit (dtp->u.p.current_unit);