diff --git a/gdb/ChangeLog b/gdb/ChangeLog
index 4377e12..f2a89f5 100644
--- a/gdb/ChangeLog
+++ b/gdb/ChangeLog
@@ -1,5 +1,78 @@
 2016-12-13  Tom Tromey  <tom@tromey.com>
 
+	* windows-tdep.c (windows_xfer_shared_library): Update.
+	* windows-nat.c (windows_make_so): Update.
+	* utils.h (make_cleanup_bfd_unref): Remove.
+	* utils.c (do_bfd_close_cleanup, make_cleanup_bfd_unref): Remove.
+	* symfile.h (symfile_bfd_open)
+	(find_separate_debug_file_in_section): Return gdb_bfd_ref_ptr.
+	* symfile.c (read_symbols, symbol_file_add)
+	(separate_debug_file_exists): Update.
+	(symfile_bfd_open): Return gdb_bfd_ref_ptr.
+	(generic_load, reread_symbols): Update.
+	* symfile-mem.c (symbol_file_add_from_memory): Update.
+	* spu-linux-nat.c (spu_bfd_open): Return gdb_bfd_ref_ptr.
+	(spu_symbol_file_add_from_memory): Update.
+	* solist.h (struct target_so_ops) <bfd_open>: Return
+	gdb_bfd_ref_ptr.
+	(solib_bfd_fopen, solib_bfd_open): Return gdb_bfd_ref_ptr.
+	* solib.c (solib_bfd_fopen, solib_bfd_open): Return
+	gdb_bfd_ref_ptr.
+	(solib_map_sections, reload_shared_libraries_1): Update.
+	* solib-svr4.c (enable_break): Update.
+	* solib-spu.c (spu_bfd_fopen): Return gdb_bfd_ref_ptr.
+	* solib-frv.c (enable_break2): Update.
+	* solib-dsbt.c (enable_break): Update.
+	* solib-darwin.c (gdb_bfd_mach_o_fat_extract): Return
+	gdb_bfd_ref_ptr.
+	(darwin_solib_get_all_image_info_addr_at_init): Update.
+	(darwin_bfd_open): Return gdb_bfd_ref_ptr.
+	* solib-aix.c (solib_aix_bfd_open): Return gdb_bfd_ref_ptr.
+	* record-full.c (record_full_save): Update.
+	* python/py-objfile.c (objfpy_add_separate_debug_file): Update.
+	* procfs.c (insert_dbx_link_bpt_in_file): Update.
+	* minidebug.c (find_separate_debug_file_in_section): Return
+	gdb_bfd_ref_ptr.
+	* machoread.c (macho_add_oso_symfile): Change abfd to
+	gdb_bfd_ref_ptr.
+	(macho_symfile_read_all_oso): Update.
+	(macho_check_dsym): Return gdb_bfd_ref_ptr.
+	(macho_symfile_read): Update.
+	* jit.c (bfd_open_from_target_memory): Return gdb_bfd_ref_ptr.
+	(jit_bfd_try_read_symtab): Update.
+	* gdb_bfd.h (gdb_bfd_open, gdb_bfd_fopen, gdb_bfd_openr)
+	(gdb_bfd_openw, gdb_bfd_openr_iovec)
+	(gdb_bfd_openr_next_archived_file, gdb_bfd_fdopenr): Return
+	gdb_bfd_ref_ptr.
+	(gdb_bfd_ref_policy): New struct.
+	(gdb_bfd_ref_ptr): New typedef.
+	* gdb_bfd.c (gdb_bfd_open, gdb_bfd_fopen, gdb_bfd_openr)
+	(gdb_bfd_openw, gdb_bfd_openr_iovec)
+	(gdb_bfd_openr_next_archived_file, gdb_bfd_fdopenr): Return
+	gdb_bfd_ref_ptr.
+	* gcore.h (create_gcore_bfd): Return gdb_bfd_ref_ptr.
+	* gcore.c (create_gcore_bfd): Return gdb_bfd_ref_ptr.
+	(gcore_command): Update.
+	* exec.c (exec_file_attach): Update.
+	* elfread.c (elf_symfile_read): Update.
+	* dwarf2read.c (dwarf2_get_dwz_file): Update.
+	(try_open_dwop_file, open_dwo_file): Return gdb_bfd_ref_ptr.
+	(open_and_init_dwo_file): Update.
+	(open_dwp_file): Return gdb_bfd_ref_ptr.
+	(open_and_init_dwp_file): Update.
+	* corelow.c (core_open): Update.
+	* compile/compile-object-load.c (compile_object_load): Update.
+	* common/gdb_ref_ptr.h (ref_ptr::operator->): New operator.
+	* coffread.c (coff_symfile_read): Update.
+	* cli/cli-dump.c (bfd_openr_or_error, bfd_openw_or_error): Return
+	gdb_bfd_ref_ptr.  Rename.
+	(dump_bfd_file, restore_command): Update.
+	* build-id.h (build_id_to_debug_bfd): Return gdb_bfd_ref_ptr.
+	* build-id.c (build_id_to_debug_bfd): Return gdb_bfd_ref_ptr.
+	(find_separate_debug_file_by_buildid): Update.
+
+2016-12-13  Tom Tromey  <tom@tromey.com>
+
 	* common/gdb_ref_ptr.h: New file.
 	* python/py-ref.h (struct gdbpy_ref_policy): New.
 	(gdbpy_ref): Now a typedef.
diff --git a/gdb/build-id.c b/gdb/build-id.c
index 886f2d7..029cb4d 100644
--- a/gdb/build-id.c
+++ b/gdb/build-id.c
@@ -67,14 +67,14 @@ build_id_verify (bfd *abfd, size_t check_len, const bfd_byte *check)
 
 /* See build-id.h.  */
 
-bfd *
+gdb_bfd_ref_ptr
 build_id_to_debug_bfd (size_t build_id_len, const bfd_byte *build_id)
 {
   char *link, *debugdir;
   VEC (char_ptr) *debugdir_vec;
   struct cleanup *back_to;
   int ix;
-  bfd *abfd = NULL;
+  gdb_bfd_ref_ptr abfd;
   int alloc_len;
 
   /* DEBUG_FILE_DIRECTORY/.build-id/ab/cdef */
@@ -127,11 +127,10 @@ build_id_to_debug_bfd (size_t build_id_len, const bfd_byte *build_id)
       if (abfd == NULL)
 	continue;
 
-      if (build_id_verify (abfd, build_id_len, build_id))
+      if (build_id_verify (abfd.get(), build_id_len, build_id))
 	break;
 
-      gdb_bfd_unref (abfd);
-      abfd = NULL;
+      abfd.release ();
     }
 
   do_cleanups (back_to);
@@ -148,25 +147,16 @@ find_separate_debug_file_by_buildid (struct objfile *objfile)
   build_id = build_id_bfd_get (objfile->obfd);
   if (build_id != NULL)
     {
-      bfd *abfd;
-
-      abfd = build_id_to_debug_bfd (build_id->size, build_id->data);
+      gdb_bfd_ref_ptr abfd (build_id_to_debug_bfd (build_id->size,
+						   build_id->data));
       /* Prevent looping on a stripped .debug file.  */
       if (abfd != NULL
-	  && filename_cmp (bfd_get_filename (abfd),
+	  && filename_cmp (bfd_get_filename (abfd.get ()),
 			   objfile_name (objfile)) == 0)
-        {
-	  warning (_("\"%s\": separate debug info file has no debug info"),
-		   bfd_get_filename (abfd));
-	  gdb_bfd_unref (abfd);
-	}
+	warning (_("\"%s\": separate debug info file has no debug info"),
+		 bfd_get_filename (abfd.get ()));
       else if (abfd != NULL)
-	{
-	  char *result = xstrdup (bfd_get_filename (abfd));
-
-	  gdb_bfd_unref (abfd);
-	  return result;
-	}
+	return xstrdup (bfd_get_filename (abfd.get ()));
     }
   return NULL;
 }
diff --git a/gdb/build-id.h b/gdb/build-id.h
index ddf0765..6c37dee 100644
--- a/gdb/build-id.h
+++ b/gdb/build-id.h
@@ -20,6 +20,8 @@
 #ifndef BUILD_ID_H
 #define BUILD_ID_H
 
+#include "gdb_bfd.h"
+
 /* Locate NT_GNU_BUILD_ID from ABFD and return its content.  */
 
 extern const struct bfd_build_id *build_id_bfd_get (bfd *abfd);
@@ -35,8 +37,8 @@ extern int build_id_verify (bfd *abfd,
    return NULL.  The returned reference to the BFD must be released by
    the caller.  */
 
-extern bfd *build_id_to_debug_bfd (size_t build_id_len,
-				   const bfd_byte *build_id);
+extern gdb_bfd_ref_ptr build_id_to_debug_bfd (size_t build_id_len,
+					      const bfd_byte *build_id);
 
 /* Find the separate debug file for OBJFILE, by using the build-id
    associated with OBJFILE's BFD.  If successful, returns a malloc'd
diff --git a/gdb/cli/cli-dump.c b/gdb/cli/cli-dump.c
index 781c638..ace721a 100644
--- a/gdb/cli/cli-dump.c
+++ b/gdb/cli/cli-dump.c
@@ -103,45 +103,40 @@ fopen_with_cleanup (const char *filename, const char *mode)
   return file;
 }
 
-static bfd *
-bfd_openr_with_cleanup (const char *filename, const char *target)
+static gdb_bfd_ref_ptr
+bfd_openr_or_error (const char *filename, const char *target)
 {
-  bfd *ibfd;
-
-  ibfd = gdb_bfd_openr (filename, target);
+  gdb_bfd_ref_ptr ibfd (gdb_bfd_openr (filename, target));
   if (ibfd == NULL)
-    error (_("Failed to open %s: %s."), filename, 
+    error (_("Failed to open %s: %s."), filename,
 	   bfd_errmsg (bfd_get_error ()));
 
-  make_cleanup_bfd_unref (ibfd);
-  if (!bfd_check_format (ibfd, bfd_object))
+  if (!bfd_check_format (ibfd.get (), bfd_object))
     error (_("'%s' is not a recognized file format."), filename);
 
   return ibfd;
 }
 
-static bfd *
-bfd_openw_with_cleanup (const char *filename, const char *target,
-			const char *mode)
+static gdb_bfd_ref_ptr
+bfd_openw_or_error (const char *filename, const char *target, const char *mode)
 {
-  bfd *obfd;
+  gdb_bfd_ref_ptr obfd;
 
   if (*mode == 'w')	/* Write: create new file */
     {
       obfd = gdb_bfd_openw (filename, target);
       if (obfd == NULL)
-	error (_("Failed to open %s: %s."), filename, 
+	error (_("Failed to open %s: %s."), filename,
 	       bfd_errmsg (bfd_get_error ()));
-      make_cleanup_bfd_unref (obfd);
-      if (!bfd_set_format (obfd, bfd_object))
-	error (_("bfd_openw_with_cleanup: %s."), bfd_errmsg (bfd_get_error ()));
+      if (!bfd_set_format (obfd.get (), bfd_object))
+	error (_("bfd_openw_or_error: %s."), bfd_errmsg (bfd_get_error ()));
     }
   else if (*mode == 'a')	/* Append to existing file.  */
     {	/* FIXME -- doesn't work...  */
       error (_("bfd_openw does not work with append."));
     }
   else
-    error (_("bfd_openw_with_cleanup: unknown mode %s."), mode);
+    error (_("bfd_openw_or_error: unknown mode %s."), mode);
 
   return obfd;
 }
@@ -187,20 +182,19 @@ dump_bfd_file (const char *filename, const char *mode,
 	       const char *target, CORE_ADDR vaddr, 
 	       const bfd_byte *buf, ULONGEST len)
 {
-  bfd *obfd;
   asection *osection;
 
-  obfd = bfd_openw_with_cleanup (filename, target, mode);
-  osection = bfd_make_section_anyway (obfd, ".newsec");
-  bfd_set_section_size (obfd, osection, len);
-  bfd_set_section_vma (obfd, osection, vaddr);
-  bfd_set_section_alignment (obfd, osection, 0);
-  bfd_set_section_flags (obfd, osection, (SEC_HAS_CONTENTS
-					  | SEC_ALLOC
-					  | SEC_LOAD));
+  gdb_bfd_ref_ptr obfd (bfd_openw_or_error (filename, target, mode));
+  osection = bfd_make_section_anyway (obfd.get (), ".newsec");
+  bfd_set_section_size (obfd.get (), osection, len);
+  bfd_set_section_vma (obfd.get (), osection, vaddr);
+  bfd_set_section_alignment (obfd.get (), osection, 0);
+  bfd_set_section_flags (obfd.get (), osection, (SEC_HAS_CONTENTS
+						 | SEC_ALLOC
+						 | SEC_LOAD));
   osection->entsize = 0;
-  if (!bfd_set_section_contents (obfd, osection, buf, 0, len))
-    warning (_("writing dump file '%s' (%s)"), filename, 
+  if (!bfd_set_section_contents (obfd.get (), osection, buf, 0, len))
+    warning (_("writing dump file '%s' (%s)"), filename,
 	     bfd_errmsg (bfd_get_error ()));
 }
 
@@ -624,12 +618,11 @@ restore_command (char *args_in, int from_tty)
   else
     {
       /* Open the file for loading.  */
-      ibfd = bfd_openr_with_cleanup (filename, NULL);
+      gdb_bfd_ref_ptr ibfd (bfd_openr_or_error (filename, NULL));
 
       /* Process the sections.  */
-      bfd_map_over_sections (ibfd, restore_section_callback, &data);
+      bfd_map_over_sections (ibfd.get (), restore_section_callback, &data);
     }
-  return;
 }
 
 static void
diff --git a/gdb/coffread.c b/gdb/coffread.c
index 501e901..db32a92 100644
--- a/gdb/coffread.c
+++ b/gdb/coffread.c
@@ -742,10 +742,10 @@ coff_symfile_read (struct objfile *objfile, symfile_add_flags symfile_flags)
 
       if (debugfile)
 	{
-	  bfd *abfd = symfile_bfd_open (debugfile);
+	  gdb_bfd_ref_ptr abfd (symfile_bfd_open (debugfile));
 
-	  make_cleanup_bfd_unref (abfd);
-	  symbol_file_add_separate (abfd, debugfile, symfile_flags, objfile);
+	  symbol_file_add_separate (abfd.get (), debugfile, symfile_flags,
+				    objfile);
 	}
     }
 
diff --git a/gdb/common/gdb_ref_ptr.h b/gdb/common/gdb_ref_ptr.h
index fbf4688..0bb77ec 100644
--- a/gdb/common/gdb_ref_ptr.h
+++ b/gdb/common/gdb_ref_ptr.h
@@ -143,6 +143,12 @@ class ref_ptr
     return result;
   }
 
+  /* Let users refer to members of the underlying pointer.  */
+  T *operator-> () const
+  {
+    return m_obj;
+  }
+
  private:
 
   T *m_obj;
diff --git a/gdb/compile/compile-object-load.c b/gdb/compile/compile-object-load.c
index c08aa2b..7351148 100644
--- a/gdb/compile/compile-object-load.c
+++ b/gdb/compile/compile-object-load.c
@@ -612,7 +612,6 @@ compile_object_load (const compile_file_names &file_names,
 		     enum compile_i_scope_types scope, void *scope_data)
 {
   struct cleanup *cleanups, *cleanups_free_objfile;
-  bfd *abfd;
   struct setup_sections_data setup_sections_data;
   CORE_ADDR addr, regs_addr, out_value_addr = 0;
   struct symbol *func_sym;
@@ -634,17 +633,16 @@ compile_object_load (const compile_file_names &file_names,
   filename = tilde_expand (file_names.object_file ());
   cleanups = make_cleanup (xfree, filename);
 
-  abfd = gdb_bfd_open (filename, gnutarget, -1);
+  gdb_bfd_ref_ptr abfd (gdb_bfd_open (filename, gnutarget, -1));
   if (abfd == NULL)
     error (_("\"%s\": could not open as compiled module: %s"),
           filename, bfd_errmsg (bfd_get_error ()));
-  make_cleanup_bfd_unref (abfd);
 
-  if (!bfd_check_format_matches (abfd, bfd_object, &matching))
+  if (!bfd_check_format_matches (abfd.get (), bfd_object, &matching))
     error (_("\"%s\": not in loadable format: %s"),
           filename, gdb_bfd_errmsg (bfd_get_error (), matching));
 
-  if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC)) != 0)
+  if ((bfd_get_file_flags (abfd.get ()) & (EXEC_P | DYNAMIC)) != 0)
     error (_("\"%s\": not in object format."), filename);
 
   setup_sections_data.last_size = 0;
@@ -653,17 +651,17 @@ compile_object_load (const compile_file_names &file_names,
   setup_sections_data.last_max_alignment = 1;
   setup_sections_data.munmap_list_headp = &munmap_list_head;
   make_cleanup (munmap_listp_free_cleanup, &munmap_list_head);
-  bfd_map_over_sections (abfd, setup_sections, &setup_sections_data);
-  setup_sections (abfd, NULL, &setup_sections_data);
+  bfd_map_over_sections (abfd.get (), setup_sections, &setup_sections_data);
+  setup_sections (abfd.get (), NULL, &setup_sections_data);
 
-  storage_needed = bfd_get_symtab_upper_bound (abfd);
+  storage_needed = bfd_get_symtab_upper_bound (abfd.get ());
   if (storage_needed < 0)
     error (_("Cannot read symbols of compiled module \"%s\": %s"),
           filename, bfd_errmsg (bfd_get_error ()));
 
   /* SYMFILE_VERBOSE is not passed even if FROM_TTY, user is not interested in
      "Reading symbols from ..." message for automatically generated file.  */
-  objfile = symbol_file_add_from_bfd (abfd, filename, 0, NULL, 0, NULL);
+  objfile = symbol_file_add_from_bfd (abfd.get (), filename, 0, NULL, 0, NULL);
   cleanups_free_objfile = make_cleanup_free_objfile (objfile);
 
   func_sym = lookup_global_symbol_from_objfile (objfile,
@@ -712,7 +710,7 @@ compile_object_load (const compile_file_names &file_names,
      called from default_symfile_relocate.  */
   symbol_table = (asymbol **) obstack_alloc (&objfile->objfile_obstack,
 					     storage_needed);
-  number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
+  number_of_symbols = bfd_canonicalize_symtab (abfd.get (), symbol_table);
   if (number_of_symbols < 0)
     error (_("Cannot parse symbols of compiled module \"%s\": %s"),
           filename, bfd_errmsg (bfd_get_error ()));
@@ -771,7 +769,7 @@ compile_object_load (const compile_file_names &file_names,
   if (missing_symbols)
     error (_("%ld symbols were missing, cannot continue."), missing_symbols);
 
-  bfd_map_over_sections (abfd, copy_sections, symbol_table);
+  bfd_map_over_sections (abfd.get (), copy_sections, symbol_table);
 
   regs_type = get_regs_type (func_sym, objfile);
   if (regs_type == NULL)
diff --git a/gdb/corelow.c b/gdb/corelow.c
index 376b7c9..04d2b87 100644
--- a/gdb/corelow.c
+++ b/gdb/corelow.c
@@ -275,7 +275,6 @@ core_open (const char *arg, int from_tty)
   int siggy;
   struct cleanup *old_chain;
   char *temp;
-  bfd *temp_bfd;
   int scratch_chan;
   int flags;
   char *filename;
@@ -310,20 +309,19 @@ core_open (const char *arg, int from_tty)
   if (scratch_chan < 0)
     perror_with_name (filename);
 
-  temp_bfd = gdb_bfd_fopen (filename, gnutarget, 
-			    write_files ? FOPEN_RUB : FOPEN_RB,
-			    scratch_chan);
+  gdb_bfd_ref_ptr temp_bfd (gdb_bfd_fopen (filename, gnutarget, 
+					   write_files ? FOPEN_RUB : FOPEN_RB,
+					   scratch_chan));
   if (temp_bfd == NULL)
     perror_with_name (filename);
 
-  if (!bfd_check_format (temp_bfd, bfd_core)
-      && !gdb_check_format (temp_bfd))
+  if (!bfd_check_format (temp_bfd.get (), bfd_core)
+      && !gdb_check_format (temp_bfd.get ()))
     {
       /* Do it after the err msg */
       /* FIXME: should be checking for errors from bfd_close (for one
          thing, on error it does not free all the storage associated
          with the bfd).  */
-      make_cleanup_bfd_unref (temp_bfd);
       error (_("\"%s\" is not a core dump: %s"),
 	     filename, bfd_errmsg (bfd_get_error ()));
     }
@@ -333,7 +331,7 @@ core_open (const char *arg, int from_tty)
 
   do_cleanups (old_chain);
   unpush_target (&core_ops);
-  core_bfd = temp_bfd;
+  core_bfd = temp_bfd.release ();
   old_chain = make_cleanup (core_close_cleanup, 0 /*ignore*/);
 
   core_gdbarch = gdbarch_from_bfd (core_bfd);
diff --git a/gdb/dwarf2read.c b/gdb/dwarf2read.c
index 9676d59..8748f7c 100644
--- a/gdb/dwarf2read.c
+++ b/gdb/dwarf2read.c
@@ -2479,7 +2479,6 @@ locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
 static struct dwz_file *
 dwarf2_get_dwz_file (void)
 {
-  bfd *dwz_bfd;
   char *data;
   struct cleanup *cleanup;
   const char *filename;
@@ -2523,14 +2522,11 @@ dwarf2_get_dwz_file (void)
 
   /* First try the file name given in the section.  If that doesn't
      work, try to use the build-id instead.  */
-  dwz_bfd = gdb_bfd_open (filename, gnutarget, -1);
+  gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
   if (dwz_bfd != NULL)
     {
-      if (!build_id_verify (dwz_bfd, buildid_len, buildid))
-	{
-	  gdb_bfd_unref (dwz_bfd);
-	  dwz_bfd = NULL;
-	}
+      if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
+	dwz_bfd.release ();
     }
 
   if (dwz_bfd == NULL)
@@ -2542,13 +2538,13 @@ dwarf2_get_dwz_file (void)
 
   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
 			   struct dwz_file);
-  result->dwz_bfd = dwz_bfd;
+  result->dwz_bfd = dwz_bfd.release ();
 
-  bfd_map_over_sections (dwz_bfd, locate_dwz_sections, result);
+  bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
 
   do_cleanups (cleanup);
 
-  gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, dwz_bfd);
+  gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
   dwarf2_per_objfile->dwz_file = result;
   return result;
 }
@@ -10454,10 +10450,9 @@ lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
    If unable to find/open the file, return NULL.
    NOTE: This function is derived from symfile_bfd_open.  */
 
-static bfd *
+static gdb_bfd_ref_ptr
 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
 {
-  bfd *sym_bfd;
   int desc, flags;
   char *absolute_name;
   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
@@ -10486,23 +10481,20 @@ try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
   if (desc < 0)
     return NULL;
 
-  sym_bfd = gdb_bfd_open (absolute_name, gnutarget, desc);
+  gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
   xfree (absolute_name);
   if (sym_bfd == NULL)
     return NULL;
-  bfd_set_cacheable (sym_bfd, 1);
+  bfd_set_cacheable (sym_bfd.get (), 1);
 
-  if (!bfd_check_format (sym_bfd, bfd_object))
-    {
-      gdb_bfd_unref (sym_bfd); /* This also closes desc.  */
-      return NULL;
-    }
+  if (!bfd_check_format (sym_bfd.get (), bfd_object))
+    return NULL;
 
   /* Success.  Record the bfd as having been included by the objfile's bfd.
      This is important because things like demangled_names_hash lives in the
      objfile's per_bfd space and may have references to things like symbol
      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
-  gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd);
+  gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
 
   return sym_bfd;
 }
@@ -10514,11 +10506,9 @@ try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
    Upon success, the canonicalized path of the file is stored in the bfd,
    same as symfile_bfd_open.  */
 
-static bfd *
+static gdb_bfd_ref_ptr
 open_dwo_file (const char *file_name, const char *comp_dir)
 {
-  bfd *abfd;
-
   if (IS_ABSOLUTE_PATH (file_name))
     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
 
@@ -10531,7 +10521,8 @@ open_dwo_file (const char *file_name, const char *comp_dir)
 
       /* NOTE: If comp_dir is a relative path, this will also try the
 	 search path, which seems useful.  */
-      abfd = try_open_dwop_file (path_to_try, 0 /*is_dwp*/, 1 /*search_cwd*/);
+      gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
+						1 /*search_cwd*/));
       xfree (path_to_try);
       if (abfd != NULL)
 	return abfd;
@@ -10617,10 +10608,9 @@ open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
 {
   struct objfile *objfile = dwarf2_per_objfile->objfile;
   struct dwo_file *dwo_file;
-  bfd *dbfd;
   struct cleanup *cleanups;
 
-  dbfd = open_dwo_file (dwo_name, comp_dir);
+  gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
   if (dbfd == NULL)
     {
       if (dwarf_read_debug)
@@ -10630,11 +10620,12 @@ open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
   dwo_file->dwo_name = dwo_name;
   dwo_file->comp_dir = comp_dir;
-  dwo_file->dbfd = dbfd;
+  dwo_file->dbfd = dbfd.release ();
 
   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
 
-  bfd_map_over_sections (dbfd, dwarf2_locate_dwo_sections, &dwo_file->sections);
+  bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
+			 &dwo_file->sections);
 
   dwo_file->cu = create_dwo_cu (dwo_file);
 
@@ -10786,12 +10777,11 @@ allocate_dwp_loaded_cutus_table (struct objfile *objfile)
    Upon success, the canonicalized path of the file is stored in the bfd,
    same as symfile_bfd_open.  */
 
-static bfd *
+static gdb_bfd_ref_ptr
 open_dwp_file (const char *file_name)
 {
-  bfd *abfd;
-
-  abfd = try_open_dwop_file (file_name, 1 /*is_dwp*/, 1 /*search_cwd*/);
+  gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
+					    1 /*search_cwd*/));
   if (abfd != NULL)
     return abfd;
 
@@ -10825,7 +10815,6 @@ open_and_init_dwp_file (void)
   struct objfile *objfile = dwarf2_per_objfile->objfile;
   struct dwp_file *dwp_file;
   char *dwp_name;
-  bfd *dbfd;
   struct cleanup *cleanups = make_cleanup (null_cleanup, 0);
 
   /* Try to find first .dwp for the binary file before any symbolic links
@@ -10847,7 +10836,7 @@ open_and_init_dwp_file (void)
     dwp_name = xstrprintf ("%s.dwp", objfile->original_name);
   make_cleanup (xfree, dwp_name);
 
-  dbfd = open_dwp_file (dwp_name);
+  gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name));
   if (dbfd == NULL
       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
     {
@@ -10865,17 +10854,18 @@ open_and_init_dwp_file (void)
       return NULL;
     }
   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
-  dwp_file->name = bfd_get_filename (dbfd);
-  dwp_file->dbfd = dbfd;
+  dwp_file->name = bfd_get_filename (dbfd.get ());
+  dwp_file->dbfd = dbfd.release ();
   do_cleanups (cleanups);
 
   /* +1: section 0 is unused */
-  dwp_file->num_sections = bfd_count_sections (dbfd) + 1;
+  dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
   dwp_file->elf_sections =
     OBSTACK_CALLOC (&objfile->objfile_obstack,
 		    dwp_file->num_sections, asection *);
 
-  bfd_map_over_sections (dbfd, dwarf2_locate_common_dwp_sections, dwp_file);
+  bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
+			 dwp_file);
 
   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
 
@@ -10895,7 +10885,8 @@ open_and_init_dwp_file (void)
   dwp_file->version = dwp_file->cus->version;
 
   if (dwp_file->version == 2)
-    bfd_map_over_sections (dbfd, dwarf2_locate_v2_dwp_sections, dwp_file);
+    bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
+			   dwp_file);
 
   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
diff --git a/gdb/elfread.c b/gdb/elfread.c
index c6d0fdb..7e2358b 100644
--- a/gdb/elfread.c
+++ b/gdb/elfread.c
@@ -1265,21 +1265,18 @@ elf_symfile_read (struct objfile *objfile, symfile_add_flags symfile_flags)
 	   && objfile->separate_debug_objfile == NULL
 	   && objfile->separate_debug_objfile_backlink == NULL)
     {
-      char *debugfile;
-
-      debugfile = find_separate_debug_file_by_buildid (objfile);
+      gdb::unique_xmalloc_ptr<char> debugfile
+	(find_separate_debug_file_by_buildid (objfile));
 
       if (debugfile == NULL)
-	debugfile = find_separate_debug_file_by_debuglink (objfile);
+	debugfile.reset (find_separate_debug_file_by_debuglink (objfile));
 
-      if (debugfile)
+      if (debugfile != NULL)
 	{
-	  struct cleanup *cleanup = make_cleanup (xfree, debugfile);
-	  bfd *abfd = symfile_bfd_open (debugfile);
+	  gdb_bfd_ref_ptr abfd (symfile_bfd_open (debugfile.get ()));
 
-	  make_cleanup_bfd_unref (abfd);
-	  symbol_file_add_separate (abfd, debugfile, symfile_flags, objfile);
-	  do_cleanups (cleanup);
+	  symbol_file_add_separate (abfd.get (), debugfile.get (),
+				    symfile_flags, objfile);
 	}
     }
 }
diff --git a/gdb/exec.c b/gdb/exec.c
index eeca005..875a675 100644
--- a/gdb/exec.c
+++ b/gdb/exec.c
@@ -258,7 +258,9 @@ exec_file_attach (const char *filename, int from_tty)
      this at the end of the function; but acquiring it now lets the
      BFD cache return it if this call refers to the same file.  */
   gdb_bfd_ref (exec_bfd);
-  cleanups = make_cleanup_bfd_unref (exec_bfd);
+  gdb_bfd_ref_ptr exec_bfd_holder (exec_bfd);
+
+  cleanups = make_cleanup (null_cleanup, NULL);
 
   /* Remove any previous exec file.  */
   exec_close ();
@@ -333,11 +335,13 @@ exec_file_attach (const char *filename, int from_tty)
 	  make_cleanup (xfree, canonical_pathname);
 	}
 
+      gdb_bfd_ref_ptr temp;
       if (write_files && !load_via_target)
-	exec_bfd = gdb_bfd_fopen (canonical_pathname, gnutarget,
-				  FOPEN_RUB, scratch_chan);
+	temp = gdb_bfd_fopen (canonical_pathname, gnutarget,
+			      FOPEN_RUB, scratch_chan);
       else
-	exec_bfd = gdb_bfd_open (canonical_pathname, gnutarget, scratch_chan);
+	temp = gdb_bfd_open (canonical_pathname, gnutarget, scratch_chan);
+      exec_bfd = temp.release ();
 
       if (!exec_bfd)
 	{
diff --git a/gdb/gcore.c b/gdb/gcore.c
index cb4d703..0b05cf9 100644
--- a/gdb/gcore.c
+++ b/gdb/gcore.c
@@ -49,15 +49,15 @@ static int gcore_memory_sections (bfd *);
 /* create_gcore_bfd -- helper for gcore_command (exported).
    Open a new bfd core file for output, and return the handle.  */
 
-bfd *
+gdb_bfd_ref_ptr
 create_gcore_bfd (const char *filename)
 {
-  bfd *obfd = gdb_bfd_openw (filename, default_gcore_target ());
+  gdb_bfd_ref_ptr obfd (gdb_bfd_openw (filename, default_gcore_target ()));
 
-  if (!obfd)
+  if (obfd == NULL)
     error (_("Failed to open '%s' for output."), filename);
-  bfd_set_format (obfd, bfd_core);
-  bfd_set_arch_mach (obfd, default_gcore_arch (), default_gcore_mach ());
+  bfd_set_format (obfd.get (), bfd_core);
+  bfd_set_arch_mach (obfd.get (), default_gcore_arch (), default_gcore_mach ());
   return obfd;
 }
 
@@ -174,7 +174,7 @@ gcore_command (char *args, int from_tty)
 		      "Opening corefile '%s' for output.\n", corefilename);
 
   /* Open the output file.  */
-  obfd = create_gcore_bfd (corefilename);
+  obfd = create_gcore_bfd (corefilename).release ();
 
   /* Need a cleanup that will close and delete the file.  */
   bfd_chain = make_cleanup (do_bfd_delete_cleanup, obfd);
diff --git a/gdb/gcore.h b/gdb/gcore.h
index 91107e0..f4f0545 100644
--- a/gdb/gcore.h
+++ b/gdb/gcore.h
@@ -20,7 +20,9 @@
 #if !defined (GCORE_H)
 #define GCORE_H 1
 
-extern bfd *create_gcore_bfd (const char *filename);
+#include "gdb_bfd.h"
+
+extern gdb_bfd_ref_ptr create_gcore_bfd (const char *filename);
 extern void write_gcore_file (bfd *obfd);
 extern bfd *load_corefile (char *filename, int from_tty);
 extern int objfile_find_memory_regions (struct target_ops *self,
diff --git a/gdb/gdb_bfd.c b/gdb/gdb_bfd.c
index df00f87..c7f02b9 100644
--- a/gdb/gdb_bfd.c
+++ b/gdb/gdb_bfd.c
@@ -356,7 +356,7 @@ gdb_bfd_iovec_fileio_fstat (struct bfd *abfd, void *stream,
 
 /* See gdb_bfd.h.  */
 
-struct bfd *
+gdb_bfd_ref_ptr
 gdb_bfd_open (const char *name, const char *target, int fd)
 {
   hashval_t hash;
@@ -428,7 +428,7 @@ gdb_bfd_open (const char *name, const char *target, int fd)
 			    bfd_get_filename (abfd));
       close (fd);
       gdb_bfd_ref (abfd);
-      return abfd;
+      return gdb_bfd_ref_ptr (abfd);
     }
 
   abfd = bfd_fopen (name, target, FOPEN_RB, fd);
@@ -449,7 +449,7 @@ gdb_bfd_open (const char *name, const char *target, int fd)
     }
 
   gdb_bfd_ref (abfd);
-  return abfd;
+  return gdb_bfd_ref_ptr (abfd);
 }
 
 /* A helper function that releases any section data attached to the
@@ -772,7 +772,7 @@ gdb_bfd_crc (struct bfd *abfd, unsigned long *crc_out)
 
 /* See gdb_bfd.h.  */
 
-bfd *
+gdb_bfd_ref_ptr
 gdb_bfd_fopen (const char *filename, const char *target, const char *mode,
 	       int fd)
 {
@@ -781,12 +781,12 @@ gdb_bfd_fopen (const char *filename, const char *target, const char *mode,
   if (result)
     gdb_bfd_ref (result);
 
-  return result;
+  return gdb_bfd_ref_ptr (result);
 }
 
 /* See gdb_bfd.h.  */
 
-bfd *
+gdb_bfd_ref_ptr
 gdb_bfd_openr (const char *filename, const char *target)
 {
   bfd *result = bfd_openr (filename, target);
@@ -794,12 +794,12 @@ gdb_bfd_openr (const char *filename, const char *target)
   if (result)
     gdb_bfd_ref (result);
 
-  return result;
+  return gdb_bfd_ref_ptr (result);
 }
 
 /* See gdb_bfd.h.  */
 
-bfd *
+gdb_bfd_ref_ptr
 gdb_bfd_openw (const char *filename, const char *target)
 {
   bfd *result = bfd_openw (filename, target);
@@ -807,12 +807,12 @@ gdb_bfd_openw (const char *filename, const char *target)
   if (result)
     gdb_bfd_ref (result);
 
-  return result;
+  return gdb_bfd_ref_ptr (result);
 }
 
 /* See gdb_bfd.h.  */
 
-bfd *
+gdb_bfd_ref_ptr
 gdb_bfd_openr_iovec (const char *filename, const char *target,
 		     void *(*open_func) (struct bfd *nbfd,
 					 void *open_closure),
@@ -835,7 +835,7 @@ gdb_bfd_openr_iovec (const char *filename, const char *target,
   if (result)
     gdb_bfd_ref (result);
 
-  return result;
+  return gdb_bfd_ref_ptr (result);
 }
 
 /* See gdb_bfd.h.  */
@@ -861,7 +861,7 @@ gdb_bfd_mark_parent (bfd *child, bfd *parent)
 
 /* See gdb_bfd.h.  */
 
-bfd *
+gdb_bfd_ref_ptr
 gdb_bfd_openr_next_archived_file (bfd *archive, bfd *previous)
 {
   bfd *result = bfd_openr_next_archived_file (archive, previous);
@@ -869,7 +869,7 @@ gdb_bfd_openr_next_archived_file (bfd *archive, bfd *previous)
   if (result)
     gdb_bfd_mark_parent (result, archive);
 
-  return result;
+  return gdb_bfd_ref_ptr (result);
 }
 
 /* See gdb_bfd.h.  */
@@ -886,7 +886,7 @@ gdb_bfd_record_inclusion (bfd *includer, bfd *includee)
 
 /* See gdb_bfd.h.  */
 
-bfd *
+gdb_bfd_ref_ptr
 gdb_bfd_fdopenr (const char *filename, const char *target, int fd)
 {
   bfd *result = bfd_fdopenr (filename, target, fd);
@@ -894,7 +894,7 @@ gdb_bfd_fdopenr (const char *filename, const char *target, int fd)
   if (result)
     gdb_bfd_ref (result);
 
-  return result;
+  return gdb_bfd_ref_ptr (result);
 }
 
 
diff --git a/gdb/gdb_bfd.h b/gdb/gdb_bfd.h
index a5b5ee9..8c4a60a 100644
--- a/gdb/gdb_bfd.h
+++ b/gdb/gdb_bfd.h
@@ -21,6 +21,7 @@
 #define GDB_BFD_H
 
 #include "registry.h"
+#include "common/gdb_ref_ptr.h"
 
 DECLARE_REGISTRY (bfd);
 
@@ -39,6 +40,34 @@ int is_target_filename (const char *name);
 
 int gdb_bfd_has_target_filename (struct bfd *abfd);
 
+/* Increment the reference count of ABFD.  It is fine for ABFD to be
+   NULL; in this case the function does nothing.  */
+
+void gdb_bfd_ref (struct bfd *abfd);
+
+/* Decrement the reference count of ABFD.  If this is the last
+   reference, ABFD will be freed.  If ABFD is NULL, this function does
+   nothing.  */
+
+void gdb_bfd_unref (struct bfd *abfd);
+
+/* A policy class for gdb::ref_ptr for BFD reference counting.  */
+struct gdb_bfd_ref_policy
+{
+  static void incref (struct bfd *abfd)
+  {
+    gdb_bfd_ref (abfd);
+  }
+
+  static void decref (struct bfd *abfd)
+  {
+    gdb_bfd_unref (abfd);
+  }
+};
+
+/* A gdb::ref_ptr that has been specialized for BFD objects.  */
+typedef gdb::ref_ptr<struct bfd, gdb_bfd_ref_policy> gdb_bfd_ref_ptr;
+
 /* Open a read-only (FOPEN_RB) BFD given arguments like bfd_fopen.
    If NAME starts with TARGET_SYSROOT_PREFIX then the BFD will be
    opened using target fileio operations if necessary.  Returns NULL
@@ -51,18 +80,7 @@ int gdb_bfd_has_target_filename (struct bfd *abfd);
    not be exactly NAME but rather NAME with TARGET_SYSROOT_PREFIX
    stripped.  */
 
-struct bfd *gdb_bfd_open (const char *name, const char *target, int fd);
-
-/* Increment the reference count of ABFD.  It is fine for ABFD to be
-   NULL; in this case the function does nothing.  */
-
-void gdb_bfd_ref (struct bfd *abfd);
-
-/* Decrement the reference count of ABFD.  If this is the last
-   reference, ABFD will be freed.  If ABFD is NULL, this function does
-   nothing.  */
-
-void gdb_bfd_unref (struct bfd *abfd);
+gdb_bfd_ref_ptr gdb_bfd_open (const char *name, const char *target, int fd);
 
 /* Mark the CHILD BFD as being a member of PARENT.  Also, increment
    the reference count of CHILD.  Calling this function ensures that
@@ -110,45 +128,46 @@ int gdb_bfd_crc (struct bfd *abfd, unsigned long *crc_out);
 /* A wrapper for bfd_fopen that initializes the gdb-specific reference
    count.  */
 
-bfd *gdb_bfd_fopen (const char *, const char *, const char *, int);
+gdb_bfd_ref_ptr gdb_bfd_fopen (const char *, const char *, const char *, int);
 
 /* A wrapper for bfd_openr that initializes the gdb-specific reference
    count.  */
 
-bfd *gdb_bfd_openr (const char *, const char *);
+gdb_bfd_ref_ptr gdb_bfd_openr (const char *, const char *);
 
 /* A wrapper for bfd_openw that initializes the gdb-specific reference
    count.  */
 
-bfd *gdb_bfd_openw (const char *, const char *);
+gdb_bfd_ref_ptr gdb_bfd_openw (const char *, const char *);
 
 /* A wrapper for bfd_openr_iovec that initializes the gdb-specific
    reference count.  */
 
-bfd *gdb_bfd_openr_iovec (const char *filename, const char *target,
-			  void *(*open_func) (struct bfd *nbfd,
-					      void *open_closure),
-			  void *open_closure,
-			  file_ptr (*pread_func) (struct bfd *nbfd,
-						  void *stream,
-						  void *buf,
-						  file_ptr nbytes,
-						  file_ptr offset),
-			  int (*close_func) (struct bfd *nbfd,
-					     void *stream),
-			  int (*stat_func) (struct bfd *abfd,
-					    void *stream,
-					    struct stat *sb));
+gdb_bfd_ref_ptr gdb_bfd_openr_iovec (const char *filename, const char *target,
+				     void *(*open_func) (struct bfd *nbfd,
+							 void *open_closure),
+				     void *open_closure,
+				     file_ptr (*pread_func) (struct bfd *nbfd,
+							     void *stream,
+							     void *buf,
+							     file_ptr nbytes,
+							     file_ptr offset),
+				     int (*close_func) (struct bfd *nbfd,
+							void *stream),
+				     int (*stat_func) (struct bfd *abfd,
+						       void *stream,
+						       struct stat *sb));
 
 /* A wrapper for bfd_openr_next_archived_file that initializes the
    gdb-specific reference count.  */
 
-bfd *gdb_bfd_openr_next_archived_file (bfd *archive, bfd *previous);
+gdb_bfd_ref_ptr gdb_bfd_openr_next_archived_file (bfd *archive, bfd *previous);
 
 /* A wrapper for bfd_fdopenr that initializes the gdb-specific
    reference count.  */
 
-bfd *gdb_bfd_fdopenr (const char *filename, const char *target, int fd);
+gdb_bfd_ref_ptr gdb_bfd_fdopenr (const char *filename, const char *target,
+				 int fd);
 
 
 
diff --git a/gdb/jit.c b/gdb/jit.c
index 03b6bd8..2101115 100644
--- a/gdb/jit.c
+++ b/gdb/jit.c
@@ -136,7 +136,7 @@ mem_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
 
 /* Open a BFD from the target's memory.  */
 
-static struct bfd *
+static gdb_bfd_ref_ptr
 bfd_open_from_target_memory (CORE_ADDR addr, ULONGEST size, char *target)
 {
   struct target_buffer *buffer = XNEW (struct target_buffer);
@@ -892,7 +892,6 @@ jit_bfd_try_read_symtab (struct jit_code_entry *code_entry,
                          CORE_ADDR entry_addr,
                          struct gdbarch *gdbarch)
 {
-  bfd *nbfd;
   struct section_addr_info *sai;
   struct bfd_section *sec;
   struct objfile *objfile;
@@ -907,8 +906,9 @@ jit_bfd_try_read_symtab (struct jit_code_entry *code_entry,
 			paddress (gdbarch, code_entry->symfile_addr),
 			pulongest (code_entry->symfile_size));
 
-  nbfd = bfd_open_from_target_memory (code_entry->symfile_addr,
-                                      code_entry->symfile_size, gnutarget);
+  gdb_bfd_ref_ptr nbfd (bfd_open_from_target_memory (code_entry->symfile_addr,
+						     code_entry->symfile_size,
+						     gnutarget));
   if (nbfd == NULL)
     {
       puts_unfiltered (_("Error opening JITed symbol file, ignoring it.\n"));
@@ -917,42 +917,42 @@ jit_bfd_try_read_symtab (struct jit_code_entry *code_entry,
 
   /* Check the format.  NOTE: This initializes important data that GDB uses!
      We would segfault later without this line.  */
-  if (!bfd_check_format (nbfd, bfd_object))
+  if (!bfd_check_format (nbfd.get (), bfd_object))
     {
       printf_unfiltered (_("\
 JITed symbol file is not an object file, ignoring it.\n"));
-      gdb_bfd_unref (nbfd);
       return;
     }
 
   /* Check bfd arch.  */
   b = gdbarch_bfd_arch_info (gdbarch);
-  if (b->compatible (b, bfd_get_arch_info (nbfd)) != b)
+  if (b->compatible (b, bfd_get_arch_info (nbfd.get ())) != b)
     warning (_("JITed object file architecture %s is not compatible "
-               "with target architecture %s."), bfd_get_arch_info
-             (nbfd)->printable_name, b->printable_name);
+               "with target architecture %s."),
+	     bfd_get_arch_info (nbfd.get ())->printable_name,
+	     b->printable_name);
 
   /* Read the section address information out of the symbol file.  Since the
      file is generated by the JIT at runtime, it should all of the absolute
      addresses that we care about.  */
-  sai = alloc_section_addr_info (bfd_count_sections (nbfd));
+  sai = alloc_section_addr_info (bfd_count_sections (nbfd.get ()));
   old_cleanups = make_cleanup_free_section_addr_info (sai);
   i = 0;
   for (sec = nbfd->sections; sec != NULL; sec = sec->next)
-    if ((bfd_get_section_flags (nbfd, sec) & (SEC_ALLOC|SEC_LOAD)) != 0)
+    if ((bfd_get_section_flags (nbfd.get (), sec) & (SEC_ALLOC|SEC_LOAD)) != 0)
       {
         /* We assume that these virtual addresses are absolute, and do not
            treat them as offsets.  */
-        sai->other[i].addr = bfd_get_section_vma (nbfd, sec);
-        sai->other[i].name = xstrdup (bfd_get_section_name (nbfd, sec));
+        sai->other[i].addr = bfd_get_section_vma (nbfd.get (), sec);
+        sai->other[i].name = xstrdup (bfd_get_section_name (nbfd.get (), sec));
         sai->other[i].sectindex = sec->index;
         ++i;
       }
   sai->num_sections = i;
 
   /* This call does not take ownership of SAI.  */
-  make_cleanup_bfd_unref (nbfd);
-  objfile = symbol_file_add_from_bfd (nbfd, bfd_get_filename (nbfd), 0, sai,
+  objfile = symbol_file_add_from_bfd (nbfd.get (),
+				      bfd_get_filename (nbfd.get ()), 0, sai,
 				      OBJF_SHARED | OBJF_NOT_FILENAME, NULL);
 
   do_cleanups (old_cleanups);
diff --git a/gdb/machoread.c b/gdb/machoread.c
index 00f25a4..dd99eb7 100644
--- a/gdb/machoread.c
+++ b/gdb/machoread.c
@@ -429,7 +429,8 @@ macho_resolve_oso_sym_with_minsym (struct objfile *main_objfile, asymbol *sym)
 /* Add oso file OSO/ABFD as a symbol file.  */
 
 static void
-macho_add_oso_symfile (oso_el *oso, bfd *abfd, const char *name,
+macho_add_oso_symfile (oso_el *oso, const gdb_bfd_ref_ptr &abfd,
+		       const char *name,
                        struct objfile *main_objfile,
 		       symfile_add_flags symfile_flags)
 {
@@ -439,7 +440,6 @@ macho_add_oso_symfile (oso_el *oso, bfd *abfd, const char *name,
   asymbol **symp;
   struct bfd_hash_table table;
   int nbr_sections;
-  struct cleanup *cleanup;
 
   /* Per section flag to mark which section have been rebased.  */
   unsigned char *sections_rebased;
@@ -448,18 +448,16 @@ macho_add_oso_symfile (oso_el *oso, bfd *abfd, const char *name,
     printf_unfiltered
       (_("Loading debugging symbols from oso: %s\n"), oso->name);
 
-  if (!bfd_check_format (abfd, bfd_object))
+  if (!bfd_check_format (abfd.get (), bfd_object))
     {
       warning (_("`%s': can't read symbols: %s."), oso->name,
                bfd_errmsg (bfd_get_error ()));
-      gdb_bfd_unref (abfd);
       return;
     }
 
-  if (abfd->my_archive == NULL && oso->mtime != bfd_get_mtime (abfd))
+  if (abfd->my_archive == NULL && oso->mtime != bfd_get_mtime (abfd.get ()))
     {
       warning (_("`%s': file time stamp mismatch."), oso->name);
-      gdb_bfd_unref (abfd);
       return;
     }
 
@@ -468,19 +466,18 @@ macho_add_oso_symfile (oso_el *oso, bfd *abfd, const char *name,
                               oso->nbr_syms))
     {
       warning (_("`%s': can't create hash table"), oso->name);
-      gdb_bfd_unref (abfd);
       return;
     }
 
-  bfd_set_cacheable (abfd, 1);
+  bfd_set_cacheable (abfd.get (), 1);
 
   /* Read symbols table.  */
-  storage = bfd_get_symtab_upper_bound (abfd);
+  storage = bfd_get_symtab_upper_bound (abfd.get ());
   symbol_table = (asymbol **) xmalloc (storage);
-  bfd_canonicalize_symtab (abfd, symbol_table);
+  bfd_canonicalize_symtab (abfd.get (), symbol_table);
 
   /* Init section flags.  */
-  nbr_sections = bfd_count_sections (abfd);
+  nbr_sections = bfd_count_sections (abfd.get ());
   sections_rebased = (unsigned char *) alloca (nbr_sections);
   for (i = 0; i < nbr_sections; i++)
     sections_rebased[i] = 0;
@@ -601,7 +598,7 @@ macho_add_oso_symfile (oso_el *oso, bfd *abfd, const char *name,
                          sec->name, sym->name,
                          paddress (arch, res));
                     }
-                  bfd_set_section_vma (abfd, sec, res);
+                  bfd_set_section_vma (abfd.get (), sec, res);
                   sections_rebased[sec->index] = 1;
                 }
             }
@@ -617,13 +614,12 @@ macho_add_oso_symfile (oso_el *oso, bfd *abfd, const char *name,
 
   /* We need to clear SYMFILE_MAINLINE to avoid interractive question
      from symfile.c:symbol_file_add_with_addrs_or_offsets.  */
-  cleanup = make_cleanup_bfd_unref (abfd);
   symbol_file_add_from_bfd
-    (abfd, name, symfile_flags & ~(SYMFILE_MAINLINE | SYMFILE_VERBOSE), NULL,
+    (abfd.get (), name, symfile_flags & ~(SYMFILE_MAINLINE | SYMFILE_VERBOSE),
+     NULL,
      main_objfile->flags & (OBJF_REORDERED | OBJF_SHARED
 			    | OBJF_READNOW | OBJF_USERLOADED),
      main_objfile);
-  do_cleanups (cleanup);
 }
 
 /* Read symbols from the vector of oso files.
@@ -651,8 +647,6 @@ macho_symfile_read_all_oso (VEC (oso_el) **oso_vector_ptr,
       pfx_len = get_archive_prefix_len (oso->name);
       if (pfx_len > 0)
 	{
-	  bfd *archive_bfd;
-	  bfd *member_bfd;
           int last_ix;
           oso_el *oso2;
           int ix2;
@@ -668,7 +662,8 @@ macho_symfile_read_all_oso (VEC (oso_el) **oso_vector_ptr,
             }
 
 	  /* Open the archive and check the format.  */
-	  archive_bfd = gdb_bfd_open (archive_name.c_str (), gnutarget, -1);
+	  gdb_bfd_ref_ptr archive_bfd (gdb_bfd_open (archive_name.c_str (),
+						     gnutarget, -1));
 	  if (archive_bfd == NULL)
 	    {
 	      warning (_("Could not open OSO archive file \"%s\""),
@@ -676,22 +671,21 @@ macho_symfile_read_all_oso (VEC (oso_el) **oso_vector_ptr,
               ix = last_ix;
 	      continue;
 	    }
-	  if (!bfd_check_format (archive_bfd, bfd_archive))
+	  if (!bfd_check_format (archive_bfd.get (), bfd_archive))
 	    {
 	      warning (_("OSO archive file \"%s\" not an archive."),
 		       archive_name.c_str ());
-	      gdb_bfd_unref (archive_bfd);
               ix = last_ix;
 	      continue;
 	    }
 
-	  member_bfd = gdb_bfd_openr_next_archived_file (archive_bfd, NULL);
+	  gdb_bfd_ref_ptr member_bfd
+	    (gdb_bfd_openr_next_archived_file (archive_bfd.get (), NULL));
 
 	  if (member_bfd == NULL)
 	    {
 	      warning (_("Could not read archive members out of "
 			 "OSO archive \"%s\""), archive_name.c_str ());
-	      gdb_bfd_unref (archive_bfd);
               ix = last_ix;
 	      continue;
 	    }
@@ -699,7 +693,6 @@ macho_symfile_read_all_oso (VEC (oso_el) **oso_vector_ptr,
           /* Load all oso in this library.  */
 	  while (member_bfd != NULL)
 	    {
-	      bfd *prev;
 	      const char *member_name = member_bfd->filename;
               int member_len = strlen (member_name);
 
@@ -721,13 +714,8 @@ macho_symfile_read_all_oso (VEC (oso_el) **oso_vector_ptr,
                     }
                 }
 
-              prev = member_bfd;
-	      member_bfd = gdb_bfd_openr_next_archived_file (archive_bfd,
-							     member_bfd);
-
-              /* Free previous member if not referenced by an oso.  */
-              if (ix2 >= last_ix)
-                gdb_bfd_unref (prev);
+	      member_bfd = gdb_bfd_openr_next_archived_file (archive_bfd.get (),
+							     member_bfd.get ());
 	    }
           for (ix2 = ix; ix2 < last_ix; ix2++)
             {
@@ -741,10 +729,8 @@ macho_symfile_read_all_oso (VEC (oso_el) **oso_vector_ptr,
 	}
       else
 	{
-          bfd *abfd;
-
-	  abfd = gdb_bfd_open (oso->name, gnutarget, -1);
-	  if (!abfd)
+	  gdb_bfd_ref_ptr abfd (gdb_bfd_open (oso->name, gnutarget, -1));
+	  if (abfd == NULL)
             warning (_("`%s': can't open to read symbols: %s."), oso->name,
                      bfd_errmsg (bfd_get_error ()));
           else
@@ -768,7 +754,7 @@ macho_symfile_read_all_oso (VEC (oso_el) **oso_vector_ptr,
    Return NULL if no valid dsym file is found (FILENAMEP is not used in
    such case).  */
 
-static bfd *
+static gdb_bfd_ref_ptr
 macho_check_dsym (struct objfile *objfile, char **filenamep)
 {
   size_t name_len = strlen (objfile_name (objfile));
@@ -776,7 +762,6 @@ macho_check_dsym (struct objfile *objfile, char **filenamep)
   const char *base_name = lbasename (objfile_name (objfile));
   size_t base_len = strlen (base_name);
   char *dsym_filename = (char *) alloca (name_len + dsym_len + base_len + 1);
-  bfd *dsym_bfd;
   bfd_mach_o_load_command *main_uuid;
   bfd_mach_o_load_command *dsym_uuid;
 
@@ -793,25 +778,23 @@ macho_check_dsym (struct objfile *objfile, char **filenamep)
       warning (_("can't find UUID in %s"), objfile_name (objfile));
       return NULL;
     }
-  dsym_bfd = gdb_bfd_openr (dsym_filename, gnutarget);
+  gdb_bfd_ref_ptr dsym_bfd (gdb_bfd_openr (dsym_filename, gnutarget));
   if (dsym_bfd == NULL)
     {
       warning (_("can't open dsym file %s"), dsym_filename);
       return NULL;
     }
 
-  if (!bfd_check_format (dsym_bfd, bfd_object))
+  if (!bfd_check_format (dsym_bfd.get (), bfd_object))
     {
-      gdb_bfd_unref (dsym_bfd);
       warning (_("bad dsym file format: %s"), bfd_errmsg (bfd_get_error ()));
       return NULL;
     }
 
-  if (bfd_mach_o_lookup_command (dsym_bfd,
+  if (bfd_mach_o_lookup_command (dsym_bfd.get (),
                                  BFD_MACH_O_LC_UUID, &dsym_uuid) == 0)
     {
       warning (_("can't find UUID in %s"), dsym_filename);
-      gdb_bfd_unref (dsym_bfd);
       return NULL;
     }
   if (memcmp (dsym_uuid->command.uuid.uuid, main_uuid->command.uuid.uuid,
@@ -819,7 +802,6 @@ macho_check_dsym (struct objfile *objfile, char **filenamep)
     {
       warning (_("dsym file UUID doesn't match the one in %s"),
 	       objfile_name (objfile));
-      gdb_bfd_unref (dsym_bfd);
       return NULL;
     }
   *filenamep = xstrdup (dsym_filename);
@@ -831,7 +813,6 @@ macho_symfile_read (struct objfile *objfile, symfile_add_flags symfile_flags)
 {
   bfd *abfd = objfile->obfd;
   long storage_needed;
-  bfd *dsym_bfd;
   VEC (oso_el) *oso_vector = NULL;
   struct cleanup *old_chain = make_cleanup (VEC_cleanup (oso_el), &oso_vector);
 
@@ -879,7 +860,7 @@ macho_symfile_read (struct objfile *objfile, symfile_add_flags symfile_flags)
       dwarf2_build_frame_info (objfile);
 
       /* Check for DSYM file.  */
-      dsym_bfd = macho_check_dsym (objfile, &dsym_filename);
+      gdb_bfd_ref_ptr dsym_bfd (macho_check_dsym (objfile, &dsym_filename));
       if (dsym_bfd != NULL)
 	{
           struct bfd_section *asect, *dsect;
@@ -896,14 +877,13 @@ macho_symfile_read (struct objfile *objfile, symfile_add_flags symfile_flags)
             {
               if (strcmp (asect->name, dsect->name) != 0)
                 break;
-              bfd_set_section_size (dsym_bfd, dsect,
+              bfd_set_section_size (dsym_bfd.get (), dsect,
                                     bfd_get_section_size (asect));
             }
 
 	  /* Add the dsym file as a separate file.  */
-	  make_cleanup_bfd_unref (dsym_bfd);
-          symbol_file_add_separate (dsym_bfd, dsym_filename, symfile_flags,
-				    objfile);
+          symbol_file_add_separate (dsym_bfd.get (), dsym_filename,
+				    symfile_flags, objfile);
 
 	  /* Don't try to read dwarf2 from main file or shared libraries.  */
 	  do_cleanups (old_chain);
diff --git a/gdb/minidebug.c b/gdb/minidebug.c
index 4323294..61a3971 100644
--- a/gdb/minidebug.c
+++ b/gdb/minidebug.c
@@ -256,11 +256,11 @@ lzma_stat (struct bfd *abfd,
    If we find one we create a iovec based bfd that decompresses the
    object data on demand.  If we don't find one, return NULL.  */
 
-bfd *
+gdb_bfd_ref_ptr
 find_separate_debug_file_in_section (struct objfile *objfile)
 {
   asection *section;
-  bfd *abfd;
+  gdb_bfd_ref_ptr abfd;
 
   if (objfile->obfd == NULL)
     return NULL;
@@ -275,16 +275,14 @@ find_separate_debug_file_in_section (struct objfile *objfile)
   if (abfd == NULL)
     return NULL;
 
-  if (!bfd_check_format (abfd, bfd_object))
+  if (!bfd_check_format (abfd.get (), bfd_object))
     {
       warning (_("Cannot parse .gnu_debugdata section; not a BFD object"));
-      gdb_bfd_unref (abfd);
       return NULL;
     }
 #else
   warning (_("Cannot parse .gnu_debugdata section; LZMA support was "
 	     "disabled at compile time"));
-  abfd = NULL;
 #endif /* !HAVE_LIBLZMA */
 
   return abfd;
diff --git a/gdb/procfs.c b/gdb/procfs.c
index ff814ba..f8fd487 100644
--- a/gdb/procfs.c
+++ b/gdb/procfs.c
@@ -3413,26 +3413,24 @@ dbx_link_addr (bfd *abfd)
 static int
 insert_dbx_link_bpt_in_file (int fd, CORE_ADDR ignored)
 {
-  bfd *abfd;
   long storage_needed;
   CORE_ADDR sym_addr;
 
-  abfd = gdb_bfd_fdopenr ("unamed", 0, fd);
+  gdb_bfd_ref_ptr abfd (gdb_bfd_fdopenr ("unamed", 0, fd));
   if (abfd == NULL)
     {
       warning (_("Failed to create a bfd: %s."), bfd_errmsg (bfd_get_error ()));
       return 0;
     }
 
-  if (!bfd_check_format (abfd, bfd_object))
+  if (!bfd_check_format (abfd.get (), bfd_object))
     {
       /* Not the correct format, so we can not possibly find the dbx_link
 	 symbol in it.	*/
-      gdb_bfd_unref (abfd);
       return 0;
     }
 
-  sym_addr = dbx_link_addr (abfd);
+  sym_addr = dbx_link_addr (abfd.get ());
   if (sym_addr != 0)
     {
       struct breakpoint *dbx_link_bpt;
@@ -3444,14 +3442,11 @@ insert_dbx_link_bpt_in_file (int fd, CORE_ADDR ignored)
       if (dbx_link_bpt == NULL)
 	{
 	  warning (_("Failed to insert dbx_link breakpoint."));
-	  gdb_bfd_unref (abfd);
 	  return 0;
 	}
-      gdb_bfd_unref (abfd);
       return 1;
     }
 
-  gdb_bfd_unref (abfd);
   return 0;
 }
 
diff --git a/gdb/python/py-objfile.c b/gdb/python/py-objfile.c
index 497d0ba..42e26b7 100644
--- a/gdb/python/py-objfile.c
+++ b/gdb/python/py-objfile.c
@@ -445,9 +445,9 @@ objfpy_add_separate_debug_file (PyObject *self, PyObject *args, PyObject *kw)
 
   TRY
     {
-      bfd *abfd = symfile_bfd_open (file_name);
+      gdb_bfd_ref_ptr abfd (symfile_bfd_open (file_name));
 
-      symbol_file_add_separate (abfd, file_name, 0, obj->objfile);
+      symbol_file_add_separate (abfd.get (), file_name, 0, obj->objfile);
     }
   CATCH (except, RETURN_MASK_ALL)
     {
diff --git a/gdb/record-full.c b/gdb/record-full.c
index 5608e70..707cb63 100644
--- a/gdb/record-full.c
+++ b/gdb/record-full.c
@@ -2571,7 +2571,7 @@ record_full_save (struct target_ops *self, const char *recfilename)
 			recfilename);
 
   /* Open the output file.  */
-  obfd = create_gcore_bfd (recfilename);
+  obfd = create_gcore_bfd (recfilename).release ();
   old_cleanups = make_cleanup (record_full_save_cleanups, obfd);
 
   /* Save the current record entry to "cur_record_full_list".  */
diff --git a/gdb/solib-aix.c b/gdb/solib-aix.c
index 75634df..6612f20 100644
--- a/gdb/solib-aix.c
+++ b/gdb/solib-aix.c
@@ -624,7 +624,7 @@ solib_aix_in_dynsym_resolve_code (CORE_ADDR pc)
 
 /* Implement the "bfd_open" target_so_ops method.  */
 
-static bfd *
+static gdb_bfd_ref_ptr
 solib_aix_bfd_open (char *pathname)
 {
   /* The pathname is actually a synthetic filename with the following
@@ -635,11 +635,7 @@ solib_aix_bfd_open (char *pathname)
      to the solib's lm_info here?  */
   const int path_len = strlen (pathname);
   char *sep;
-  char *filename;
   int filename_len;
-  char *member_name;
-  bfd *archive_bfd, *object_bfd;
-  struct cleanup *cleanup;
   int found_file;
   char *found_pathname;
 
@@ -658,69 +654,57 @@ solib_aix_bfd_open (char *pathname)
     }
   filename_len = sep - pathname;
 
-  filename = xstrprintf ("%.*s", filename_len, pathname);
-  cleanup = make_cleanup (xfree, filename);
-  member_name = xstrprintf ("%.*s", path_len - filename_len - 2, sep + 1);
-  make_cleanup (xfree, member_name);
+  std::string filename (string_printf ("%.*s", filename_len, pathname));
+  std::string member_name (string_printf ("%.*s", path_len - filename_len - 2,
+					  sep + 1));
 
   /* Calling solib_find makes certain that sysroot path is set properly
      if program has a dependency on .a archive and sysroot is set via
      set sysroot command.  */
-  found_pathname = solib_find (filename, &found_file);
+  found_pathname = solib_find (&filename[0], &found_file);
   if (found_pathname == NULL)
       perror_with_name (pathname);
-  archive_bfd = solib_bfd_fopen (found_pathname, found_file);
+  gdb_bfd_ref_ptr archive_bfd (solib_bfd_fopen (found_pathname, found_file));
   if (archive_bfd == NULL)
     {
       warning (_("Could not open `%s' as an executable file: %s"),
-	       filename, bfd_errmsg (bfd_get_error ()));
-      do_cleanups (cleanup);
+	       filename.c_str (), bfd_errmsg (bfd_get_error ()));
       return NULL;
     }
 
-  if (bfd_check_format (archive_bfd, bfd_object))
-    {
-      do_cleanups (cleanup);
-      return archive_bfd;
-    }
+  if (bfd_check_format (archive_bfd.get (), bfd_object))
+    return archive_bfd;
 
-  if (! bfd_check_format (archive_bfd, bfd_archive))
+  if (! bfd_check_format (archive_bfd.get (), bfd_archive))
     {
       warning (_("\"%s\": not in executable format: %s."),
-	       filename, bfd_errmsg (bfd_get_error ()));
-      gdb_bfd_unref (archive_bfd);
-      do_cleanups (cleanup);
+	       filename.c_str (), bfd_errmsg (bfd_get_error ()));
       return NULL;
     }
 
-  object_bfd = gdb_bfd_openr_next_archived_file (archive_bfd, NULL);
+  gdb_bfd_ref_ptr object_bfd
+    (gdb_bfd_openr_next_archived_file (archive_bfd.get (), NULL));
   while (object_bfd != NULL)
     {
-      bfd *next;
-
-      if (strcmp (member_name, object_bfd->filename) == 0)
+      if (member_name == object_bfd->filename)
 	break;
 
-      next = gdb_bfd_openr_next_archived_file (archive_bfd, object_bfd);
-      gdb_bfd_unref (object_bfd);
-      object_bfd = next;
+      object_bfd = gdb_bfd_openr_next_archived_file (archive_bfd.get (),
+						     object_bfd.get ());
     }
 
   if (object_bfd == NULL)
     {
-      warning (_("\"%s\": member \"%s\" missing."), filename, member_name);
-      gdb_bfd_unref (archive_bfd);
-      do_cleanups (cleanup);
+      warning (_("\"%s\": member \"%s\" missing."), filename.c_str (),
+	       member_name.c_str ());
       return NULL;
     }
 
-  if (! bfd_check_format (object_bfd, bfd_object))
+  if (! bfd_check_format (object_bfd.get (), bfd_object))
     {
       warning (_("%s(%s): not in object format: %s."),
-	       filename, member_name, bfd_errmsg (bfd_get_error ()));
-      gdb_bfd_unref (archive_bfd);
-      gdb_bfd_unref (object_bfd);
-      do_cleanups (cleanup);
+	       filename.c_str (), member_name.c_str (),
+	       bfd_errmsg (bfd_get_error ()));
       return NULL;
     }
 
@@ -728,12 +712,11 @@ solib_aix_bfd_open (char *pathname)
      along with appended parenthesized member name in order to allow commands
      listing all shared libraries to display.  Otherwise, we would only be
      displaying the name of the archive member object.  */
-  xfree (bfd_get_filename (object_bfd));
+  xfree (bfd_get_filename (object_bfd.get ()));
   object_bfd->filename = xstrprintf ("%s%s",
-                                     bfd_get_filename (archive_bfd), sep);
+                                     bfd_get_filename (archive_bfd.get ()),
+				     sep);
 
-  gdb_bfd_unref (archive_bfd);
-  do_cleanups (cleanup);
   return object_bfd;
 }
 
diff --git a/gdb/solib-darwin.c b/gdb/solib-darwin.c
index 24cf848..51d42c7 100644
--- a/gdb/solib-darwin.c
+++ b/gdb/solib-darwin.c
@@ -427,7 +427,7 @@ darwin_in_dynsym_resolve_code (CORE_ADDR pc)
    counting properly.  This will either return NULL, or return a new
    reference to a BFD.  */
 
-static bfd *
+static gdb_bfd_ref_ptr
 gdb_bfd_mach_o_fat_extract (bfd *abfd, bfd_format format,
 			    const bfd_arch_info_type *arch)
 {
@@ -441,7 +441,7 @@ gdb_bfd_mach_o_fat_extract (bfd *abfd, bfd_format format,
   else
     gdb_bfd_mark_parent (result, abfd);
 
-  return result;
+  return gdb_bfd_ref_ptr (result);
 }
 
 /* Extract dyld_all_image_addr when the process was just created, assuming the
@@ -452,8 +452,6 @@ darwin_solib_get_all_image_info_addr_at_init (struct darwin_info *info)
 {
   char *interp_name;
   CORE_ADDR load_addr = 0;
-  bfd *dyld_bfd = NULL;
-  struct cleanup *cleanup;
 
   /* This method doesn't work with an attached process.  */
   if (current_inferior ()->attach_flag)
@@ -464,42 +462,30 @@ darwin_solib_get_all_image_info_addr_at_init (struct darwin_info *info)
   if (!interp_name)
     return;
 
-  cleanup = make_cleanup (null_cleanup, NULL);
-
   /* Create a bfd for the interpreter.  */
-  dyld_bfd = gdb_bfd_open (interp_name, gnutarget, -1);
-  if (dyld_bfd)
+  gdb_bfd_ref_ptr dyld_bfd (gdb_bfd_open (interp_name, gnutarget, -1));
+  if (dyld_bfd != NULL)
     {
-      bfd *sub;
-
-      make_cleanup_bfd_unref (dyld_bfd);
-      sub = gdb_bfd_mach_o_fat_extract
-	(dyld_bfd, bfd_object, gdbarch_bfd_arch_info (target_gdbarch ()));
-      if (sub)
-	{
-	  dyld_bfd = sub;
-	  make_cleanup_bfd_unref (sub);
-	}
+      gdb_bfd_ref_ptr sub
+	(gdb_bfd_mach_o_fat_extract (dyld_bfd.get (), bfd_object,
+				     gdbarch_bfd_arch_info (target_gdbarch ())));
+      if (sub != NULL)
+	dyld_bfd = sub;
       else
-	dyld_bfd = NULL;
-    }
-  if (!dyld_bfd)
-    {
-      do_cleanups (cleanup);
-      return;
+	dyld_bfd.release ();
     }
+  if (dyld_bfd == NULL)
+    return;
 
   /* We find the dynamic linker's base address by examining
      the current pc (which should point at the entry point for the
      dynamic linker) and subtracting the offset of the entry point.  */
   load_addr = (regcache_read_pc (get_current_regcache ())
-               - bfd_get_start_address (dyld_bfd));
+               - bfd_get_start_address (dyld_bfd.get ()));
 
   /* Now try to set a breakpoint in the dynamic linker.  */
   info->all_image_addr =
-    lookup_symbol_from_bfd (dyld_bfd, "_dyld_all_image_infos");
-
-  do_cleanups (cleanup);
+    lookup_symbol_from_bfd (dyld_bfd.get (), "_dyld_all_image_infos");
 
   if (info->all_image_addr == 0)
     return;
@@ -634,13 +620,11 @@ darwin_lookup_lib_symbol (struct objfile *objfile,
   return (struct block_symbol) {NULL, NULL};
 }
 
-static bfd *
+static gdb_bfd_ref_ptr
 darwin_bfd_open (char *pathname)
 {
   char *found_pathname;
   int found_file;
-  bfd *abfd;
-  bfd *res;
 
   /* Search for shared library file.  */
   found_pathname = solib_find (pathname, &found_file);
@@ -648,24 +632,21 @@ darwin_bfd_open (char *pathname)
     perror_with_name (pathname);
 
   /* Open bfd for shared library.  */
-  abfd = solib_bfd_fopen (found_pathname, found_file);
+  gdb_bfd_ref_ptr abfd (solib_bfd_fopen (found_pathname, found_file));
 
-  res = gdb_bfd_mach_o_fat_extract (abfd, bfd_object,
-				    gdbarch_bfd_arch_info (target_gdbarch ()));
-  if (!res)
-    {
-      make_cleanup_bfd_unref (abfd);
-      error (_("`%s': not a shared-library: %s"),
-	     bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
-    }
+  gdb_bfd_ref_ptr res
+    (gdb_bfd_mach_o_fat_extract (abfd.get (), bfd_object,
+				 gdbarch_bfd_arch_info (target_gdbarch ())));
+  if (res == NULL)
+    error (_("`%s': not a shared-library: %s"),
+	   bfd_get_filename (abfd.get ()), bfd_errmsg (bfd_get_error ()));
 
   /* The current filename for fat-binary BFDs is a name generated
      by BFD, usually a string containing the name of the architecture.
      Reset its value to the actual filename.  */
-  xfree (bfd_get_filename (res));
+  xfree (bfd_get_filename (res.get ()));
   res->filename = xstrdup (pathname);
 
-  gdb_bfd_unref (abfd);
   return res;
 }
 
diff --git a/gdb/solib-dsbt.c b/gdb/solib-dsbt.c
index d66fe5d..14cab05 100644
--- a/gdb/solib-dsbt.c
+++ b/gdb/solib-dsbt.c
@@ -816,7 +816,6 @@ enable_break (void)
     {
       unsigned int interp_sect_size;
       char *buf;
-      bfd *tmp_bfd = NULL;
       CORE_ADDR addr;
       struct int_elf32_dsbt_loadmap *ldm;
       int ret;
@@ -832,6 +831,7 @@ enable_break (void)
 	 loaded so that we can load its symbols and place a breakpoint
 	 in the dynamic linker itself.  */
 
+      gdb_bfd_ref_ptr tmp_bfd;
       TRY
 	{
 	  tmp_bfd = solib_bfd_open (buf);
@@ -852,29 +852,31 @@ enable_break (void)
 
       /* Record the relocated start and end address of the dynamic linker
 	 text and plt section for dsbt_in_dynsym_resolve_code.  */
-      interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
+      interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".text");
       if (interp_sect)
 	{
 	  info->interp_text_sect_low
-	    = bfd_section_vma (tmp_bfd, interp_sect);
+	    = bfd_section_vma (tmp_bfd.get (), interp_sect);
 	  info->interp_text_sect_low
 	    += displacement_from_map (ldm, info->interp_text_sect_low);
 	  info->interp_text_sect_high
 	    = info->interp_text_sect_low
-	    + bfd_section_size (tmp_bfd, interp_sect);
+	    + bfd_section_size (tmp_bfd.get (), interp_sect);
 	}
-      interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
+      interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".plt");
       if (interp_sect)
 	{
 	  info->interp_plt_sect_low =
-	    bfd_section_vma (tmp_bfd, interp_sect);
+	    bfd_section_vma (tmp_bfd.get (), interp_sect);
 	  info->interp_plt_sect_low
 	    += displacement_from_map (ldm, info->interp_plt_sect_low);
 	  info->interp_plt_sect_high =
-	    info->interp_plt_sect_low + bfd_section_size (tmp_bfd, interp_sect);
+	    info->interp_plt_sect_low + bfd_section_size (tmp_bfd.get (),
+							  interp_sect);
 	}
 
-      addr = gdb_bfd_lookup_symbol (tmp_bfd, cmp_name, "_dl_debug_state");
+      addr = gdb_bfd_lookup_symbol (tmp_bfd.get (), cmp_name,
+				    "_dl_debug_state");
       if (addr != 0)
 	{
 	  if (solib_dsbt_debug)
@@ -901,10 +903,7 @@ enable_break (void)
 	  ret = 0;
 	}
 
-      /* We're done with the temporary bfd.  */
-      gdb_bfd_unref (tmp_bfd);
-
-      /* We're also done with the loadmap.  */
+      /* We're done with the loadmap.  */
       xfree (ldm);
 
       return ret;
diff --git a/gdb/solib-frv.c b/gdb/solib-frv.c
index 61a4ed0..0387b44 100644
--- a/gdb/solib-frv.c
+++ b/gdb/solib-frv.c
@@ -532,7 +532,6 @@ enable_break2 (void)
     {
       unsigned int interp_sect_size;
       char *buf;
-      bfd *tmp_bfd = NULL;
       int status;
       CORE_ADDR addr, interp_loadmap_addr;
       gdb_byte addr_buf[FRV_PTR_SIZE];
@@ -554,6 +553,7 @@ enable_break2 (void)
          be trivial on GNU/Linux).  Therefore, we have to try an alternate
          mechanism to find the dynamic linker's base address.  */
 
+      gdb_bfd_ref_ptr tmp_bfd;
       TRY
         {
           tmp_bfd = solib_bfd_open (buf);
@@ -575,7 +575,6 @@ enable_break2 (void)
 	{
 	  warning (_("Unable to determine dynamic linker loadmap address."));
 	  enable_break_failure_warning ();
-	  gdb_bfd_unref (tmp_bfd);
 	  return 0;
 	}
 
@@ -590,41 +589,41 @@ enable_break2 (void)
 	  warning (_("Unable to load dynamic linker loadmap at address %s."),
 	           hex_string_custom (interp_loadmap_addr, 8));
 	  enable_break_failure_warning ();
-	  gdb_bfd_unref (tmp_bfd);
 	  return 0;
 	}
 
       /* Record the relocated start and end address of the dynamic linker
          text and plt section for svr4_in_dynsym_resolve_code.  */
-      interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
+      interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".text");
       if (interp_sect)
 	{
 	  interp_text_sect_low
-	    = bfd_section_vma (tmp_bfd, interp_sect);
+	    = bfd_section_vma (tmp_bfd.get (), interp_sect);
 	  interp_text_sect_low
 	    += displacement_from_map (ldm, interp_text_sect_low);
 	  interp_text_sect_high
-	    = interp_text_sect_low + bfd_section_size (tmp_bfd, interp_sect);
+	    = interp_text_sect_low + bfd_section_size (tmp_bfd.get (),
+						       interp_sect);
 	}
-      interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
+      interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".plt");
       if (interp_sect)
 	{
 	  interp_plt_sect_low =
-	    bfd_section_vma (tmp_bfd, interp_sect);
+	    bfd_section_vma (tmp_bfd.get (), interp_sect);
 	  interp_plt_sect_low
 	    += displacement_from_map (ldm, interp_plt_sect_low);
 	  interp_plt_sect_high =
-	    interp_plt_sect_low + bfd_section_size (tmp_bfd, interp_sect);
+	    interp_plt_sect_low + bfd_section_size (tmp_bfd.get (),
+						    interp_sect);
 	}
 
-      addr = gdb_bfd_lookup_symbol (tmp_bfd, cmp_name, "_dl_debug_addr");
+      addr = gdb_bfd_lookup_symbol (tmp_bfd.get (), cmp_name, "_dl_debug_addr");
 
       if (addr == 0)
 	{
 	  warning (_("Could not find symbol _dl_debug_addr "
 		     "in dynamic linker"));
 	  enable_break_failure_warning ();
-	  gdb_bfd_unref (tmp_bfd);
 	  return 0;
 	}
 
@@ -675,7 +674,6 @@ enable_break2 (void)
 		     "(at address %s) from dynamic linker"),
 	           hex_string_custom (addr + 8, 8));
 	  enable_break_failure_warning ();
-	  gdb_bfd_unref (tmp_bfd);
 	  return 0;
 	}
       addr = extract_unsigned_integer (addr_buf, sizeof addr_buf, byte_order);
@@ -687,15 +685,11 @@ enable_break2 (void)
 		     "(at address %s) from dynamic linker"),
 	           hex_string_custom (addr, 8));
 	  enable_break_failure_warning ();
-	  gdb_bfd_unref (tmp_bfd);
 	  return 0;
 	}
       addr = extract_unsigned_integer (addr_buf, sizeof addr_buf, byte_order);
 
-      /* We're done with the temporary bfd.  */
-      gdb_bfd_unref (tmp_bfd);
-
-      /* We're also done with the loadmap.  */
+      /* We're done with the loadmap.  */
       xfree (ldm);
 
       /* Remove all the solib event breakpoints.  Their addresses
diff --git a/gdb/solib-spu.c b/gdb/solib-spu.c
index fa2977e..ab98656 100644
--- a/gdb/solib-spu.c
+++ b/gdb/solib-spu.c
@@ -319,36 +319,32 @@ spu_bfd_iovec_stat (bfd *abfd, void *stream, struct stat *sb)
   return 0;
 }
 
-static bfd *
+static gdb_bfd_ref_ptr
 spu_bfd_fopen (char *name, CORE_ADDR addr)
 {
-  bfd *nbfd;
   CORE_ADDR *open_closure = XNEW (CORE_ADDR);
 
   *open_closure = addr;
 
-  nbfd = gdb_bfd_openr_iovec (name, "elf32-spu",
-			      spu_bfd_iovec_open, open_closure,
-			      spu_bfd_iovec_pread, spu_bfd_iovec_close,
-			      spu_bfd_iovec_stat);
-  if (!nbfd)
+  gdb_bfd_ref_ptr nbfd (gdb_bfd_openr_iovec (name, "elf32-spu",
+					     spu_bfd_iovec_open, open_closure,
+					     spu_bfd_iovec_pread,
+					     spu_bfd_iovec_close,
+					     spu_bfd_iovec_stat));
+  if (nbfd == NULL)
     return NULL;
 
-  if (!bfd_check_format (nbfd, bfd_object))
-    {
-      gdb_bfd_unref (nbfd);
-      return NULL;
-    }
+  if (!bfd_check_format (nbfd.get (), bfd_object))
+    return NULL;
 
   return nbfd;
 }
 
 /* Open shared library BFD.  */
-static bfd *
+static gdb_bfd_ref_ptr
 spu_bfd_open (char *pathname)
 {
   char *original_name = strrchr (pathname, '@');
-  bfd *abfd;
   asection *spu_name;
   unsigned long long addr;
   int fd;
@@ -362,22 +358,23 @@ spu_bfd_open (char *pathname)
     internal_error (__FILE__, __LINE__, "bad object ID");
 
   /* Open BFD representing SPE executable.  */
-  abfd = spu_bfd_fopen (original_name, (CORE_ADDR) addr);
-  if (!abfd)
+  gdb_bfd_ref_ptr abfd (spu_bfd_fopen (original_name, (CORE_ADDR) addr));
+  if (abfd == NULL)
     error (_("Cannot read SPE executable at %s"), original_name);
 
   /* Retrieve SPU name note.  */
-  spu_name = bfd_get_section_by_name (abfd, ".note.spu_name");
+  spu_name = bfd_get_section_by_name (abfd.get (), ".note.spu_name");
   if (spu_name)
     {
-      int sect_size = bfd_section_size (abfd, spu_name);
+      int sect_size = bfd_section_size (abfd.get (), spu_name);
 
       if (sect_size > 20)
 	{
 	  char *buf
 	    = (char *) alloca (sect_size - 20 + strlen (original_name) + 1);
 
-	  bfd_get_section_contents (abfd, spu_name, buf, 20, sect_size - 20);
+	  bfd_get_section_contents (abfd.get (), spu_name, buf, 20,
+				    sect_size - 20);
 	  buf[sect_size - 20] = '\0';
 
 	  strcat (buf, original_name);
diff --git a/gdb/solib-svr4.c b/gdb/solib-svr4.c
index 0e18292..b801364 100644
--- a/gdb/solib-svr4.c
+++ b/gdb/solib-svr4.c
@@ -2355,7 +2355,6 @@ enable_break (struct svr4_info *info, int from_tty)
       int load_addr_found = 0;
       int loader_found_in_list = 0;
       struct so_list *so;
-      bfd *tmp_bfd = NULL;
       struct target_ops *tmp_bfd_target;
 
       sym_addr = 0;
@@ -2369,6 +2368,7 @@ enable_break (struct svr4_info *info, int from_tty)
          be trivial on GNU/Linux).  Therefore, we have to try an alternate
          mechanism to find the dynamic linker's base address.  */
 
+      gdb_bfd_ref_ptr tmp_bfd;
       TRY
         {
 	  tmp_bfd = solib_bfd_open (interp_name);
@@ -2382,11 +2382,9 @@ enable_break (struct svr4_info *info, int from_tty)
 	goto bkpt_at_symbol;
 
       /* Now convert the TMP_BFD into a target.  That way target, as
-         well as BFD operations can be used.  */
-      tmp_bfd_target = target_bfd_reopen (tmp_bfd);
-      /* target_bfd_reopen acquired its own reference, so we can
-         release ours now.  */
-      gdb_bfd_unref (tmp_bfd);
+         well as BFD operations can be used.  target_bfd_reopen
+         acquires its own reference.  */
+      tmp_bfd_target = target_bfd_reopen (tmp_bfd.get ());
 
       /* On a running target, we can get the dynamic linker's base
          address from the shared library table.  */
@@ -2397,7 +2395,7 @@ enable_break (struct svr4_info *info, int from_tty)
 	    {
 	      load_addr_found = 1;
 	      loader_found_in_list = 1;
-	      load_addr = lm_addr_check (so, tmp_bfd);
+	      load_addr = lm_addr_check (so, tmp_bfd.get ());
 	      break;
 	    }
 	  so = so->next;
@@ -2418,7 +2416,7 @@ enable_break (struct svr4_info *info, int from_tty)
 	    if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
 	      {
 		CORE_ADDR space_size = (CORE_ADDR) 1 << addr_bit;
-		CORE_ADDR tmp_entry_point = exec_entry_point (tmp_bfd,
+		CORE_ADDR tmp_entry_point = exec_entry_point (tmp_bfd.get (),
 							      tmp_bfd_target);
 
 		gdb_assert (load_addr < space_size);
@@ -2447,7 +2445,7 @@ enable_break (struct svr4_info *info, int from_tty)
 	    = get_thread_arch_regcache (inferior_ptid, target_gdbarch ());
 
 	  load_addr = (regcache_read_pc (regcache)
-		       - exec_entry_point (tmp_bfd, tmp_bfd_target));
+		       - exec_entry_point (tmp_bfd.get (), tmp_bfd_target));
 	}
 
       if (!loader_found_in_list)
@@ -2460,29 +2458,30 @@ enable_break (struct svr4_info *info, int from_tty)
 
       /* Record the relocated start and end address of the dynamic linker
          text and plt section for svr4_in_dynsym_resolve_code.  */
-      interp_sect = bfd_get_section_by_name (tmp_bfd, ".text");
+      interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".text");
       if (interp_sect)
 	{
 	  info->interp_text_sect_low =
-	    bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
+	    bfd_section_vma (tmp_bfd.get (), interp_sect) + load_addr;
 	  info->interp_text_sect_high =
 	    info->interp_text_sect_low
-	    + bfd_section_size (tmp_bfd, interp_sect);
+	    + bfd_section_size (tmp_bfd.get (), interp_sect);
 	}
-      interp_sect = bfd_get_section_by_name (tmp_bfd, ".plt");
+      interp_sect = bfd_get_section_by_name (tmp_bfd.get (), ".plt");
       if (interp_sect)
 	{
 	  info->interp_plt_sect_low =
-	    bfd_section_vma (tmp_bfd, interp_sect) + load_addr;
+	    bfd_section_vma (tmp_bfd.get (), interp_sect) + load_addr;
 	  info->interp_plt_sect_high =
 	    info->interp_plt_sect_low
-	    + bfd_section_size (tmp_bfd, interp_sect);
+	    + bfd_section_size (tmp_bfd.get (), interp_sect);
 	}
 
       /* Now try to set a breakpoint in the dynamic linker.  */
       for (bkpt_namep = solib_break_names; *bkpt_namep != NULL; bkpt_namep++)
 	{
-	  sym_addr = gdb_bfd_lookup_symbol (tmp_bfd, cmp_name_and_sec_flags,
+	  sym_addr = gdb_bfd_lookup_symbol (tmp_bfd.get (),
+					    cmp_name_and_sec_flags,
 					    *bkpt_namep);
 	  if (sym_addr != 0)
 	    break;
diff --git a/gdb/solib.c b/gdb/solib.c
index c4b2cdc..7fc4463 100644
--- a/gdb/solib.c
+++ b/gdb/solib.c
@@ -474,15 +474,15 @@ solib_find (char *in_pathname, int *fd)
    function.  If unsuccessful, the FD will be closed (unless FD was
    -1).  */
 
-bfd *
+gdb_bfd_ref_ptr
 solib_bfd_fopen (char *pathname, int fd)
 {
-  bfd *abfd = gdb_bfd_open (pathname, gnutarget, fd);
+  gdb_bfd_ref_ptr abfd (gdb_bfd_open (pathname, gnutarget, fd));
 
-  if (abfd != NULL && !gdb_bfd_has_target_filename (abfd))
-    bfd_set_cacheable (abfd, 1);
+  if (abfd != NULL && !gdb_bfd_has_target_filename (abfd.get ()))
+    bfd_set_cacheable (abfd.get (), 1);
 
-  if (!abfd)
+  if (abfd == NULL)
     {
       make_cleanup (xfree, pathname);
       error (_("Could not open `%s' as an executable file: %s"),
@@ -496,12 +496,11 @@ solib_bfd_fopen (char *pathname, int fd)
 
 /* Find shared library PATHNAME and open a BFD for it.  */
 
-bfd *
+gdb_bfd_ref_ptr
 solib_bfd_open (char *pathname)
 {
   char *found_pathname;
   int found_file;
-  bfd *abfd;
   const struct bfd_arch_info *b;
 
   /* Search for shared library file.  */
@@ -517,22 +516,20 @@ solib_bfd_open (char *pathname)
     }
 
   /* Open bfd for shared library.  */
-  abfd = solib_bfd_fopen (found_pathname, found_file);
+  gdb_bfd_ref_ptr abfd (solib_bfd_fopen (found_pathname, found_file));
 
   /* Check bfd format.  */
-  if (!bfd_check_format (abfd, bfd_object))
-    {
-      make_cleanup_bfd_unref (abfd);
-      error (_("`%s': not in executable format: %s"),
-	     bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
-    }
+  if (!bfd_check_format (abfd.get (), bfd_object))
+    error (_("`%s': not in executable format: %s"),
+	   bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
 
   /* Check bfd arch.  */
   b = gdbarch_bfd_arch_info (target_gdbarch ());
-  if (!b->compatible (b, bfd_get_arch_info (abfd)))
+  if (!b->compatible (b, bfd_get_arch_info (abfd.get ())))
     warning (_("`%s': Shared library architecture %s is not compatible "
                "with target architecture %s."), bfd_get_filename (abfd),
-             bfd_get_arch_info (abfd)->printable_name, b->printable_name);
+             bfd_get_arch_info (abfd.get ())->printable_name,
+	     b->printable_name);
 
   return abfd;
 }
@@ -556,18 +553,17 @@ solib_map_sections (struct so_list *so)
   char *filename;
   struct target_section *p;
   struct cleanup *old_chain;
-  bfd *abfd;
 
   filename = tilde_expand (so->so_name);
   old_chain = make_cleanup (xfree, filename);
-  abfd = ops->bfd_open (filename);
+  gdb_bfd_ref_ptr abfd (ops->bfd_open (filename));
   do_cleanups (old_chain);
 
   if (abfd == NULL)
     return 0;
 
   /* Leave bfd open, core_xfer_memory and "info files" need it.  */
-  so->abfd = abfd;
+  so->abfd = abfd.release ();
 
   /* Copy the full path name into so_name, allowing symbol_file_add
      to find it later.  This also affects the =library-loaded GDB/MI
@@ -575,14 +571,14 @@ solib_map_sections (struct so_list *so)
      the library's host-side path.  If we let the target dictate
      that objfile's path, and the target is different from the host,
      GDB/MI will not provide the correct host-side path.  */
-  if (strlen (bfd_get_filename (abfd)) >= SO_NAME_MAX_PATH_SIZE)
+  if (strlen (bfd_get_filename (so->abfd)) >= SO_NAME_MAX_PATH_SIZE)
     error (_("Shared library file name is too long."));
-  strcpy (so->so_name, bfd_get_filename (abfd));
+  strcpy (so->so_name, bfd_get_filename (so->abfd));
 
-  if (build_section_table (abfd, &so->sections, &so->sections_end))
+  if (build_section_table (so->abfd, &so->sections, &so->sections_end))
     {
       error (_("Can't find the file sections in `%s': %s"),
-	     bfd_get_filename (abfd), bfd_errmsg (bfd_get_error ()));
+	     bfd_get_filename (so->abfd), bfd_errmsg (bfd_get_error ()));
     }
 
   for (p = so->sections; p < so->sections_end; p++)
@@ -1351,7 +1347,6 @@ reload_shared_libraries_1 (int from_tty)
   for (so = so_list_head; so != NULL; so = so->next)
     {
       char *filename, *found_pathname = NULL;
-      bfd *abfd;
       int was_loaded = so->symbols_loaded;
       symfile_add_flags add_flags = SYMFILE_DEFER_BP_RESET;
 
@@ -1360,12 +1355,11 @@ reload_shared_libraries_1 (int from_tty)
 
       filename = tilde_expand (so->so_original_name);
       make_cleanup (xfree, filename);
-      abfd = solib_bfd_open (filename);
+      gdb_bfd_ref_ptr abfd (solib_bfd_open (filename));
       if (abfd != NULL)
 	{
-	  found_pathname = xstrdup (bfd_get_filename (abfd));
+	  found_pathname = xstrdup (bfd_get_filename (abfd.get ()));
 	  make_cleanup (xfree, found_pathname);
-	  gdb_bfd_unref (abfd);
 	}
 
       /* If this shared library is no longer associated with its previous
diff --git a/gdb/solist.h b/gdb/solist.h
index f709483..ca02051 100644
--- a/gdb/solist.h
+++ b/gdb/solist.h
@@ -22,6 +22,7 @@
 #define SO_NAME_MAX_PATH_SIZE 512	/* FIXME: Should be dynamic */
 /* For domain_enum domain.  */
 #include "symtab.h"
+#include "gdb_bfd.h"
 
 /* Forward declaration for target specific link map information.  This
    struct is opaque to all but the target specific file.  */
@@ -121,7 +122,7 @@ struct target_so_ops
     int (*in_dynsym_resolve_code) (CORE_ADDR pc);
 
     /* Find and open shared library binary file.  */
-    bfd *(*bfd_open) (char *pathname);
+    gdb_bfd_ref_ptr (*bfd_open) (char *pathname);
 
     /* Optional extra hook for finding and opening a solib.
        If TEMP_PATHNAME is non-NULL: If the file is successfully opened a
@@ -178,10 +179,10 @@ extern char *exec_file_find (char *in_pathname, int *fd);
 extern char *solib_find (char *in_pathname, int *fd);
 
 /* Open BFD for shared library file.  */
-extern bfd *solib_bfd_fopen (char *pathname, int fd);
+extern gdb_bfd_ref_ptr solib_bfd_fopen (char *pathname, int fd);
 
 /* Find solib binary file and open it.  */
-extern bfd *solib_bfd_open (char *in_pathname);
+extern gdb_bfd_ref_ptr solib_bfd_open (char *in_pathname);
 
 /* FIXME: gdbarch needs to control this variable.  */
 extern struct target_so_ops *current_target_so_ops;
diff --git a/gdb/spu-linux-nat.c b/gdb/spu-linux-nat.c
index f1d58ec..9d333b8 100644
--- a/gdb/spu-linux-nat.c
+++ b/gdb/spu-linux-nat.c
@@ -318,37 +318,35 @@ spu_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
   return 0;
 }
 
-static bfd *
+static gdb_bfd_ref_ptr
 spu_bfd_open (ULONGEST addr)
 {
-  struct bfd *nbfd;
   asection *spu_name;
 
   ULONGEST *open_closure = XNEW (ULONGEST);
   *open_closure = addr;
 
-  nbfd = gdb_bfd_openr_iovec ("<in-memory>", "elf32-spu",
-			      spu_bfd_iovec_open, open_closure,
-			      spu_bfd_iovec_pread, spu_bfd_iovec_close,
-			      spu_bfd_iovec_stat);
-  if (!nbfd)
+  gdb_bfd_ref_ptr nbfd (gdb_bfd_openr_iovec ("<in-memory>", "elf32-spu",
+					     spu_bfd_iovec_open, open_closure,
+					     spu_bfd_iovec_pread,
+					     spu_bfd_iovec_close,
+					     spu_bfd_iovec_stat));
+  if (nbfd == NULL)
     return NULL;
 
-  if (!bfd_check_format (nbfd, bfd_object))
-    {
-      gdb_bfd_unref (nbfd);
-      return NULL;
-    }
+  if (!bfd_check_format (nbfd.get (), bfd_object))
+    return NULL;
 
   /* Retrieve SPU name note and update BFD name.  */
-  spu_name = bfd_get_section_by_name (nbfd, ".note.spu_name");
+  spu_name = bfd_get_section_by_name (nbfd.get (), ".note.spu_name");
   if (spu_name)
     {
-      int sect_size = bfd_section_size (nbfd, spu_name);
+      int sect_size = bfd_section_size (nbfd.get (), spu_name);
       if (sect_size > 20)
 	{
 	  char *buf = (char *)alloca (sect_size - 20 + 1);
-	  bfd_get_section_contents (nbfd, spu_name, buf, 20, sect_size - 20);
+	  bfd_get_section_contents (nbfd.get (), spu_name, buf, 20,
+				    sect_size - 20);
 	  buf[sect_size - 20] = '\0';
 
 	  xfree ((char *)nbfd->filename);
@@ -367,7 +365,6 @@ static void
 spu_symbol_file_add_from_memory (int inferior_fd)
 {
   ULONGEST addr;
-  struct bfd *nbfd;
 
   gdb_byte id[128];
   char annex[32];
@@ -385,15 +382,12 @@ spu_symbol_file_add_from_memory (int inferior_fd)
     return;
 
   /* Open BFD representing SPE executable and read its symbols.  */
-  nbfd = spu_bfd_open (addr);
-  if (nbfd)
+  gdb_bfd_ref_ptr nbfd (spu_bfd_open (addr));
+  if (nbfd != NULL)
     {
-      struct cleanup *cleanup = make_cleanup_bfd_unref (nbfd);
-
-      symbol_file_add_from_bfd (nbfd, bfd_get_filename (nbfd),
+      symbol_file_add_from_bfd (nbfd.get (), bfd_get_filename (nbfd),
 				SYMFILE_VERBOSE | SYMFILE_MAINLINE,
 				NULL, 0, NULL);
-      do_cleanups (cleanup);
     }
 }
 
diff --git a/gdb/symfile-mem.c b/gdb/symfile-mem.c
index 58257b9..ec283b2 100644
--- a/gdb/symfile-mem.c
+++ b/gdb/symfile-mem.c
@@ -102,20 +102,21 @@ symbol_file_add_from_memory (struct bfd *templ, CORE_ADDR addr,
     error (_("Failed to read a valid object file image from memory."));
 
   gdb_bfd_ref (nbfd);
+  /* Manage the new reference for the duration of this function.  */
+  gdb_bfd_ref_ptr nbfd_holder (nbfd);
+
   xfree (bfd_get_filename (nbfd));
   if (name == NULL)
     nbfd->filename = xstrdup ("shared object read from target memory");
   else
     nbfd->filename = name;
 
-  cleanup = make_cleanup_bfd_unref (nbfd);
-
   if (!bfd_check_format (nbfd, bfd_object))
     error (_("Got object file from memory but can't read symbols: %s."),
 	   bfd_errmsg (bfd_get_error ()));
 
   sai = alloc_section_addr_info (bfd_count_sections (nbfd));
-  make_cleanup (xfree, sai);
+  cleanup = make_cleanup (xfree, sai);
   i = 0;
   for (sec = nbfd->sections; sec != NULL; sec = sec->next)
     if ((bfd_get_section_flags (nbfd, sec) & (SEC_ALLOC|SEC_LOAD)) != 0)
diff --git a/gdb/symfile.c b/gdb/symfile.c
index 52f99bf..4775d5b 100644
--- a/gdb/symfile.c
+++ b/gdb/symfile.c
@@ -876,8 +876,7 @@ read_symbols (struct objfile *objfile, symfile_add_flags add_flags)
       && objfile->separate_debug_objfile == NULL
       && objfile->separate_debug_objfile_backlink == NULL)
     {
-      bfd *abfd = find_separate_debug_file_in_section (objfile);
-      struct cleanup *cleanup = make_cleanup_bfd_unref (abfd);
+      gdb_bfd_ref_ptr abfd (find_separate_debug_file_in_section (objfile));
 
       if (abfd != NULL)
 	{
@@ -885,11 +884,9 @@ read_symbols (struct objfile *objfile, symfile_add_flags add_flags)
 	     virtual section-as-bfd like the bfd filename containing the
 	     section.  Therefore use also non-canonical name form for the same
 	     file containing the section.  */
-	  symbol_file_add_separate (abfd, objfile->original_name, add_flags,
-				    objfile);
+	  symbol_file_add_separate (abfd.get (), objfile->original_name,
+				    add_flags, objfile);
 	}
-
-      do_cleanups (cleanup);
     }
   if ((add_flags & SYMFILE_NO_READ) == 0)
     require_partial_symbols (objfile, 0);
@@ -1287,13 +1284,10 @@ struct objfile *
 symbol_file_add (const char *name, symfile_add_flags add_flags,
 		 struct section_addr_info *addrs, objfile_flags flags)
 {
-  bfd *bfd = symfile_bfd_open (name);
-  struct cleanup *cleanup = make_cleanup_bfd_unref (bfd);
-  struct objfile *objf;
+  gdb_bfd_ref_ptr bfd (symfile_bfd_open (name));
 
-  objf = symbol_file_add_from_bfd (bfd, name, add_flags, addrs, flags, NULL);
-  do_cleanups (cleanup);
-  return objf;
+  return symbol_file_add_from_bfd (bfd.get (), name, add_flags, addrs,
+				   flags, NULL);
 }
 
 /* Call symbol_file_add() with default values and update whatever is
@@ -1354,7 +1348,6 @@ separate_debug_file_exists (const char *name, unsigned long crc,
 {
   unsigned long file_crc;
   int file_crc_p;
-  bfd *abfd;
   struct stat parent_stat, abfd_stat;
   int verified_as_different;
 
@@ -1367,9 +1360,9 @@ separate_debug_file_exists (const char *name, unsigned long crc,
   if (filename_cmp (name, objfile_name (parent_objfile)) == 0)
     return 0;
 
-  abfd = gdb_bfd_open (name, gnutarget, -1);
+  gdb_bfd_ref_ptr abfd (gdb_bfd_open (name, gnutarget, -1));
 
-  if (!abfd)
+  if (abfd == NULL)
     return 0;
 
   /* Verify symlinks were not the cause of filename_cmp name difference above.
@@ -1383,24 +1376,19 @@ separate_debug_file_exists (const char *name, unsigned long crc,
      numbers will never set st_ino to zero, this is merely an
      optimization, so we do not need to worry about false negatives.  */
 
-  if (bfd_stat (abfd, &abfd_stat) == 0
+  if (bfd_stat (abfd.get (), &abfd_stat) == 0
       && abfd_stat.st_ino != 0
       && bfd_stat (parent_objfile->obfd, &parent_stat) == 0)
     {
       if (abfd_stat.st_dev == parent_stat.st_dev
 	  && abfd_stat.st_ino == parent_stat.st_ino)
-	{
-	  gdb_bfd_unref (abfd);
-	  return 0;
-	}
+	return 0;
       verified_as_different = 1;
     }
   else
     verified_as_different = 0;
 
-  file_crc_p = gdb_bfd_crc (abfd, &file_crc);
-
-  gdb_bfd_unref (abfd);
+  file_crc_p = gdb_bfd_crc (abfd.get (), &file_crc);
 
   if (!file_crc_p)
     return 0;
@@ -1721,10 +1709,9 @@ set_initial_language (void)
    includes a newly malloc'd` copy of NAME (tilde-expanded and made
    absolute).  In case of trouble, error() is called.  */
 
-bfd *
+gdb_bfd_ref_ptr
 symfile_bfd_open (const char *name)
 {
-  bfd *sym_bfd;
   int desc = -1;
   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
 
@@ -1760,20 +1747,17 @@ symfile_bfd_open (const char *name)
       name = absolute_name;
     }
 
-  sym_bfd = gdb_bfd_open (name, gnutarget, desc);
-  if (!sym_bfd)
+  gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (name, gnutarget, desc));
+  if (sym_bfd == NULL)
     error (_("`%s': can't open to read symbols: %s."), name,
 	   bfd_errmsg (bfd_get_error ()));
 
-  if (!gdb_bfd_has_target_filename (sym_bfd))
-    bfd_set_cacheable (sym_bfd, 1);
+  if (!gdb_bfd_has_target_filename (sym_bfd.get ()))
+    bfd_set_cacheable (sym_bfd.get (), 1);
 
-  if (!bfd_check_format (sym_bfd, bfd_object))
-    {
-      make_cleanup_bfd_unref (sym_bfd);
-      error (_("`%s': can't read symbols: %s."), name,
-	     bfd_errmsg (bfd_get_error ()));
-    }
+  if (!bfd_check_format (sym_bfd.get (), bfd_object))
+    error (_("`%s': can't read symbols: %s."), name,
+	   bfd_errmsg (bfd_get_error ()));
 
   do_cleanups (back_to);
 
@@ -2073,7 +2057,6 @@ static void print_transfer_performance (struct ui_file *stream,
 void
 generic_load (const char *args, int from_tty)
 {
-  bfd *loadfile_bfd;
   char *filename;
   struct cleanup *old_cleanups = make_cleanup (null_cleanup, 0);
   struct load_section_data cbdata;
@@ -2114,25 +2097,23 @@ generic_load (const char *args, int from_tty)
     }
 
   /* Open the file for loading.  */
-  loadfile_bfd = gdb_bfd_open (filename, gnutarget, -1);
+  gdb_bfd_ref_ptr loadfile_bfd (gdb_bfd_open (filename, gnutarget, -1));
   if (loadfile_bfd == NULL)
     {
       perror_with_name (filename);
       return;
     }
 
-  make_cleanup_bfd_unref (loadfile_bfd);
-
-  if (!bfd_check_format (loadfile_bfd, bfd_object))
+  if (!bfd_check_format (loadfile_bfd.get (), bfd_object))
     {
       error (_("\"%s\" is not an object file: %s"), filename,
 	     bfd_errmsg (bfd_get_error ()));
     }
 
-  bfd_map_over_sections (loadfile_bfd, add_section_size_callback,
+  bfd_map_over_sections (loadfile_bfd.get (), add_section_size_callback,
 			 (void *) &total_progress.total_size);
 
-  bfd_map_over_sections (loadfile_bfd, load_section_callback, &cbdata);
+  bfd_map_over_sections (loadfile_bfd.get (), load_section_callback, &cbdata);
 
   using namespace std::chrono;
 
@@ -2144,7 +2125,7 @@ generic_load (const char *args, int from_tty)
 
   steady_clock::time_point end_time = steady_clock::now ();
 
-  entry = bfd_get_start_address (loadfile_bfd);
+  entry = bfd_get_start_address (loadfile_bfd.get ());
   entry = gdbarch_addr_bits_remove (target_gdbarch (), entry);
   ui_out_text (uiout, "Start address ");
   ui_out_field_fmt (uiout, "address", "%s", paddress (target_gdbarch (), entry));
@@ -2568,22 +2549,16 @@ reread_symbols (void)
 
 	  /* Clean up any state BFD has sitting around.  */
 	  {
-	    struct bfd *obfd = objfile->obfd;
+	    gdb_bfd_ref_ptr obfd (objfile->obfd);
 	    char *obfd_filename;
 
 	    obfd_filename = bfd_get_filename (objfile->obfd);
 	    /* Open the new BFD before freeing the old one, so that
 	       the filename remains live.  */
-	    objfile->obfd = gdb_bfd_open (obfd_filename, gnutarget, -1);
+	    gdb_bfd_ref_ptr temp (gdb_bfd_open (obfd_filename, gnutarget, -1));
+	    objfile->obfd = temp.release ();
 	    if (objfile->obfd == NULL)
-	      {
-		/* We have to make a cleanup and error here, rather
-		   than erroring later, because once we unref OBFD,
-		   OBFD_FILENAME will be freed.  */
-		make_cleanup_bfd_unref (obfd);
-		error (_("Can't open %s to read symbols."), obfd_filename);
-	      }
-	    gdb_bfd_unref (obfd);
+	      error (_("Can't open %s to read symbols."), obfd_filename);
 	  }
 
 	  original_name = xstrdup (objfile->original_name);
diff --git a/gdb/symfile.h b/gdb/symfile.h
index 59952cb..7a2e6fb 100644
--- a/gdb/symfile.h
+++ b/gdb/symfile.h
@@ -25,6 +25,7 @@
 #include "probe.h"
 #include "symfile-add-flags.h"
 #include "objfile-flags.h"
+#include "gdb_bfd.h"
 
 /* Opaque declarations.  */
 struct target_section;
@@ -499,7 +500,7 @@ extern void set_initial_language (void);
 
 extern void find_lowest_section (bfd *, asection *, void *);
 
-extern bfd *symfile_bfd_open (const char *);
+extern gdb_bfd_ref_ptr symfile_bfd_open (const char *);
 
 extern int get_section_index (struct objfile *, char *);
 
@@ -646,6 +647,6 @@ extern void elfmdebug_build_psymtabs (struct objfile *,
 
 /* From minidebug.c.  */
 
-extern bfd *find_separate_debug_file_in_section (struct objfile *);
+extern gdb_bfd_ref_ptr find_separate_debug_file_in_section (struct objfile *);
 
 #endif /* !defined(SYMFILE_H) */
diff --git a/gdb/utils.c b/gdb/utils.c
index 77c38bf..6ee6fc8 100644
--- a/gdb/utils.c
+++ b/gdb/utils.c
@@ -151,18 +151,6 @@ make_cleanup_freeargv (char **arg)
   return make_cleanup (do_freeargv, arg);
 }
 
-static void
-do_bfd_close_cleanup (void *arg)
-{
-  gdb_bfd_unref ((bfd *) arg);
-}
-
-struct cleanup *
-make_cleanup_bfd_unref (bfd *abfd)
-{
-  return make_cleanup (do_bfd_close_cleanup, abfd);
-}
-
 /* Helper function which does the work for make_cleanup_fclose.  */
 
 static void
diff --git a/gdb/utils.h b/gdb/utils.h
index 349530e..4407eeb 100644
--- a/gdb/utils.h
+++ b/gdb/utils.h
@@ -81,8 +81,6 @@ extern struct cleanup *(make_cleanup_free_section_addr_info
 
 extern struct cleanup *make_cleanup_fclose (FILE *file);
 
-extern struct cleanup *make_cleanup_bfd_unref (bfd *abfd);
-
 struct obstack;
 extern struct cleanup *make_cleanup_obstack_free (struct obstack *obstack);
 
diff --git a/gdb/windows-nat.c b/gdb/windows-nat.c
index 5b79f34..efccd71 100644
--- a/gdb/windows-nat.c
+++ b/gdb/windows-nat.c
@@ -669,32 +669,27 @@ windows_make_so (const char *name, LPVOID load_addr)
   p = strchr (so->so_name, '\0') - (sizeof ("/cygwin1.dll") - 1);
   if (p >= so->so_name && strcasecmp (p, "/cygwin1.dll") == 0)
     {
-      bfd *abfd;
       asection *text = NULL;
       CORE_ADDR text_vma;
 
-      abfd = gdb_bfd_open (so->so_name, "pei-i386", -1);
+      gdb_bfd_ref_ptr abfd (gdb_bfd_open (so->so_name, "pei-i386", -1));
 
-      if (!abfd)
+      if (abfd == NULL)
 	return so;
 
-      if (bfd_check_format (abfd, bfd_object))
-	text = bfd_get_section_by_name (abfd, ".text");
+      if (bfd_check_format (abfd.get (), bfd_object))
+	text = bfd_get_section_by_name (abfd.get (), ".text");
 
       if (!text)
-	{
-	  gdb_bfd_unref (abfd);
-	  return so;
-	}
+	return so;
 
       /* The symbols in a dll are offset by 0x1000, which is the
 	 offset from 0 of the first byte in an image - because of the
 	 file header and the section alignment.  */
       cygwin_load_start = (CORE_ADDR) (uintptr_t) ((char *)
 						   load_addr + 0x1000);
-      cygwin_load_end = cygwin_load_start + bfd_section_size (abfd, text);
-
-      gdb_bfd_unref (abfd);
+      cygwin_load_end = cygwin_load_start + bfd_section_size (abfd.get (),
+							      text);
     }
 #endif
 
diff --git a/gdb/windows-tdep.c b/gdb/windows-tdep.c
index 810607a..2f79d8d 100644
--- a/gdb/windows-tdep.c
+++ b/gdb/windows-tdep.c
@@ -372,7 +372,6 @@ windows_xfer_shared_library (const char* so_name, CORE_ADDR load_addr,
 			     struct gdbarch *gdbarch, struct obstack *obstack)
 {
   char *p;
-  struct bfd * dll;
   CORE_ADDR text_offset;
 
   obstack_grow_str (obstack, "<library name=\"");
@@ -380,12 +379,11 @@ windows_xfer_shared_library (const char* so_name, CORE_ADDR load_addr,
   obstack_grow_str (obstack, p);
   xfree (p);
   obstack_grow_str (obstack, "\"><segment address=\"");
-  dll = gdb_bfd_open (so_name, gnutarget, -1);
+  gdb_bfd_ref_ptr dll (gdb_bfd_open (so_name, gnutarget, -1));
   /* The following calls are OK even if dll is NULL.
      The default value 0x1000 is returned by pe_text_section_offset
      in that case.  */
-  text_offset = pe_text_section_offset (dll);
-  gdb_bfd_unref (dll);
+  text_offset = pe_text_section_offset (dll.get ());
   obstack_grow_str (obstack, paddress (gdbarch, load_addr + text_offset));
   obstack_grow_str (obstack, "\"/></library>");
 }
