Exemplo n.º 1
0
static Elf *
get_elf (const gchar *file,
         gint        *fd)
{
  Elf *elf;

  if (elf_version (EV_CURRENT) == EV_NONE )
    return NULL;

  *fd = g_open (file, O_RDONLY, 0);
  if (*fd < 0)
    return NULL;

  elf = elf_begin (*fd, ELF_C_READ, NULL);
  if (elf == NULL)
    {
      g_close (*fd, NULL);
      *fd = -1;
      return NULL;
    }

  if (elf_kind (elf) != ELF_K_ELF)
    {
      g_close (*fd, NULL);
      *fd = -1;
      return NULL;
    }

  return elf;
}
Exemplo n.º 2
0
/**
 * dnf_package_check_filename:
 * @pkg: a #DnfPackage *instance.
 * @valid: Set to %TRUE if the package is valid.
 * @error: a #GError or %NULL..
 *
 * Checks the package is already downloaded and valid.
 *
 * Returns: %TRUE if the package was checked successfully
 *
 * Since: 0.1.0
 **/
gboolean
dnf_package_check_filename(DnfPackage *pkg, gboolean *valid, GError **error)
{
    LrChecksumType checksum_type_lr;
    char *checksum_valid = NULL;
    const gchar *path;
    const unsigned char *checksum;
    gboolean ret = TRUE;
    int checksum_type_hy;
    int fd;

    /* check if the file does not exist */
    path = dnf_package_get_filename(pkg);
    g_debug("checking if %s already exists...", path);
    if (!g_file_test(path, G_FILE_TEST_EXISTS)) {
        *valid = FALSE;
        goto out;
    }

    /* check the checksum */
    checksum = dnf_package_get_chksum(pkg, &checksum_type_hy);
    checksum_valid = hy_chksum_str(checksum, checksum_type_hy);
    checksum_type_lr = dnf_repo_checksum_hy_to_lr(checksum_type_hy);
    fd = g_open(path, O_RDONLY, 0);
    if (fd < 0) {
        ret = FALSE;
        g_set_error(error,
                 DNF_ERROR,
                 DNF_ERROR_INTERNAL_ERROR,
                 "Failed to open %s", path);
        goto out;
    }
    ret = lr_checksum_fd_cmp(checksum_type_lr,
                 fd,
                 checksum_valid,
                 TRUE, /* use xattr value */
                 valid,
                 error);
    if (!ret) {
        g_close(fd, NULL);
        goto out;
    }
    ret = g_close(fd, error);
    if (!ret)
        goto out;
out:
    g_free(checksum_valid);
    return ret;
}
Exemplo n.º 3
0
static gchar *
create_temporary_file (void)
{
  const gchar *tmpdir;
  gchar *tmp_fn;
  gint fd;

  tmpdir = g_get_tmp_dir ();
  if (tmpdir == NULL)
    return NULL;

  /* this is just silly, but gcc warns if we try to use tpmnam() */
  tmp_fn = g_build_filename (tmpdir, "gstreamer-filesink-test-XXXXXX", NULL);
  fd = g_mkstemp (tmp_fn);
  if (fd < 0) {
    GST_ERROR ("can't create temp file %s: %s", tmp_fn, g_strerror (errno));
    g_free (tmp_fn);
    return NULL;
  }
  /* don't want the file, just a filename (hence silly, see above) */
  g_close (fd, NULL);
  g_remove (tmp_fn);

  return tmp_fn;
}
Exemplo n.º 4
0
Arquivo: t_s4.c Projeto: xmms2/s4
static void _open (int flags)
{
	int fd = g_file_open_tmp ("t_s4-XXXXXX", &name, NULL);
	g_close (fd, NULL);
	g_unlink (name);

	s4 = s4_open (name, NULL, flags);
}
Exemplo n.º 5
0
/**
 * fu_io_channel_shutdown:
 * @self: a #FuIOChannel
 * @error: a #GError, or %NULL
 *
 * Closes the file descriptor for the device.
 *
 * Returns: %TRUE if all the FD was closed.
 *
 * Since: 1.2.2
 **/
gboolean
fu_io_channel_shutdown (FuIOChannel *self, GError **error)
{
	g_return_val_if_fail (FU_IS_IO_CHANNEL (self), FALSE);
	if (!g_close (self->fd, error))
		return FALSE;
	self->fd = -1;
	return TRUE;
}
Exemplo n.º 6
0
/* For FNAL we base the detection on the number of elements per site */
int io_detect_fm(char *filename){
  FILE *fp;
  int status, words;
  int32type magic_no, revmagic_no, gmtime_stamp, size_of_element,
    elem_per_site;
  int byterevflag = 0;

  /* Node 0 reads and checks */
  if(this_node == 0){
    fp = g_open(filename,"rb");
    if(fp == NULL)status = -2;
    else
      {
	words = g_read(&magic_no, sizeof(int32type), 1, fp);

	if(words != 1)status = -3;
	else
	  {
	    revmagic_no = magic_no;
	    byterevn(&revmagic_no, 1);

	    status = -1;
	    if(revmagic_no == IO_UNI_MAGIC)byterevflag = 1;
	    if(magic_no == IO_UNI_MAGIC || revmagic_no == IO_UNI_MAGIC){
	      g_read(&gmtime_stamp, sizeof(gmtime_stamp), 1, fp);
	      g_read(&size_of_element, sizeof(int32type), 1, fp);
	      g_read(&elem_per_site, sizeof(int32type), 1, fp);

	      if(byterevflag){
		byterevn(&size_of_element, 1);
		byterevn(&elem_per_site, 1);
	      }

	      if(size_of_element != sizeof(float))status = -1;
	      else 
		if(elem_per_site == sizeof(fsu3_matrix)/sizeof(float))
		  status = FILE_TYPE_KS_FMPROP;
	      else 
		if(elem_per_site == sizeof(fwilson_propagator)/sizeof(float) ||
		   elem_per_site == sizeof(fwilson_vector)/sizeof(float))
		  status = FILE_TYPE_W_FMPROP;
	      else 
		if(elem_per_site == 4*sizeof(fsu3_matrix)/sizeof(float))
		  status = FILE_TYPE_GAUGE_FNAL;
	    }
	  }
      }
    g_close(fp);
  }
  /* Node 0 broadcasts the result */
  broadcast_bytes((char *)&status, sizeof(int));

  /* All nodes return the same value */
  return status;
}
Exemplo n.º 7
0
int close(int filedes) {

    g_fs_close_status status = g_close(filedes);

    if (status == G_FS_CLOSE_SUCCESSFUL) {
        return 0;
    } else if (status == G_FS_CLOSE_INVALID_FD) {
        errno = EBADF;
    } else {
        errno = EIO;
    }

    return -1;
}
Exemplo n.º 8
0
void
fu_plugin_destroy (FuPlugin *plugin)
{
	FuPluginData *data = fu_plugin_get_data (plugin);
	if (data->timeout_id != 0) {
		g_source_remove (data->timeout_id);
		data->timeout_id = 0;
	}
	g_object_unref (data->udev);
	g_free (data->force_path);
	/* in case destroying before force power turned off */
	if (data->bolt_fd >= 0)
		g_close (data->bolt_fd, NULL);
}
Exemplo n.º 9
0
int io_detect(char *filename, file_table ft[], int ntypes){
  FILE *fp;
  int i, status, words;
  int32type magic_no;
  int32type revmagic_no;
  char editfilename[513];

  /* Node 0 reads and checks */
  if(this_node == 0){
    fp = g_open(filename,"rb");
    if(fp == NULL){
      /* Special provision for partition or multifile format.  Try
	 adding the extension to the filename */
      strncpy(editfilename,filename,504);
      editfilename[504] = '\0';  /* Just in case of truncation */
      strcat(editfilename,".vol0000");
      fp = g_open(editfilename,"rb");
    }

    if(fp == NULL)status = -2;
    else
      {
	words = g_read(&magic_no, sizeof(int32type), 1, fp);
	g_close(fp);

	if(words != 1)status = -3;
	else
	  {
	    revmagic_no = magic_no;
	    byterevn(&revmagic_no, 1);

	    status = -1;
	    for(i = 0; i < ntypes; i++){
	      if(ft[i].magic_no == magic_no || 
		 ft[i].magic_no == revmagic_no)
		{
		  status = ft[i].type;
		  break;
		}
	    }
	  }
      }
  }

  /* Node 0 broadcasts the result */
  broadcast_bytes((char *)&status, sizeof(int));

  /* All nodes return the same value */
  return status;
}
Exemplo n.º 10
0
static gboolean
fu_plugin_thunderbolt_power_kernel_force_power (FuPlugin *plugin, gboolean enable,
						GError **error)
{
	FuPluginData *data = fu_plugin_get_data (plugin);
	gint fd;
	gint ret;

	if (!fu_plugin_thunderbolt_power_kernel_supported (plugin)) {
		g_set_error (error,
			     FWUPD_ERROR,
			     FWUPD_ERROR_NOT_SUPPORTED,
			     "unable to set power to %d (missing kernel support)",
			     enable);
		return FALSE;
	}
	g_debug ("Setting force power to %d using kernel", enable);
	fd = g_open (data->force_path, O_WRONLY);
	if (fd == -1) {
		g_set_error (error,
			     FWUPD_ERROR,
			     FWUPD_ERROR_INTERNAL,
			     "failed to open %s", data->force_path);
		return FALSE;
	}
	ret = write (fd, enable ? "1" : "0", 1);
	if (ret < 1) {
		g_set_error (error, G_IO_ERROR,
			     g_io_error_from_errno (errno),
			     "could not write to force_power': %s",
			     g_strerror (errno));
		g_close (fd, NULL);
		return FALSE;
	}

	return g_close (fd, error);
}
Exemplo n.º 11
0
static void 
r_source_cmplx_fm_f(cmplx_source_file *csf)

/* Close the file and free associated structures */
{
  g_sync();
  if(this_node==0)
    {
      if(csf->fp != NULL)g_close(csf->fp);
      fflush(stdout);
    }
  free(csf->header);
  free(csf);
  
} /* r_source_cmplx_fm_f */
Exemplo n.º 12
0
int nand_info(struct cmd_param *params)
{
	struct chip_param_io chip_params;
	int fd = -1, ret = 0;
	int block_size;
	off_t chip_size, media_size;
	const char *dev;

	if ((dev = param_get_string(params, "dev")) == NULL) {
		fprintf(stderr, "Please supply 'dev' parameter, eg. "
		    "'dev=/dev/gnand0'\n");
		return (1);
	}

	if ((fd = g_open(dev, 1)) == -1) {
		perrorf("Cannot open %s", dev);
		return (1);
	}

	if (ioctl(fd, NAND_IO_GET_CHIP_PARAM, &chip_params) == -1) {
		perrorf("Cannot ioctl(NAND_IO_GET_CHIP_PARAM)");
		ret = 1;
		goto out;
	}

	if (ioctl(fd, DIOCGMEDIASIZE, &media_size) == -1) {
		perrorf("Cannot ioctl(DIOCGMEDIASIZE)");
		ret = 1;
		goto out;
	}

	block_size = chip_params.page_size * chip_params.pages_per_block;
	chip_size = block_size * chip_params.blocks;

	printf("Device:\t\t\t%s\n", dev);
	printf("Page size:\t\t%d bytes\n", chip_params.page_size);
	printf("Block size:\t\t%d bytes (%d KB)\n", block_size,
	    block_size / 1024);
	printf("OOB size per page:\t%d bytes\n", chip_params.oob_size);
	printf("Chip size:\t\t%jd MB\n", (uintmax_t)(chip_size / 1024 / 1024));
	printf("Slice size:\t\t%jd MB\n",
	    (uintmax_t)(media_size / 1024 / 1024));

out:
	g_close(fd);

	return (ret);
}
Exemplo n.º 13
0
static gboolean
fu_plugin_thunderbolt_power_set (FuPlugin *plugin, gboolean enable,
				 GError **error)
{
	FuPluginData *data = fu_plugin_get_data (plugin);

	/* prefer bolt API if available */
	if (fu_plugin_thunderbolt_power_bolt_supported (plugin)) {
		g_debug ("Setting force power to %d using bolt", enable);
		if (enable)
			return fu_plugin_thunderbolt_power_bolt_force_power (plugin, error);
		return data->bolt_fd >= 0 ? g_close (data->bolt_fd, error) : TRUE;
	}

	return fu_plugin_thunderbolt_power_kernel_force_power (plugin, enable, error);
}
Exemplo n.º 14
0
static void test_engine_ngspice_error_no_such_file_or_directory() {
	TestEngineNgspiceResources *test_resources = test_engine_ngspice_resources_new();

	// make sure that the given file does not exist
	g_free(test_resources->resources->netlist_file);
	gint fd = g_file_open_tmp(NULL, &test_resources->resources->netlist_file, NULL);
	g_close(fd, NULL);
	g_remove(test_resources->resources->netlist_file);

	ngspice_watcher_build_and_launch(test_resources->resources);
	g_main_loop_run(test_resources->loop);

	g_assert_nonnull(test_resources->log_list);
	g_assert_true(g_str_has_suffix(test_resources->log_list->data, " No such file or directory\n"));

	test_engine_ngspice_resources_finalize(test_resources);
}
Exemplo n.º 15
0
size_t
geom_get_size(char *gname)
{
	size_t sz;
	int g;

	g = g_open(gname, 0);
	if (g == -1)
		return (0);

	sz = g_mediasize(g);
	if (sz == -1)
		return (0);

	g_close(g);

	return (sz);
}
Exemplo n.º 16
0
int
main(int argc, char **argv)
{
	struct stat sb;
	struct disk d;

	if (argc < 2)
		errx(1, "Usage: %s <GEOM provider name> | "
		    "<disk image file name>", argv[0]);
	d.name = argv[1];
	if (stat(d.name, &sb) == 0 && S_ISREG(sb.st_mode)) {
		d.fd = open(d.name, O_RDONLY);
		if (d.fd < 0)
			err(1, "open %s", d.name);
		d.mediasize = sb.st_size;
		d.sectorsize = 512;
		d.file = 1;
	} else {
		d.fd = g_open(d.name, 0);
		if (d.fd < 0)
			err(1, "g_open %s", d.name);
		d.mediasize = g_mediasize(d.fd);
		d.sectorsize = g_sectorsize(d.fd);
		d.file = 0;
	}
	d.offset = 0;
	printf("%s \"%s\" opened\n", d.file ? "Disk image": "GEOM provider",
	    d.name);
	printf("Mediasize: %ju Bytes (%ju sectors)\nSectorsize: %u Bytes\n",
	    d.mediasize, d.mediasize / d.sectorsize, d.sectorsize);

	inspect_disk(&d);

	if (d.file)
		close(d.fd);
	else
		g_close(d.fd);
	return (0);
}
Exemplo n.º 17
0
Arquivo: reg.c Projeto: silview/C100A
int32 REG_Exit( void )
{

	#ifdef ENABLE_THREAD
		if( backup_hdl != NULL )
			CloseHandle( backup_hdl );
			
		if( refresh_hdl != NULL )
			CloseHandle( refresh_hdl );
	#else
	    __msg("ready to refresh all reg files.\n");
		__refresh_all_reg_file( );
	    __msg("has refreshed all reg files.\n");
	#endif  // #ifdef ENABLE_THREAD
	
	#ifdef REG_LOG
		g_close( log_fp );
		log_fp = NULL;
	#endif  // #ifdef REG_LOG

			
	return __reg_exit( );
}
Exemplo n.º 18
0
// Use the functions in glib's file utilities to work with a file
// POSIX style.  You'd do this kind of thing if you wanted to handle
// file names with Unicode characters in them on Windows w/o needing
// to use ifdefs and the wide character API in your application code:
gint
posix_style_open_write_and_close_file_on_windows ()
{

  // setup for error handling:
  GError *err = NULL;

  /* Build a filename in the user's home directory. */
  gchar *path = g_build_filename (g_get_home_dir(), "foo", NULL);

  // We'll need to set the mode POSIX style and provide an int for the
  // file descriptor. mode_t came in when we included sys/stat.h:
  mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
  int fp; // posix stuff has integers for file descriptors

  // open (or create if it's not there already), truncate, and make
  // sure it's write only:
  if ((fp = g_open(path, O_WRONLY | O_CREAT | O_TRUNC, mode)) == -1) {
    g_printf("Your file can not be opened!\n");
    perror("Cannot open output file\n");
    exit(-1);
  } else {
    g_printf("Your file is open\n");
  }
  
  // write something to the file old school:
  gchar buf1[] = "This is a test.\n";
  write(fp, buf1, 16);
  
  // close the file and handle errors if they occur:
  g_close(fp, &err);
  handle_error(err);

  // all good:
  g_printf("The file is now closed.\n");
  return 0;
}
Exemplo n.º 19
0
static int read_probe_eeprom(unsigned int addr, struct probe_eeprom *eeprom)
{
	GString *path = g_string_sized_new(64);
	char eeprom_buf[EEPROM_SIZE];
	ssize_t rd;
	int fd;

	probe_eeprom_path(addr, path);
	fd = g_open(path->str, O_RDONLY);
	g_string_free(path, TRUE);
	if (fd < 0)
		return -1;

	rd = read(fd, eeprom_buf, EEPROM_SIZE);
	g_close(fd, NULL);
	if (rd != EEPROM_SIZE)
		return -1;

	eeprom->type = RB32(eeprom_buf + EEPROM_OFF_TYPE);
	eeprom->rev = RB32(eeprom_buf + EEPROM_OFF_REV);
	eeprom->shunt = RB32(eeprom_buf + EEPROM_OFF_SHUNT);
	eeprom->pwr_sw = R8(eeprom_buf + EEPROM_OFF_PWR_SW);
	/* Don't care about the serial number and tag for now. */

	/* Check if we have some sensible values. */
	if (eeprom->rev != 'B')
		/* 'B' is the only supported revision with EEPROM for now. */
		return -1;

	if (eeprom->type != EEPROM_PROBE_TYPE_USB &&
	    eeprom->type != EEPROM_PROBE_TYPE_JACK &&
	    eeprom->type != EEPROM_PROBE_TYPE_HE10)
		return -1;

	return 0;
}
Exemplo n.º 20
0
off_t diskfile_device_size(const char *path) {
	int fd = g_open(path, 0);
	off_t size = g_mediasize(fd);
	g_close(fd);
    return size;
}
Exemplo n.º 21
0
static gchar *
spawn_dbus_daemon (const gchar *binary,
    const gchar *configuration,
    TestUser user,
    GPid *daemon_pid)
{
  GError *error = NULL;
  GString *address;
  gint address_fd;
  const gchar *const argv[] = {
      binary,
      configuration,
      "--nofork",
      "--print-address=1", /* stdout */
#ifdef DBUS_UNIX
      "--systemd-activation",
#endif
      NULL
  };
#ifdef DBUS_UNIX
  const struct passwd *pwd = NULL;
#endif

  if (user != TEST_USER_ME)
    {
#ifdef DBUS_UNIX
      if (getuid () != 0)
        {
          g_message ("SKIP: cannot use alternative uid when not uid 0");
          return NULL;
        }

      switch (user)
        {
          case TEST_USER_ROOT:
            break;

          case TEST_USER_MESSAGEBUS:
            pwd = getpwnam (DBUS_USER);

            if (pwd == NULL)
              {
                g_message ("SKIP: user '%s' does not exist", DBUS_USER);
                return NULL;
              }

            break;

          case TEST_USER_OTHER:
            pwd = getpwnam (DBUS_TEST_USER);

            if (pwd == NULL)
              {
                g_message ("SKIP: user '%s' does not exist", DBUS_TEST_USER);
                return NULL;
              }

            break;

          default:
            g_assert_not_reached ();
        }
#else
      g_message ("SKIP: cannot use alternative uid on Windows");
      return NULL;
#endif
    }

  g_spawn_async_with_pipes (NULL, /* working directory */
      (gchar **) argv, /* g_s_a_w_p() is not const-correct :-( */
      NULL, /* envp */
      G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH,
#ifdef DBUS_UNIX
      child_setup, (gpointer) pwd,
#else
      NULL, NULL,
#endif
      daemon_pid,
      NULL, /* child's stdin = /dev/null */
      &address_fd,
      NULL, /* child's stderr = our stderr */
      &error);
  g_assert_no_error (error);

  address = g_string_new (NULL);

  /* polling until the dbus-daemon writes out its address is a bit stupid,
   * but at least it's simple, unlike dbus-launch... in principle we could
   * use select() here, but life's too short */
  while (1)
    {
      gssize bytes;
      gchar buf[4096];
      gchar *newline;

      bytes = read (address_fd, buf, sizeof (buf));

      if (bytes > 0)
        g_string_append_len (address, buf, bytes);

      newline = strchr (address->str, '\n');

      if (newline != NULL)
        {
          if ((newline > address->str) && ('\r' == newline[-1]))
            newline -= 1;
          g_string_truncate (address, newline - address->str);
          break;
        }

      g_usleep (G_USEC_PER_SEC / 10);
    }

  g_close (address_fd, NULL);

  return g_string_free (address, FALSE);
}
Exemplo n.º 22
0
int nand_write_oob(struct cmd_param *params)
{
	struct chip_param_io chip_params;
	struct nand_oob_rw req;
	char *dev, *in;
	int fd = -1, fd_in = -1, ret = 0;
	uint8_t *buf = NULL;
	int page;

	if (!(dev = param_get_string(params, "dev"))) {
		fprintf(stderr, "Please supply valid 'dev' parameter.\n");
		return (1);
	}

	if (!(in = param_get_string(params, "in"))) {
		fprintf(stderr, "Please supply valid 'in' parameter.\n");
		return (1);
	}

	if ((page = param_get_int(params, "page")) < 0) {
		fprintf(stderr, "Please supply valid 'page' parameter.\n");
		return (1);
	}

	if ((fd = g_open(dev, 1)) == -1) {
		perrorf("Cannot open %s", dev);
		return (1);
	}

	if ((fd_in = open(in, O_RDONLY)) == -1) {
		perrorf("Cannot open %s", in);
		ret = 1;
		goto out;
	}

	if (ioctl(fd, NAND_IO_GET_CHIP_PARAM, &chip_params) == -1) {
		perrorf("Cannot ioctl(NAND_IO_GET_CHIP_PARAM)");
		ret = 1;
		goto out;
	}

	buf = malloc(chip_params.oob_size);
	if (buf == NULL) {
		perrorf("Cannot allocate %d bytes\n", chip_params.oob_size);
		ret = 1;
		goto out;
	}

	if (read(fd_in, buf, chip_params.oob_size) == -1) {
		perrorf("Cannot read from %s", in);
		ret = 1;
		goto out;
	}

	req.page = page;
	req.len = chip_params.oob_size;
	req.data = buf;

	if (ioctl(fd, NAND_IO_OOB_PROG, &req) == -1) {
		perrorf("Cannot write OOB to %s", dev);
		ret = 1;
		goto out;
	}

out:
	g_close(fd);
	if (fd_in != -1)
		close(fd_in);
	if (buf)
		free(buf);

	return (ret);
}
Exemplo n.º 23
0
Arquivo: m_file.c Projeto: camgunz/d2k
bool M_Close(int fd) {
  clear_file_error();

  return g_close(fd, &file_error);
}
Exemplo n.º 24
0
int nand_write(struct cmd_param *params)
{
	struct chip_param_io chip_params;
	char *dev, *file;
	int in_fd = -1, ret = 0, done = 0;
	int fd, block_size, mult, pos, count;
	uint8_t *buf = NULL;

	if (!(dev = param_get_string(params, "dev"))) {
		fprintf(stderr, "Please supply 'dev' argument.\n");
		return (1);
	}

	if (!(file = param_get_string(params, "in"))) {
		fprintf(stderr, "Please supply 'in' argument.\n");
		return (1);
	}

	if ((fd = g_open(dev, 1)) == -1) {
		perrorf("Cannot open %s", dev);
		return (1);
	}

	if ((in_fd = open(file, O_RDONLY)) == -1) {
		perrorf("Cannot open file %s", file);
		ret = 1;
		goto out;
	}

	if (ioctl(fd, NAND_IO_GET_CHIP_PARAM, &chip_params) == -1) {
		perrorf("Cannot ioctl(NAND_IO_GET_CHIP_PARAM)");
		ret = 1;
		goto out;
	}

	block_size = chip_params.page_size * chip_params.pages_per_block;

	if (param_has_value(params, "page")) {
		pos = chip_params.page_size * param_get_int(params, "page");
		mult = chip_params.page_size;
	} else if (param_has_value(params, "block")) {
		pos = block_size * param_get_int(params, "block");
		mult = block_size;
	} else if (param_has_value(params, "pos")) {
		pos = param_get_int(params, "pos");
		mult = 1;
		if (pos % chip_params.page_size) {
			fprintf(stderr, "Position must be page-size "
			    "aligned!\n");
			ret = 1;
			goto out;
		}
	} else {
		fprintf(stderr, "You must specify one of: 'block', 'page',"
		    "'pos' arguments\n");
		ret = 1;
		goto out;
	}

	if (!(param_has_value(params, "count")))
		count = mult;
	else
		count = param_get_int(params, "count") * mult;

	if (!(buf = malloc(chip_params.page_size))) {
		perrorf("Cannot allocate buffer [size %x]",
		    chip_params.page_size);
		ret = 1;
		goto out;
	}

	lseek(fd, pos, SEEK_SET);

	while (done < count) {
		if ((ret = read(in_fd, buf, chip_params.page_size)) !=
		    (int32_t)chip_params.page_size) {
			if (ret > 0) {
				/* End of file ahead, truncate here */
				break;
			} else {
				perrorf("Cannot read from %s", file);
				ret = 1;
				goto out;
			}
		}

		if ((ret = write(fd, buf, chip_params.page_size)) !=
		    (int32_t)chip_params.page_size) {
			ret = 1;
			goto out;
		}

		done += ret;
	}

out:
	g_close(fd);
	if (in_fd != -1)
		close(in_fd);
	if (buf)
		free(buf);

	return (ret);
}
Exemplo n.º 25
0
static gchar *
spawn_dbus_daemon (const gchar *binary,
    const gchar *configuration,
    const gchar *listen_address,
    TestUser user,
    const gchar *runtime_dir,
    GPid *daemon_pid)
{
  GError *error = NULL;
  GString *address;
  gint address_fd;
  GPtrArray *argv;
  gchar **envp;
#ifdef DBUS_UNIX
  const struct passwd *pwd = NULL;
#endif

  if (user != TEST_USER_ME)
    {
#ifdef DBUS_UNIX
      if (getuid () != 0)
        {
          g_test_skip ("cannot use alternative uid when not uid 0");
          return NULL;
        }

      switch (user)
        {
          case TEST_USER_ROOT:
            break;

          case TEST_USER_MESSAGEBUS:
            pwd = getpwnam (DBUS_USER);

            if (pwd == NULL)
              {
                gchar *message = g_strdup_printf ("user '%s' does not exist",
                    DBUS_USER);

                g_test_skip (message);
                g_free (message);
                return NULL;
              }

            break;

          case TEST_USER_OTHER:
            pwd = getpwnam (DBUS_TEST_USER);

            if (pwd == NULL)
              {
                gchar *message = g_strdup_printf ("user '%s' does not exist",
                    DBUS_TEST_USER);

                g_test_skip (message);
                g_free (message);
                return NULL;
              }

            break;

          case TEST_USER_ME:
            /* cannot get here, fall through */
          default:
            g_assert_not_reached ();
        }
#else
      g_test_skip ("cannot use alternative uid on Windows");
      return NULL;
#endif
    }

  envp = g_get_environ ();

  if (runtime_dir != NULL)
    envp = g_environ_setenv (envp, "XDG_RUNTIME_DIR", runtime_dir, TRUE);

  argv = g_ptr_array_new_with_free_func (g_free);
  g_ptr_array_add (argv, g_strdup (binary));
  g_ptr_array_add (argv, g_strdup (configuration));
  g_ptr_array_add (argv, g_strdup ("--nofork"));
  g_ptr_array_add (argv, g_strdup ("--print-address=1")); /* stdout */

  if (listen_address != NULL)
    g_ptr_array_add (argv, g_strdup (listen_address));

#ifdef DBUS_UNIX
  g_ptr_array_add (argv, g_strdup ("--systemd-activation"));
#endif

  g_ptr_array_add (argv, NULL);

  g_spawn_async_with_pipes (NULL, /* working directory */
      (gchar **) argv->pdata,
      envp,
      G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH,
#ifdef DBUS_UNIX
      child_setup, (gpointer) pwd,
#else
      NULL, NULL,
#endif
      daemon_pid,
      NULL, /* child's stdin = /dev/null */
      &address_fd,
      NULL, /* child's stderr = our stderr */
      &error);
  g_assert_no_error (error);

  g_ptr_array_free (argv, TRUE);
  g_strfreev (envp);

  address = g_string_new (NULL);

  /* polling until the dbus-daemon writes out its address is a bit stupid,
   * but at least it's simple, unlike dbus-launch... in principle we could
   * use select() here, but life's too short */
  while (1)
    {
      gssize bytes;
      gchar buf[4096];
      gchar *newline;

      bytes = read (address_fd, buf, sizeof (buf));

      if (bytes > 0)
        g_string_append_len (address, buf, bytes);

      newline = strchr (address->str, '\n');

      if (newline != NULL)
        {
          if ((newline > address->str) && ('\r' == newline[-1]))
            newline -= 1;
          g_string_truncate (address, newline - address->str);
          break;
        }

      g_usleep (G_USEC_PER_SEC / 10);
    }

  g_close (address_fd, NULL);

  return g_string_free (address, FALSE);
}
Exemplo n.º 26
0
int nand_read_oob(struct cmd_param *params)
{
	struct chip_param_io chip_params;
	struct nand_oob_rw req;
	char *dev, *out;
	int fd = -1, fd_out = -1, ret = 0;
	int page;
	uint8_t *buf = NULL;

	if ((page = param_get_int(params, "page")) < 0) {
		fprintf(stderr, "You must supply valid 'page' argument.\n");
		return (1);
	}

	if (!(dev = param_get_string(params, "dev"))) {
		fprintf(stderr, "You must supply 'dev' argument.\n");
		return (1);
	}

	if ((out = param_get_string(params, "out"))) {
		if ((fd_out = open(out, O_WRONLY | O_CREAT)) == -1) {
			perrorf("Cannot open %s", out);
			ret = 1;
			goto out;
		}
	}

	if ((fd = g_open(dev, 1)) == -1) {
		perrorf("Cannot open %s", dev);
		ret = 1;
		goto out;
	}

	if (ioctl(fd, NAND_IO_GET_CHIP_PARAM, &chip_params) == -1) {
		perrorf("Cannot ioctl(NAND_IO_GET_CHIP_PARAM)");
		ret = 1;
		goto out;
	}

	buf = malloc(chip_params.oob_size);
	if (buf == NULL) {
		perrorf("Cannot allocate %d bytes\n", chip_params.oob_size);
		ret = 1;
		goto out;
	}

	req.page = page;
	req.len = chip_params.oob_size;
	req.data = buf;

	if (ioctl(fd, NAND_IO_OOB_READ, &req) == -1) {
		perrorf("Cannot read OOB from %s", dev);
		ret = 1;
		goto out;
	}

	if (fd_out != -1)
		write(fd_out, buf, chip_params.oob_size);
	else
		hexdump(buf, chip_params.oob_size);

out:
	close(fd_out);

	if (fd != -1)
		g_close(fd);
	if (buf)
		free(buf);

	return (ret);
}
Exemplo n.º 27
0
int
g_print_stats (char *file, uint32_t flags, size_t block_sz)
{
  g_setjmp (0, "g_print_stats", NULL, NULL);

  if (block_sz)
    {
      g_act_1.block_sz = block_sz;
    }

  if (g_fopen (file, "r", F_DL_FOPEN_BUFFER | flags, &g_act_1))
    {
      return 2;
    }

  if (gfl & F_OPT_LOADQ)
    {
      goto rc_end;
    }

  void *buffer = calloc (1, g_act_1.block_sz);

  pt_g_bmatch proc_match = g_bmatch;

  int r = 0;

  if (gfl & F_OPT_SORT)
    {
      if (gfl & F_OPT_NOBUFFER)
	{
	  print_str ("ERROR: %s: unable to sort with buffering disabled\n",
		     g_act_1.file);
	  goto r_end;
	}

      void *s_exec = (void*) g_act_1.exec_args.exc;

      if (l_sfo == L_STFO_SORT)
	{
	  if (g_print_do_filter (&g_act_1, s_exec))
	    {
	      goto r_end;
	    }
	}

      if (gfl & F_OPT_KILL_GLOBAL)
	{
	  goto r_end;
	}

      if (do_sort (&g_act_1, g_sort_field, g_sort_flags))
	{
	  goto r_end;
	}

      if (l_sfo == L_STFO_FILTER)
	{
	  if (g_print_do_filter (&g_act_1, s_exec))
	    {
	      goto r_end;
	    }
	}

      if (gfl & F_OPT_KILL_GLOBAL)
	{
	  goto r_end;
	}

      g_act_1.max_hits = 0;
      g_act_1.max_results = 0;

      if (g_act_1.j_offset == 2)
	{
	  g_act_1.buffer.r_pos = md_last (&g_act_1.buffer);
	}
      else
	{
	  g_act_1.buffer.r_pos = md_first (&g_act_1.buffer);
	}

      //proc_match = g_bmatch_dummy;

      md_g_free_cb (&g_act_1._match_rr, g_cl_mrr);
    }

  __d_is_wb w_d_s = g_act_1.w_d;

  g_act_1.w_d = g_act_1.w_d_pr;

  g_do_ppprint (&g_act_1, F_GH_PRE_PRINT, &g_act_1.pre_print_mech,
		g_act_1.g_proc4_pr);

  if (gfl0 & F_OPT_LOADQA)
    {
      goto r_end;
    }

  g_act_1.w_d = w_d_s;

  void *ptr;

  size_t c = 0;

  g_setjmp (F_SIGERR_CONTINUE, "g_print_stats(loop)", NULL, NULL);

  g_act_1.buffer.offset = 0;

  if (!sigsetjmp(g_sigjmp.env, 1))
    {
      while ((ptr = g_read (buffer, &g_act_1, g_act_1.block_sz)))
	{
	  if ((gfl & F_OPT_KILL_GLOBAL))
	    {
	      break;
	    }

	  if ((r = proc_match (ptr, &g_act_1, &g_act_1.buffer)))
	    {
	      if (r == -1)
		{
		  print_str ("ERROR: %s: [%d] matching record failed\n",
			     g_act_1.file, r);
		  break;
		}

	      continue;
	    }

	  c++;
	  g_act_1.g_proc4 ((void*) &g_act_1, ptr, NULL);

	}

    }
  else
    {
      print_str (
	  "ERROR: %s: an exception has occured, terminating enumeration and attempt cleanup..\n",
	  g_act_1.file);
      EXITVAL = 2;
      goto r_end;
    }

  g_act_1.w_d = g_act_1.w_d_po;

  g_do_ppprint (&g_act_1, F_GH_POST_PRINT, &g_act_1.post_print_mech,
		g_act_1.g_proc4_po);

  if (gfl & F_OPT_MODE_RAWDUMP)
    {
#ifdef HAVE_ZLIB_H
      if ((g_act_1.flags & F_GH_IO_GZIP) && g_act_1.gz_fh1)
	{
	  gzflush(g_act_1.gz_fh1, Z_FINISH);
	}
#endif
      fflush (stdout);
    }

  // g_setjmp(0, "dirlog_print_stats(2)", NULL, NULL);

  if (!(g_act_1.flags & F_GH_ISONLINE) && (gfl0 & F_OPT_STATS))
    {
      fprintf (
	  stderr,
	  "STATS: %s: processed %llu/%llu records\n",
	  file,
	  (unsigned long long int) c,
	  !g_act_1.buffer.count ?
	      (unsigned long long int) c : g_act_1.buffer.count);
    }

  if (0 == c && 0 == EXITVAL)
    {
      EXITVAL = 2;
    }

  r_end:

  free (buffer);

  rc_end:

  g_close (&g_act_1);

  return EXITVAL;
}
Exemplo n.º 28
0
static void job_dispose (GObject *obj)
{
        Job *job = JOB (obj);
        GObjectClass *parent_class = g_type_class_peek (G_TYPE_OBJECT);
        JobOutput *output;
        gint i;
        gchar *name_hexstr;

        if (job->output == NULL) {
                return;
        }
        output = job->output;

        /* free semaphore */
        if (output->semaphore != NULL) {
                if (sem_close (output->semaphore) == -1) {
                        GST_ERROR ("sem_close failure: %s", g_strerror (errno));
                }
                if (sem_unlink (output->semaphore_name) == -1) {
                        GST_ERROR ("sem_unlink %s error: %s", job->name, g_strerror (errno));
                }
                g_free (output->semaphore_name);
        }

        /* free encoders output */
        if (job->is_live) {
                if (output->master_m3u8_playlist != NULL) {
                        g_free (output->master_m3u8_playlist);
                        for (i = 0; i < output->encoder_count; i++) {
                                if (output->encoders[i].record_path != NULL) {
                                        g_free (output->encoders[i].record_path);
                                }
                                m3u8playlist_free (output->encoders[i].m3u8_playlist);
                        }
                }
        }
        g_free (output->encoders);

        /* free share memory */
        if (job->output_fd != -1) {
                g_close (job->output_fd, NULL);
                if (munmap (output->job_description, job->output_size) == -1) {
                        GST_ERROR ("munmap %s error: %s", job->name, g_strerror (errno));
                }
                name_hexstr = unicode_file_name_2_shm_name (job->name);
                if (shm_unlink (name_hexstr) == -1) {
                        GST_ERROR ("shm_unlink %s error: %s", job->name, g_strerror (errno));
                }
                g_free (name_hexstr);
        }
        g_free (output);

        if (job->description != NULL) {
                g_free (job->description);
                job->description = NULL;
        }

        if (job->exe_path != NULL) {
                g_free (job->exe_path);
                job->exe_path = NULL;
        }

        if (job->name != NULL) {
                g_free (job->name);
                job->name = NULL;
        }

        G_OBJECT_CLASS (parent_class)->dispose (obj);
}
Exemplo n.º 29
0
/* note that address_entry has already been validated =>
 *  both host and port (guaranteed to be a number in [0, 65535]) are set (family is optional)
 */
static gboolean
try_tcp (GDBusServer  *server,
         const gchar  *address_entry,
         GHashTable   *key_value_pairs,
         gboolean      do_nonce,
         GError      **error)
{
  gboolean ret;
  const gchar *host;
  const gchar *port;
  gint port_num;
  GResolver *resolver;
  GList *resolved_addresses;
  GList *l;

  ret = FALSE;
  resolver = NULL;
  resolved_addresses = NULL;

  host = g_hash_table_lookup (key_value_pairs, "host");
  port = g_hash_table_lookup (key_value_pairs, "port");
  /* family = g_hash_table_lookup (key_value_pairs, "family"); */
  if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
    {
      g_set_error_literal (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
                           _("Cannot specify nonce file when creating a server"));
      goto out;
    }

  if (host == NULL)
    host = "localhost";
  if (port == NULL)
    port = "0";
  port_num = strtol (port, NULL, 10);

  resolver = g_resolver_get_default ();
  resolved_addresses = g_resolver_lookup_by_name (resolver,
                                                  host,
                                                  NULL,
                                                  error);
  if (resolved_addresses == NULL)
    goto out;

  /* TODO: handle family */
  for (l = resolved_addresses; l != NULL; l = l->next)
    {
      GInetAddress *address = G_INET_ADDRESS (l->data);
      GSocketAddress *socket_address;
      GSocketAddress *effective_address;

      socket_address = g_inet_socket_address_new (address, port_num);
      if (!g_socket_listener_add_address (server->listener,
                                          socket_address,
                                          G_SOCKET_TYPE_STREAM,
                                          G_SOCKET_PROTOCOL_TCP,
                                          NULL, /* GObject *source_object */
                                          &effective_address,
                                          error))
        {
          g_object_unref (socket_address);
          goto out;
        }
      if (port_num == 0)
        /* make sure we allocate the same port number for other listeners */
        port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));

      g_object_unref (effective_address);
      g_object_unref (socket_address);
    }

  if (do_nonce)
    {
      gint fd;
      guint n;
      gsize bytes_written;
      gsize bytes_remaining;
      char *file_escaped;

      server->nonce = g_new0 (guchar, 16);
      for (n = 0; n < 16; n++)
        server->nonce[n] = g_random_int_range (0, 256);
      fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
                            &server->nonce_file,
                            error);
      if (fd == -1)
        {
          g_socket_listener_close (server->listener);
          goto out;
        }
    again:
      bytes_written = 0;
      bytes_remaining = 16;
      while (bytes_remaining > 0)
        {
          gssize ret;
          ret = write (fd, server->nonce + bytes_written, bytes_remaining);
          if (ret == -1)
            {
              if (errno == EINTR)
                goto again;
              g_set_error (error,
                           G_IO_ERROR,
                           g_io_error_from_errno (errno),
                           _("Error writing nonce file at '%s': %s"),
                           server->nonce_file,
                           strerror (errno));
              goto out;
            }
          bytes_written += ret;
          bytes_remaining -= ret;
        }
      if (!g_close (fd, error))
        goto out;
      file_escaped = g_uri_escape_string (server->nonce_file, "/\\", FALSE);
      server->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
                                                host,
                                                port_num,
                                                file_escaped);
      g_free (file_escaped);
    }
  else
    {
      server->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
    }
  server->is_using_listener = TRUE;
  ret = TRUE;

 out:
  g_list_free_full (resolved_addresses, g_object_unref);
  g_object_unref (resolver);
  return ret;
}
Exemplo n.º 30
0
static void gst_disk_cache_free_file(int f)
{
  g_close(f);
}