Hi All,
I don’t know if this is the correct mailing list to
ask such questions ,If not please bear with this. Re-posting it on this list
coz found no reply in darwin-kernel list.
I am Implementing my own lsof on Mac10.3.0 to get the list
of open files for process ( i.e. file descriptors, file name). Below is the
code snippet describing the problem.
int kread(u_long addr, char *buf,int len);
void process_file(u_long fp);
int main()
{
struct proc kp;
struct filedesc fd;
struct file fl;
struct file **ofb = NULL;
int iNumberofFiles = 0;
int iBlockSize = 0 ;
kd = kvm_open(NULL,
"/dev/mem", NULL, O_RDONLY, NULL);
if (kd == NULL)
{
printf("Error
occured \n");
}
kip = kvm_getprocs(kd, KERN_PROC_ALL, 0,
&cnt);
if (kip == NULL)
{
printf("Error occured during proc read\n");
}
printf("Count of proc structures are
%d\n",cnt);
for (int i = 0; i < cnt; i++)
{
//Reading proc structure
kread((u_long)kip[i].kp_eproc.e_paddr, (char *)&kp, sizeof(kp));
printf("Process Identifier is %d \t
%s\n",kp.p_pid,kp.p_comm,kp.p_cpticks);
// reading filedesc structure
kread((u_long)kp.p_fd, (char *)&fd, sizeof(fd));
printf("Total number of files are %d\n",fd.fd_nfiles);
iNumberofFiles =
fd.fd_nfiles ;
iBlockSize =
sizeof(struct file *) * iNumberofFiles;
ofb = (struct
file **)malloc(iBlockSize);
// reading the list of file structures
if(kread((u_long)fd.fd_ofiles, (char *)ofb, iBlockSize))
printf("ERROR\n");
for(int i = 0; i
< iNumberofFiles ; i++)
{
process_file((u_long)ofb[i]);
}
}
return 0 ;
}
void process_file(u_long fp)
{
struct file fl;
// Why I am not allowed to
use instance of struct file?
int flag;
if
(kread((u_long)fp, (char *)&fl, sizeof(fl)))
{
printf("Error in reading the internal file structure");
}
}
This time I can read struct proc, struct filedesc
using kread() which in turn uses kvm_read() to access the kernel virtual
memory, but when I am declaring struct file fl in method process_file() to read
individual file structures, I am getting compilation error “error: aggregate `file fl' has
incomplete type and cannot be defined”. Unlike struct proc and
struct filedesc I am not able to kread the file structure, which is not
private on Mac10.3.
lsof uses the structures successfully , then why it is
not accessible to my programme.
Is there is any special privilege required to do the
same ? Please help !
Thanks,
Manish