<commit_before>/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */


/*
  Utility program used to signal a safe_process it's time to shutdown

  Usage:
    safe_kill <pid>
*/

#include <windows.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <psapi.h>
#include <dbghelp.h>
#include <tlhelp32.h>

static DWORD find_child(DWORD pid)
{
  HANDLE h= NULL;
  PROCESSENTRY32 pe={ 0 };
  DWORD child_pid = 0;
  pe.dwSize = sizeof(PROCESSENTRY32);
  h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if(h == INVALID_HANDLE_VALUE)
    return 0;

  for (BOOL ret = Process32First(h, &pe); ret; ret = Process32Next(h, &pe))
  {
    if (pe.th32ParentProcessID == pid)
    {
      child_pid = pe.th32ProcessID;
      break;
    }
  }
  CloseHandle(h);
  return (child_pid);
}

static int create_dump(DWORD pid)
{
  char path[MAX_PATH];
  char working_dir[MAX_PATH];
  int ret= -1;
  HANDLE process= INVALID_HANDLE_VALUE;
  HANDLE file= INVALID_HANDLE_VALUE;
  char *p;

  for(;;)
  {
    process= OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, (DWORD)pid);
    if (!process)
    {
      fprintf(stderr,"safe_kill : cannot open process pid=%u to create dump, last error %u\n",
        pid, GetLastError());
      goto exit;
    }

    DWORD size= MAX_PATH;
    if (QueryFullProcessImageName(process, 0, path, &size) == 0)
    {
      fprintf(stderr,"safe_kill : cannot read process path for pid %u, last error %u\n",
        pid, GetLastError());
      goto exit;
    }
    const char *filename= strrchr(path, '\\');
    if (filename)
    {
      filename++;
      // We are not interested in my_safe_process.exe,
      // since it is only used to start up other programs.
      // We're interested however in my_safe_processes' child.
      if (strcmp(filename, "my_safe_process.exe") == 0)
      {
        pid= find_child(pid);
        if (!pid)
        {
          fprintf(stderr,"safe_kill : can't find child process for safe_process.exe\n");
          goto exit;
        }
        CloseHandle(process);
      }
      else
        break;
    }
  }

  if ((p= strrchr(path, '.')) == 0)
    p= path + strlen(path);

  strncpy(p, ".dmp", path + MAX_PATH - p);

  /* Create dump in current directory.*/
  const char *filename= strrchr(path, '\\');
  if (filename == 0)
    filename= path;
  else
    filename++;

  if (!GetCurrentDirectory(MAX_PATH, working_dir))
  {
    fprintf(stderr, "GetCurrentDirectory failed, last error %u",GetLastError());
    goto exit;
  }

  file= CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
    0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

  if (file == INVALID_HANDLE_VALUE)
  {
    fprintf(stderr,"safe_kill : CreateFile() failed for file %s, working dir %s, last error = %u\n",
      filename, working_dir, GetLastError());
    goto exit;
  }

  if (!MiniDumpWriteDump(process, pid, file, MiniDumpNormal, 0,0,0))
  {
    fprintf(stderr, "Failed to write minidump to %s, working dir %s, last error %u\n",
      filename, working_dir, GetLastError());
    goto exit;
  }

  ret= 0;
  fprintf(stderr, "Minidump written to %s, directory %s\n", filename, working_dir);

exit:
  if(process!= 0 && process != INVALID_HANDLE_VALUE)
    CloseHandle(process);

  if (file != 0 && file != INVALID_HANDLE_VALUE)
    CloseHandle(file);
  return ret;
}


int main(int argc, const char** argv )
{
  DWORD pid= -1;
  HANDLE shutdown_event;
  char safe_process_name[32]= {0};
  int retry_open_event= 2;
  /* Ignore any signals */
  signal(SIGINT,   SIG_IGN);
  signal(SIGBREAK, SIG_IGN);
  signal(SIGTERM,  SIG_IGN);

  if ((argc != 2 && argc != 3) || (argc == 3 && strcmp(argv[2],"dump"))) {
    fprintf(stderr, "safe_kill <pid> [dump]\n");
    exit(2);
  }
  pid= atoi(argv[1]);<commit_msg>Windows- "my_safe_kill <pid> dump" will now also dump child processes<commit_after>/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */


/*
  Utility program used to signal a safe_process it's time to shutdown

  Usage:
    safe_kill <pid>
*/

#include <windows.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <psapi.h>
#include <dbghelp.h>
#include <tlhelp32.h>
#include <vector>


static std::vector<DWORD> find_children(DWORD pid)
{
  HANDLE h= NULL;
  PROCESSENTRY32 pe={ 0 };
  std::vector<DWORD> children;

  pe.dwSize = sizeof(PROCESSENTRY32);
  h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if(h == INVALID_HANDLE_VALUE)
    return children;

  for (BOOL ret = Process32First(h, &pe); ret; ret = Process32Next(h, &pe))
  {
    if (pe.th32ParentProcessID == pid)
      children.push_back(pe.th32ProcessID);
  }
  CloseHandle(h);
  return children;
}

void dump_single_process(DWORD pid)
{
  HANDLE file = 0;
  HANDLE process= 0;
  DWORD size= MAX_PATH;
  char path[MAX_PATH];
  char working_dir[MAX_PATH];
  char tmpname[MAX_PATH];

  process= OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
  if (!process)
  {
    fprintf(stderr, "safe_kill : cannot open process pid=%u to create dump, last error %u\n",
      pid, GetLastError());
    goto exit;
  }

  if (QueryFullProcessImageName(process, 0, path, &size) == 0)
  {
    fprintf(stderr, "safe_kill : cannot read process path for pid %u, last error %u\n",
      pid, GetLastError());
    goto exit;
  }

  char *filename= strrchr(path, '\\');
  if (filename)
  {
    filename++;
    // We are not interested in dump of some proceses (my_safe_process.exe,cmd.exe)
    // since they are only used to start up other programs.
    // We're interested however in their children;
    const char *exclude_programs[] = {"my_safe_process.exe","cmd.exe", 0};
    for(size_t i=0; exclude_programs[i]; i++)
      if (_stricmp(filename, exclude_programs[i]) == 0)
        goto exit;
  }
  else
    filename= path;

  // Add .dmp extension
  char *p;
  if ((p= strrchr(filename, '.')) == 0)
    p= filename + strlen(filename);

  strncpy(p, ".dmp", path + MAX_PATH - p);

  // f file with this name exist, generate unique name with .dmp extension
  if (GetFileAttributes(filename) != INVALID_FILE_ATTRIBUTES)
  {
    if (!GetTempFileName(".", filename, 0, tmpname))
    {
      fprintf(stderr, "GetTempFileName failed, last error %u", GetLastError());
      goto exit;
    }
    strncat(tmpname, ".dmp", sizeof(tmpname));
    filename= tmpname;
  }

  
  if (!GetCurrentDirectory(MAX_PATH, working_dir))
  {
    fprintf(stderr, "GetCurrentDirectory failed, last error %u", GetLastError());
    goto exit;
  }

  file= CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
    0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

  if (file == INVALID_HANDLE_VALUE)
  {
    fprintf(stderr, "safe_kill : CreateFile() failed for file %s, working dir %s, last error = %u\n",
      filename, working_dir, GetLastError());
    goto exit;
  }

  if (!MiniDumpWriteDump(process, pid, file, MiniDumpNormal, 0, 0, 0))
  {
    fprintf(stderr, "Failed to write minidump to %s, working dir %s, last error %u\n",
      filename, working_dir, GetLastError());
    goto exit;
  }

  fprintf(stderr, "Minidump written to %s, directory %s\n", filename, working_dir);

exit:
  if (process != 0 && process != INVALID_HANDLE_VALUE)
    CloseHandle(process);

  if (file != 0 && file != INVALID_HANDLE_VALUE)
    CloseHandle(file);
}


static int create_dump(DWORD pid, int recursion_depth= 5)
{
  if (recursion_depth < 0)
    return 0;

  dump_single_process(pid);
  std::vector<DWORD> children= find_children(pid);
  for(size_t i=0; i < children.size(); i++)
    create_dump(children[i], recursion_depth -1);
  return 0;
}


int main(int argc, const char** argv )
{
  DWORD pid= -1;
  HANDLE shutdown_event;
  char safe_process_name[32]= {0};
  int retry_open_event= 2;
  /* Ignore any signals */
  signal(SIGINT,   SIG_IGN);
  signal(SIGBREAK, SIG_IGN);
  signal(SIGTERM,  SIG_IGN);

  if ((argc != 2 && argc != 3) || (argc == 3 && strcmp(argv[2],"dump"))) {
    fprintf(stderr, "safe_kill <pid> [dump]\n");
    exit(2);
  }
  pid= atoi(argv[1]);
{'fraction_non_alphanumeric': 0.12284828397305678, 'fraction_numerical': 0.015182294450978295, 'mean_word_length': 3.443705463182898, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7312211', 'n_tokens_mistral': 3286, 'n_tokens_neox': 3114, 'n_words': 975}