Esempio n. 1
0
static void *WSF_CALL
wsf_malloc_wrapper (
    axutil_allocator_t * allocator,
    size_t size)
{
    return ruby_xmalloc(size);
}
Esempio n. 2
0
static VALUE dir_s_entries(VALUE klass, VALUE v_dir){
  HANDLE fhandle;
  WIN32_FIND_DATA data;
  VALUE v_array;
  char* path;

  Check_Type(v_dir, T_STRING);

  memset(&data, 0, sizeof(data));
  v_array = rb_ary_new();

  // Append *.* to base path since that will be used for reads, etc.
  path = (char*)ruby_xmalloc(RSTRING_LEN(v_dir) + strlen("/*.*") + 1);
  sprintf(path, "%s%s", RSTRING_PTR(v_dir), "/*.*");

  fhandle = FindFirstFileEx(path, FindExInfoBasic, &data, FindExSearchNameMatch, NULL, 0);

  if (fhandle == INVALID_HANDLE_VALUE)
    rb_raise_win_error("FindFirstFileEx", GetLastError());
  else
    rb_ary_push(v_array, rb_str_new2(data.cFileName));

  while(FindNextFile(fhandle, &data))
    rb_ary_push(v_array, rb_str_new2(data.cFileName));

  FindClose(fhandle);

  return v_array;
}
Esempio n. 3
0
static VALUE get_trnsl_func(VALUE self)
{
	spop_func *func = ruby_xmalloc(sizeof(spop_func));
	*func = translate;
	VALUE wrapped = Data_Wrap_Struct(rb_cParams, NULL, free, func);
	return wrapped;
}
Esempio n. 4
0
request *
new_request(void)
{
  request *req = (request *)ruby_xmalloc(sizeof(request));
  memset(req, 0, sizeof(request));
  return req;
}
Esempio n. 5
0
/*
 * call-seq: Fiddle.malloc(size)
 *
 * Allocate +size+ bytes of memory and return the integer memory address
 * for the allocated memory.
 */
static VALUE
rb_fiddle_malloc(VALUE self, VALUE size)
{
    void *ptr;

    ptr = (void*)ruby_xmalloc(NUM2INT(size));
    return PTR2NUM(ptr);
}
Esempio n. 6
0
File: cptr.c Progetto: ArekX/RAGE
VALUE
rb_dlptr_malloc(long size, freefunc_t func)
{
    void *ptr;

    ptr = ruby_xmalloc((size_t)size);
    memset(ptr,0,(size_t)size);
    return rb_dlptr_new(ptr, size, func);
}
Esempio n. 7
0
static void
buffer_size_changed(struct buffer *buffer)
{
    clReleaseMemObject(buffer->data);
    buffer->data = clCreateBuffer(context, CL_MEM_READ_WRITE,
                                  buffer->num_items * buffer->member_size, NULL, NULL);
    ruby_xfree(buffer->cachebuf);
    buffer->cachebuf = ruby_xmalloc(buffer->num_items * buffer->member_size);
}
Esempio n. 8
0
File: gc.c Progetto: 1nueve/MacRuby
void *
ruby_xmalloc2(size_t n, size_t size)
{
    size_t len = size * n;
    if (n != 0 && size != len / n) {
	rb_raise(rb_eArgError, "malloc: possible integer overflow");
    }
    return ruby_xmalloc(len);
}
Esempio n. 9
0
/*
 * call-seq: DL.malloc
 *
 * Allocate +size+ bytes of memory and return the integer memory address
 * for the allocated memory.
 */
VALUE
rb_dl_malloc(VALUE self, VALUE size)
{
    void *ptr;

    rb_secure(4);
    ptr = (void*)ruby_xmalloc(NUM2INT(size));
    return PTR2NUM(ptr);
}
Esempio n. 10
0
header *
new_header(size_t fsize, size_t flimit, size_t vsize, size_t vlimit)
{
  header *h;
  h = ruby_xmalloc(sizeof(header));
  h->field = new_buffer(fsize, flimit);
  h->value = new_buffer(vsize, vlimit);
  return h;
}
Esempio n. 11
0
static void
bt_init(void *ptr, size_t size)
{
    struct bt_iter_arg *arg = (struct bt_iter_arg *)ptr;
    arg->btobj = backtrace_alloc(rb_cBacktrace);
    GetCoreDataFromValue(arg->btobj, rb_backtrace_t, arg->bt);
    arg->bt->backtrace_base = arg->bt->backtrace = ruby_xmalloc(sizeof(rb_backtrace_location_t) * size);
    arg->bt->backtrace_size = 0;
}
Esempio n. 12
0
static void cs_list_append( struct curl_state *state ) {
  struct curl_state_list *item = NULL;

  assert(state != NULL);
  item = ruby_xmalloc(sizeof(struct curl_state_list));
  item->state = state;
  item->next = NULL;

  SGLIB_LIST_ADD(struct curl_state_list, cs_list, item, next);
}
Esempio n. 13
0
static VALUE
rb_fiddle_ptr_malloc(long size, freefunc_t func)
{
    void *ptr;

    rb_secure(4);
    ptr = ruby_xmalloc((size_t)size);
    memset(ptr,0,(size_t)size);
    return rb_fiddle_ptr_new(ptr, size, func);
}
Esempio n. 14
0
static VALUE setup_trnsl_params(VALUE self, VALUE dx, VALUE dy, VALUE dz)
{
	trnsl_params *params = ruby_xmalloc(sizeof(trnsl_params));
	params->dx = NUM2DBL(dx);
	params->dy = NUM2DBL(dy);
	params->dz = NUM2DBL(dz);
	VALUE wrapped = Data_Wrap_Struct(rb_cParams, NULL, free, params);
	rb_iv_set(self, "params", wrapped);
	return wrapped;
}
Esempio n. 15
0
static VALUE dir_initialize(int argc, VALUE* argv, VALUE self){
  HANDLE chandle;
  VALUE v_path, v_encoding;
  NDirStruct* ptr;

  rb_scan_args(argc, argv, "11", &v_path, &v_encoding);

  // Make sure first argument is a string
  SafeStringValue(v_path);

  Data_Get_Struct(self, NDirStruct, ptr);

  ptr->path = RSTRING_PTR(v_path);

  chandle = CreateFile(
    ptr->path,
    GENERIC_READ,
    FILE_SHARE_READ,
    NULL,
    OPEN_EXISTING,
    FILE_FLAG_BACKUP_SEMANTICS,
    NULL
  );

  // Need to do some extra handling to verify argument is a directory
  if(chandle == INVALID_HANDLE_VALUE){
    rb_raise_win_error("CreateFile", GetLastError());
  }
  else{
    BY_HANDLE_FILE_INFORMATION info;

    if (!GetFileInformationByHandle(chandle, &info)){
      CloseHandle(chandle);
      rb_raise_win_error("GetFileInformationByHandle", GetLastError());
    }

    if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){
      CloseHandle(chandle);
      rb_raise_win_error("GetFileInformationByHandle", 20); // Errno::ENOTDIR
    }

    ptr->chandle = chandle;
    ptr->fhandle = INVALID_HANDLE_VALUE;
    ptr->position = 0;

    // Append *.* to base path since that will be used for reads, etc.
    ptr->path = (char*)ruby_xmalloc(RSTRING_LEN(v_path) + strlen("/*.*") + 1);
    sprintf(ptr->path, "%s%s", RSTRING_PTR(v_path), "/*.*");
  }

  rb_iv_set(self, "@path", v_path);

  return self;
}
Esempio n. 16
0
VALUE
c_CompletionResult_struct_alloc(VALUE klass)
{

    CompletionResult_t *ptr;
    ptr = (CompletionResult_t *) ruby_xmalloc(sizeof(CompletionResult_t));
    ptr->data = NULL;
    ptr->parent = Qnil;

    return Data_Wrap_Struct(
        klass, NULL, c_CompletionResult_struct_free, (void *) ptr);
}
Esempio n. 17
0
void *
ruby_xrealloc(void *ptr, size_t size)
{
    void *mem;

    if (size < 0) {
	rb_raise(rb_eArgError, "negative re-allocation size");
    }
    if (ptr == NULL) {
	return ruby_xmalloc(size);
    }
    if (size == 0) {
	size = 1;
    }
    
#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
    {
	size_t old_size = malloc_size(ptr);
	if (old_size >= size) {
	    return ptr;
	}
	mem = ruby_xmalloc(size);
	if (mem == NULL) {
	    rb_memerror();
	}
	auto_zone_write_barrier_memmove(__auto_zone, mem, ptr, old_size);
	xfree(ptr);
    }
#else
    mem = malloc_zone_realloc(__auto_zone, ptr, size);

    if (mem == NULL) {
	rb_memerror();
    }
#endif

    return mem;
}
Esempio n. 18
0
File: gc.c Progetto: alloy/MacRuby
void *
ruby_xrealloc(void *ptr, size_t size)
{
    if (ptr == NULL) {
	return ruby_xmalloc(size);
    }
    if (size == 0) {
	size = 1;
    }
    void *mem = malloc_zone_realloc(__auto_zone, ptr, size);
    if (mem == NULL) {
	rb_memerror();
    }
    return mem;
}
Esempio n. 19
0
static VALUE setup_cop_params(int argc, VALUE *argv, VALUE self)
{
	cop_params *params = ruby_xmalloc(sizeof(cop_params));
	params->funcs = ruby_xcalloc(argc, sizeof(spop_func));
	params->params = ruby_xcalloc(argc, sizeof(void*));
	params->n = argc;
	int i;
	for(i=0; i < argc; i++){
		spop_func *buf;
		get_func_param_from_spop(argv[i], &buf, &params->params[i]);
		params->funcs[i] = *buf;
	}
	VALUE wrapped = Data_Wrap_Struct(rb_cParams, NULL, free_cop_params, params);
	rb_iv_set(self, "params", wrapped);
	return wrapped;
}
Esempio n. 20
0
// ----------------------------------------------------------------------------------
//
// def create_index(namespace, set, bin, name, data_type, options = {})
//
// params:
//   namespace - string, namespace to be indexed
//   set - string, set to be indexed
//   bin - string, bin or complex position name to be indexed
//   name - string, name of the index
//   data_type = symbol, data type of index, :string or :numeric
//
//  ------
//  RETURN:
//    1. AerospikeC::IndexTask object
//
// @TODO options policy
//
static VALUE create_index(int argc, VALUE * argv, VALUE self) {
  rb_aero_TIMED(tm);

  as_error err;
  aerospike * as = rb_aero_CLIENT;

  VALUE ns;
  VALUE set;
  VALUE bin;
  VALUE name;
  VALUE data_type;
  VALUE options;

  rb_scan_args(argc, argv, "51", &ns, &set, &bin, &name, &data_type, &options);

  // default values for optional arguments
  if ( NIL_P(options) ) options = rb_hash_new();

  int d_type;

  if ( data_type == numeric_sym ) {
    d_type = AS_INDEX_NUMERIC;
  }
  else if ( data_type == string_sym ) {
    d_type = AS_INDEX_STRING;
  }
  else if  ( data_type == geo_sphere_sym ) {
    d_type = AS_INDEX_GEO2DSPHERE;
  }
  else {
    rb_raise(rb_aero_OptionError, "[AerospikeC::Client][create_index] data_type must be :string or :numeric");
  }

  as_index_task * task = (as_index_task *) ruby_xmalloc( sizeof(as_index_task) );
  if (! task) rb_raise(rb_aero_MemoryError, "[AerospikeC::Client][create_index] Error while allocating memory for aerospike task");


  if ( aerospike_index_create(as, &err, task, NULL, StringValueCStr(ns), StringValueCStr(set),
                              StringValueCStr(bin), StringValueCStr(name), d_type) != AEROSPIKE_OK )
    raise_as_error(err);

  VALUE index_task_struct = Data_Wrap_Struct(rb_aero_IndexTask, NULL, index_task_deallocate, task);

  rb_aero_logger(AS_LOG_LEVEL_DEBUG, &tm, 1, rb_str_new2("[Client][create_index] done"));

  return rb_funcall(rb_aero_IndexTask, rb_intern("new"), 1, index_task_struct);
}
Esempio n. 21
0
static VALUE dir_s_pwd(VALUE klass){
  char* buffer;
  DWORD size;

  // First call, get the required size
  size = GetCurrentDirectory(0, NULL);
  buffer = (char*)ruby_xmalloc(size);

  // Second call, actually get the result
  if(!GetCurrentDirectory(size, buffer))
    rb_raise_win_error("GetCurrentDirectory", GetLastError());

  while(strstr(buffer, "\\"))
    buffer[strcspn(buffer, "\\")] = '/';

  return rb_str_new2(buffer);
}
static const char *
make_unique_str(st_table *tbl, const char *str, long len)
{
    if (!str) {
	return NULL;
    }
    else {
	char *result;

	if ((result = keep_unique_str(tbl, str)) == NULL) {
	    result = (char *)ruby_xmalloc(len+1);
	    strncpy(result, str, len);
	    result[len] = 0;
	    st_add_direct(tbl, (st_data_t)result, 1);
	}
	return result;
    }
}
Esempio n. 23
0
static client_t *
new_client_t(int client_fd, struct sockaddr_in client_addr){
  client_t *client;
    
  client = ruby_xmalloc(sizeof(client_t));
  memset(client, 0, sizeof(client_t));
    
  /* printf("size %d\n", sizeof(client_t)); */

  client->fd = client_fd;
    
  client->remote_addr = inet_ntoa(client_addr.sin_addr);
  client->remote_port = ntohs(client_addr.sin_port);
  client->req = new_request();
  client->body_type = BODY_TYPE_NONE;
  //printf("input_buf_size %d\n", client->input_buf_size);
  return client;
}
Esempio n. 24
0
File: gc.c Progetto: 1nueve/MacRuby
void *
ruby_xrealloc(void *ptr, size_t size)
{
    if ((ssize_t)size < 0) {
	negative_size_allocation_error("negative re-allocation size");
    }
    if (ptr == NULL) {
	return ruby_xmalloc(size);
    }
    if (size == 0) {
	size = 1;
    }

    if (stress_gc && !dont_gc) {
	garbage_collect();
    }

    void *mem = malloc_zone_realloc(__auto_zone, ptr, size);
    if (mem == NULL) {
	rb_memerror();
    }
    return mem;
}
Esempio n. 25
0
int
init_parser(client_t *cli, const char *name, const short port)
{
  VALUE object;
  char r_port[7];

  cli->http = (http_parser*)ruby_xmalloc(sizeof(http_parser));
  memset(cli->http, 0, sizeof(http_parser));
    
  cli->environ = rb_hash_new();

  rb_hash_aset(cli->environ, version_key, version_val);
  rb_hash_aset(cli->environ, scheme_key, scheme_val);
  rb_hash_aset(cli->environ, errors_key, errors_val);
  rb_hash_aset(cli->environ, multithread_key, multithread_val);
  rb_hash_aset(cli->environ, multiprocess_key, multiprocess_val);
  rb_hash_aset(cli->environ, run_once_key, run_once_val);
  rb_hash_aset(cli->environ, script_key, script_val);
  rb_hash_aset(cli->environ, server_name_key, server_name_val);
  rb_hash_aset(cli->environ, server_port_key, server_port_val);

  // query_string
  rb_hash_aset(cli->environ, query_string, empty_string);

  object = rb_str_new2(cli->remote_addr);
  rb_hash_aset(cli->environ, rb_remote_addr, object);

  sprintf(r_port, "%d", cli->remote_port);
  object = rb_str_new2(r_port);
  rb_hash_aset(cli->environ, rb_remote_port, object);

  http_parser_init(cli->http, HTTP_REQUEST);
  cli->http->data = cli;

  return 0;
}
Esempio n. 26
0
int argv_of_pid(int pid, VALUE* v_cmdline, VALUE* v_exe, VALUE* v_environ) {
  int mib[3], argmax, nargs, c = 0;
  size_t size;
  char *procargs, *sp, *np, *cp;
  int show_args = 1;

  mib[0] = CTL_KERN;
  mib[1] = KERN_ARGMAX;

  size = sizeof(argmax);

  if (sysctl(mib, 2, &argmax, &size, NULL, 0) == -1)
    goto ERROR_A;

  // Allocate space for the arguments.
  procargs = (char *)ruby_xmalloc(argmax);

  /*
   * Make a sysctl() call to get the raw argument space of the process.
   * The layout is documented in start.s, which is part of the Csu
   * project.  In summary, it looks like:
   *
   * /---------------\ 0x00000000
   * :               :
   * :               :
   * |---------------|
   * | argc          |
   * |---------------|
   * | arg[0]        |
   * |---------------|
   * :               :
   * :               :
   * |---------------|
   * | arg[argc - 1] |
   * |---------------|
   * | 0             |
   * |---------------|
   * | env[0]        |
   * |---------------|
   * :               :
   * :               :
   * |---------------|
   * | env[n]        |
   * |---------------|
   * | 0             |
   * |---------------| <-- Beginning of data returned by sysctl() is here.
   * | argc          |
   * |---------------|
   * | exec_path     |
   * |:::::::::::::::|
   * |               |
   * | String area.  |
   * |               |
   * |---------------| <-- Top of stack.
   * :               :
   * :               :
   * \---------------/ 0xffffffff
   */
  mib[0] = CTL_KERN;
  mib[1] = KERN_PROCARGS2;
  mib[2] = pid;

  size = (size_t)argmax;

  if (sysctl(mib, 3, procargs, &size, NULL, 0) == -1)
    goto ERROR_B;

  memcpy(&nargs, procargs, sizeof(nargs));
  cp = procargs + sizeof(nargs);

  // Copy exec_path to ruby String.
  *v_exe = rb_str_new2(cp);

  // Skip the saved exec_path.
  for (; cp < &procargs[size]; cp++) {
    if (*cp == '\0')
      break; // End of exec_path reached.
  }

  if (cp == &procargs[size])
    goto ERROR_B;

  // Skip trailing '\0' characters.
  for (; cp < &procargs[size]; cp++){
    if (*cp != '\0')
      break; // Beginning of first argument reached.
  }

  if (cp == &procargs[size])
    goto ERROR_B;

  // Save where the argv[0] string starts.
  sp = cp;

  /*
   * Iterate through the '\0'-terminated strings and convert '\0' to ' '
   * until a string is found that has a '=' character in it (or there are
   * no more strings in procargs).  There is no way to deterministically
   * know where the command arguments end and the environment strings
   * start, which is why the '=' character is searched for as a heuristic.
   */
  for (np = NULL; c < nargs && cp < &procargs[size]; cp++) {
    if (*cp == '\0') {
      c++;

      if (np != NULL)
        *np = ' '; // Convert previous '\0'.

      // Note location of current '\0'.
      np = cp;

      if (!show_args) {
        /*
         * Don't convert '\0' characters to ' '.
         * However, we needed to know that the
         * command name was terminated, which we
         * now know.
         */
        break;
      }
    }
  }

  /*
   * sp points to the beginning of the arguments/environment string, and
   * np should point to the '\0' terminator for the string.
   */
  if (np == NULL || np == sp)
    goto ERROR_B; // Empty or unterminated string.

  // Make a copy of the string to ruby String.
  *v_cmdline = rb_str_new2(sp);

  // Read environment variables to ruby Hash.
  *v_environ = rb_hash_new();

  while (cp[0]) {
    sp = strsep(&cp, "=");

    if (!sp || !cp)
      break;

    rb_hash_aset(*v_environ, rb_str_new2(sp), rb_str_new2(cp));
    cp += strlen(cp) + 1;
  }

  // Cleanup.
  ruby_xfree(procargs);
  return 0;

  ERROR_B:
  ruby_xfree(procargs);
  ERROR_A:
  return -1;
}
Esempio n. 27
0
static VALUE blake2_alloc(VALUE klass) {
  Blake2 *blake2_obj = (Blake2 *)ruby_xmalloc(sizeof(Blake2));

  return Data_Wrap_Struct(klass, NULL, blake2_free, blake2_obj);
}
Esempio n. 28
0
static void rb_smbfile_read_by_data(RB_SMBFILE_DATA *data)
{
  smbc_read_fn fn;
  ssize_t read_size;
  char *buffer = data->buffer + data->buffer_used_size;
  size_t buffer_size = data->buffer_size - data->buffer_used_size;

  if (buffer_size == 0) {
    /* Buffer is full */
    if (data->buffer_pos < data->buffer_used_size) {
      /* But remained data exists */
      return;
    }

    /* Rewind */
    data->buffer_used_size = 0;
    data->buffer_pos = 0;
    buffer = data->buffer;
    buffer_size = data->buffer_size;
  }

  fn = smbc_getFunctionRead(data->smbcctx);

try:
  read_size = (*fn)(data->smbcctx, data->smbcfile, buffer, buffer_size);
  if (read_size < 0) {
    if (errno != EBADF) {
      rb_sys_fail("Bad SMBCFILE");
    }
    else {
      rb_smbfile_reopen_by_data(data);
      goto try;
    }
  }

  data->buffer_used_size += read_size;
  data->eof = (read_size == 0);
}

static VALUE rb_smbfile_close(VALUE self);

static VALUE rb_smbfile_initialize(int argc, VALUE *argv, VALUE self)
{
  RB_SMBFILE_DATA_FROM_OBJ(self, data);
  VALUE smb_obj, url_obj, mode_obj;

  rb_scan_args(argc, argv, "21", &smb_obj, &url_obj, &mode_obj);
  RB_SMB_DATA_FROM_OBJ(smb_obj, smb_data);

  if (NIL_P(mode_obj)) {
    data->fmode = FMODE_READABLE;
    // FIXME data->fmode = FMODE_READABLE | DEFAULT_TEXTMODE;
    data->oflags = O_RDONLY;
  }
  else if (FIXNUM_P(mode_obj)) {
    rb_raise(rb_eArgError, "FIXME");
    data->fmode = 0;
    data->oflags = NUM2INT(mode_obj);
  }
  else {
    const char *mode_str = StringValueCStr(mode_obj);
    data->fmode = rb_io_modestr_fmode(mode_str);
    data->oflags = rb_io_modestr_oflags(mode_str);
  }

  data->smb_obj = smb_obj;
  data->smb_data = smb_data;
  data->smbcctx = smb_data->smbcctx;
  data->url = ruby_strdup(RSTRING_PTR(url_obj));

  data->buffer = ruby_xmalloc(RB_SMBFILE_BUFFER_SIZE);
  data->buffer_size = RB_SMBFILE_BUFFER_SIZE;

  rb_smbfile_open_by_data(data);

  if (rb_block_given_p()) {
    return rb_ensure(rb_yield, self, rb_smbfile_close, self);
  }

  return self;
}
Esempio n. 29
0
/*
 * call-seq:
 *    ProcTable.ps(pid=nil)
 *    ProcTable.ps(pid=nil){ |ps| ... }
 *
 * In block form, yields a ProcTableStruct for each process entry that you
 * have rights to.  This method returns an array of ProcTableStruct's in
 * non-block form.
 *
 * If a +pid+ is provided, then only a single ProcTableStruct is yielded or
 * returned, or nil if no process information is found for that +pid+.
 */
static VALUE pt_ps(int argc, VALUE* argv, VALUE klass){
  int err;
  char state[8];
  struct kinfo_proc* procs;
  VALUE v_pid, v_tty_num, v_tty_dev, v_start_time;
  VALUE v_pstruct = Qnil;
  VALUE v_array = rb_ary_new();
  size_t length, count;
  size_t i = 0;
  int g;
  VALUE v_cmdline, v_exe, v_environ, v_groups;

  // Passed into sysctl call
  static const int name_mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};

  rb_scan_args(argc, argv, "01", &v_pid);

  // Get size of proc kproc buffer
  err = sysctl( (int *) name_mib, PROC_MIB_LEN, NULL, &length, NULL, 0);

  if(err == -1)
    rb_raise(cProcTableError, "sysctl: %s", strerror(errno));

  // Populate the kproc buffer
  procs = ruby_xmalloc(length);

  err = sysctl( (int *) name_mib, PROC_MIB_LEN, procs, &length, NULL, 0);

  if(err == -1)
    rb_raise(cProcTableError, "sysctl: %s", strerror(errno));

  // If we're here, we got our list
  count = length / sizeof(struct kinfo_proc);

  for(i = 0; i < count; i++) {
    v_tty_num = Qnil;
    v_tty_dev = Qnil;
    v_start_time = Qnil;

    // If a PID is provided, skip unless the PID matches
    if( (!NIL_P(v_pid)) && (procs[i].kp_proc.p_pid != NUM2INT(v_pid)) )
      continue;

    // cmdline will be set only if process exists and belongs to current user or
    // current user is root
    v_cmdline = Qnil;
    v_exe = Qnil;
    v_environ = Qnil;
    argv_of_pid(procs[i].kp_proc.p_pid, &v_cmdline, &v_exe, &v_environ);

    // Get the start time of the process
    v_start_time = rb_time_new(
      procs[i].kp_proc.p_un.__p_starttime.tv_sec,
      procs[i].kp_proc.p_un.__p_starttime.tv_usec
    );

    // Get the state of the process
    switch(procs[i].kp_proc.p_stat)
    {
      case SIDL:
        strcpy(state, "idle");
        break;
      case SRUN:
        strcpy(state, "run");
        break;
      case SSLEEP:
        strcpy(state, "sleep");
        break;
      case SSTOP:
        strcpy(state, "stop");
        break;
      case SZOMB:
        strcpy(state, "zombie");
        break;
      default:
        strcpy(state, "unknown");
        break;
    }

    // Get ttynum and ttydev. If ttynum is -1, there is no tty.
    if(procs[i].kp_eproc.e_tdev != -1){
      v_tty_num = INT2FIX(procs[i].kp_eproc.e_tdev),
      v_tty_dev = rb_str_new2(devname(procs[i].kp_eproc.e_tdev, S_IFCHR));
    }

    v_groups = rb_ary_new();

    for (g = 0; g < procs[i].kp_eproc.e_ucred.cr_ngroups; ++g)
      rb_ary_push(v_groups, INT2FIX(procs[i].kp_eproc.e_ucred.cr_groups[g]));

    v_pstruct = rb_struct_new(
      sProcStruct,
      INT2FIX(procs[i].kp_proc.p_pid),
      INT2FIX(procs[i].kp_eproc.e_ppid),
      INT2FIX(procs[i].kp_eproc.e_pgid),
      INT2FIX(procs[i].kp_eproc.e_pcred.p_ruid),
      INT2FIX(procs[i].kp_eproc.e_pcred.p_rgid),
      INT2FIX(procs[i].kp_eproc.e_ucred.cr_uid),
      rb_ary_entry(v_groups, 0),
      v_groups,
      INT2FIX(procs[i].kp_eproc.e_pcred.p_svuid),
      INT2FIX(procs[i].kp_eproc.e_pcred.p_svgid),
      rb_str_new2(procs[i].kp_proc.p_comm),
      rb_str_new2(state),
      rb_float_new(procs[i].kp_proc.p_pctcpu),
      Qnil,
      v_tty_num,
      v_tty_dev,
      rb_str_new2(procs[i].kp_eproc.e_wmesg),
      INT2FIX(procs[i].kp_proc.p_rtime.tv_sec),
      INT2FIX(procs[i].kp_proc.p_priority),
      INT2FIX(procs[i].kp_proc.p_usrpri),
      INT2FIX(procs[i].kp_proc.p_nice),
      v_cmdline,
      v_exe,
      v_environ,
      v_start_time,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_maxrss) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_ixrss) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_idrss) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_isrss) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_minflt) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_majflt) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_nswap) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_inblock) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_oublock) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_msgsnd) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_msgrcv) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_nsignals) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_nvcsw) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_nivcsw) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_utime.tv_sec) : Qnil,
      (procs[i].kp_proc.p_ru && procs[i].kp_proc.p_stat != 5) ? LONG2NUM(procs[i].kp_proc.p_ru->ru_stime.tv_sec) : Qnil
    );

    OBJ_FREEZE(v_pstruct); // This is read-only data

    if(rb_block_given_p())
      rb_yield(v_pstruct);
    else
      rb_ary_push(v_array, v_pstruct);
  }

  if(procs)
    free(procs);

  if(!rb_block_given_p()){
    if(NIL_P(v_pid))
      return v_array;
    else
      return v_pstruct;
  }

  return Qnil;
}
Esempio n. 30
0
static VALUE dir_s_home(int argc, VALUE* argv, VALUE klass){
  VALUE v_user;
  SID* sid;
  DWORD cbSid, cbDom, cbData, lpType;
  SID_NAME_USE peUse;
  LPSTR str_sid;
  LONG rv;
  HKEY phkResult;
  char* user;
  char subkey[MAX_PATH];
  char* lpData;
  char* dom;
  const char* key_base = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\";

  rb_scan_args(argc, argv, "01", &v_user);

  // If no user specified, get home directory for current user
  if(NIL_P(v_user)){
    DWORD size = UNLEN+1;
    user = (char*)ruby_xmalloc(UNLEN+1);

    if(!GetUserName(user, &size))
      rb_raise_win_error("GetUserName", GetLastError());
  }
  else{
    Check_Type(v_user, T_STRING);
    user = RSTRING_PTR(v_user);
  }
  
  sid = (SID*)ruby_xmalloc(MAX_PATH);
  dom = (char*)ruby_xmalloc(MAX_PATH);

  cbSid = MAX_PATH;
  cbDom = MAX_PATH;

  // Get the user's SID
  if (!LookupAccountName(NULL, user, sid, &cbSid, dom, &cbDom, &peUse)){
    ruby_xfree(sid);
    ruby_xfree(dom);
    rb_raise(rb_eArgError, "can't find user %s", user);
  }

  ruby_xfree(dom); // Don't need this any more
    
  // Get the stringy version of the SID
  if (!ConvertSidToStringSid(sid, &str_sid)){
    ruby_xfree(sid);
    rb_raise_win_error("ConvertSidToStringSid", GetLastError());
  }

  ruby_xfree(sid); // Don't need this any more

  // Mash the stringified SID onto our base key
  if(snprintf(subkey, MAX_PATH, "%s%s", key_base, str_sid) < 0)
    rb_raise_win_error("snprintf", GetLastError());

  // Get the key handle we need
  rv = RegOpenKeyEx(HKEY_LOCAL_MACHINE, subkey, 0, KEY_QUERY_VALUE, &phkResult);

  if (rv != ERROR_SUCCESS)
    rb_raise_win_error("RegOpenKeyEx", GetLastError());

  lpData = (char*)malloc(MAX_PATH);
  cbData = MAX_PATH;
  lpType = REG_EXPAND_SZ;

  // Finally, get the user's home directory
  rv = RegQueryValueEx(phkResult, "ProfileImagePath", NULL, &lpType, (LPBYTE)lpData, &cbData);

  if (rv != ERROR_SUCCESS){
    ruby_xfree(lpData);
    rb_raise(rb_eArgError, "can't find home directory for user %s", user);
  }

  return rb_str_new2(lpData);
}