+2018-08-01  Zenith  <zenith432@users.sourceforge.net>
+
+       PR 23460
+       * plugin.c (bfd_plugin_open_input): Close file descriptor if the
+       call to fstat fails.
+       (try_claim): Always close the file descriptor at the end of the
+       function.
+       (try_load_plugin): If a plugin has already been registered, then
+       skip the dlopen and onload steps and go straight to claiming the
+       file.  If these is an error, close the plugin.
+
 2018-08-01  Alan Modra  <amodra@gmail.com>
 
        * elf64-ppc.c (plt_stub_pad): Delay plt_stub_size call until needed.
 
 }
 
 /* Register a claim-file handler. */
-static ld_plugin_claim_file_handler claim_file;
+static ld_plugin_claim_file_handler claim_file = NULL;
 
 static enum ld_plugin_status
 register_claim_file (ld_plugin_claim_file_handler handler)
   if (iobfd == ibfd)
     {
       struct stat stat_buf;
+
       if (fstat (file->fd, &stat_buf))
-       return 0;
+       {
+         close(file->fd);
+         return 0;
+       }
+
       file->offset = 0;
       file->filesize = stat_buf.st_size;
     }
   file.handle = abfd;
   if (!bfd_plugin_open_input (abfd, &file))
     return 0;
-  claim_file (&file, &claimed);
-  if (!claimed)
-    close (file.fd);
+  if (claim_file)
+    claim_file (&file, &claimed);
+  close (file.fd);
   return claimed;
 }
 
 static int
 try_load_plugin (const char *pname, bfd *abfd, int *has_plugin_p)
 {
-  void *plugin_handle;
+  void *plugin_handle = NULL;
   struct ld_plugin_tv tv[4];
   int i;
   ld_plugin_onload onload;
   enum ld_plugin_status status;
 
+  if (claim_file)
+    goto have_claim_file;
+
   *has_plugin_p = 0;
 
   plugin_handle = dlopen (pname, RTLD_NOW);
   if (status != LDPS_OK)
     goto err;
 
+have_claim_file:
   *has_plugin_p = 1;
 
   abfd->plugin_format = bfd_plugin_no;
   return 1;
 
  err:
+  if (plugin_handle)
+    dlclose (plugin_handle);
+  register_claim_file (NULL);
   return 0;
 }
 
       int valid_plugin;
 
       full_name = concat (p, "/", ent->d_name, NULL);
-      if (stat(full_name, &s) == 0 && S_ISREG (s.st_mode))
+      if (stat (full_name, &s) == 0 && S_ISREG (s.st_mode))
        found = try_load_plugin (full_name, abfd, &valid_plugin);
       if (has_plugin <= 0)
        has_plugin = valid_plugin;