summaryrefslogtreecommitdiffstats
path: root/winsup/utils/module_info.cc
blob: bf3a18bf35c134f1d569eb9104870ed051e0a17c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* module_info.cc

   Written by Egor Duda <deo@logos-m.ru>

This file is part of Cygwin.

This software is a copyrighted work licensed under the terms of the
Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
details. */

#include <stdlib.h>
#include <windows.h>
#include <psapi.h>
#include "loadlib.h"

/* Returns full name of Dll, which is loaded by hProcess at BaseAddress.
   Uses psapi.dll. */

char *
psapi_get_module_name (HANDLE hProcess, LPVOID BaseAddress)
{
  DWORD len;
  MODULEINFO mi;
  unsigned int i;
  HMODULE dh_buf[1];
  HMODULE *DllHandle = dh_buf;
  DWORD cbNeeded;
  BOOL ok;

  char name_buf[MAX_PATH + 1];

  ok = EnumProcessModules (hProcess, DllHandle, sizeof (HMODULE), &cbNeeded);

  if (!ok || !cbNeeded)
    goto failed;
  DllHandle = (HMODULE *) malloc (cbNeeded);
  if (!DllHandle)
    goto failed;
  ok = EnumProcessModules (hProcess, DllHandle, cbNeeded, &cbNeeded);
  if (!ok)
    {
      free (DllHandle);
      goto failed;
    }

  for (i = 0; i < cbNeeded / sizeof (HMODULE); i++)
    {
      if (!GetModuleInformation (hProcess, DllHandle[i], &mi, sizeof (mi)))
	{
	  free (DllHandle);
	  goto failed;
	}

      len = GetModuleFileNameExA (hProcess, DllHandle[i], name_buf, MAX_PATH);
      if (len == 0)
	{
	  free (DllHandle);
	  goto failed;
	}

      if (mi.lpBaseOfDll == BaseAddress)
	{
	  free (DllHandle);
	  return strdup (name_buf);
	}
    }

failed:
  return NULL;
}