Пример #1
0
static int do_server(int type)
{
	int rv = -1;
	static char log_ent[128] = DAEMON_NAME "-";

	rv = setup_config(type);
	if (rv < 0)
		return rv;

	if (!local) {
		log_error("Cannot find myself in the configuration.");
		exit(EXIT_FAILURE);
	}

	if (daemonize) {
		if (daemon(0, 0) < 0) {
			perror("daemon error");
			exit(EXIT_FAILURE);
		}
	}

	/* The lockfile must be written to _after_ the call to daemon(), so
	 * that the lockfile contains the pid of the daemon, not the parent. */
	lock_fd = create_lockfile();
	if (lock_fd < 0)
		return lock_fd;

	atexit(server_exit);

	strcat(log_ent, type_to_string(local->type));
	cl_log_set_entity(log_ent);
	cl_log_enable_stderr(enable_stderr ? TRUE : FALSE);
	cl_log_set_facility(HA_LOG_FACILITY);
	cl_inherit_logging_environment(0);

	log_info("BOOTH %s %s daemon is starting",
			type_to_string(local->type), RELEASE_STR);

	signal(SIGUSR1, (__sighandler_t)tickets_log_info);
	signal(SIGTERM, (__sighandler_t)sig_exit_handler);
	signal(SIGINT, (__sighandler_t)sig_exit_handler);
	/* we'll handle errors there and then */
	signal(SIGPIPE, SIG_IGN);

	set_scheduler();
	/* we don't want to be killed by the OOM-killer */
	if (set_procfs_val("/proc/self/oom_score_adj", "-999"))
		(void)set_procfs_val("/proc/self/oom_adj", "-16");
	set_proc_title("%s %s %s for [%s]:%d",
			DAEMON_NAME,
			cl.configfile,
			type_to_string(local->type),
			local->addr_string,
			booth_conf->port);

	rv = limit_this_process();
	if (rv)
		return rv;

#ifdef COREDUMP_NURSING
	if (cl_enable_coredumps(TRUE) < 0){
		log_error("enabling core dump failed");
	}
	cl_cdtocoredir();
	prctl(PR_SET_DUMPABLE, (unsigned long)TRUE, 0UL, 0UL, 0UL);
#else
	if (chdir(BOOTH_CORE_DIR) < 0) {
		log_error("cannot change working directory to %s", BOOTH_CORE_DIR);
	}
#endif

	signal(SIGCHLD, (__sighandler_t)wait_child);
	rv = loop(lock_fd);

	return rv;
}
Пример #2
0
const char* datafile_type_to_string(enum datafile_type datafile_type)
{
  return type_to_string(datafile_type_table, datafile_type);
}
Пример #3
0
static void
report_header(
	FILE		*fp,
	uint		form,
	uint		type,
	fs_path_t	*mount,
	int		flags)
{
	char		*typename = type_to_string(type);
	char		scratch[64];
	uint		i, count;

	if (flags & NO_HEADER_FLAG)
		return;

	/* line 1 */
	fprintf(fp, _("%s quota on %s (%s)\n"),
		typename, mount->fs_dir, mount->fs_name);

	/* line 2 */
	for (i = 0; i < 10; i++)
		fputc(' ', fp);
	if (form & XFS_BLOCK_QUOTA)
		fprintf(fp, (flags & HUMAN_FLAG) ?
			"%13c %s %13c" : "%20c %s %20c",
			' ', form_to_string(XFS_BLOCK_QUOTA), ' ');
	if (form & XFS_INODE_QUOTA)
		fprintf(fp, (flags & HUMAN_FLAG) ?
			"%13c %s %13c" : "%20c %s %20c",
			' ', form_to_string(XFS_INODE_QUOTA), ' ');
	if (form & XFS_RTBLOCK_QUOTA)
		fprintf(fp, (flags & HUMAN_FLAG) ?
			"%9c %s %9c" : "%15c %s %15c",
			' ', form_to_string(XFS_RTBLOCK_QUOTA), ' ');
	fputc('\n', fp);

	/* line 3 */
	snprintf(scratch, sizeof(scratch), "%s ID", typename);
	fprintf(fp, "%-10s ", scratch);
	if (form & XFS_BLOCK_QUOTA)
		fprintf(fp, (flags & HUMAN_FLAG) ?
			_("  Used   Soft   Hard Warn/Grace   ") :
		_("      Used       Soft       Hard    Warn/Grace     "));
	if (form & XFS_INODE_QUOTA)
		fprintf(fp, (flags & HUMAN_FLAG) ?
			_("  Used   Soft   Hard Warn/Grace  ") :
		_("      Used       Soft       Hard    Warn/ Grace     "));
	if (form & XFS_RTBLOCK_QUOTA)
		fprintf(fp, (flags & HUMAN_FLAG) ?
			_("  Used   Soft   Hard Warn/Grace   ") :
		_("      Used       Soft       Hard    Warn/Grace     "));
	fputc('\n', fp);

	/* line 4 */
	for (i = 0; i < 10; i++)
		fputc('-', fp);
	fputc(' ', fp);
	count = (flags & HUMAN_FLAG) ? 33 : 50;
	if (form & XFS_BLOCK_QUOTA) {
		for (i = 0; i < count; i++)
			fputc('-', fp);
		fputc(' ', fp);
	}
	if (form & XFS_INODE_QUOTA) {
		for (i = 0; i < count; i++)
			fputc('-', fp);
		fputc(' ', fp);
	}
	if (form & XFS_RTBLOCK_QUOTA) {
		for (i = 0; i < count; i++)
			fputc('-', fp);
		fputc(' ', fp);
	}
	fputc('\n', fp);
}
Пример #4
0
void pcb_creation_printf(PCB_p pcb_ptr) {
    printf("Process created: Type: %s, PID %d at %d with priority %d.\n",
            type_to_string(pcb_ptr->process_type), pcb_ptr->pid,
            pcb_ptr->creation, pcb_ptr->priority);

}
Пример #5
0
static status_t
catAttr(const char *attribute, const char *fileName, bool keepRaw = false)
{
    int fd = open(fileName, O_RDONLY);
    if (fd < 0)
        return errno;

    attr_info info;
    if (fs_stat_attr(fd, attribute, &info) < 0)
        return errno;

    // limit size of the attribute, only the first 64k will make it on screen
    off_t size = info.size;
    bool cut = false;
    if (size > 64 * 1024) {
        size = 64 * 1024;
        cut = true;
    }

    char* buffer = (char*)malloc(size);
    if (!buffer) {
        fprintf(stderr, "Could not allocate read buffer!\n");
        return B_NO_MEMORY;
    }

    ssize_t bytesRead = fs_read_attr(fd, attribute, info.type, 0, buffer, size);
    if (bytesRead < 0) {
        free(buffer);
        return errno;
    }

    if (bytesRead != size) {
        fprintf(stderr, "Could only read %ld bytes from attribute!\n",
                bytesRead);
        free(buffer);
        return B_ERROR;
    }

    if (keepRaw) {
        off_t pos = 0;
        ssize_t written = 0;
        while (pos < info.size) {
            // write what we have read so far
            written = write(STDOUT_FILENO, buffer, bytesRead);
            // check for write error
            if (written < bytesRead) {
                if (written >= 0) {
                    fprintf(stderr, "Could only write %ld bytes to stream!\n",
                            written);
                    written = B_ERROR;
                } else {
                    fprintf(stderr, "Failed to write to stream: %s\n",
                            strerror(written));
                }
                break;
            }
            // read next chunk of data at pos
            pos += bytesRead;
            bytesRead = fs_read_attr(fd, attribute, info.type, pos, buffer,
                                     size);
            // check for read error
            if (bytesRead < size && pos + bytesRead < info.size) {
                if (bytesRead >= 0) {
                    fprintf(stderr, "Could only read %ld bytes from "
                            "attribute!\n", bytesRead);
                } else {
                    fprintf(stderr, "Failed to read from attribute: %s\n",
                            strerror(bytesRead));
                }
                written = B_ERROR;
                break;
            }
        }
        free(buffer);
        if (written > 0)
            written = B_OK;
        return written;
    }

    switch (info.type) {
    case B_INT8_TYPE:
        printf("%s : int8 : %d\n", fileName, *((int8 *)buffer));
        break;
    case B_UINT8_TYPE:
        printf("%s : uint8 : %u\n", fileName, *((uint8 *)buffer));
        break;
    case B_INT16_TYPE:
        printf("%s : int16 : %d\n", fileName, *((int16 *)buffer));
        break;
    case B_UINT16_TYPE:
        printf("%s : uint16 : %u\n", fileName, *((uint16 *)buffer));
        break;
    case B_INT32_TYPE:
        printf("%s : int32 : %ld\n", fileName, *((int32 *)buffer));
        break;
    case B_UINT32_TYPE:
        printf("%s : uint32 : %lu\n", fileName, *((uint32 *)buffer));
        break;
    case B_INT64_TYPE:
        printf("%s : int64 : %Ld\n", fileName, *((int64 *)buffer));
        break;
    case B_UINT64_TYPE:
        printf("%s : uint64 : %Lu\n", fileName, *((uint64 *)buffer));
        break;
    case B_FLOAT_TYPE:
        printf("%s : float : %f\n", fileName, *((float *)buffer));
        break;
    case B_DOUBLE_TYPE:
        printf("%s : double : %f\n", fileName, *((double *)buffer));
        break;
    case B_BOOL_TYPE:
        printf("%s : bool : %d\n", fileName, *((unsigned char *)buffer));
        break;
    case B_STRING_TYPE:
        printf("%s : string : %s\n", fileName, buffer);
        break;

    case B_MIME_STRING_TYPE:
    case 'MSIG':
    case 'MSDC':
    case 'MPTH':
        printf("%s : %s : %s\n", fileName, type_to_string(info.type),
               buffer);
        break;

    case B_MESSAGE_TYPE:
    {
        BMessage message;
        if (!cut && message.Unflatten(buffer) == B_OK) {
            printf("%s : message :\n", fileName);
            message.PrintToStream();
            break;
        }
        // supposed to fall through
    }

    default:
        // The rest of the attributes types are displayed as raw data
        printf("%s : %s : \n", fileName, type_to_string(info.type));
        dumpRawData(buffer, size);
        break;
    }

    free(buffer);
    return B_OK;
}
Пример #6
0
			value_type infer_binary_type(object_converter factory, node_type &left, node_type &right) {
				value_type rt = right->infer_type(factory);
				value_type lt = left->infer_type(factory);
				if (lt == type_multi || rt == type_multi) {
					if (lt == rt)
						return type_tbd;
					if (lt == type_multi)
						lt = left->infer_type(factory, rt);
					else 
						rt = right->infer_type(factory, lt);
				}
				if (lt == rt)
					return lt;
				if (rt == type_invalid || lt == type_invalid)
					return type_invalid;
				if (rt == type_tbd && lt == type_tbd)
					return type_tbd;
				if (factory->can_convert(rt, lt)) {
					right = add_convert_node(right, lt);
					return lt;
				}
				if (factory->can_convert(lt, rt)) {
					left = add_convert_node(left, rt);
					return rt;
				}
				if (can_convert(rt, lt)) {
					right = add_convert_node(right, lt);
					return lt;
				}
				if (can_convert(lt, rt)) {
					left = add_convert_node(left, rt);
					return rt;
				}
				factory->error("Cannot compare " + left->to_string() + " to " + right->to_string() + " (" + type_to_string(lt) + " to " + type_to_string(rt) + ")");
				return type_invalid;
			}
Пример #7
0
void
c_get_string (struct value *value, gdb_byte **buffer,
	      int *length, struct type **char_type,
	      const char **charset)
{
  int err, width;
  unsigned int fetchlimit;
  struct type *type = check_typedef (value_type (value));
  struct type *element_type = TYPE_TARGET_TYPE (type);
  int req_length = *length;
  enum bfd_endian byte_order
    = gdbarch_byte_order (get_type_arch (type));
  enum c_string_type kind;

  if (element_type == NULL)
    goto error;

  if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
    {
      /* If we know the size of the array, we can use it as a limit on
	 the number of characters to be fetched.  */
      if (TYPE_NFIELDS (type) == 1
	  && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_RANGE)
	{
	  LONGEST low_bound, high_bound;

	  get_discrete_bounds (TYPE_FIELD_TYPE (type, 0),
			       &low_bound, &high_bound);
	  fetchlimit = high_bound - low_bound + 1;
	}
      else
	fetchlimit = UINT_MAX;
    }
  else if (TYPE_CODE (type) == TYPE_CODE_PTR)
    fetchlimit = UINT_MAX;
  else
    /* We work only with arrays and pointers.  */
    goto error;

  if (! c_textual_element_type (element_type, 0))
    goto error;
  kind = classify_type (element_type,
			get_type_arch (element_type),
			charset);
  width = TYPE_LENGTH (element_type);

  /* If the string lives in GDB's memory instead of the inferior's,
     then we just need to copy it to BUFFER.  Also, since such strings
     are arrays with known size, FETCHLIMIT will hold the size of the
     array.  */
  if ((VALUE_LVAL (value) == not_lval
       || VALUE_LVAL (value) == lval_internalvar)
      && fetchlimit != UINT_MAX)
    {
      int i;
      const gdb_byte *contents = value_contents (value);

      /* If a length is specified, use that.  */
      if (*length >= 0)
	i  = *length;
      else
 	/* Otherwise, look for a null character.  */
 	for (i = 0; i < fetchlimit; i++)
	  if (extract_unsigned_integer (contents + i * width,
					width, byte_order) == 0)
 	    break;
  
      /* I is now either a user-defined length, the number of non-null
 	 characters, or FETCHLIMIT.  */
      *length = i * width;
      *buffer = xmalloc (*length);
      memcpy (*buffer, contents, *length);
      err = 0;
    }
  else
    {
      CORE_ADDR addr = value_as_address (value);

      err = read_string (addr, *length, width, fetchlimit,
			 byte_order, buffer, length);
      if (err)
	{
	  xfree (*buffer);
	  if (err == EIO)
	    throw_error (MEMORY_ERROR, "Address %s out of bounds",
			 paddress (get_type_arch (type), addr));
	  else
	    error (_("Error reading string from inferior: %s"),
		   safe_strerror (err));
	}
    }

  /* If the LENGTH is specified at -1, we want to return the string
     length up to the terminating null character.  If an actual length
     was specified, we want to return the length of exactly what was
     read.  */
  if (req_length == -1)
    /* If the last character is null, subtract it from LENGTH.  */
    if (*length > 0
 	&& extract_unsigned_integer (*buffer + *length - width,
				     width, byte_order) == 0)
      *length -= width;
  
  /* The read_string function will return the number of bytes read.
     If length returned from read_string was > 0, return the number of
     characters read by dividing the number of bytes by width.  */
  if (*length != 0)
     *length = *length / width;

  *char_type = element_type;

  return;

 error:
  {
    char *type_str;

    type_str = type_to_string (type);
    if (type_str)
      {
	make_cleanup (xfree, type_str);
	error (_("Trying to read string with inappropriate type `%s'."),
	       type_str);
      }
    else
      error (_("Trying to read string with inappropriate type."));
  }
}
Пример #8
0
static int
quota_mount(
	FILE		*fp,
	__uint32_t	id,
	char		*name,
	uint		form,
	uint		type,
	fs_path_t	*mount,
	uint		flags)
{
	fs_disk_quota_t	d;
	char		*dev = mount->fs_name;
	char		c[8], h[8], s[8];
	uint		qflags;
	int		count;

	xfsquotactl(XFS_QSYNC, dev, type, 0, NULL);
	if (xfsquotactl(XFS_GETQUOTA, dev, type, id, (void *)&d) < 0)
		return 0;

	if (!(flags & VERBOSE_FLAG)) {
		count = 0;
		if ((form & XFS_BLOCK_QUOTA) && d.d_bcount)
			count++;
		if ((form & XFS_INODE_QUOTA) && d.d_icount)
			count++;
		if ((form & XFS_RTBLOCK_QUOTA) && d.d_rtbcount)
			count++;
		if (!count)
			return 0;
	}

	if (!(flags & NO_HEADER_FLAG)) {
		fprintf(fp,
			_("Disk quotas for %s %s (%u)\nFilesystem%s"),
			type_to_string(type), name, id,
			(flags & HUMAN_FLAG) ? "  " : "         ");
		if (form & XFS_BLOCK_QUOTA)
			fprintf(fp, (flags & HUMAN_FLAG) ?
			_(" Blocks  Quota  Limit Warn/Time    ") :
	_("     Blocks      Quota      Limit  Warn/Time      "));
		if (form & XFS_INODE_QUOTA)
			fprintf(fp, (flags & HUMAN_FLAG) ?
			_("  Files  Quota  Limit Warn/Time    ") :
	_("      Files      Quota      Limit  Warn/Time      "));
		if  (form & XFS_RTBLOCK_QUOTA)
			fprintf(fp, (flags & HUMAN_FLAG) ?
			_("Realtime Quota  Limit Warn/Time    ") :
	_("   Realtime      Quota      Limit  Warn/Time      "));
		fputs("Mounted on\n", fp);
	}

	if (flags & HUMAN_FLAG) {
		count = fprintf(fp, "%-12s", dev);
		if (count > 13)
			fprintf(fp, "\n%12s", " ");
	} else {
		count = fprintf(fp, "%-19s", dev);
		if (count > 20)
			fprintf(fp, "\n%19s", " ");
	}

	if (form & XFS_BLOCK_QUOTA) {
		qflags = (flags & HUMAN_FLAG);
		if (d.d_blk_hardlimit && d.d_bcount > d.d_blk_hardlimit)
			qflags |= LIMIT_FLAG;
		if (d.d_blk_softlimit && d.d_bcount > d.d_blk_softlimit)
			qflags |= QUOTA_FLAG;
		if (flags & HUMAN_FLAG)
			fprintf(fp, " %6s %6s %6s  %02d %8s ",
				bbs_to_string(d.d_bcount, c, sizeof(c)),
				bbs_to_string(d.d_blk_softlimit, s, sizeof(s)),
				bbs_to_string(d.d_blk_hardlimit, h, sizeof(h)),
				d.d_bwarns,
				time_to_string(d.d_btimer, qflags));
		else
			fprintf(fp, " %10llu %10llu %10llu   %02d %9s ",
				(unsigned long long)d.d_bcount >> 1,
				(unsigned long long)d.d_blk_softlimit >> 1,
				(unsigned long long)d.d_blk_hardlimit >> 1,
				d.d_bwarns,
				time_to_string(d.d_btimer, qflags));
	}
Пример #9
0
Program::Program(const std::string& vs, const std::string& fs, const std::string& debug_name)
	: _debug_name(debug_name)
{
	VLOG_SCOPE_F(1, "Compiling GLSL %s", debug_name.c_str());

	CHECK_FOR_GL_ERROR;

	GLuint vs_id = load_shader(GL_VERTEX_SHADER,   vs.c_str(), debug_name.c_str());
	GLuint fs_id = load_shader(GL_FRAGMENT_SHADER, fs.c_str(), debug_name.c_str());

	_program = glCreateProgram();

#if TARGET_OS_IPHONE
	// For debugger:
	glLabelObjectEXT(GL_PROGRAM_OBJECT_EXT, _program, 0, debug_name.c_str());
#endif

	glAttachShader(_program, vs_id);
	glAttachShader(_program, fs_id);

	//GLuint color_number = 0;
	//glBindFragDataLocation(_program, color_number, "out_frag_color");

	link_program(_program, debug_name.c_str());

	/* too early to validate: uniforms haven't been bound yet.
	   Using two samplers of different type (sampler2D and sampler_cube)
	   will break the validation.
	 */
	//validate();

	CHECK_FOR_GL_ERROR;

	//debug_print();

#if 0
	LOG_F(INFO, "Shader: %s", debug_name.c_str());
	LOG_F(INFO, "-------------------------------------");
	LOG_F(INFO, "%s", vs.c_str());
	LOG_F(INFO, "-------------------------------------");
	LOG_F(INFO, "%s", fs.c_str());
	LOG_F(INFO, "-------------------------------------");
#endif

	GLint num_attribs;
	glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTES, &num_attribs);

	for (int i=0; i<num_attribs; ++i) {
		GLint size;
		GLenum type;
		GLchar name[1024];
		glGetActiveAttrib(_program, i, sizeof(name), NULL, &size, &type, name);
		int location = glGetAttribLocation(_program, name);
		CHECK_NE_F(location, -1, "Attribute '%s' not found in shader '%s'", name, _debug_name.c_str());
		VLOG_F(1, "Attribute %d: %10s, %d x %s, location: %d", i, name, size, type_to_string(type), location);
		_attributes.emplace_back(Attribute{name, size, type, location});
	}

	GLint num_uniforms;
	glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &num_uniforms);

	for (int i=0; i<num_uniforms; ++i) {
		GLint size;
		GLenum type;
		GLchar name[1024];
		glGetActiveUniform(_program, i, sizeof(name), NULL, &size, &type, name);
		int location = glGetUniformLocation(_program, name);
		CHECK_NE_F(location, -1, "Uniform '%s' not found in shader '%s'", name, _debug_name.c_str());
		VLOG_F(1, "Uniform %d: %10s, %d x %s, location: %d", i, name, size, type_to_string(type), location);
		_uniforms.emplace_back(Uniform{name, size, type, location});
	}
}
Пример #10
0
bool writePLY(const std::string& filename,const cv::Mat& disparityImage,cv::Mat img,const cv::Mat& Q,const cv::Mat& rH)
{
#define VALID(i,_x,_y) validPixel(i,mapped,_posImage,_x,_y)

    std::ofstream file(filename.c_str());

    if(!file)
    {
        std::cerr<<"Can't open file "<<filename<<std::endl;
        return false;
    }


    int i=0;
    cv::Mat mapped=cv::Mat(3,disparityImage.rows*disparityImage.cols,cv::DataType<float>::type,1.0);

    if(!rH.empty())
    {
        //Only count pixels of disparity image which mapped via rH^(-1) are inside the unrectified image
        cv::Mat p=cv::Mat(3,disparityImage.rows*disparityImage.cols,cv::DataType<float>::type,1.0);

        for(float y=0;y<disparityImage.rows;y++)
        {
            for(float x=0;x<disparityImage.cols;x++,i++)
            {
                p.at<float>(0,i)=x;
                p.at<float>(1,i)=y;
            }
        }
        cv::Mat rHF;
        rH.convertTo(rHF,cv::DataType<float>::type);
        fprintf(stderr,"\nSolving Equation System %ix%i %ix%i %ix%i",rHF.rows,rHF.cols,mapped.rows,mapped.cols,p.rows,p.cols);
        cv::solve(rHF,p,mapped);
        rHF.release();
        p.release();
        for(i=0;i<mapped.cols;i++)
        {
            mapped.at<float>(0,i)=mapped.at<float>(0,i)/mapped.at<float>(2,i);
            mapped.at<float>(1,i)=mapped.at<float>(1,i)/mapped.at<float>(2,i);
        }
    }else
    {
    	fprintf(stderr,"\nRectifying Homography is empty");
      mapped.create(2,disparityImage.rows*disparityImage.cols,cv::DataType<float>::type);
      mapped.setTo(cv::Scalar(1.0));
    }


    i=0;
    int noVertices=0;
    int noTriangles=0;

    cv::Mat _posImage(disparityImage.rows,disparityImage.cols,cv::DataType<cv::Vec3f>::type);
    //Reproject image point
    if(type_to_string(disparityImage)!="short" && type_to_string(disparityImage)!="float")
    {
        std::cerr<<"Converting disparity image to datatype float"<<std::endl;
        cv::Mat tmp;
        disparityImage.convertTo(tmp,CV_32F);
        cv::reprojectImageTo3D(tmp,_posImage,Q,true);
    }else
    {
        cv::reprojectImageTo3D(disparityImage,_posImage,Q,true);
    }
    std::stringstream verticesBuffer;
    std::stringstream trianglesBuffer;

    //Write vertices into buffer
    int * indexToVertex = new int[disparityImage.rows*disparityImage.cols];
    std::cout<<mapped.rows<<std::endl;
    std::cout<<mapped.cols<<std::endl;
    float * z=new float[mapped.cols];

    for(int x=0;x<disparityImage.cols;x++)
    {
        for(int y=0;y<disparityImage.rows;y++,i++)
        {
            if(validPixel(i,mapped,_posImage,x,y))//Only those vertices which are valid
            {
                verticesBuffer<<_posImage.at<cv::Vec3f>(y,x)[0]<<" "<<_posImage.at<cv::Vec3f>(y,x)[1]<<" "<<_posImage.at<cv::Vec3f>(y,x)[2]<<
                                " "<<(int)img.at<cv::Vec3b>(y,x)[0]<<" "<<(int)img.at<cv::Vec3b>(y,x)[1]<<" "<<(int)img.at<cv::Vec3b>(y,x)[2]<<std::endl;
                z[i]=_posImage.at<cv::Vec3f>(y,x)[2];
                indexToVertex[i]=noVertices++; //Keep track of what pixel maps to which vertex
            }
        }
    }

    //Write triangles into a buffer
    i=0;
    bool first=true;
    for(double x=0;x<disparityImage.cols;x++)
    {
        for(double y=0;y<disparityImage.rows;y++,i++)
        {
            if(x<disparityImage.rows-1 && y<disparityImage.cols-1 && VALID(i,x,y)) //Only those vertices which are valid
            {
                const int right_idx=(x+1)*disparityImage.rows + y;
                //first triangle (i,i+1,right_idx+1)
                if(VALID(i+1,x,y+1) && VALID(right_idx+1,x+1,y+1)) //Only those triangles which contain noly valid vertices
                {
                    if(fabs(z[i]-z[i+1])<0.1 && fabs(z[i]-z[right_idx+1])<0.1)
                    {
                        noTriangles++;
                        if(!first)
                        {
                            trianglesBuffer<<std::endl;
                        }else
                        {
                            first=false;
                        }
                        trianglesBuffer<<"3 "<<indexToVertex[i]<<" "<<indexToVertex[i+1]<<" "<<indexToVertex[right_idx+1];
                    }
                }
                //second triangle (i,right_idx+1,right_idx)
                if(VALID(right_idx+1,x+1,y+1) && VALID(right_idx,x+1,y)) //Only those triangles which contain noly valid vertices
                {
                    if(fabs(z[right_idx+1]-z[i])<0.1 && fabs(z[right_idx]-z[i])<0.1)
                    {
                        noTriangles++;
                        if(!first)
                        {
                            trianglesBuffer<<std::endl;
                        }else
                        {
                            first=false;
                        }
                        trianglesBuffer<<"3 "<<indexToVertex[i]<<" "<<indexToVertex[right_idx+1]<<" "<<indexToVertex[right_idx];
                    }
                }
            }
        }
    }
    delete [] z;
    delete [] indexToVertex;

    //Write PLY header
    file << "ply\nformat ascii 1.0\nelement vertex "
         << noVertices << "\nproperty float x\nproperty float y\nproperty float z";

    file << "\nproperty uchar red\nproperty uchar green\nproperty uchar blue";

    file << "\nelement face " << noTriangles
         << "\nproperty list uint8 int32 vertex_indices\nend_header\n";

    //Write vetices buffer to file
    file<<verticesBuffer.str();
    file.flush();
    //Write triangles buffer to file
    file<<trianglesBuffer.str();
    file.flush();
    file.close();
    return true;
#undef VALID
}
Пример #11
0
/* 
 * Make the given NODE simple - i.e. return a temporary for complex subtrees 
 * The appropriate code is also generated and pushed onto the code stack
*/
value *make_simple(environment *env, NODE *node, int flag, int return_type) {
	int i_value = 0;
	char *s_tmp = NULL;
	value *val1 = NULL, *val2 = NULL, *temporary = NULL, *temp = NULL;
	static int if_count = 0;
	static int while_count = 0;	
	tac_quad *temp_quad = NULL;
	environment *new_env = NULL;
	if (node==NULL) return NULL;
	switch(type_of(node)) {
		case LEAF: 
			return make_simple(env, node->left, flag, return_type);
		case CONSTANT:
			i_value = cast_from_node(node)->value;
			s_tmp = malloc(sizeof(char) * 25);
			sprintf(s_tmp, "%d", i_value);
			return int_value(i_value);
		case IDENTIFIER:
			return string_value(cast_from_node(node)->lexeme);
		case IF:
			build_if_stmt(env, node, ++if_count, NULL, NULL, flag, return_type);
			return NULL;
		case BREAK:
			s_tmp = malloc(sizeof(char) * 25);
			sprintf(s_tmp, "__while%dend", while_count);
			append_code(make_goto(s_tmp));
			return NULL;			
		case CONTINUE:
			s_tmp = malloc(sizeof(char) * 25);
			sprintf(s_tmp, "__while%d", while_count);
			append_code(make_goto(s_tmp));
			return NULL;
		case WHILE:
			build_while_stmt(env, node, ++while_count, ++if_count, flag, return_type);
			return NULL;	
		case '=':
			if (flag == INTERPRET_FN_SCAN) return NULL;
			val1 = make_simple(env, node->left, flag, return_type);
			val2 = make_simple(env, node->right, flag, return_type);
			if (val2 && val2->value_type!=VT_INTEGR && val2->value_type!=VT_FUNCTN) {
				if (val2->value_type == VT_STRING) {
					val2 = get(env, val2->data.string_value);
				}
				else {
					val2 = get(env, val2->identifier);
				}
				if (!val2) fatal("Undeclared identifier");					
			}
			/* Check the LHS variable has already been defined */
			temp = get(env, to_string(val1));
			assert(temp!=NULL, "Variable not defined");
			/* Type check the assignment */
			type_check_assignment(val1, val2, vt_type_convert(temp->value_type));
			temporary = assign(env, val1, val2, 0);
			if (flag != INTERPRET_FN_SCAN) append_code(make_quad_value("=", val2, NULL, temporary, TT_ASSIGN, 0));
			return NULL;
		case '*':
		case '/':
		case '>':
		case '<':										
		case '%':							
		case '-':									
		case '+':
		case NE_OP:
		case LE_OP:
		case GE_OP:				
		case EQ_OP:
			temporary = generate_temporary(env, int_value(0));
			val1 = make_simple(env, node->left, flag, return_type);
			val2 = make_simple(env, node->right, flag, return_type);
			if (val1->value_type==VT_STRING) val1 = get(env, correct_string_rep(val1));
			if (val2->value_type==VT_STRING) val2 = get(env, correct_string_rep(val2));
			assert(val1 != NULL, "Operand value 1 must not be null");	
			assert(val2 != NULL, "Operand value 2 must not be null");				
			if (flag != INTERPRET_FN_SCAN) append_code(make_quad_value(type_to_string(type_of(node)), val1, val2, temporary, TT_OP, type_of(node)));
			return temporary;
		case '~':
			if (flag != INTERPRET_PARAMS && flag!=INTERPRET_FN_SCAN) {
				/* Params should not be registered, because at this point we're not in the correct environment */
				register_variable_subtree_tac(env, node, VT_ANY);
			}
			val1 = make_simple(env, node->left, flag, return_type);
			val2 = make_simple(env, node->right, flag, return_type);
			if (flag == INTERPRET_PARAMS) {
				return int_param(to_string(val2), to_int(env, val1));
			}			
			return NULL;
		case 'D':
			/* val1 is FN definition */
			/* val1 is executed in current environment */
			val1 = make_simple(env, node->left, flag, return_type);
			
			/* New FN body environment */
			new_env = create_environment(env);
			if (val1!=NULL) {
				/* Point function to the correct fn body */
				val1->data.func->node_value = node->right;			
				/* Store function definition in environment */
				val2 = store_function(env, val1, new_env);
			}
			if (flag != INTERPRET_FN_SCAN) {
				/* Write out FN Name label */
				append_code(make_begin_fn(val2));				
				append_code(make_fn_def(val2));
				/* Make init frame */
				temp_quad = make_init_frame();
				append_code(temp_quad);
				/* Define parameters with default empty values */
				register_params(new_env, val2->data.func->params);
				append_code(make_fn_body(val2));
				/* Look inside fn body */
				val2 = make_simple(new_env, node->right, EMBEDDED_FNS, val1->data.func->return_type);
				/* Update prepare frame with environment size */
				temp_quad->operand1 = int_value(env_size(new_env));
				/* Write end of function marker */
				append_code(make_end_fn(val2));
			}
			return NULL;
		case 'd':
			/* val1 is the type */
			val1 = make_simple(env, node->left, flag, return_type);
			/* val2 is fn name & params */
			val2 = make_simple(env, node->right, flag, return_type);
			/* Store return type */
			val2->data.func->return_type = to_int(env, val1);
			return val2;
		case 'F':
			/* FN name in val1 */
			val1 = make_simple(env, node->left, flag, return_type);
			/* Pull our parameters */
			val2 = make_simple(env, node->right, INTERPRET_PARAMS, return_type);
			return build_function(env, val1, val2);
		case RETURN:
			val1 = make_simple(env, node->left, flag, return_type);
			/* Provide lookup for non-constants */
			if (val1 && val1->value_type!=VT_INTEGR) {
				if (val1->value_type == VT_STRING) {
					val1 = get(env, val1->data.string_value);
				}
				else {
					val1 = get(env, val1->identifier);
				}
				if (!val1) fatal("Undeclared identifier");
			}
			type_check_return(val1, return_type);
			append_code(make_return(val1));
			return NULL;
		case ',':
			val1 = make_simple(env, node->left, flag, return_type);
			val2 = make_simple(env, node->right, flag, return_type);
			if (val1 && val2) {
				return join(val1, val2);
			}
			return NULL;	
		case APPLY:
			/* FN Name */
			val1 = make_simple(env, node->left, flag, return_type);
			/* Params */
			val2 = make_simple(env, node->right, flag, return_type);
			/* Lookup function */
			temp = search(env, to_string(val1), VT_FUNCTN, VT_ANY, 1);
			if (temp) {
				int fn_return_type;
				append_code(prepare_fn(val2));
				append_code(push_params(env, val2));
				/* If we can't typecheck, set a special UNDEFINED flag to say we can't */
				/* typecheck. This can happen with function variables, we do not EASILY know the */
				/* return type of the functions they are bound to until runtime. */
				fn_return_type = UNDEFINED;
				if (temp->data.func) {
					fn_return_type = temp->data.func->return_type;	
				} 
				/* Temporary for result (if any) */
				switch(fn_return_type) {
					case INT:
						temporary = generate_temporary(env, int_value(0));
						break;
					case VOID:
						temporary = generate_temporary(env, NULL);
						break;						
					case FUNCTION:
						temporary = generate_temporary(env, null_fn);
						break;
					default:
						temporary = generate_untypechecked_temporary(env);
						break;
				}
				append_code(make_fn_call(temporary, temp));
				return temporary;
			}
			else {
				fatal("Cannot find function '%s'", to_string(val1));
			}
			return NULL;
		case FUNCTION:
		case INT:
		case VOID:
			return int_value(type_of(node));
		case ';':
			make_simple(env, node->left, flag, return_type);
			make_simple(env, node->right, flag, return_type);			
			return NULL;
		default:
			fatal("Unrecognised node type");
			return NULL;
	}
}
Пример #12
0
bool writePLYBinary(const std::string& filename,const cv::Mat& disparityImage,cv::Mat img,const cv::Mat& Q,const cv::Mat& rH)
{
#define VALID(i,_x,_y) validPixel(i,mapped,_posImage,_x,_y)


    std::ofstream file(filename.c_str(),std::ios::binary | std::ios::out);

    if(!file)
    {
        std::cerr<<"Can't open file "<<filename<<std::endl;
        return false;
    }


    int i=0;
    cv::Mat mapped=cv::Mat(3,disparityImage.rows*disparityImage.cols,cv::DataType<float>::type,1.0);

    if(!rH.empty())
    {
        //Only count pixels of disparity image which mapped via rH^(-1) are inside the unrectified image
        cv::Mat p=cv::Mat(3,disparityImage.rows*disparityImage.cols,cv::DataType<float>::type,1.0);

        for(float y=0;y<disparityImage.rows;y++)
        {
            for(float x=0;x<disparityImage.cols;x++,i++)
            {
                p.at<float>(0,i)=x;
                p.at<float>(1,i)=y;
            }
        }
        cv::Mat rHF;
        rH.convertTo(rHF,cv::DataType<float>::type);
        fprintf(stderr,"\nSolving Equation System %ix%i %ix%i %ix%i",rHF.rows,rHF.cols,mapped.rows,mapped.cols,p.rows,p.cols);
        cv::solve(rHF,p,mapped);
        rHF.release();
        p.release();
        for(i=0;i<mapped.cols;i++)
        {
            mapped.at<float>(0,i)=mapped.at<float>(0,i)/mapped.at<float>(2,i);
            mapped.at<float>(1,i)=mapped.at<float>(1,i)/mapped.at<float>(2,i);
        }
    }else
    {
        fprintf(stderr,"\nRectifying Homography is empty");
      mapped.create(2,disparityImage.rows*disparityImage.cols,cv::DataType<float>::type);
      mapped.setTo(cv::Scalar(1.0));
    }


    i=0;
    int noVertices=0;
    int noTriangles=0;

    cv::Mat _posImage(disparityImage.rows,disparityImage.cols,cv::DataType<cv::Vec3f>::type);
    //Reproject image point
    if(type_to_string(disparityImage)!="short" && type_to_string(disparityImage)!="float")
    {
        std::cerr<<"Converting disparity image to datatype float"<<std::endl;
        cv::Mat tmp;
        disparityImage.convertTo(tmp,CV_32F);
        cv::reprojectImageTo3D(tmp,_posImage,Q,true);
    }else
    {
        cv::reprojectImageTo3D(disparityImage,_posImage,Q,true);
    }

    //Write vertices into buffer
    int * indexToVertex = new int[disparityImage.rows*disparityImage.cols];
    memset(indexToVertex,0,disparityImage.rows*disparityImage.cols*sizeof(int));
    float * z=new float[mapped.cols];
    char * vertexBuffer =new char[disparityImage.rows*disparityImage.cols*(4*3+3)];
    for(int x=0;x<disparityImage.cols;x++)
    {
        for(int y=0;y<disparityImage.rows;y++,i++)
        {
            if(validPixel(i,mapped,_posImage,x,y))//Only those vertices which are valid
            {
                char * buffC = vertexBuffer + (noVertices)*(4*3+3) + 4*3;
                float * buffF = (float*) (vertexBuffer + (noVertices)*(4*3+3));
                buffF[0]=_posImage.at<cv::Vec3f>(y,x)[0];
                buffF[1]=_posImage.at<cv::Vec3f>(y,x)[1];
                buffF[2]=_posImage.at<cv::Vec3f>(y,x)[2];
                buffC[0]=img.at<cv::Vec3b>(y,x)[0];
                buffC[1]=img.at<cv::Vec3b>(y,x)[1];
                buffC[2]=img.at<cv::Vec3b>(y,x)[2];
                z[i]=_posImage.at<cv::Vec3f>(y,x)[2];
                indexToVertex[i]=noVertices++; //Keep track of what pixel maps to which vertex
            }
        }
    }

    //Write triangles into a buffer
    i=0;
    char * trianglesBuffer = new char[disparityImage.cols*disparityImage.cols*2*(1+3*4)];
    for(double x=0;x<disparityImage.cols;x++)
    {
        for(double y=0;y<disparityImage.rows;y++,i++)
        {
            if(x<disparityImage.rows-1 && y<disparityImage.cols-1 && VALID(i,x,y)) //Only those vertices which are valid
            {
                const int right_idx=(x+1)*disparityImage.rows + y;
                //first triangle (i,i+1,right_idx+1)
                if(VALID(i+1,x,y+1) && VALID(right_idx+1,x+1,y+1)) //Only those triangles which contain noly valid vertices
                {
                    if(fabs(z[i]-z[i+1])<0.1 && fabs(z[i]-z[right_idx+1])<0.1)
                    {

                        char * buffC= trianglesBuffer +  noTriangles*(1+3*4);
                        int * buffI= (int*)(buffC+1);
                        buffC[0]=3;
                        buffI[0]=indexToVertex[i];
                        buffI[1]=indexToVertex[i+1];
                        buffI[2]=indexToVertex[right_idx+2];
                        if(buffI[0]>=noVertices || buffI[1]>=noVertices || buffI[2]>=noVertices)
                        {
                            std::cout<<"ARRRRGHHHHH "<<buffI[0]<<" "<<buffI[1]<<" "<<buffI[2]<<" "<<noVertices<<" "<<i<<std::endl;
                        }
                        noTriangles++;
                    }
                }
                //second triangle (i,right_idx+1,right_idx)
//                if(VALID(right_idx+1,x+1,y+1) && VALID(right_idx,x+1,y)) //Only those triangles which contain noly valid vertices
//                {
//                    if(fabs(z[right_idx+1]-z[i])<0.1 && fabs(z[right_idx]-z[i])<0.1)
//                    {
//                        char * buffC= trianglesBuffer +  noTriangles*(1+3*4);
//                        int * buffI= (int*)(buffC+1);
//                        buffC[0]=3;
//                        buffI[0]=indexToVertex[i];
//                        buffI[1]=indexToVertex[right_idx+1];
//                        buffI[2]=indexToVertex[right_idx];
//                        noTriangles++;
//                    }
//                }
            }
        }
    }
    delete [] z;
    delete [] indexToVertex;

    file << "ply\nformat binary_little_endian 1.0\n"
    << "element vertex "<< noVertices << "\nproperty float32 x\nproperty float32 y\nproperty float32 z"
    << "\nproperty uchar red\nproperty uchar green\nproperty uchar blue\n"
    << "element face " << noTriangles
    << "\nproperty list uint8 int32 vertex_indices\n"
    << "end_header\n";


    file.write(vertexBuffer,(noVertices)*(sizeof(float)*3+3));
    file.write(trianglesBuffer,(noTriangles)*(1+3*sizeof(int)));
//    noVertices=0;
//    char * buffC = vertexBuffer + (noVertices)*(4*3+3) + 4*3;
//    float * buffF = (float*) (vertexBuffer + (noVertices)*(4*3+3));
//    buffF[0]=100;
//    buffF[1]=0;
//    buffF[2]=0;
//    buffC[0]=255;
//    buffC[1]=0;
//    buffC[2]=0;
//    noVertices++;
//    buffC = vertexBuffer + (noVertices)*(4*3+3) + 4*3;
//    buffF = (float*) (vertexBuffer + (noVertices)*(4*3+3));
//    buffF[0]=0;
//    buffF[1]=100;
//    buffF[2]=0;
//    buffC[0]=0;
//    buffC[1]=0;
//    buffC[2]=255;
//    noVertices++;
//    buffC = vertexBuffer + (noVertices)*(4*3+3) + 4*3;
//    buffF = (float*) (vertexBuffer + (noVertices)*(4*3+3));
//    buffF[0]=0;
//    buffF[1]=0;
//    buffF[2]=100;
//    buffC[0]=0;
//    buffC[1]=255;
//    buffC[2]=0;
//    noVertices++;
//    noTriangles=0;
//    buffC= trianglesBuffer +  noTriangles*(1+3*4);
//    int * buffI= (int*)(buffC+1);
//    buffC[0]=3;
//    buffI[0]=0;
//    buffI[1]=1;
//    buffI[2]=2;
//    noTriangles++;

//    file << "ply\nformat binary_little_endian 1.0\n"
//    << "element vertex "<< 3 << "\nproperty float32 x\nproperty float32 y\nproperty float32 z"
//    << "\nproperty uchar red\nproperty uchar green\nproperty uchar blue\n"
//    << "element face " << 1
//    << "\nproperty list uint8 int32 vertex_indices\n"
//    << "end_header\n";


//    file.write(vertexBuffer,3*(sizeof(float)*3+3));
//    file.write(trianglesBuffer,(1+3*sizeof(int)));



    file.flush();
    file.close();
    delete [] vertexBuffer;
    delete [] trianglesBuffer;
    return true;
#undef VALID
}
Пример #13
0
static void
FlashProc (ClientData clientData)
{
    Tcl_Interp *interp = (Tcl_Interp *) clientData;
    Tki_Object *object;
    char *color;
    FlashItem *p;
    int max = 0;

    Tk_Window window;
    Tk_Window tkwin = Tk_MainWindow(interp);

    for (p = flashList; p != NULL; p = p->nextPtr) {

	if (p->id == NULL) continue;

	object = Tki_LookupObject (p->id);
	if (object == NULL) continue;

	window = Tk_NameToWindow(interp, object->editor->toplevel, tkwin);
	if (! window) {
	    continue;
	}

	if (! object->editor->color) {
	    if ((object->flash) % 2) {
		color = "black";
	    } else {
		color = "white";
	    }
	} else {
	    color = object->color;
	    if ((object->flash) % 2) {
		if (strcasecmp(color, "white") == 0) color = "black";
	    } else {
		color = "white";
	    }
	}

	Tcl_VarEval (interp, type_to_string (object->type),
		     "__color ", object->id, " ", color, 
		     (char *) NULL);

#if 1
	if (object->editor) {


	    Tki_EditorAttribute(object->editor, interp, 1, &flashIcon);
            const char *tresult = Tcl_GetStringResult(interp);
	    if ((*tresult != '\0') &&
		(strcmp(tresult, "yes") == 0 
		 || strcmp(tresult, "true") == 0
		 || strcmp(tresult, "on") == 0
		 || strcmp(tresult, "1") == 0)) {
		char *buf = (object->flash % 2) ? "icon" : "noicon";
		Tcl_VarEval(interp, "if ![winfo ismapped ", 
			    object->editor->toplevel,
			    "] {", "wm iconbitmap ", object->editor->toplevel,
			    " ", buf, "}", (char *) NULL);
	    }
	}
#endif

	object->flash -= 1;

	if (object->flash == 0) {
	    TkiNoTrace (m_color, interp, object, 1, &object->color);
	    ckfree (p->id);
	    p->id = NULL;
	}

	max = ( object->flash > max ) ? object->flash : max;
    }

    if (max <= 0) {      /* everything is done - remove the flashList */

	FlashItem *q;

        for (p = flashList; p != NULL; p = q) {
            q = p->nextPtr;
            if (p->id != NULL) ckfree (p->id);
            ckfree ((char *) p);
        }

        flashList = NULL;
    }

    Tcl_Eval (interp, "update");

    if (max > 0) {
	Tk_CreateTimerHandler (500, FlashProc, (ClientData) interp);
    }
}
Пример #14
0
	std::string get_type_as_string(parsers::where::evaluation_context context) {
		return type_to_string(get_type(context));
	}
int
cc_rfkill_glib_open (CcRfkillGlib *rfkill)
{
	CcRfkillGlibPrivate *priv;
	int fd;
	int ret;
	GList *events;

	g_return_val_if_fail (RFKILL_IS_GLIB (rfkill), -1);
	g_return_val_if_fail (rfkill->priv->fd == -1, -1);

	priv = rfkill->priv;

	fd = open("/dev/rfkill", O_RDWR);
	if (fd < 0) {
		if (errno == EACCES)
			g_warning ("Could not open RFKILL control device, please verify your installation");
		return fd;
	}

	ret = fcntl(fd, F_SETFL, O_NONBLOCK);
	if (ret < 0) {
		g_debug ("Can't set RFKILL control device to non-blocking");
		close(fd);
		return ret;
	}

	events = NULL;

	while (1) {
		struct rfkill_event event;
		struct rfkill_event *event_ptr;
		ssize_t len;

		len = read(fd, &event, sizeof(event));
		if (len < 0) {
			if (errno == EAGAIN)
				break;
			g_debug ("Reading of RFKILL events failed");
			break;
		}

		if (len != RFKILL_EVENT_SIZE_V1) {
			g_warning ("Wrong size of RFKILL event\n");
			continue;
		}

		if (event.op != RFKILL_OP_ADD)
			continue;

		g_debug ("Read killswitch of type '%s' (idx=%d): soft %d hard %d",
			 type_to_string (event.type),
			 event.idx, event.soft, event.hard);

		event_ptr = g_memdup (&event, sizeof(event));
		events = g_list_prepend (events, event_ptr);
	}

	/* Setup monitoring */
	priv->fd = fd;
	priv->channel = g_io_channel_unix_new (priv->fd);
	priv->watch_id = g_io_add_watch (priv->channel,
					 G_IO_IN | G_IO_HUP | G_IO_ERR,
					 (GIOFunc) event_cb,
					 rfkill);

	events = g_list_reverse (events);
	emit_changed_signal_and_free (rfkill, events);

	return fd;
}
Пример #16
0
static int do_server(int type)
{
	int rv = -1;
	static char log_ent[128] = DAEMON_NAME "-";

	rv = setup_config(type);
	if (rv < 0)
		return rv;


	if (!local) {
		log_error("Cannot find myself in the configuration.");
		exit(EXIT_FAILURE);
	}

	if (!daemonize) {
		if (daemon(0, 0) < 0) {
			perror("daemon error");
			exit(EXIT_FAILURE);
		}
	}

	/* The lockfile must be written to _after_ the call to daemon(), so
	 * that the lockfile contains the pid of the daemon, not the parent. */
	lock_fd = create_lockfile();
	if (lock_fd < 0)
		return lock_fd;

	atexit(server_exit);

	strcat(log_ent, type_to_string(local->type));
	cl_log_set_entity(log_ent);
	cl_log_enable_stderr(enable_stderr ? TRUE : FALSE);
	cl_log_set_facility(HA_LOG_FACILITY);
	cl_inherit_logging_environment(0);

	log_info("BOOTH %s %s daemon is starting",
			type_to_string(local->type), RELEASE_STR);

	signal(SIGUSR1, (__sighandler_t)tickets_log_info);
	signal(SIGTERM, (__sighandler_t)sig_exit_handler);
	signal(SIGINT, (__sighandler_t)sig_exit_handler);

	set_scheduler();
	set_oom_adj(-16);
	set_proc_title("%s %s %s for [%s]:%d",
			DAEMON_NAME,
			cl.configfile,
			type_to_string(local->type),
			local->addr_string,
			booth_conf->port);

	rv = limit_this_process();
	if (rv)
		return rv;

	if (cl_enable_coredumps(TRUE) < 0){
		cl_log(LOG_ERR, "enabling core dump failed");
	}
	cl_cdtocoredir();
	prctl(PR_SET_DUMPABLE, (unsigned long)TRUE, 0UL, 0UL, 0UL);

	rv = loop(lock_fd);

	return rv;
}
Пример #17
0
static void
print_symbol (SYMR *sym_ptr, int number, const char *strbase, AUXU *aux_base,
	      int ifd, FDR *fdp)
{
  sc_t storage_class = (sc_t) sym_ptr->sc;
  st_t symbol_type   = (st_t) sym_ptr->st;
  ulong index	     = sym_ptr->index;
  char *used_ptr     = aux_used + (aux_base - aux_symbols);
  scope_t *scope_ptr;

  printf ("\n    Symbol# %d: \"%s\"\n", number, sym_ptr->iss + strbase);

  if (aux_base != (AUXU *) 0 && index != indexNil)
    switch (symbol_type)
      {
      case st_Nil:
      case st_Label:
	break;

      case st_File:
      case st_Block:
	printf ("      End+1 symbol: %ld\n", index);
	if (want_scope)
	  {
	    if (free_scope == (scope_t *) 0)
	      scope_ptr = xmalloc (sizeof (scope_t));
	    else
	      {
		scope_ptr = free_scope;
		free_scope = scope_ptr->prev;
	      }
	    scope_ptr->open_sym = number;
	    scope_ptr->st = symbol_type;
	    scope_ptr->sc = storage_class;
	    scope_ptr->prev = cur_scope;
	    cur_scope = scope_ptr;
	  }
	break;

      case st_End:
	if (storage_class == sc_Text || storage_class == sc_Info)
	  printf ("      First symbol: %ld\n", index);
	else
	  {
	    used_ptr[index] = 1;
	    printf ("      First symbol: %ld\n", (long) aux_base[index].isym);
	  }

	if (want_scope)
	  {
	    if (cur_scope == (scope_t *) 0)
	      printf ("      Can't pop end scope\n");
	    else
	      {
		scope_ptr = cur_scope;
		cur_scope = scope_ptr->prev;
		scope_ptr->prev = free_scope;
		free_scope = scope_ptr;
	      }
	  }
	break;

      case st_Proc:
      case st_StaticProc:
	if (MIPS_IS_STAB(sym_ptr))
	  ;
	else if (ifd == -1)		/* local symbol */
	  {
	    used_ptr[index] = used_ptr[index+1] = 1;
	    printf ("      End+1 symbol: %-7ld   Type:  %s\n",
		    (long) aux_base[index].isym,
		    type_to_string (aux_base, index+1, fdp));
	  }
	else			/* global symbol */
	  printf ("      Local symbol: %ld\n", index);

	if (want_scope)
	  {
	    if (free_scope == (scope_t *) 0)
	      scope_ptr = xmalloc (sizeof (scope_t));
	    else
	      {
		scope_ptr = free_scope;
		free_scope = scope_ptr->prev;
	      }
	    scope_ptr->open_sym = number;
	    scope_ptr->st = symbol_type;
	    scope_ptr->sc = storage_class;
	    scope_ptr->prev = cur_scope;
	    cur_scope = scope_ptr;
	  }
	break;

#ifdef stStruct
      case st_Struct:
      case st_Union:
      case st_Enum:
	printf ("      End+1 symbol: %lu\n", index);
	break;
#endif

      default:
	if (!MIPS_IS_STAB (sym_ptr))
	  {
	    used_ptr[index] = 1;
	    printf ("      Type: %s\n",
		    type_to_string (aux_base, index, fdp));
	  }
	break;
      }

  if (want_scope)
    {
      printf ("      Scopes:  ");
      if (cur_scope == (scope_t *) 0)
	printf (" none\n");
      else
	{
	  for (scope_ptr = cur_scope;
	       scope_ptr != (scope_t *) 0;
	       scope_ptr = scope_ptr->prev)
	    {
	      const char *class;
	      if (scope_ptr->st == st_Proc || scope_ptr->st == st_StaticProc)
		class = "func.";
	      else if (scope_ptr->st == st_File)
		class = "file";
	      else if (scope_ptr->st == st_Block && scope_ptr->sc == sc_Text)
		class = "block";
	      else if (scope_ptr->st == st_Block && scope_ptr->sc == sc_Info)
		class = "type";
	      else
Пример #18
0
static int loop(int fd)
{
	void (*workfn) (int ci);
	void (*deadfn) (int ci);
	int rv, i;

	rv = setup_transport();
	if (rv < 0)
		goto fail;

	rv = setup_ticket();
	if (rv < 0)
		goto fail;


	client_add(local->tcp_fd, booth_transport + TCP,
			process_listener, NULL);


	rv = write_daemon_state(fd, BOOTHD_STARTED);
	if (rv != 0) {
		log_error("write daemon state %d to lockfile error %s: %s",
                      BOOTHD_STARTED, cl.lockfile, strerror(errno));
		goto fail;
	}

	log_info("BOOTH %s daemon started, node id is 0x%08X (%d).",
		type_to_string(local->type),
			local->site_id, local->site_id);

	while (1) {
		rv = poll(pollfds, client_maxi + 1, poll_timeout);
		if (rv == -1 && errno == EINTR)
			continue;
		if (rv < 0) {
			log_error("poll failed: %s (%d)", strerror(errno), errno);
			goto fail;
		}

		for (i = 0; i <= client_maxi; i++) {
			if (clients[i].fd < 0)
				continue;

			if (pollfds[i].revents & POLLIN) {
				workfn = clients[i].workfn;
				if (workfn)
					workfn(i);
			}
			if (pollfds[i].revents &
					(POLLERR | POLLHUP | POLLNVAL)) {
				deadfn = clients[i].deadfn;
				if (deadfn)
					deadfn(i);
			}
		}

		process_tickets();
	}

	return 0;

fail:
	return -1;
}
Пример #19
0
/*
 * verify_checkpoint --
 *     Open a cursor on each table at the last checkpoint and walk through
 *     the tables in parallel. The key/values should match across all
 *     tables.
 */
static int
verify_checkpoint(WT_SESSION *session)
{
	WT_CURSOR **cursors;
	const char *type0, *typei;
	char next_uri[128], ckpt[128];
	int i, ret, t_ret;
	uint64_t key_count;

	ret = t_ret = 0;
	key_count = 0;
	snprintf(ckpt, 128, "checkpoint=%s", g.checkpoint_name);
	cursors = calloc((size_t)g.ntables, sizeof(*cursors));
	if (cursors == NULL)
		return (log_print_err("verify_checkpoint", ENOMEM, 1));

	for (i = 0; i < g.ntables; i++) {
		/*
		 * TODO: LSM doesn't currently support reading from
		 * checkpoints.
		 */
		if (g.cookies[i].type == LSM)
			continue;
		snprintf(next_uri, 128, "table:__wt%04d", i);
		if ((ret = session->open_cursor(
		    session, next_uri, NULL, ckpt, &cursors[i])) != 0) {
			(void)log_print_err(
			    "verify_checkpoint:session.open_cursor", ret, 1);
			goto err;
		}
	}

	while (ret == 0) {
		ret = cursors[0]->next(cursors[0]);
		if (ret == 0)
			++key_count;
		else if (ret != WT_NOTFOUND) {
			(void)log_print_err("cursor->next", ret, 1);
			goto err;
		}
		/*
		 * Check to see that all remaining cursors have the
		 * same key/value pair.
		 */
		for (i = 1; i < g.ntables; i++) {
			/*
			 * TODO: LSM doesn't currently support reading from
			 * checkpoints.
			 */
			if (g.cookies[i].type == LSM)
				continue;
			t_ret = cursors[i]->next(cursors[i]);
			if (t_ret != 0 && t_ret != WT_NOTFOUND) {
				(void)log_print_err("cursor->next", ret, 1);
				goto err;
			}

			if (ret == WT_NOTFOUND && t_ret == WT_NOTFOUND)
				continue;
			else if (ret == WT_NOTFOUND || t_ret == WT_NOTFOUND) {
				(void)log_print_err(
				    "verify_checkpoint tables with different"
				    " amount of data", EFAULT, 1);
				goto err;
			}

			type0 = type_to_string(g.cookies[0].type);
			typei = type_to_string(g.cookies[i].type);
			if ((ret = compare_cursors(
			    cursors[0], type0, cursors[i], typei)) != 0) {
				(void)diagnose_key_error(
				    cursors[0], 0, cursors[i], i);
				(void)log_print_err(
				    "verify_checkpoint - mismatching data",
				    EFAULT, 1);
				goto err;
			}
		}
	}
	printf("Finished verifying a checkpoint with %d tables and %" PRIu64
	    " keys\n", g.ntables, key_count);

err:	for (i = 0; i < g.ntables; i++) {
		if (cursors[i] != NULL &&
		    (ret = cursors[i]->close(cursors[i])) != 0)
			(void)log_print_err(
			    "verify_checkpoint:cursor close", ret, 1);
	}
	free(cursors);
	return (0);
}
Пример #20
0
const char * SuperFamicomCartridge::type_string() const
{
  return type_to_string(type);
}
Пример #21
0
void
c_get_string (struct value *value, gdb_byte **buffer,
	      int *length, struct type **char_type,
	      const char **charset)
{
  int err, width;
  unsigned int fetchlimit;
  struct type *type = check_typedef (value_type (value));
  struct type *element_type = TYPE_TARGET_TYPE (type);
  int req_length = *length;
  enum bfd_endian byte_order
    = gdbarch_byte_order (get_type_arch (type));

  if (element_type == NULL)
    goto error;

  if (TYPE_CODE (type) == TYPE_CODE_ARRAY)
    {
      /* If we know the size of the array, we can use it as a limit on
	 the number of characters to be fetched.  */
      if (TYPE_NFIELDS (type) == 1
	  && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_RANGE)
	{
	  LONGEST low_bound, high_bound;

	  get_discrete_bounds (TYPE_FIELD_TYPE (type, 0),
			       &low_bound, &high_bound);
	  fetchlimit = high_bound - low_bound + 1;
	}
      else
	fetchlimit = UINT_MAX;
    }
  else if (TYPE_CODE (type) == TYPE_CODE_PTR)
    fetchlimit = UINT_MAX;
  else
    /* We work only with arrays and pointers.  */
    goto error;

  if (! c_textual_element_type (element_type, 0))
    goto error;
  classify_type (element_type, get_type_arch (element_type), charset);
  width = TYPE_LENGTH (element_type);

  /* If the string lives in GDB's memory instead of the inferior's,
     then we just need to copy it to BUFFER.  Also, since such strings
     are arrays with known size, FETCHLIMIT will hold the size of the
     array.  */
  if ((VALUE_LVAL (value) == not_lval
       || VALUE_LVAL (value) == lval_internalvar)
      && fetchlimit != UINT_MAX)
    {
      int i;
      const gdb_byte *contents = value_contents (value);

      /* If a length is specified, use that.  */
      if (*length >= 0)
	i  = *length;
      else
 	/* Otherwise, look for a null character.  */
 	for (i = 0; i < fetchlimit; i++)
	  if (extract_unsigned_integer (contents + i * width,
					width, byte_order) == 0)
 	    break;
  
      /* I is now either a user-defined length, the number of non-null
 	 characters, or FETCHLIMIT.  */
      *length = i * width;
      *buffer = (gdb_byte *) xmalloc (*length);
      memcpy (*buffer, contents, *length);
      err = 0;
    }
  else
    {
      CORE_ADDR addr = value_as_address (value);

      /* Prior to the fix for PR 16196 read_string would ignore fetchlimit
	 if length > 0.  The old "broken" behaviour is the behaviour we want:
	 The caller may want to fetch 100 bytes from a variable length array
	 implemented using the common idiom of having an array of length 1 at
	 the end of a struct.  In this case we want to ignore the declared
	 size of the array.  However, it's counterintuitive to implement that
	 behaviour in read_string: what does fetchlimit otherwise mean if
	 length > 0.  Therefore we implement the behaviour we want here:
	 If *length > 0, don't specify a fetchlimit.  This preserves the
	 previous behaviour.  We could move this check above where we know
	 whether the array is declared with a fixed size, but we only want
	 to apply this behaviour when calling read_string.  PR 16286.  */
      if (*length > 0)
	fetchlimit = UINT_MAX;

      err = read_string (addr, *length, width, fetchlimit,
			 byte_order, buffer, length);
      if (err)
	{
	  xfree (*buffer);
	  memory_error (err, addr);
	}
    }

  /* If the LENGTH is specified at -1, we want to return the string
     length up to the terminating null character.  If an actual length
     was specified, we want to return the length of exactly what was
     read.  */
  if (req_length == -1)
    /* If the last character is null, subtract it from LENGTH.  */
    if (*length > 0
 	&& extract_unsigned_integer (*buffer + *length - width,
				     width, byte_order) == 0)
      *length -= width;
  
  /* The read_string function will return the number of bytes read.
     If length returned from read_string was > 0, return the number of
     characters read by dividing the number of bytes by width.  */
  if (*length != 0)
     *length = *length / width;

  *char_type = element_type;

  return;

 error:
  {
    char *type_str;

    type_str = type_to_string (type);
    if (type_str)
      {
	make_cleanup (xfree, type_str);
	error (_("Trying to read string with inappropriate type `%s'."),
	       type_str);
      }
    else
      error (_("Trying to read string with inappropriate type."));
  }
}
Пример #22
0
void pcb_printf(PCB_p pcb_ptr) {
    printf(
            "PID: %2d, Original Priority: %d, Current Boost: %d, State: %2d, PC: %u, Type:%s\n",
            pcb_ptr->pid, pcb_ptr->priority, pcb_ptr->boost, pcb_ptr->state,
            pcb_ptr->PC, type_to_string(pcb_ptr->process_type));
}