/*
copyright (c) 2012 Kazuki Iwamoto http://www.maid.org/ iwm@maid.org

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <windows.h>
#include <tchar.h>


int
main (int   argc,
      char *argv[])
{
  DWORD dwSize;
  HANDLE hHeap;
  LPSTR *lpszName = NULL;
  LPTSTR lpszEnvironment, lpszPath;

  hHeap = GetProcessHeap ();
  dwSize = GetEnvironmentVariable (_T("Path"), NULL, 0);
  if (dwSize > 0)
    {
      lpszEnvironment = HeapAlloc (hHeap, 0, (dwSize + 1) * sizeof (TCHAR));
      if (GetEnvironmentVariable (_T("Path"), lpszEnvironment, dwSize)
                                                                == dwSize - 1)
        {
          lpszEnvironment[dwSize + 1] = '\0';
          lpszPath = lpszEnvironment;
          while (*lpszPath != '\0' && !lpszName)
            {
              DWORD dwSignature, dwRead;
              HANDLE hFile;
              LPTSTR lpszSeparator, lpszFile;
              IMAGE_DOS_HEADER idh;
              IMAGE_FILE_HEADER ifh;
              IMAGE_OPTIONAL_HEADER ioh;

              for (lpszSeparator = lpszPath;
                            *lpszSeparator != '\0' && *lpszSeparator != ';';
                                                            lpszSeparator++);
              *lpszSeparator = '\0';
              dwSize = lstrlen (lpszPath);
              lpszFile = HeapAlloc (hHeap, 0,
                (dwSize + lstrlen (_T("msvcrt.dll")) + 2) * sizeof (TCHAR));
              lstrcpy (lpszFile, lpszPath);
              if (lpszFile[dwSize - 1] != '\\')
                lstrcat (lpszFile, _T("\\"));
              lstrcat (lpszFile, _T("msvcrt.dll"));
              hFile = CreateFile (lpszFile, GENERIC_READ, FILE_SHARE_READ,
                            NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
              HeapFree (hHeap, 0, lpszFile);
              if (hFile != INVALID_HANDLE_VALUE)
                {
                  if (ReadFile (hFile, &idh,
                                sizeof (IMAGE_DOS_HEADER), &dwRead, NULL)
                    && dwRead == sizeof (IMAGE_DOS_HEADER)
                    && idh.e_magic == IMAGE_DOS_SIGNATURE
                    && SetFilePointer (hFile, idh.e_lfanew, NULL, FILE_BEGIN)
                                                    != INVALID_SET_FILE_POINTER
                    && ReadFile (hFile, &dwSignature,
                                sizeof (DWORD), &dwRead, NULL)
                    && dwRead == sizeof (DWORD)
                    && ReadFile (hFile, &ifh,
                                sizeof (IMAGE_FILE_HEADER), &dwRead, NULL)
                    && dwRead == sizeof (IMAGE_FILE_HEADER)
                    && ifh.NumberOfSections > 0
                    && ReadFile (hFile, &ioh,
                                sizeof (IMAGE_OPTIONAL_HEADER), &dwRead, NULL)
                    && dwRead == sizeof (IMAGE_OPTIONAL_HEADER)
                    && ioh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
                                                        .VirtualAddress > 0)
                    {
                      PIMAGE_SECTION_HEADER pish;

                      pish = HeapAlloc (hHeap, 0,
                        ifh.NumberOfSections * sizeof (IMAGE_SECTION_HEADER));
                      if (ReadFile (hFile, pish,
                        ifh.NumberOfSections * sizeof (IMAGE_SECTION_HEADER),
                                                                &dwRead, NULL)
                        && dwRead == ifh.NumberOfSections
                                            * sizeof (IMAGE_SECTION_HEADER))
                        {
                          int i;
                          IMAGE_EXPORT_DIRECTORY ied;

                          for (i = 0; i < ifh.NumberOfSections; i++)
                            if (pish[i].VirtualAddress
                            <= ioh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
                                                                .VirtualAddress
                            && ioh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
                                                                .VirtualAddress
                            < pish[i].VirtualAddress + pish[i].SizeOfRawData
                                && SetFilePointer (hFile,
                                ioh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
                                                                .VirtualAddress
                                                    - pish[i].VirtualAddress
                                                    + pish[i].PointerToRawData,
                                NULL, FILE_BEGIN) != INVALID_SET_FILE_POINTER
                                && ReadFile (hFile, &ied,
                                sizeof (IMAGE_EXPORT_DIRECTORY), &dwRead, NULL)
                                && dwRead == sizeof (IMAGE_EXPORT_DIRECTORY))
                              {
                                LPDWORD lpdwName;

                                lpdwName = HeapAlloc (hHeap, 0,
                                        ied.NumberOfNames * sizeof (DWORD));
                                for (i = 0; i < ifh.NumberOfSections; i++)
                                  if (pish[i].VirtualAddress
                                                        <= ied.AddressOfNames
                                      && ied.AddressOfNames
                                                    < pish[i].VirtualAddress
                                                    + pish[i].SizeOfRawData
                                      && SetFilePointer (hFile,
                                                    ied.AddressOfNames
                                                    - pish[i].VirtualAddress
                                                    + pish[i].PointerToRawData,
                                                            NULL, FILE_BEGIN)
                                                    != INVALID_SET_FILE_POINTER
                                      && ReadFile (hFile, lpdwName,
                                        ied.NumberOfNames * sizeof (DWORD),
                                                                &dwRead, NULL)
                                      && dwRead == ied.NumberOfNames
                                                            * sizeof (DWORD))
                                    {
                                      lpszName = HeapAlloc (hHeap, 0,
                                                        (ied.NumberOfNames + 1)
                                                            * sizeof (LPSTR));
                                      lpszName[ied.NumberOfNames] = NULL;
                                      for (i = 0; i < ied.NumberOfNames; i++)
                                        {
                                          int j;

                                          lpszName[i] = HeapAlloc (hHeap,
                                            HEAP_ZERO_MEMORY, sizeof (CHAR));
                                          for (j = 0; j < ifh.NumberOfSections;
                                                                        j++)
                                            if (pish[j].VirtualAddress
                                                                <= lpdwName[i]
                                                && lpdwName[i] < pish[j]
                                                                .VirtualAddress
                                                        + pish[j].SizeOfRawData
                                                && SetFilePointer (hFile, 
                                                    lpdwName[i]
                                                    - pish[j].VirtualAddress
                                                    + pish[j].PointerToRawData,
                                                            NULL, FILE_BEGIN)
                                                != INVALID_SET_FILE_POINTER)
                                              {
                                                CHAR cName;

                                                dwSize = 0;
                                                while (ReadFile (hFile, &cName,
                                                        sizeof (CHAR), &dwRead,
                                                                        NULL)
                                                    && dwRead == sizeof (CHAR)
                                                            && cName != '\0')
                                                  {
                                                    lpszName[i] = HeapReAlloc
                                                        (hHeap,
                                                        0,
                                                        lpszName[i],
                                                        (dwSize + 2)
                                                            * sizeof (CHAR));
                                                    (lpszName[i])[dwSize++]
                                                                    = cName;
                                                  }
                                                if (lpszName[i])
                                                  (lpszName[i])[dwSize] = '\0';
                                                break;
                                              }
                                        }
                                      break;
                                    }
                                HeapFree (hHeap, 0, lpdwName);
                                break;
                              }
                        }
                      HeapFree (hHeap, 0, pish);
                    }
                  CloseHandle (hFile);
                }
              lpszPath += lstrlen (lpszPath) + 1;
            }
        }
      HeapFree (hHeap, 0, lpszEnvironment);
    }
  if (lpszName)
    {
      int i;
      DWORD dwWrite;
      HANDLE hFile;
      LPSTR lpszHead = "LIBRARY msvcrt\r\nEXPORTS\r\n";

      hFile = GetStdHandle (STD_OUTPUT_HANDLE);
      WriteFile (hFile, lpszHead,
                        lstrlenA (lpszHead) * sizeof (CHAR), &dwWrite, NULL);
      for (i = 0; lpszName[i]; i++)
        {
          int j;
          LPSTR lpszPrivate[] = {"\?\?_E__non_rtti_object@@UAEPAXI@Z",
                                 "\?\?_Ebad_cast@@UAEPAXI@Z",
                                 "\?\?_Ebad_typeid@@UAEPAXI@Z",
                                 "\?\?_Eexception@@UAEPAXI@Z",
                                 "\?\?_G__non_rtti_object@@UAEPAXI@Z",
                                 "\?\?_Gbad_cast@@UAEPAXI@Z",
                                 "\?\?_Gbad_typeid@@UAEPAXI@Z",
                                 "\?\?_Gexception@@UAEPAXI@Z",
                                 NULL};
          for (j = 0; lpszPrivate[j]; j++)
            if (lstrcmpA (lpszName[i], lpszPrivate[j]) == 0)
              break;
          if (!lpszPrivate[j])
            {
              LPSTR lpszData[] = {"_onexit",
                                  "atexit",
                                  NULL};

              WriteFile (hFile, "\t", sizeof (CHAR), &dwWrite, NULL);
              WriteFile (hFile, lpszName[i],
                    lstrlenA (lpszName[i]) * sizeof (CHAR), &dwWrite, NULL);
              for (j = 0; lpszData[j]; j++)
                if (lstrcmpA (lpszName[i], lpszData[j]) == 0)
                  break;
              if (lpszData[j])
                WriteFile (hFile, " DATA", sizeof (CHAR) * 5, &dwWrite, NULL);
              WriteFile (hFile, "\r\n", sizeof (CHAR) * 2, &dwWrite, NULL);
            }
          HeapFree (hHeap, 0, lpszName[i]);
        }
      HeapFree (hHeap, 0, lpszName);
    }
  return lpszName ? 0 : -1;
}
