github.com/cnboonhan/delve@v0.0.0-20230908061759-363f2388c2fb/pkg/proc/native/proc_freebsd.c (about)

     1  #include <sys/param.h>
     2  #include <sys/mount.h>
     3  #include <sys/queue.h>
     4  #include <sys/sysctl.h>
     5  
     6  #include <stdlib.h>
     7  #include <string.h>
     8  #include <errno.h>
     9  
    10  #include "proc_freebsd.h"
    11  
    12  /*
    13   * Returns the absolute pathname of the process's executable, if one was found.
    14   * Must be freed by the caller. Sets errno on failure.
    15   */
    16  char * find_executable(int pid) {
    17  	struct procstat *ps;
    18  	struct kinfo_proc *kp;
    19  	char *pathname;
    20  
    21  	/*
    22  	 * procstat_open_sysctl is for running processes. For core files, use
    23  	 * procstat_open_core
    24  	 */
    25  	ps = procstat_open_sysctl();
    26  	kp = kinfo_getproc(pid);
    27  	pathname = malloc(MNAMELEN);
    28  	if (ps && kp && pathname)
    29  		procstat_getpathname(ps, kp, pathname, MNAMELEN);
    30  	free(kp);
    31  	procstat_close(ps);
    32  	return (pathname);
    33  }
    34  
    35  /*
    36   * Returns the comm value of the process, which is usually the basename of its
    37   * executable. Must be freed by the caller.  Sets errno on failure.
    38   */
    39  char * find_command_name(int pid) {
    40  	char *command_name = NULL;
    41  	struct kinfo_proc *kinfo;
    42  
    43  	kinfo = kinfo_getproc(pid);
    44  	if (kinfo != NULL) {
    45  		command_name = malloc(COMMLEN + 1);
    46  		if (command_name != NULL)
    47  			strlcpy(command_name, kinfo->ki_comm, COMMLEN + 1);
    48  		free(kinfo);
    49  	}
    50  
    51  	return (command_name);
    52  }
    53  
    54  int find_status(int pid){
    55  	char status;
    56  	struct kinfo_proc *kinfo;
    57  	kinfo = kinfo_getproc(pid);
    58  	if (kinfo != NULL)
    59  		status = kinfo->ki_stat;
    60  	else
    61  		status = '?';
    62  	free(kinfo);
    63  
    64  	return (status);
    65  }
    66  
    67  uintptr_t get_entry_point(int pid) {
    68      void *ep = NULL;
    69  
    70      errno = EINVAL;
    71  
    72      struct procstat *ps = procstat_open_sysctl();
    73      if (ps == NULL)
    74          return 0;
    75  
    76      uint cnt = 0;
    77      struct kinfo_proc *kipp = procstat_getprocs(ps, KERN_PROC_PID, pid, &cnt);
    78      if (cnt == 0)
    79          return 0;
    80  
    81      Elf_Auxinfo *auxv = procstat_getauxv(ps, kipp, &cnt);
    82      if (auxv == NULL)
    83          return 0;
    84  
    85      for (int i = 0; i < cnt; i++) {
    86          if (auxv[i].a_type == AT_ENTRY) {
    87              ep = auxv[i].a_un.a_ptr;
    88              break;
    89          }
    90      }
    91      procstat_freeauxv(ps, auxv);
    92      errno = 0;
    93      return (uintptr_t)ep;
    94  }