Example #1
0
int
randomize_fd(int fd, int type, int unique, double denom)
{
	u_char *buf;
	u_int slen;
	u_long i, j, numnode, selected;
	struct rand_node *n, *prev;
	int bufleft, eof, fndstr, ret;
	size_t bufc, buflen;
	ssize_t len;

	rand_root = rand_tail = NULL;
	bufc = i = 0;
	bufleft = eof = fndstr = numnode = 0;

	if (type == RANDOM_TYPE_UNSET)
		type = RANDOM_TYPE_LINES;

	buflen = sizeof(u_char) * MAXBSIZE;
	buf = (u_char *)malloc(buflen);
	if (buf == NULL)
		err(1, "malloc");

	while (!eof) {
		/* Check to see if we have bits in the buffer */
		if (bufleft == 0) {
			len = read(fd, buf, buflen);
			if (len == -1)
				err(1, "read");
			else if (len == 0) {
				eof++;
				break;
			} else if ((size_t)len < buflen)
				buflen = (size_t)len;

			bufleft = (int)len;
		}

		/* Look for a newline */
		for (i = bufc; i <= buflen && bufleft >= 0; i++, bufleft--) {
			if (i == buflen) {
				if (fndstr) {
					if (!eof) {
						memmove(buf, &buf[bufc], i - bufc);
						i -= bufc;
						bufc = 0;
						len = read(fd, &buf[i], buflen - i);
						if (len == -1)
							err(1, "read");
						else if (len == 0) {
							eof++;
							break;
						} else if (len < (ssize_t)(buflen - i))
							buflen = i + (size_t)len;

						bufleft = (int)len;
						fndstr = 0;
					}
				} else {
					buflen *= 2;
					buf = (u_char *)realloc(buf, buflen);
					if (buf == NULL)
						err(1, "realloc");

					if (!eof) {
						len = read(fd, &buf[i], buflen - i);
						if (len == -1)
							err(1, "read");
						else if (len == 0) {
							eof++;
							break;
						} else if (len < (ssize_t)(buflen - i))
							buflen = i + (size_t)len;

						bufleft = (int)len;
					}

				}
			}

			if ((type == RANDOM_TYPE_LINES && buf[i] == '\n') ||
			    (type == RANDOM_TYPE_WORDS && isspace(buf[i])) ||
			    (eof && i == buflen - 1)) {
			make_token:
				if (numnode == RANDOM_MAX_PLUS1) {
					errno = EFBIG;
					err(1, "too many delimiters");
				}
				numnode++;
				n = rand_node_allocate();
				if (-1 != (int)i) {
					slen = i - (u_long)bufc;
					n->len = slen + 2;
					n->cp = (u_char *)malloc(slen + 2);
					if (n->cp == NULL)
						err(1, "malloc");

					memmove(n->cp, &buf[bufc], slen);
					n->cp[slen] = buf[i];
					n->cp[slen + 1] = '\0';
					bufc = i + 1;
				}
				rand_node_append(n);
				fndstr = 1;
			}
		}
	}

	(void)close(fd);

	/* Necessary evil to compensate for files that don't end with a newline */
	if (bufc != i) {
		i--;
		goto make_token;
	}

	for (i = numnode; i > 0; i--) {
		selected = random() % numnode;

		for (j = 0, prev = n = rand_root; n != NULL; j++, prev = n, n = n->next) {
			if (j == selected) {
				if (n->cp == NULL)
					break;

				if ((int)(denom * random() /
					RANDOM_MAX_PLUS1) == 0) {
					ret = printf("%.*s",
						(int)n->len - 1, n->cp);
					if (ret < 0)
						err(1, "printf");
				}
				if (unique) {
					if (n == rand_root)
						rand_root = n->next;
					if (n == rand_tail)
						rand_tail = prev;

					prev->next = n->next;
					rand_node_free(n);
					numnode--;
				}
				break;
			}
		}
	}

	fflush(stdout);

	if (!unique)
		rand_node_free_rec(rand_root);

	return(0);
}
struct packet *readPacket(int sockfd) {
    //printf("In readPacket()\n");
    char delimiter = '^';
    char buffer[PACKET_SIZE];
    struct packet *packet = (struct packet *) malloc(sizeof(struct packet));
    struct header *header = (struct header *) malloc(sizeof(struct header));
    packet->header = header;

    //start receiving packet

    //receive 2 bytes for message type
    int bytes_received = recv(sockfd, buffer, 2, 0);
    if (bytes_received == 0) {
        //printf("Recevied zero bytes. Probably because someone terminated.\n");
        return NULL;
    }
    if (bytes_received != 2) {
        char buffer2[2];
        bytes_received += recv(sockfd, buffer2, 1, 0);
        buffer[1] = buffer2[0];
        if (bytes_received != 2) {
            fprintf(stderr, "Error while reading package hearder. Can't proceed.\n");
            exit(-1);
        }

    }
    buffer[bytes_received] = 0;
    if (bytes_received == 0) {
        //printf("Recevied zero bytes. Probably because someone terminated.\n");
        return NULL;
    }
    //printf("Message Type: %s, bytes received: %d\n", buffer, bytes_received);
    packet->header->messageType = atoi(buffer);
    //printf("Received a packet of type: %d\n", packet->header->messageType);
    bytes_received = recv(sockfd, buffer, 1, 0); //discard the delimiter
    //receive the message length
    bytes_received = recv(sockfd, buffer, 1, 0); //first character of length
    //printf("Received byte : %d\n", bytes_received);
    char length[PACKET_SIZE];
    int index = 0;
    while (buffer[0] != delimiter) {
        //printf("Parsing : %c\n", buffer[0]);
        length[index] = buffer[0];
        index++;
        bytes_received = recv(sockfd, buffer, 1, 0);

    }
    length[index] = 0;
    //printf("length chars: %s\n", length);
    packet->header->length = atoi(length);
    //printf("Packet Lenth: %d\n", packet->header->length);
    //read the file name, we have last read the delimiter

    //%02d^%d^%s^%s
    bytes_received = recv(sockfd, buffer, 1, 0);
    char filename[1000];
    index = 0;
    while (buffer[0] != delimiter) {
        filename[index] = buffer[0];
        index++;
        bytes_received = recv(sockfd, buffer, 1, 0);
    }
    filename[index] = 0;
    packet->header->fileName = filename;
    //printf("Filename: %s\n", packet->header->fileName);

    //if message is empty
    if (packet->header->length == 0) {
        packet->message = strdup("");
        return packet;
    }

    //receive the message
    int message_lenght_to_be_received = packet->header->length;

    char *message = (char *) malloc(0);
    int messageLength = 0;
    do {
        bytes_received = recv(sockfd, buffer, message_lenght_to_be_received, 0);
        buffer[bytes_received] = 0;

        //need to concat the buffers received
        messageLength += bytes_received;
        message = realloc(message, messageLength);
        int i;
        for (i = (messageLength - bytes_received); i < messageLength; i++) {
            message[i] = buffer[i - (messageLength - bytes_received)];
        }

        //printf("Bytes of message received: %d Buffer: %s\n", bytes_received, buffer);
        message_lenght_to_be_received -= bytes_received;
    } while (message_lenght_to_be_received > 0);
    message = realloc(message, messageLength + 1);
    message[messageLength] = 0;
    //printf("Bytes of message received: %d Buffer: %s\n", messageLength, message);

//    char *message = "";
//    while (message_lenght_to_be_received > PACKET_SIZE) {
//        bytes_received = recv(sockfd, buffer, PACKET_SIZE, 0);
//        //message = stringConcat(message, buffer);
//        message_lenght_to_be_received = message_lenght_to_be_received - PACKET_SIZE;
//    }
//    bytes_received = recv(sockfd, buffer, message_lenght_to_be_received, 0); //receive only the remaining message
//    buffer[bytes_received] = 0;
//    printf("Buffer: %s, Buffer Size: %d\n", buffer, sizeof(buffer));
    //message = stringConcat(message, buffer);
    packet->message = message;
    //printf("Message: %s\n", packet->message);
    return packet;
}
void collisions_search(void) {
    if (sweeps_init_done!=1) {
        sweeps_init_done = 1;
#ifdef OPENMP
        sweeps_proc 	= omp_get_max_threads();
#endif // OPENMP
        sweepphi	= (struct phivaluelist*) calloc(sweeps_proc,sizeof(struct phivaluelist));
        clist		= (struct collisionlist*)calloc(sweeps_proc,sizeof(struct collisionlist));
#ifndef TREE
        // Sort particles according to their phi position to speed up sorting of lines.
        // Initially the particles are not pre-sorted, thus qsort is faster than insertionsort.
        // Note that this rearranges particles and will cause problems if the particle id is used elsewhere.
        qsort (&(particles[N_collisions]), N-N_collisions, sizeof(struct particle), compare_particle);
    } else {
        // Keep particles sorted according to their phi position to speed up sorting of lines.
        collisions_sweep_insertionsort_particles();
#endif //TREE
    }
    for (int i=N_collisions; i<N; i++) {
        double phi  = atan2(particles[i].y,particles[i].x);
        if (phi != phi) continue;
        double r = sqrt(particles[i].x*particles[i].x + particles[i].y*particles[i].y);
        double w = (particles[i].x*particles[i].vy - particles[i].y*particles[i].vx) / r;
        if (w != w) continue;
        double oldphi = phi-0.5*dt*w-collisions_max_r/r*2.*M_PI;
        double newphi = phi+0.5*dt*w+collisions_max_r/r*2.*M_PI;
        add_to_phivlist(oldphi,newphi,i);
    }

    #pragma omp parallel for schedule (static,1)
    for (int proci=0; proci<sweeps_proc; proci++) {
        struct phivaluelist* sweepphii = &(sweepphi[proci]);
#ifdef TREE
        // Use quicksort when there is a tree. Particles are not pre-sorted.
        qsort (sweepphii->phivalues, sweepphii->N, sizeof(struct phivalue), compare_phivalue);
#else //TREE 
        // Use insertionsort when there is a tree. Particles are pre-sorted.
        collisions_sweep_insertionsort_phivaluelist(sweepphii);
#endif //TREE

        // SWEEPL: List of lines intersecting the plane.
        struct phivaluelist sweepl = {NULL,0,0};

        for (int i=0; i<sweepphii->N; i++) {
            struct phivalue phiv = sweepphii->phivalues[i];
            if (phiv.inout == 0) {
                // Add event if start of line
                if (sweepl.N>=sweepl.Nmax) {
                    sweepl.Nmax +=32;
                    sweepl.phivalues = realloc(sweepl.phivalues,sizeof(struct phivalue)*sweepl.Nmax);
                }
                sweepl.phivalues[sweepl.N] = phiv;
                // Check for collisions with other particles in SWEEPL
                for (int k=0; k<sweepl.N; k++) {
                    int p1 = phiv.pt;
                    int p2 = sweepl.phivalues[k].pt;
                    if (p1==p2) continue;
                    int gbnphi = phiv.nphi;
                    if (sweepl.phivalues[k].nphi!=0) {
                        if (sweepl.phivalues[k].nphi==phiv.nphi) continue;
                        int tmp = p1;
                        p1 = p2;
                        p2 = tmp;
                        gbnphi = sweepl.phivalues[k].nphi;
                    }
                    detect_collision_of_pair(p1,p2,proci,sweepl.phivalues[k].crossing||phiv.crossing);
                }
                sweepl.N++;
            } else {
                // Remove event if end of line
                for (int j=0; j<sweepl.N; j++) {
                    if (sweepl.phivalues[j].pt == phiv.pt) {
                        sweepl.N--;
                        sweepl.phivalues[j] = sweepl.phivalues[sweepl.N];
                        j--;
                        break;
                    }
                }
            }
        }
        free(sweepl.phivalues);
    }

}
Example #4
0
void buffer_resize(buffer* b) {
  int nsize = 2 * b->size + 1;
  b->content = realloc(b->content, nsize * sizeof(int));
  b->size = nsize;
}
  int MESH_Send_NonVertexEntities_FN(Mesh_ptr mesh, int torank, MSTK_Comm comm,
                           int *numreq, int *maxreq, MPI_Request **requests,
                           int *numptrs2free, int *maxptrs2free,
                           void ***ptrs2free) {
    int i, j, nv, ne, nf, nr;
    int nevs, nfes, nrfs, nfe, nrv, nrf, dir;
    int maxnfe, maxnrf;
    int *mesh_info;
    int *list_edge=NULL, *list_face=NULL, *list_region=NULL;
    MVertex_ptr mv;
    MEdge_ptr me;
    MFace_ptr mf;
    MRegion_ptr mr;
    List_ptr mfedges, mrfaces, mrverts;
    RepType rtype;
    double coor[3];
    MPI_Request mpirequest;

    if (requests == NULL)
      MSTK_Report("MESH_Surf_SendMesh","MPI requests array is NULL",MSTK_FATAL);

    if (*maxreq == 0) {
      *maxreq = 25;
      *requests = (MPI_Request *) malloc(*maxreq*sizeof(MPI_Request));
      *numreq = 0;
    }
    else if (*maxreq < (*numreq) + 13) {
      *maxreq = 2*(*maxreq) + 11;
      *requests = (MPI_Request *) realloc(*requests,*maxreq*sizeof(MPI_Request));
    }
  

    ne = MESH_Num_Edges(mesh);
    nf = MESH_Num_Faces(mesh);
    nr = MESH_Num_Regions(mesh);

    /* some other known quantitites - 5 items per edge (2 for verts
       and 3 for extra data), maxnfe+4 items per face (1 for number of
       edges, maxnfe for edge indices, anad 3 for extra data),
       maxnrf+4 items per region (1 for number of faces, maxnrf for
       face indices and 3 for extra data */


    maxnfe = 0;
    for (i = 0; i < nf; i++) {
      mf = MESH_Face(mesh,i);
      nfe = MF_Num_Edges(mf);
      if (nfe > maxnfe)
        maxnfe = nfe;
    }

    maxnrf = 0;
    for (i = 0; i < nr; i++) {
      mr = MESH_Region(mesh,i);
      nrf = MR_Num_Faces(mr);
      if (nrf > maxnrf)
        maxnrf = nrf;
    }

    // The amount of extra info we are sending and their meaning is obviously
    // known on the receiving side too. So nevs, nfes and nrfs can be 
    // calculated without us sending it


    nevs = (2+3)*ne;    
    nfes = (1 + maxnfe + 3)*nf;
    nrfs = (1 + maxnrf + 3)*nr;
    
    /* Reserve nevs spots for each edge */

    list_edge = (int *) malloc(5*ne*sizeof(int));

    nevs = 0;

    /* Store the vertex ids, then the 3 auxilliary data fields */

    for(i = 0; i < ne; i++) {
      me = MESH_Edge(mesh,i);
      list_edge[nevs]   = MV_ID(ME_Vertex(me,0));
      list_edge[nevs+1] = MV_ID(ME_Vertex(me,1));
      list_edge[nevs+2] = (ME_GEntID(me)<<3) | (ME_GEntDim(me));
      list_edge[nevs+3] = (ME_MasterParID(me) <<3) | (ME_OnParBoundary(me)<<2) | (ME_PType(me));
      list_edge[nevs+4] = ME_GlobalID(me);
      nevs += 5;
    }

    /* send detailed edge info */

    MPI_Isend(list_edge,nevs,MPI_INT,torank,torank,comm,&mpirequest);
    (*requests)[*numreq] = mpirequest;
    (*numreq)++;
  

    /* Reserve nfes spots for each face */

    list_face = (int *) malloc(nfes*sizeof(int));

    nfes = 0;

    /* first store nfe, then the edge ids, then the 3 auxilliary data fields */

    for(i = 0; i < nf; i++) {
      mf = MESH_Face(mesh,i);
      mfedges = MF_Edges(mf,1,0);
      nfe = List_Num_Entries(mfedges);
      list_face[nfes] = nfe;
      for(j = 0; j < nfe; j++) {
        dir = MF_EdgeDir_i(mf,j) ? 1 : -1;
        list_face[nfes+j+1] = dir*ME_ID(List_Entry(mfedges,j));
      }
      list_face[nfes+nfe+1] = (MF_GEntID(mf)<<3) | (MF_GEntDim(mf));
      list_face[nfes+nfe+2] = (MF_MasterParID(mf)<<3) | (MF_OnParBoundary(mf)<<2) | (MF_PType(mf));
      list_face[nfes+nfe+3] = MF_GlobalID(mf);
      nfes += (nfe + 4);
      List_Delete(mfedges);
    }


    /* send detailed face info */

    MPI_Isend(list_face,nfes,MPI_INT,torank,torank,comm,&mpirequest);
    (*requests)[*numreq] = mpirequest;
    (*numreq)++;

    
    if (nr) {

      list_region = (int *) malloc(nrfs*sizeof(int));
      
      nrfs = 0;
      
      /* first store nrf, then the face ids, then the 3 auxilliary data fields */
      
      for(i = 0; i < nr; i++) {
        mr = MESH_Region(mesh,i);
        mrfaces = MR_Faces(mr);
        nrf = List_Num_Entries(mrfaces);
        list_region[nrfs] = nrf;
        for(j = 0; j < nrf; j++) {
          dir = MR_FaceDir_i(mr,j) == 1 ? 1 : -1;
          list_region[nrfs+j+1] = dir*MF_ID(List_Entry(mrfaces,j));
        }
        list_region[nrfs+nrf+1] = (MR_GEntID(mr)<<3) | (MR_GEntDim(mr));
        list_region[nrfs+nrf+2] = (MR_MasterParID(mr)<<3) | (MR_PType(mr)); /* MR_PType is 2 bits; 3 bit is 0 */
        list_region[nrfs+nrf+3] = MR_GlobalID(mr);
        nrfs += (nrf + 4);
        List_Delete(mrfaces);
      }
      
      /* send detailed region info */
      
      MPI_Isend(list_region,nrfs,MPI_INT,torank,torank,comm,&mpirequest);
      (*requests)[*numreq] = mpirequest;
      (*numreq)++;
      
    }
      

    /* collect allocated memory so it can be freed in a higher level
       routine after MPI_Waitall or MPI_Test has ensured that the send
       has been completed */

    if (ptrs2free == NULL) 
      MSTK_Report("MESH_Surf_SendMesh_FN","ptrs2free array is NULL",MSTK_FATAL);

    int nptrs = 3;

    if (*maxptrs2free == 0) {
      *maxptrs2free = 25;
      *ptrs2free = (void **) malloc(*maxptrs2free*sizeof(void *));
      *numptrs2free = 0;
    }
    else if (*maxptrs2free < (*numptrs2free) + nptrs) {
      *maxptrs2free = 2*(*maxptrs2free) + nptrs;
      *ptrs2free = (void **) realloc(*ptrs2free,(*maxptrs2free)*sizeof(void *));
    }

    if (ne)
      (*ptrs2free)[(*numptrs2free)++] = list_edge;
    if (nf)
      (*ptrs2free)[(*numptrs2free)++] = list_face;
    if (nr)
      (*ptrs2free)[(*numptrs2free)++] = list_region;

    return 1;
  }
Example #6
0
struct keylist *keys_get(enum sce_key type)
{
	const char *name = NULL;
	char base[256];
	char path[256];
	void *tmp = NULL;
	char *id;
	DIR *dp;
	struct dirent *dent;
	struct keylist *klist;
	u8 bfr[4];

	klist = malloc(sizeof *klist);
	if (klist == NULL)
		goto fail;

	memset(klist, 0, sizeof *klist);

	name = id2name(type, t_key2file, NULL);
	if (name == NULL)
		goto fail;

	if (key_build_path(base) < 0)
		goto fail;

	dp = opendir(base);
	if (dp == NULL)
		goto fail;

	while ((dent = readdir(dp)) != NULL) {
		if (strncmp(dent->d_name, name, strlen(name)) == 0 &&
		    strstr(dent->d_name, "key") != NULL) {
			tmp = realloc(klist->keys, (klist->n + 1) * sizeof(struct key));
			if (tmp == NULL)
				goto fail;

			id = strrchr(dent->d_name, '-');
			if (id != NULL)
				id++;

			klist->keys = tmp;
			memset(&klist->keys[klist->n], 0, sizeof(struct key));

			snprintf(path, sizeof path, "%s/%s-key-%s", base, name, id);
			key_read(path, 32, klist->keys[klist->n].key);
	
			snprintf(path, sizeof path, "%s/%s-iv-%s", base, name, id);
			key_read(path, 16, klist->keys[klist->n].iv);
	
			klist->keys[klist->n].pub_avail = -1;
			klist->keys[klist->n].priv_avail = -1;

			snprintf(path, sizeof path, "%s/%s-pub-%s", base, name, id);
			if (key_read(path, 40, klist->keys[klist->n].pub) == 0) {
				snprintf(path, sizeof path, "%s/%s-ctype-%s", base, name, id);
				key_read(path, 4, bfr);

				klist->keys[klist->n].pub_avail = 1;
				klist->keys[klist->n].ctype = be32(bfr);
			}

			snprintf(path, sizeof path, "%s/%s-priv-%s", base, name, id);
			if (key_read(path, 21, klist->keys[klist->n].priv) == 0)
				klist->keys[klist->n].priv_avail = 1;


			klist->n++;
		}
	}

	return klist;

fail:
	if (klist != NULL) {
		if (klist->keys != NULL)
			free(klist->keys);
		free(klist);
	}
	klist = NULL;

	return NULL;
}
Example #7
0
int try_mount_root()
{
	// create the /rootfs directory
	if (mkdir("/rootfs", 0755) != 0)
	{
		fprintf(stderr, "init: failed to create /rootfs: %s\n", strerror(errno));
		return -1;
	};
	
	// get the list of devices
	size_t numDevs = 0;
	DIR *dirp = opendir("/dev");
	if (dirp == NULL)
	{
		fprintf(stderr, "init: failed to scan /dev: %s\n", strerror(errno));
		return -1;
	};

	struct dirent *ent;
	while ((ent = readdir(dirp)) != NULL)
	{
		if (memcmp(ent->d_name, "sd", 2) == 0)
		{
			char *devname = (char*) malloc(strlen(ent->d_name) + strlen("/dev/") + 1);
			sprintf(devname, "/dev/%s", ent->d_name);

			devList = (char**) realloc(devList, sizeof(char*) * (numDevs+1));
			devList[numDevs++] = devname;

			printf("init: detected candidate storage device: %s\n", devname);
		};
	};

	devList = (char**) realloc(devList, sizeof(char*) * (numDevs+1));
	devList[numDevs] = NULL;

	closedir(dirp);

	char names[256*16];
	int drvcount = (int) __syscall(__SYS_fsdrv, names, 256);
	if (drvcount == -1)
	{
		fprintf(stderr, "init: cannot get filesystem driver list: %s\n", strerror(errno));
		return 1;
	};

	struct system_state sst;
	if (__syscall(__SYS_systat, &sst, sizeof(struct system_state)) != 0)
	{
		fprintf(stderr, "init: failed to get system state: %s\n", strerror(errno));
	};
	
	char idbuf[33];
	id_to_string(idbuf, sst.sst_bootid);
	printf("init: kernel boot ID is %s\n", idbuf);

	const char *scan = names;
	while (drvcount--)
	{
		const char *fstype = scan;
		scan += 16;
		
		if (try_mount_root_with_type(fstype, sst.sst_bootid) == 0) return 0;
	};
	
	return -1;
};
Example #8
0
/*
 * Computes entropy from integer frequencies for various encoding methods and
 * picks the best encoding.
 *
 * FIXME: we could reuse some of the code here for the actual encoding
 * parameters too. Eg the best 'k' for SUBEXP or the code lengths for huffman.
 *
 * Returns the best codec to use.
 */
enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) {
    enum cram_encoding best_encoding = E_NULL;
    int best_size = INT_MAX, bits;
    int nvals, i, ntot = 0, max_val = 0, min_val = INT_MAX, k;
    int *vals = NULL, *freqs = NULL, vals_alloc = 0, *codes;

    //cram_stats_dump(st);

    /* Count number of unique symbols */
    for (nvals = i = 0; i < MAX_STAT_VAL; i++) {
	if (!st->freqs[i])
	    continue;
	if (nvals >= vals_alloc) {
	    vals_alloc = vals_alloc ? vals_alloc*2 : 1024;
	    vals  = realloc(vals,  vals_alloc * sizeof(int));
	    freqs = realloc(freqs, vals_alloc * sizeof(int));
	    if (!vals || !freqs) {
		if (vals)  free(vals);
		if (freqs) free(freqs);
		return E_HUFFMAN; // Cannot do much else atm
	    }
	}
	vals[nvals] = i;
	freqs[nvals] = st->freqs[i];
	ntot += freqs[nvals];
	if (max_val < i) max_val = i;
	if (min_val > i) min_val = i;
	nvals++;
    }
    if (st->h) {
	HashIter *iter=  HashTableIterCreate();
	HashItem *hi;
	int i;

	while ((hi = HashTableIterNext(st->h, iter))) {
	    if (nvals >= vals_alloc) {
		vals_alloc = vals_alloc ? vals_alloc*2 : 1024;
		vals  = realloc(vals,  vals_alloc * sizeof(int));
		freqs = realloc(freqs, vals_alloc * sizeof(int));
		if (!vals || !freqs)
		    return E_HUFFMAN; // Cannot do much else atm
	    }
	    i = (size_t)hi->key;
	    vals[nvals]=i;
	    freqs[nvals] = hi->data.i;
	    ntot += freqs[nvals];
	    if (max_val < i) max_val = i;
	    if (min_val > i) min_val = i;
	    nvals++;
	}
	HashTableIterDestroy(iter);
    }

    st->nvals = nvals;
    assert(ntot == st->nsamp);

#if 0
    // RANDOMISER
    switch(random()%10) {
    case 0:  return E_HUFFMAN;
    case 1:  return E_HUFFMAN;
    //case 1:  return E_BETA; // Java doesn't support E_BETA for BYTE vals
    default: return E_EXTERNAL;
    }
#endif

    if (nvals <= 1) {
	free(vals);
	free(freqs);

	if (fd->verbose > 1)
	    fprintf(stderr, "0 values => 0 bits\n");

	return E_HUFFMAN;
    }

    if (fd->verbose > 1)
	fprintf(stderr, "Range = %d..%d, nvals=%d, ntot=%d\n",
		min_val, max_val, nvals, ntot);

    /* Theoretical entropy */
    if (fd->verbose > 1) {
	double dbits = 0;
	for (i = 0; i < nvals; i++) {
	    dbits += freqs[i] * log((double)freqs[i]/ntot);
	}
	dbits /= -log(2);
	if (fd->verbose > 1)
	    fprintf(stderr, "Entropy = %f\n", dbits);
    }

    if (nvals > 1 && ntot > 256) {
#if 0
	/*
	 * CRUDE huffman estimator. Round to closest and round up from 0
	 * to 1 bit.
	 *
	 * With and without ITF8 incase we have a few discrete values but with
	 * large magnitude.
	 *
	 * Note rans0/arith0 and Z_HUFFMAN_ONLY vs internal huffman can be
	 * compared in this way, but order-1 (eg rans1) or maybe LZ77 modes
	 * may detect the correlation of high bytes to low bytes in multi-
	 * byte values. So this predictor breaks down.
	 */
	double dbits = 0;  // entropy + ~huffman
	double dbitsH = 0;
	double dbitsE = 0; // external entropy + ~huffman
	double dbitsEH = 0;
	int F[256] = {0}, n = 0;
	double e = 0; // accumulated error bits
	for (i = 0; i < nvals; i++) {
	    double x; int X;
	    unsigned int v = vals[i];

	    //Better encoding would cope with sign.
	    //v = ABS(vals[i])*2+(vals[i]<0);

	    if (!(v & ~0x7f)) {
		F[v]             += freqs[i], n+=freqs[i];
	    } else if (!(v & ~0x3fff)) {
		F[(v>>8) |0x80] += freqs[i];
		F[ v     &0xff] += freqs[i], n+=2*freqs[i];
	    } else if (!(v & ~0x1fffff)) {
Example #9
0
File: sink.c Project: Phuehvk/upb
void *upb_realloc(void *ud, void *ptr, size_t size) {
  UPB_UNUSED(ud);
  return realloc(ptr, size);
}
Example #10
0
void
env_opt_add(unsigned char *ep)
{
	unsigned char *vp, c;

	if (opt_reply == NULL)		/*XXX*/
		return;			/*XXX*/

	if (ep == NULL || *ep == '\0') {
		/* Send user defined variables first. */
		env_default(1, 0);
		while ((ep = env_default(0, 0)))
			env_opt_add(ep);

		/* Now add the list of well know variables.  */
		env_default(1, 1);
		while ((ep = env_default(0, 1)))
			env_opt_add(ep);
		return;
	}
	vp = env_getvalue(ep);
	if (opt_replyp + (vp ? 2 * strlen((char *)vp) : 0) +
				2 * strlen((char *)ep) + 6 > opt_replyend)
	{

		int len;
		opt_replyend += OPT_REPLY_SIZE;
		len = opt_replyend - opt_reply;
		opt_reply = (unsigned char *)realloc(opt_reply, len);
		if (opt_reply == NULL) {
/*@*/			printf("env_opt_add: realloc() failed!!!\n");
			opt_reply = opt_replyp = opt_replyend = NULL;
			return;
		}
		opt_replyp = opt_reply + len - (opt_replyend - opt_replyp);
		opt_replyend = opt_reply + len;
	}
	if (opt_welldefined(ep))
#ifdef	OLD_ENVIRON
		if (telopt_environ == TELOPT_OLD_ENVIRON)
			*opt_replyp++ = old_env_var;
		else
#endif
			*opt_replyp++ = NEW_ENV_VAR;
	else
		*opt_replyp++ = ENV_USERVAR;
	for (;;) {
		while ((c = *ep++)) {
			if (opt_replyp + (2 + 2) > opt_replyend)
				return;
			switch(c&0xff) {
			case IAC:
				*opt_replyp++ = IAC;
				break;
			case NEW_ENV_VAR:
			case NEW_ENV_VALUE:
			case ENV_ESC:
			case ENV_USERVAR:
				*opt_replyp++ = ENV_ESC;
				break;
			}
			*opt_replyp++ = c;
		}
		if ((ep = vp)) {
			if (opt_replyp + (1 + 2 + 2) > opt_replyend)
				return;
#ifdef	OLD_ENVIRON
			if (telopt_environ == TELOPT_OLD_ENVIRON)
				*opt_replyp++ = old_env_value;
			else
#endif
				*opt_replyp++ = NEW_ENV_VALUE;
			vp = NULL;
		} else
			break;
	}
}
/**
 * ags_automation_toolbar_load_port:
 * @automation_toolbar: an #AgsAutomationToolbar
 * @control_name: the specifier as string
 *
 * Applies all port to appropriate #AgsMachine.
 *
 * Since: 0.4.3
 */
void
ags_automation_toolbar_apply_port(AgsAutomationToolbar *automation_toolbar,
				  gchar *control_name)
{
  AgsAutomationEditor *automation_editor;
  AgsMachine *machine;

  GtkTreeModel *model;
  GtkTreeIter iter;

  gchar **specifier, *current;
  guint length;
  gboolean is_active;
  
  automation_editor = gtk_widget_get_ancestor(automation_toolbar,
					      AGS_TYPE_AUTOMATION_EDITOR);
  machine = automation_editor->selected_machine;

  model = gtk_combo_box_get_model(automation_toolbar->port);

  /* create specifier array */
  specifier = NULL;
  length = 0;
  
  if(gtk_tree_model_get_iter_first(model,
				   &iter)){
    do{
      gtk_tree_model_get(model,
			 &iter,
			 0, &is_active,
			 -1);

      if(is_active){
	if(length == 0){
	  specifier = (gchar **) malloc(2 * sizeof(gchar *));
	}else{
	  specifier = (gchar **) realloc(specifier,
					 (length + 2) * sizeof(gchar *));
	}
      
	gtk_tree_model_get(model,
			   &iter,
			   1, &current,
			   -1);
	specifier[length] = current;

	length++;
      }
    }while(gtk_tree_model_iter_next(model,
				    &iter));
    specifier[length] = NULL;
  }

  if(machine->automation_port != NULL){
    free(machine->automation_port);
  }

  /* apply */
  machine->automation_port = specifier;
  
  if(g_strv_contains(specifier,
		     control_name)){
    AgsScaleArea *scale_area;
    AgsAutomationArea *automation_area;

    AgsAudio *audio;
    AgsAutomation *automation;

    GList *list;

    gboolean found_audio, found_output, found_input;
    
    audio = machine->audio;
    list = audio->automation;
    
    /* add port */
    found_audio = FALSE;
    found_output = FALSE;
    found_input = FALSE;
    
    while((list = ags_automation_find_specifier(list,
						control_name)) != NULL &&
	  (!found_audio || !found_output || !found_input)){
      if(AGS_AUTOMATION(list->data)->channel_type == G_TYPE_NONE &&
	 !found_audio){
	scale_area = ags_scale_area_new(automation_editor->audio_scale,
					control_name,
					AGS_AUTOMATION(list->data)->lower,
					AGS_AUTOMATION(list->data)->upper,
					AGS_AUTOMATION(list->data)->steps);
	ags_scale_add_area(automation_editor->audio_scale,
			   scale_area);
	gtk_widget_queue_draw(automation_editor->audio_scale);
	
	automation_area = ags_automation_area_new(automation_editor->audio_automation_edit->drawing_area,
						  audio,
						  G_TYPE_NONE,
						  control_name);
	ags_automation_edit_add_area(automation_editor->audio_automation_edit,
				     automation_area);
	gtk_widget_queue_draw(automation_editor->audio_automation_edit->drawing_area);

	found_audio = TRUE;
      }

      if(AGS_AUTOMATION(list->data)->channel_type == AGS_TYPE_OUTPUT &&
	 !found_output){
	scale_area = ags_scale_area_new(automation_editor->output_scale,
					control_name,
					AGS_AUTOMATION(list->data)->lower,
					AGS_AUTOMATION(list->data)->upper,
					AGS_AUTOMATION(list->data)->steps);
	ags_scale_add_area(automation_editor->output_scale,
			   scale_area);
	gtk_widget_queue_draw(automation_editor->output_scale);
	
	automation_area = ags_automation_area_new(automation_editor->output_automation_edit->drawing_area,
						  audio,
						  AGS_TYPE_OUTPUT,
						  control_name);
	ags_automation_edit_add_area(automation_editor->output_automation_edit,
				     automation_area);
	gtk_widget_queue_draw(automation_editor->output_automation_edit->drawing_area);
	
	found_output = TRUE;
      }

      if(AGS_AUTOMATION(list->data)->channel_type == AGS_TYPE_INPUT &&
	 !found_input){
	scale_area = ags_scale_area_new(automation_editor->input_scale,
					control_name,
					AGS_AUTOMATION(list->data)->lower,
					AGS_AUTOMATION(list->data)->upper,
					AGS_AUTOMATION(list->data)->steps);
	ags_scale_add_area(automation_editor->input_scale,
			   scale_area);
	gtk_widget_queue_draw(automation_editor->input_scale);
	
	automation_area = ags_automation_area_new(automation_editor->input_automation_edit->drawing_area,
						  audio,
						  AGS_TYPE_INPUT,
						  control_name);
	ags_automation_edit_add_area(automation_editor->input_automation_edit,
				     automation_area);
	gtk_widget_queue_draw(automation_editor->input_automation_edit->drawing_area);
	
	found_input = TRUE;
      }
      
      list = list->next;
    }
  }else{
    AgsAutomationEdit *automation_edit;
    AgsScale *scale;
    
    GList *scale_area;
    GList *automation_area;

    /* remove audio port */
    automation_edit = automation_editor->audio_automation_edit;
    scale = automation_editor->audio_scale;

    scale_area = ags_scale_area_find_specifier(scale->scale_area,
					       control_name);
    
    if(scale_area != NULL){
      automation_area = ags_automation_area_find_specifier(automation_edit->automation_area,
							   control_name);

      ags_scale_remove_area(scale,
			    scale_area->data);
      gtk_widget_queue_draw(scale);

      ags_automation_edit_remove_area(automation_edit,
				      automation_area->data);
      gtk_widget_queue_draw(automation_edit->drawing_area);
    }
    
    /* remove output port */
    automation_edit = automation_editor->output_automation_edit;
    scale = automation_editor->output_scale;
    
    scale_area = ags_scale_area_find_specifier(scale->scale_area,
					       control_name);

    if(scale_area != NULL){
      automation_area = ags_automation_area_find_specifier(automation_edit->automation_area,
							   control_name);

      ags_scale_remove_area(scale,
			    scale_area->data);
      gtk_widget_queue_draw(scale);

      ags_automation_edit_remove_area(automation_edit,
				      automation_area->data);
      gtk_widget_queue_draw(automation_edit->drawing_area);
    }

    /* remove input port */
    automation_edit = automation_editor->input_automation_edit;
    scale = automation_editor->input_scale;
    
    scale_area = ags_scale_area_find_specifier(scale->scale_area,
					       control_name);

    if(scale_area != NULL){
      automation_area = ags_automation_area_find_specifier(automation_edit->automation_area,
							   control_name);

      ags_scale_remove_area(scale,
			    scale_area->data);
      gtk_widget_queue_draw(scale);

      ags_automation_edit_remove_area(automation_edit,
				      automation_area->data);
      gtk_widget_queue_draw(automation_edit->drawing_area);
    }
  }
}
Example #12
0
static int read_summary_log(const char *filename, int index)
{
    summary_file *curfile = NULL;
    char linebuffer[1024];
    char *linestart;
    int drivers = 0;
    FILE *file;

    /* open the logfile */
    file = fopen(filename, "r");
    if (file == NULL)
    {
        fprintf(stderr, "Error: file '%s' not found\n", filename);
        return 1;
    }

    /* parse it */
    while (fgets(linebuffer, sizeof(linebuffer), file) != NULL)
    {
    	/* trim the leading/trailing spaces */
    	linestart = trim_string(linebuffer);

        /* is this one of our specials? */
        if (strncmp(linestart, "@@@@@", 5) == 0)
        {
        	/* advance past the signature */
        	linestart += 5;

			/* look for the driver= tag */
			if (strncmp(linestart, "driver=", 7) == 0)
			{
				curfile = parse_driver_tag(linestart + 7, index);
				if (curfile == NULL)
					goto error;
				drivers++;
			}

			/* look for the source= tag */
			else if (strncmp(linestart, "source=", 7) == 0)
			{
				/* error if no driver yet */
				if (curfile == NULL)
				{
					fprintf(stderr, "Unexpected @@@@@source= tag\n");
					goto error;
				}

				/* copy the string */
				strcpy(curfile->source, trim_string(linestart + 7));
			}

			/* look for the dir= tag */
			else if (strncmp(linestart, "dir=", 4) == 0)
			{
				char *dirname = trim_string(linestart + 4);

				/* allocate a copy of the string */
				lists[index].dir = (char *)malloc(strlen(dirname) + 1);
				if (lists[index].dir == NULL)
					goto error;
				strcpy(lists[index].dir, dirname);
				fprintf(stderr, "Directory %s\n", lists[index].dir);
			}
		}

        /* if not, consider other options */
        else if (curfile != NULL)
        {
            int foundchars = 0;
            char *curptr;

            /* look for the pngcrc= tag */
			if (strncmp(linestart, "pngcrc: ", 7) == 0)
            {
            }

			/* otherwise, accumulate the text */
			else
			{
				/* find the end of the line and normalize it with a CR */
				for (curptr = linestart; *curptr != 0 && *curptr != '\n' && *curptr != '\r'; curptr++)
					if (!isspace((UINT8)*curptr))
						foundchars = 1;
				*curptr++ = '\n';
				*curptr = 0;

				/* ignore blank lines */
				if (!foundchars)
					continue;

				/* see if we have enough room */
				if (curfile->textsize[index] + (curptr - linestart) + 1 >= curfile->textalloc[index])
				{
					curfile->textalloc[index] = curfile->textsize[index] + (curptr - linestart) + 256;
					curfile->text[index] = (char *)realloc(curfile->text[index], curfile->textalloc[index]);
					if (curfile->text[index] == NULL)
					{
						fprintf(stderr, "Unable to allocate memory for text\n");
						goto error;
					}
				}

				/* append our text */
				strcpy(curfile->text[index] + curfile->textsize[index], linestart);
				curfile->textsize[index] += curptr - linestart;
			}
		}

		/* look for the M.A.M.E. header */
		else if (strncmp(linestart, "M.A.M.E. v", 10) == 0)
		{
			char *start = linestart + 10;
			char *end;

			/* find the end */
			for (end = start; !isspace((UINT8)*end); end++) ;
			*end = 0;
			strcpy(lists[index].version, start);
			fprintf(stderr, "Parsing results from version %s\n", lists[index].version);
		}
    }

    fclose(file);
    fprintf(stderr, "Parsed %d drivers\n", drivers);
    return 0;

error:
    fclose(file);
    return 1;
}
Example #13
0
static int stream_readL(lua_State *L) {
	struct stream *stream;
	u8_t buf[1024];
	u8_t *buf_ptr, *body_ptr;
	size_t header_len;
	ssize_t n;

	/*
	 * 1: Stream (self)
	 * 2: Playback (self)
	 */

	stream = lua_touserdata(L, 1);


	/* shortcut, just read to streambuf */
	if (stream->num_crlf == 4) {
		n = streambuf_feed_fd(stream->fd, L);
		if (n == 0) {
			/* closed */
			lua_pushboolean(L, FALSE);
			return 1;
		}

		if (n == -ENOSPC) {
			lua_pushinteger(L, 0);
			return 1;
		}

		if (n < 0) {
			CLOSESOCKET(stream->fd);

			lua_pushnil(L);
			lua_pushstring(L, strerror(n));
			return 2;

		}

		lua_pushinteger(L, n);
		return 1;
	}

	/* read buffer, but we must not overflow the stream fifo */
	n = streambuf_get_freebytes();
	if (n > (ssize_t)sizeof(buf)) {
		n = sizeof(buf);
	}

	n = recv(stream->fd, buf, sizeof(buf), 0);

	/* socket closed */
	if (n == 0) {
		lua_pushboolean(L, FALSE);
		return 1;
	}

	/* socket error */
	if (n < 0) {
		// XXXX do we need to handle timeout here?
		CLOSESOCKET(stream->fd);

		lua_pushnil(L);
		lua_pushstring(L, strerror(SOCKETERROR));
		return 2;
	}

	buf_ptr = buf;


	/* read http header */
	if (stream->num_crlf < 4) {
		stream->body = realloc(stream->body, stream->body_len + n);
		body_ptr = stream->body + stream->body_len;
		stream->body_len += n;

		while (n) {
			*body_ptr++ = *buf_ptr;

			if (*buf_ptr == '\n' || *buf_ptr == '\r') {
				stream->num_crlf++;
			}
			else {
				stream->num_crlf = 0;
			}

			buf_ptr++;
			n--;

			if (stream->num_crlf == 4) {
				header_len = body_ptr - stream->body;

				//LOG_DEBUG(log_audio_decode, "headers %d %*s\n", header_len, header_len, stream->body);

				/* Send headers to SqueezeCenter */
				lua_getfield(L, 2, "_streamHttpHeaders");
				lua_pushvalue(L, 2);
				lua_pushlstring(L, (char *)stream->body, header_len);
				lua_call(L, 2, 0);

				/* do not free the header here - leave it to disconnect -
				 * so that it can be used by the proxy code
				 */

				/* Send headers to proxy clients */
				proxy_chunk(stream->body, header_len, L);

				break;
			}
		}
	}

	/* we need to loop when playing sound effects, so we need to remember where the stream starts */
	streambuf_lptr = streambuf_fifo.wptr;

	/* feed remaining buffer */
	streambuf_feedL(buf_ptr, n, L);

	lua_pushboolean(L, TRUE);
	return 1;
}
Example #14
0
void editor (char *filename, int startpos)
{
    int stop    = FALSE; // exit main loop?
    int fline   = 0;     // no. of first displayed line
    int cline   = 0;     // no. of line with cursor
    int shift   = 0;     // shift to the right
    int ccol    = 0;     // column of the cursor position in the file window

    int        k, i, ndisp, rc, reply;
    char       *p, buf[1024];

    if (editor_open_file (filename) < 0) return;
    cline = min1 (startpos, nl-1);
    fline = max1 (0, cline - video_vsize()/2);

    // enter the loop
    while (1)
    {
        if (stop)
        {
            rc = 0;
            if (changed)
            {
                rc = -1;
                reply = fly_ask (0, "   Save file `%s'?   ", " Yes \n No \n Cancel ", filename);
                if (reply == 1) rc = editor_save_file (filename);
                if (reply == 2) rc = 0;
                if (reply == 3) stop = FALSE;
            }
            if (rc == 0) break;
        }
        
        ndisp = video_vsize()-1;
        // draw the screen
        for (i=0; i<ndisp; i++)
        {
            video_put_n_cell (' ', _BackWhite+_Black, video_hsize(), i, 0);
            if (i+fline < nl)
                editor_display_line (i, fline+i, shift);
        }
        video_put_n_cell (' ', _BackBlue+_White, video_hsize(), video_vsize()-1, 0);
        snprintf1 (buf, sizeof(buf), "L%d:C%d:S%d %c %s%s", cline, ccol, shift, fl_sym.v,
                 changed ? "*" : "", filename);
        video_put (buf, video_vsize()-1, 0);
        video_set_cursor (cline-fline, ccol-shift);
        video_update (0);

        // get a keyboard/mouse event and process it
        k = getmessage (-1);
        if (IS_KEY(k))
        {
            switch (k)
            {
                // Navigation keys
                
            case _Up:
            case _Down:
            case _PgUp:
            case _PgDn:
                fly_scroll_it (k, &fline, &cline, nl, video_vsize()-1);
                break;

            case _Right:
                ccol++;
                if (ccol-shift > video_hsize()-1) shift = ccol-video_hsize()+1;
                break;

            case _Left:
                ccol = max1 (ccol-1, 0);
                if (ccol < shift) shift = ccol;
                break;

            case _Home:
                ccol = 0; shift = 0;
                break;

            case _End:
                ccol = strlen(lines[cline]);
                if (ccol-shift > video_hsize()-1) shift = ccol-video_hsize()+1;
                break;

            case _CtrlHome:
                fline = 0; cline = 0; ccol = 0; shift = 0; break;

            case _CtrlEnd:
                fline = max1 (0, nl-video_vsize()+1);
                cline = min1 (fline+video_vsize()-1, nl-1);
                shift = 0;
                ccol = 0;
                break;

                // Action keys

            case _CtrlY:
                put_clipboard (lines[cline]);
                free (lines[cline]);
                for (i=cline; i<nl-1; i++)
                    lines[i] = lines[i+1];
                nl--;
                changed = TRUE;
                break;

            case _ShiftInsert:
            case _CtrlV:
                p = get_clipboard ();
                if (p == NULL || *p == '\0') break;
                if (nl == na)
                {
                    na *= 2;
                    lines = realloc (lines, sizeof(char *) * na);
                }
                for (i=nl-1; i>cline; i--)
                    lines[i+1] = lines[i];
                lines[cline+1] = p;
                ccol = 0;
                shift = 0;
                cline++;
                if (cline-fline == video_vsize()-1) fline++;
                nl++;
                changed = TRUE;
                break;

            case _BackSpace:
                if (ccol == 0)
                {
                    // ccol == 0: glue this line to the previous
                    if (cline == 0) break;
                    p = malloc (strlen (lines[cline])+strlen(lines[cline-1])+1);
                    strcpy (p, lines[cline-1]);
                    strcat (p, lines[cline]);
                    ccol = strlen (lines[cline-1]);
                    if (ccol-shift > video_hsize()-1) shift = ccol-video_hsize()+1;
                    free (lines[cline-1]);
                    free (lines[cline]);
                    lines[cline-1] = p;
                    for (i=cline; i<nl-1; i++)
                        lines[i] = lines[i+1];
                    cline--;
                    nl--;
                }
                else
                {
                    // ccol != 0: delete char at ccol-1, move cursor left
                    str_delete (lines[cline], lines[cline]+ccol-1);
                    ccol--;
                    if (ccol < shift) shift = ccol;
                }
                changed = TRUE;
                break;

            case _Enter:
                if (nl == na)
                {
                    na *= 2;
                    lines = realloc (lines, sizeof(char *) * na);
                }
                for (i=nl-1; i>cline; i--)
                    lines[i+1] = lines[i];
                if (ccol < strlen (lines[cline]))
                {
                    lines[cline+1] = strdup (lines[cline]+ccol);
                    lines[cline][ccol] = '\0';
                }
                else
                {
                    lines[cline+1] = strdup ("");
                }
                ccol = 0;
                shift = 0;
                cline++;
                if (cline-fline == video_vsize()-1) fline++;
                nl++;
                changed = TRUE;
                break;

            case _Delete:
                if (ccol >= strlen (lines[cline]))
                {
                    // glue previous line to this one
                    if (cline == nl-1) break;
                    p = malloc (ccol+strlen(lines[cline+1])+1);
                    strcpy (p, lines[cline]);
                    memset (p+strlen(lines[cline]), ' ', ccol-strlen(lines[cline]));
                    strcpy (p+ccol, lines[cline+1]);
                    free (lines[cline]);
                    free (lines[cline+1]);
                    lines[cline] = p;
                    for (i=cline+1; i<nl-1; i++)
                        lines[i] = lines[i+1];
                    nl--;
                }
                else
                {
                    // ccol != 0: delete char at ccol-1, move cursor left
                    str_delete (lines[cline], lines[cline]+ccol);
                }
                changed = TRUE;
                break;

            case _F2:
                rc = editor_save_file (filename);
                if (rc == 0) changed = FALSE;
                break;
                
            case _Esc:
            case _F10:
                stop = TRUE; break;

                // character keys
                
            default:
                if (k >= ' ' && k <= 255)
                {
                    str_insert_at (cline, k, ccol);
                    ccol++;
                    changed = TRUE;
                }
            }
        }
        else if (IS_MOUSE(k))
        {
        }
        else if (IS_SYSTEM(k))
        {
            switch (SYS_TYPE(k))
            {
            case SYSTEM_QUIT:
                stop = TRUE; break;
            }
        }
    }

    if (nl != 0 && lines != NULL)
        for (i=0; i<nl; i++)
            free (lines[i]);
    if (na != 0 && lines != NULL) free (lines);
    na = 0;
    lines = NULL;
}
int getdelim1(char **lineptr, size_t *n, int delim, FILE *stream)
{
        char *p;                    // reads stored here
        size_t const rchunk = 512;  // number of bytes to read
        size_t const mchunk = 512;  // number of extra bytes to malloc
        size_t m = rchunk + 1;      // initial buffer size

        if (*lineptr) {
                if (*n < m) {
                        *lineptr = (char*)realloc(*lineptr, m);
                        if (!*lineptr) return -1;
                        *n = m;
                }
        } else {
                *lineptr = (char*)malloc(m);
                if (!*lineptr) return -1;
                *n = m;
        }

        m = 0; // record length including seperator

        do {
                size_t i;     // number of bytes read etc
                size_t j = 0; // number of bytes searched

                p = *lineptr + m;

                i = fread(p, 1, rchunk, stream);
                if (i < rchunk && ferror(stream))
                        return -1;
		while (j < i) {
                        ++j;
                        if (*p++ == (char)delim) {
                                *p = '\0';
                                if (j != i) {
                                        if (fseek(stream, j - i, SEEK_CUR))
                                                return -1;
                                        if (feof(stream))
                                                clearerr(stream);
                                }
                                m += j;
                                return m;
                        }
                }

                m += j;
                if (feof(stream)) {
                        if (m) return m;
                        if (!i) return -1;
                }

                // allocate space for next read plus possible null terminator
                i = ((m + (rchunk + 1 > mchunk ? rchunk + 1 : mchunk) +
                      mchunk - 1) / mchunk) * mchunk;
                if (i != *n) {
                        *lineptr = (char*)realloc(*lineptr, i);
                        if (!*lineptr) return -1;
                        *n = i;
                }
        } while (1);
}
Example #16
0
void handle_fstab_record(struct MNvramObserver* observer,
			 struct ParsedRecord* record,
			 void* obj1, void* obj2, void* obj3){
    assert(record);
    struct FstabObserver* fobserver = (struct FstabObserver*)observer;
    s_channels_mount = (struct MountsPublicInterface*)obj1;     /*obj1 - channels filesystem interface*/
    s_transparent_mount = (struct MountsPublicInterface*)obj2;  /*obj2 - whole filesystem interface*/

    if ( observer->is_valid_record(observer, record) != 0 ) return; /*skip record invalid*/

    /*check array*/
    if ( fobserver->postpone_mounts_array == NULL ){
	assert( fobserver->postpone_mounts_count ==0 );
    }

    /*extend array & add record to mounts array
      no checks for duplicated items doing*/
    ++fobserver->postpone_mounts_count;
    fobserver->postpone_mounts_array 
	= realloc(fobserver->postpone_mounts_array, 
		  sizeof(*fobserver->postpone_mounts_array)*fobserver->postpone_mounts_count);
    assert(fobserver->postpone_mounts_array != NULL);
    /*record added into postopne mounts list and must be handled later*/
    struct FstabRecordContainer* record_container = &fobserver->postpone_mounts_array[ fobserver->postpone_mounts_count -1 ];
    record_container->mount_status = EFstabMountWaiting;
    copy_record(record, &record_container->mount);

    /*get all params*/
    char* channel_alias = NULL;
    char* mount_path = NULL;
    char* access = NULL;
    char* removable = NULL;
    char* fsname = NULL;
    GET_FSTAB_PARAMS(record, &channel_alias, &mount_path, &access, &removable, &fsname);

    int write=0;     
    if ( !strcmp(access, FSTAB_VAL_ACCESS_WRITE) )  write =1;

    /*if archivemount is available and want mount tar in read-only mode*/
    if ( !strcasecmp( fsname, "tar") && !strcmp(access, FSTAB_VAL_ACCESS_READ) ){
#ifdef FUSEGLUE_EXT
        int    expect_absolute_path;
        char   proxy_mode;
        int    archivemount_argc;
        char **archivemount_argv;
        fs_main archivemount_entrypoint =
            fusefs_entrypoint_get_args_by_fsname("archivemount", write, 
                                                 channel_alias, mount_path,
                                                 &expect_absolute_path, &proxy_mode,
                                                 &archivemount_argc, &archivemount_argv);
        /*If archivemount is available then use it for tar mounting*/
        if ( archivemount_entrypoint ){
            /*mount fusefs*/
            int mount_res = exec_fuse_main(mount_path, expect_absolute_path, proxy_mode,
                                           archivemount_entrypoint,
                                           archivemount_argc, archivemount_argv);
            if (mount_res!=0){
                ZRT_LOG(L_ERROR, "exec_fuse_main err=%d", mount_res);
            }
        }
        else
#endif /*FUSEGLUE_EXT*/
        /*If no archimemount available and for compatibility use old approach.
          For first fstab handling (s_updated_fstab_records=0) after
          checks try mount channel with keys access=ro, removable=no*/
            if ( !s_updated_fstab_records  ){
                fobserver->mount_import(fobserver, record_container);
        }
    }
#ifdef FUSEGLUE_EXT
    /*Mount all another file systems*/
    else{
        int    fs_expect_absolute_path;
        int    fs_proxy_mode;
        int    fs_argc=0;
        char **fs_argv;
        fs_main fs_entrypoint =
            fusefs_entrypoint_get_args_by_fsname(fsname, write, 
                                                 channel_alias, mount_path,
                                                 &fs_expect_absolute_path, &fs_proxy_mode,
                                                 &fs_argc, &fs_argv);

        /*If fuse extensions are available and trying mount tar archive then use archivemount*/
        if (   fs_entrypoint != NULL ){
            /*mount fusefs*/
            int mount_res = exec_fuse_main(mount_path, fs_expect_absolute_path, fs_proxy_mode,
                                           fs_entrypoint, fs_argc, fs_argv);
            if (mount_res!=0){
                ZRT_LOG(L_ERROR, "exec_fuse_main err=%d", mount_res);
            }
        }
    }
#endif /*FUSEGLUE_EXT*/

    ZRT_LOG(L_SHORT, "fstab record channel=%s, mount_path=%s, access=%s, removable=%s, fsname=%s",
	    channel_alias, mount_path, access, removable, fsname);
}
Example #17
0
/* returns true when video_thread_loop should quit */
static bool video_thread_handle_packet(
      thread_video_t *thr,
      const thread_packet_t *incoming)
{
#ifdef HAVE_OVERLAY
   unsigned i;
#endif
   thread_packet_t pkt = *incoming;
   bool            ret = false;

   switch (pkt.type)
   {
      case CMD_INIT:
         thr->driver_data = thr->driver->init(&thr->info,
               thr->input, thr->input_data);
         pkt.data.b = thr->driver_data;
         thr->driver->viewport_info(thr->driver_data, &thr->vp);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_FREE:
         if (thr->driver_data)
         {
            if (thr->driver && thr->driver->free)
               thr->driver->free(thr->driver_data);
         }
         thr->driver_data = NULL;
         video_thread_reply(thr, &pkt);
         return true;

      case CMD_SET_ROTATION:
         if (thr->driver && thr->driver->set_rotation)
            thr->driver->set_rotation(thr->driver_data, pkt.data.i);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_READ_VIEWPORT:
      {
         struct video_viewport vp;

         vp.x                     = 0;
         vp.y                     = 0;
         vp.width                 = 0;
         vp.height                = 0;
         vp.full_width            = 0;
         vp.full_height           = 0;

         thr->driver->viewport_info(thr->driver_data, &vp);

         if (memcmp(&vp, &thr->read_vp, sizeof(vp)) == 0)
         {
            /* We can read safely
             *
             * read_viewport() in GL driver calls
             * 'cached frame render' to be able to read from
             * back buffer.
             *
             * This means frame() callback in threaded wrapper will
             * be called from this thread, causing a timeout, and
             * no frame to be rendered.
             *
             * To avoid this, set a flag so wrapper can see if
             * it's called in this "special" way. */
            thr->frame.within_thread = true;

            if (thr->driver->read_viewport)
               ret = thr->driver->read_viewport(thr->driver_data,
                     (uint8_t*)pkt.data.v);

            pkt.data.b = ret;
            thr->frame.within_thread = false;
         }
         else
         {
            /* Viewport dimensions changed right after main
             * thread read the async value. Cannot read safely. */
            pkt.data.b = false;
         }
         video_thread_reply(thr, &pkt);
         break;
      }

      case CMD_SET_SHADER:
         if (thr->driver && thr->driver->set_shader)
            ret = thr->driver->set_shader(thr->driver_data,
                     pkt.data.set_shader.type,
                     pkt.data.set_shader.path);

         pkt.data.b = ret;
         video_thread_reply(thr, &pkt);
         break;

      case CMD_ALIVE:
         if (thr->driver && thr->driver->alive)
            ret = thr->driver->alive(thr->driver_data);

         pkt.data.b = ret;
         video_thread_reply(thr, &pkt);
         break;

#ifdef HAVE_OVERLAY
      case CMD_OVERLAY_ENABLE:
         if (thr->overlay && thr->overlay->enable)
            thr->overlay->enable(thr->driver_data, pkt.data.b);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_OVERLAY_LOAD:

         if (thr->overlay && thr->overlay->load)
            ret = thr->overlay->load(thr->driver_data,
                  pkt.data.image.data,
                  pkt.data.image.num);

         pkt.data.b = ret;
         thr->alpha_mods = pkt.data.image.num;
         thr->alpha_mod = (float*)realloc(thr->alpha_mod,
               thr->alpha_mods * sizeof(float));

         for (i = 0; i < thr->alpha_mods; i++)
         {
            /* Avoid temporary garbage data. */
            thr->alpha_mod[i] = 1.0f;
         }

         video_thread_reply(thr, &pkt);
         break;

      case CMD_OVERLAY_TEX_GEOM:
         if (thr->overlay && thr->overlay->tex_geom)
            thr->overlay->tex_geom(thr->driver_data,
                  pkt.data.rect.index,
                  pkt.data.rect.x,
                  pkt.data.rect.y,
                  pkt.data.rect.w,
                  pkt.data.rect.h);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_OVERLAY_VERTEX_GEOM:
         if (thr->overlay && thr->overlay->vertex_geom)
            thr->overlay->vertex_geom(thr->driver_data,
                  pkt.data.rect.index,
                  pkt.data.rect.x,
                  pkt.data.rect.y,
                  pkt.data.rect.w,
                  pkt.data.rect.h);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_OVERLAY_FULL_SCREEN:
         if (thr->overlay && thr->overlay->full_screen)
            thr->overlay->full_screen(thr->driver_data,
                  pkt.data.b);
         video_thread_reply(thr, &pkt);
         break;
#endif

      case CMD_POKE_SET_VIDEO_MODE:
         if (thr->poke && thr->poke->set_video_mode)
            thr->poke->set_video_mode(thr->driver_data,
                  pkt.data.new_mode.width,
                  pkt.data.new_mode.height,
                  pkt.data.new_mode.fullscreen);
         video_thread_reply(thr, &pkt);
         break;
      case CMD_POKE_SET_FILTERING:
         if (thr->poke && thr->poke->set_filtering)
            thr->poke->set_filtering(thr->driver_data,
                  pkt.data.filtering.index,
                  pkt.data.filtering.smooth);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_POKE_GET_VIDEO_OUTPUT_SIZE:
         if (thr->poke && thr->poke->get_video_output_size)
            thr->poke->get_video_output_size(thr->driver_data,
                  &pkt.data.output.width,
                  &pkt.data.output.height);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_POKE_GET_VIDEO_OUTPUT_PREV:
         if (thr->poke && thr->poke->get_video_output_prev)
            thr->poke->get_video_output_prev(thr->driver_data);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_POKE_GET_VIDEO_OUTPUT_NEXT:
         if (thr->poke && thr->poke->get_video_output_next)
            thr->poke->get_video_output_next(thr->driver_data);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_POKE_SET_ASPECT_RATIO:
         thr->poke->set_aspect_ratio(thr->driver_data,
               pkt.data.i);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_POKE_SET_OSD_MSG:
         if (thr->poke && thr->poke->set_osd_msg)
            thr->poke->set_osd_msg(thr->driver_data,
                  pkt.data.osd_message.msg,
                  &pkt.data.osd_message.params, NULL);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_FONT_INIT:
         if (pkt.data.font_init.method)
            pkt.data.font_init.return_value =
                  pkt.data.font_init.method
                  (pkt.data.font_init.font_driver,
                     pkt.data.font_init.font_handle,
                     pkt.data.font_init.video_data,
                     pkt.data.font_init.font_path,
                     pkt.data.font_init.font_size,
                     pkt.data.font_init.api);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_CUSTOM_COMMAND:
         if (pkt.data.custom_command.method)
            pkt.data.custom_command.return_value =
                  pkt.data.custom_command.method
                  (pkt.data.custom_command.data);
         video_thread_reply(thr, &pkt);
         break;

      case CMD_VIDEO_NONE:
         /* Never reply on no command. Possible deadlock if
          * thread sends command right after frame update. */
         break;
      default:
         video_thread_reply(thr, &pkt);
         break;
   }

   return false;
}
Example #18
0
int tsm_screen_resize(struct tsm_screen *con, unsigned int x,
		      unsigned int y)
{
	struct line **cache;
	unsigned int i, j, width, diff;
	int ret;
	bool *tab_ruler;

	if (!con || !x || !y)
		return -EINVAL;

	if (con->size_x == x && con->size_y == y)
		return 0;

	/* First make sure the line buffer is big enough for our new screen.
	 * That is, allocate all new lines and make sure each line has enough
	 * cells to hold the new screen or the current screen. If we fail, we
	 * can safely return -ENOMEM and the buffer is still valid. We must
	 * allocate the new lines to at least the same size as the current
	 * lines. Otherwise, if this function fails in later turns, we will have
	 * invalid lines in the buffer. */
	if (y > con->line_num) {
		/* resize main buffer */
		cache = realloc(con->main_lines, sizeof(struct line*) * y);
		if (!cache)
			return -ENOMEM;

		if (con->lines == con->main_lines)
			con->lines = cache;
		con->main_lines = cache;

		/* resize alt buffer */
		cache = realloc(con->alt_lines, sizeof(struct line*) * y);
		if (!cache)
			return -ENOMEM;

		if (con->lines == con->alt_lines)
			con->lines = cache;
		con->alt_lines = cache;

		/* allocate new lines */
		if (x > con->size_x)
			width = x;
		else
			width = con->size_x;

		while (con->line_num < y) {
			ret = line_new(con, &con->main_lines[con->line_num],
				       width);
			if (ret)
				return ret;

			ret = line_new(con, &con->alt_lines[con->line_num],
				       width);
			if (ret) {
				line_free(con->main_lines[con->line_num]);
				return ret;
			}

			++con->line_num;
		}
	}

	/* Resize all lines in the buffer if we increase screen width. This
	 * will guarantee that all lines are big enough so we can resize the
	 * buffer without reallocating them later. */
	if (x > con->size_x) {
		tab_ruler = realloc(con->tab_ruler, sizeof(bool) * x);
		if (!tab_ruler)
			return -ENOMEM;
		con->tab_ruler = tab_ruler;

		for (i = 0; i < con->line_num; ++i) {
			ret = line_resize(con, con->main_lines[i], x);
			if (ret)
				return ret;

			ret = line_resize(con, con->alt_lines[i], x);
			if (ret)
				return ret;
		}
	}

	for (j = 0; j < con->line_num; ++j) {
		if (j >= con->size_y)
			i = 0;
		else
			i = con->size_x;

		if (x < con->main_lines[j]->size)
			width = x;
		else
			width = con->main_lines[j]->size;
		for (; i < width; ++i)
			cell_init(con, &con->main_lines[j]->cells[i]);

		if (x < con->alt_lines[j]->size)
			width = x;
		else
			width = con->alt_lines[j]->size;
		for (; i < width; ++i)
			cell_init(con, &con->alt_lines[j]->cells[i]);
	}

	/* xterm destroys margins on resize, so do we */
	con->margin_top = 0;
	con->margin_bottom = con->size_y - 1;

	/* reset tabs */
	for (i = 0; i < x; ++i) {
		if (i % 8 == 0)
			con->tab_ruler[i] = true;
		else
			con->tab_ruler[i] = false;
	}

	/* We need to adjust x-size first as screen_scroll_up() and friends may
	 * have to reallocate lines. The y-size is adjusted after them to avoid
	 * missing lines when shrinking y-size.
	 * We need to carefully look for the functions that we call here as they
	 * have stronger invariants as when called normally. */

	con->size_x = x;
	if (con->cursor_x >= con->size_x)
		con->cursor_x = con->size_x - 1;

	/* scroll buffer if screen height shrinks */
	if (con->size_y != 0 && y < con->size_y) {
		diff = con->size_y - y;
		screen_scroll_up(con, diff);
		if (con->cursor_y > diff)
			con->cursor_y -= diff;
		else
			con->cursor_y = 0;
	}

	con->size_y = y;
	con->margin_bottom = con->size_y - 1;
	if (con->cursor_y >= con->size_y)
		con->cursor_y = con->size_y - 1;

	return 0;
}
Example #19
0
int
__netlink_request (struct netlink_handle *h, int type)
{
  struct netlink_res *nlm_next;
  struct netlink_res **new_nlm_list;
  static volatile size_t buf_size = 4096;
  char *buf;
  struct sockaddr_nl nladdr;
  struct nlmsghdr *nlmh;
  ssize_t read_len;
  bool done = false;
  bool use_malloc = false;

  if (__netlink_sendreq (h, type) < 0)
    return -1;

  size_t this_buf_size = buf_size;
  if (__libc_use_alloca (this_buf_size))
    buf = alloca (this_buf_size);
  else
    {
      buf = malloc (this_buf_size);
      if (buf != NULL)
	use_malloc = true;
      else
	goto out_fail;
    }

  struct iovec iov = { buf, this_buf_size };

  if (h->nlm_list != NULL)
    new_nlm_list = &h->end_ptr->next;
  else
    new_nlm_list = &h->nlm_list;

  while (! done)
    {
      struct msghdr msg =
	{
	  (void *) &nladdr, sizeof (nladdr),
	  &iov, 1,
	  NULL, 0,
	  0
	};

      read_len = TEMP_FAILURE_RETRY (recvmsg (h->fd, &msg, 0));
      if (read_len < 0)
	goto out_fail;

      if (nladdr.nl_pid != 0)
	continue;

      if (__builtin_expect (msg.msg_flags & MSG_TRUNC, 0))
	{
	  if (this_buf_size >= SIZE_MAX / 2)
	    goto out_fail;

	  nlm_next = *new_nlm_list;
	  while (nlm_next != NULL)
	    {
	      struct netlink_res *tmpptr;

	      tmpptr = nlm_next->next;
	      free (nlm_next);
	      nlm_next = tmpptr;
	    }
	  *new_nlm_list = NULL;

	  if (__libc_use_alloca (2 * this_buf_size))
	    buf = extend_alloca (buf, this_buf_size, 2 * this_buf_size);
	  else
	    {
	      this_buf_size *= 2;

	      char *new_buf = realloc (use_malloc ? buf : NULL, this_buf_size);
	      if (new_buf == NULL)
		goto out_fail;
	      new_buf = buf;

	      use_malloc = true;
	    }
	  buf_size = this_buf_size;

	  iov.iov_base = buf;
	  iov.iov_len = this_buf_size;

	  /* Increase sequence number, so that we can distinguish
	     between old and new request messages.  */
	  h->seq++;

	  if (__netlink_sendreq (h, type) < 0)
	    goto out_fail;

	  continue;
	}

      size_t count = 0;
      size_t remaining_len = read_len;
      for (nlmh = (struct nlmsghdr *) buf;
	   NLMSG_OK (nlmh, remaining_len);
	   nlmh = (struct nlmsghdr *) NLMSG_NEXT (nlmh, remaining_len))
	{
	  if ((pid_t) nlmh->nlmsg_pid != h->pid
	      || nlmh->nlmsg_seq != h->seq)
	    continue;

	  ++count;
	  if (nlmh->nlmsg_type == NLMSG_DONE)
	    {
	      /* We found the end, leave the loop.  */
	      done = true;
	      break;
	    }
	  if (nlmh->nlmsg_type == NLMSG_ERROR)
	    {
	      struct nlmsgerr *nlerr = (struct nlmsgerr *) NLMSG_DATA (nlmh);
	      if (nlmh->nlmsg_len < NLMSG_LENGTH (sizeof (struct nlmsgerr)))
		errno = EIO;
	      else
		errno = -nlerr->error;
	      goto out_fail;
	    }
	}

      /* If there was nothing with the expected nlmsg_pid and nlmsg_seq,
	 there is no point to record it.  */
      if (count == 0)
	continue;

      nlm_next = (struct netlink_res *) malloc (sizeof (struct netlink_res)
						+ read_len);
      if (nlm_next == NULL)
	goto out_fail;
      nlm_next->next = NULL;
      nlm_next->nlh = memcpy (nlm_next + 1, buf, read_len);
      nlm_next->size = read_len;
      nlm_next->seq = h->seq;
      if (h->nlm_list == NULL)
	h->nlm_list = nlm_next;
      else
	h->end_ptr->next = nlm_next;
      h->end_ptr = nlm_next;
    }

  if (use_malloc)
    free (buf);
  return 0;

out_fail:
  if (use_malloc)
    free (buf);
  return -1;
}
Example #20
0
/*
 * Compiles a substitution pattern
 */
struct rewrite_subst *
rewrite_subst_compile(
		struct rewrite_info *info,
		const char *str
)
{
	size_t subs_len;
	struct berval *subs = NULL, *tmps;
	struct rewrite_submatch *submatch = NULL;

	struct rewrite_subst *s = NULL;

	char *result, *begin, *p;
	int nsub = 0, l;

	assert( info != NULL );
	assert( str != NULL );

	result = strdup( str );
	if ( result == NULL ) {
		return NULL;
	}

	/*
	 * Take care of substitution string
	 */
	for ( p = begin = result, subs_len = 0; p[ 0 ] != '\0'; p++ ) {

		/*
		 * Keep only single escapes '%'
		 */
		if (  !IS_REWRITE_SUBMATCH_ESCAPE( p[ 0 ] ) ) {
			continue;
		} 

		if (  IS_REWRITE_SUBMATCH_ESCAPE( p[ 1 ] ) ) {
			/* Pull &p[1] over p, including the trailing '\0' */
			AC_MEMCPY((char *)p, &p[ 1 ], strlen( p ) );
			continue;
		}

		tmps = ( struct berval * )realloc( subs,
				sizeof( struct berval )*( nsub + 1 ) );
		if ( tmps == NULL ) {
			goto cleanup;
		}
		subs = tmps;
		
		/*
		 * I think an `if l > 0' at runtime is better outside than
		 * inside a function call ...
		 */
		l = p - begin;
		if ( l > 0 ) {
			subs_len += l;
			subs[ nsub ].bv_len = l;
			subs[ nsub ].bv_val = malloc( l + 1 );
			if ( subs[ nsub ].bv_val == NULL ) {
				goto cleanup;
			}
			AC_MEMCPY( subs[ nsub ].bv_val, begin, l );
			subs[ nsub ].bv_val[ l ] = '\0';
		} else {
			subs[ nsub ].bv_val = NULL;
			subs[ nsub ].bv_len = 0;
		}
		
		/*
		 * Substitution pattern
		 */
		if ( isdigit( (unsigned char) p[ 1 ] ) ) {
			struct rewrite_submatch *tmpsm;
			int d = p[ 1 ] - '0';

			/*
			 * Add a new value substitution scheme
			 */

			tmpsm = ( struct rewrite_submatch * )realloc( submatch,
					sizeof( struct rewrite_submatch )*( nsub + 1 ) );
			if ( tmpsm == NULL ) {
				goto cleanup;
			}
			submatch = tmpsm;
			submatch[ nsub ].ls_submatch = d;

			/*
			 * If there is no argument, use default
			 * (substitute substring as is)
			 */
			if ( p[ 2 ] != '{' ) {
				submatch[ nsub ].ls_type = 
					REWRITE_SUBMATCH_ASIS;
				submatch[ nsub ].ls_map = NULL;
				begin = ++p + 1;

			} else {
				struct rewrite_map *map;

				submatch[ nsub ].ls_type =
					REWRITE_SUBMATCH_XMAP;

				map = rewrite_xmap_parse( info,
						p + 3, (const char **)&begin );
				if ( map == NULL ) {
					goto cleanup;
				}
				submatch[ nsub ].ls_map = map;
				p = begin - 1;
			}

		/*
		 * Map with args ...
		 */
		} else if ( p[ 1 ] == '{' ) {
			struct rewrite_map *map;
			struct rewrite_submatch *tmpsm;

			map = rewrite_map_parse( info, p + 2,
					(const char **)&begin );
			if ( map == NULL ) {
				goto cleanup;
			}
			p = begin - 1;

			/*
			 * Add a new value substitution scheme
			 */
			tmpsm = ( struct rewrite_submatch * )realloc( submatch,
					sizeof( struct rewrite_submatch )*( nsub + 1 ) );
			if ( tmpsm == NULL ) {
				goto cleanup;
			}
			submatch = tmpsm;
			submatch[ nsub ].ls_type =
				REWRITE_SUBMATCH_MAP_W_ARG;
			submatch[ nsub ].ls_map = map;

		/*
		 * Escape '%' ...
		 */
		} else if ( p[ 1 ] == '%' ) {
			AC_MEMCPY( &p[ 1 ], &p[ 2 ], strlen( &p[ 1 ] ) );
			continue;

		} else {
			goto cleanup;
		}

		nsub++;
	}
	
	/*
	 * Last part of string
	 */
	tmps = (struct berval * )realloc( subs, sizeof( struct berval )*( nsub + 1 ) );
	if ( tmps == NULL ) {
		/*
		 * XXX need to free the value subst stuff!
		 */
		free( subs );
		goto cleanup;
	}
	subs = tmps;
	l = p - begin;
	if ( l > 0 ) {
		subs_len += l;
		subs[ nsub ].bv_len = l;
		subs[ nsub ].bv_val = malloc( l + 1 );
		if ( subs[ nsub ].bv_val == NULL ) {
			free( subs );
			goto cleanup;
		}
		AC_MEMCPY( subs[ nsub ].bv_val, begin, l );
		subs[ nsub ].bv_val[ l ] = '\0';
	} else {
		subs[ nsub ].bv_val = NULL;
		subs[ nsub ].bv_len = 0;
	}

	s = calloc( sizeof( struct rewrite_subst ), 1 );
	if ( s == NULL ) {
		goto cleanup;
	}

	s->lt_subs_len = subs_len;
        s->lt_subs = subs;
        s->lt_num_submatch = nsub;
        s->lt_submatch = submatch;

cleanup:;
	free( result );

	return s;
}
Example #21
0
/* return an (malloc'ed) array of "external" port for which there is
 * a port mapping. number is the size of the array */
unsigned short *
get_portmappings_in_range(unsigned short startport, unsigned short endport,
                          int proto, unsigned int * number)
{
	unsigned short * array;
	unsigned int capacity;
	unsigned short eport;
	IPTC_HANDLE h;
	const struct ipt_entry * e;
	const struct ipt_entry_match *match;

	*number = 0;
	capacity = 128;
	array = calloc(capacity, sizeof(unsigned short));
	if(!array)
	{
		syslog(LOG_ERR, "get_portmappings_in_range() : calloc error");
		return NULL;
	}

	h = iptc_init("nat");
	if(!h)
	{
		syslog(LOG_ERR, "get_redirect_rule_by_index() : "
		                "iptc_init() failed : %s",
		       iptc_strerror(errno));
		free(array);
		return NULL;
	}
	if(!iptc_is_chain(miniupnpd_nat_chain, h))
	{
		syslog(LOG_ERR, "chain %s not found", miniupnpd_nat_chain);
		free(array);
		array = NULL;
	}
	else
	{
#ifdef IPTABLES_143
		for(e = iptc_first_rule(miniupnpd_nat_chain, h);
		    e;
			e = iptc_next_rule(e, h))
#else
		for(e = iptc_first_rule(miniupnpd_nat_chain, &h);
		    e;
			e = iptc_next_rule(e, &h))
#endif
		{
			if(proto == e->ip.proto)
			{
				match = (const struct ipt_entry_match *)&e->elems;
				if(0 == strncmp(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN))
				{
					const struct ipt_tcp * info;
					info = (const struct ipt_tcp *)match->data;
					eport = info->dpts[0];
				}
				else
				{
					const struct ipt_udp * info;
					info = (const struct ipt_udp *)match->data;
					eport = info->dpts[0];
				}
				if(startport <= eport && eport <= endport)
				{
					if(*number >= capacity)
					{
						/* need to increase the capacity of the array */
						array = realloc(array, sizeof(unsigned short)*capacity);
						if(!array)
						{
							syslog(LOG_ERR, "get_portmappings_in_range() : realloc(%u) error",
							       (unsigned)sizeof(unsigned short)*capacity);
							*number = 0;
							break;
						}
						array[*number] = eport;
						(*number)++;
					}
				}
			}
		}
	}
	if(h)
#ifdef IPTABLES_143
		iptc_free(h);
#else
		iptc_free(&h);
#endif
	return array;
}
Example #22
0
void bwa_cal_sa_reg_gap(int tid, bwt_t * const bwt[2], int n_seqs,
		bwa_seq_t *seqs, const gap_opt_t *opt) {
	int i, max_l = 0, max_len;
	gap_stack_t *stack;
	bwt_width_t *w[2], *seed_w[2];
	const ubyte_t *seq[2];
	gap_opt_t local_opt = *opt;

	// initiate priority stack
	for (i = max_len = 0; i != n_seqs; ++i)
		if (seqs[i].len > max_len)
			max_len = seqs[i].len;
	if (opt->fnr > 0.0)
		local_opt.max_diff = bwa_cal_maxdiff(max_len, BWA_AVG_ERR, opt->fnr);
	if (local_opt.max_diff < local_opt.max_gapo)
		local_opt.max_gapo = local_opt.max_diff;
	stack = gap_init_stack(local_opt.max_diff, local_opt.max_gapo,
			local_opt.max_gape, &local_opt);

	seed_w[0] = (bwt_width_t*) calloc(opt->seed_len + 1, sizeof(bwt_width_t));
	seed_w[1] = (bwt_width_t*) calloc(opt->seed_len + 1, sizeof(bwt_width_t));
	w[0] = w[1] = 0;
	for (i = 0; i != n_seqs; ++i) {
		bwa_seq_t *p = seqs + i;
#ifdef HAVE_PTHREAD
		if (opt->n_threads > 1) {
			pthread_mutex_lock(&g_seq_lock);
			if (p->tid < 0) { // unassigned
				int j;
				for (j = i; j < n_seqs && j < i + THREAD_BLOCK_SIZE; ++j)
					seqs[j].tid = tid;
			} else if (p->tid != tid) {
				pthread_mutex_unlock(&g_seq_lock);
				continue;
			}
			pthread_mutex_unlock(&g_seq_lock);
		}
#endif
		p->sa = 0;
		p->type = BWA_TYPE_NO_MATCH;
		p->c1 = p->c2 = 0;
		p->n_aln = 0;
		p->aln = 0;
		seq[0] = p->seq;
		seq[1] = p->rseq;
		if (max_l < p->len) {
			max_l = p->len;
			w[0] = (bwt_width_t*) realloc(w[0], (max_l + 1)
					* sizeof(bwt_width_t));
			w[1] = (bwt_width_t*) realloc(w[1], (max_l + 1)
					* sizeof(bwt_width_t));
			memset(w[0], 0, (max_l + 1) * sizeof(bwt_width_t));
			memset(w[1], 0, (max_l + 1) * sizeof(bwt_width_t));
		}
		bwt_cal_width(bwt[0], p->len, seq[0], w[0]);
		bwt_cal_width(bwt[1], p->len, seq[1], w[1]);
		if (opt->fnr > 0.0)
			local_opt.max_diff = bwa_cal_maxdiff(p->len, BWA_AVG_ERR, opt->fnr);
		local_opt.seed_len = opt->seed_len < p->len ? opt->seed_len
				: 0x7fffffff;
		if (p->len > opt->seed_len) {
			bwt_cal_width(bwt[0], opt->seed_len, seq[0] + (p->len
					- opt->seed_len), seed_w[0]);
			bwt_cal_width(bwt[1], opt->seed_len, seq[1] + (p->len
					- opt->seed_len), seed_w[1]);
		}
		// core function
		p->aln = bwt_match_gap(bwt, p->len, seq, w, p->len <= opt->seed_len ? 0
				: seed_w, &local_opt, &p->n_aln, stack);
		// store the alignment
		free(p->name);
		free(p->seq);
		free(p->rseq);
		free(p->qual);
		p->name = 0;
		p->seq = p->rseq = p->qual = 0;
	}
	free(seed_w[0]);
	free(seed_w[1]);
	free(w[0]);
	free(w[1]);
	gap_destroy_stack(stack);
}
Example #23
0
void load_volume_table() {
    int alloc = 2;
    device_volumes = malloc(alloc * sizeof(Volume));

    // Insert an entry for /tmp, which is the ramdisk and is always mounted.
    device_volumes[0].mount_point = "/tmp";
    device_volumes[0].fs_type = "ramdisk";
    device_volumes[0].device = NULL;
    device_volumes[0].device2 = NULL;
    device_volumes[0].fs_type2 = NULL;
    device_volumes[0].fs_options = NULL;
    device_volumes[0].fs_options2 = NULL;
    device_volumes[0].length = 0;
    num_volumes = 1;

    FILE* fstab = fopen("/etc/recovery.fstab", "r");
    if (fstab == NULL) {
        LOGE("failed to open /etc/recovery.fstab (%s)\n", strerror(errno));
        return;
    }

    char buffer[1024];
    int i;
    while (fgets(buffer, sizeof(buffer)-1, fstab)) {
        for (i = 0; buffer[i] && isspace(buffer[i]); ++i);
        if (buffer[i] == '\0' || buffer[i] == '#') continue;

        char* original = strdup(buffer);

        char* mount_point = strtok(buffer+i, " \t\n");
        char* fs_type = strtok(NULL, " \t\n");
        char* device = strtok(NULL, " \t\n");
        // lines may optionally have a second device, to use if
        // mounting the first one fails.
        char* options = NULL;
        char* device2 = strtok(NULL, " \t\n");
        if (device2) {
            if (device2[0] == '/') {
                options = strtok(NULL, " \t\n");
            } else {
                options = device2;
                device2 = NULL;
            }
        }

        if (mount_point && fs_type && device) {
            while (num_volumes >= alloc) {
                alloc *= 2;
                device_volumes = realloc(device_volumes, alloc*sizeof(Volume));
            }
            device_volumes[num_volumes].mount_point = strdup(mount_point);
            device_volumes[num_volumes].fs_type = strdup(fs_type);
            device_volumes[num_volumes].device = strdup(device);
            device_volumes[num_volumes].device2 =
                device2 ? strdup(device2) : NULL;

            device_volumes[num_volumes].length = 0;

            device_volumes[num_volumes].fs_type2 = NULL;
            device_volumes[num_volumes].fs_options = NULL;
            device_volumes[num_volumes].fs_options2 = NULL;

            if (parse_options(options, device_volumes + num_volumes) != 0) {
                LOGE("skipping malformed recovery.fstab line: %s\n", original);
            } else {
                ++num_volumes;
            }
        } else {
            LOGE("skipping malformed recovery.fstab line: %s\n", original);
        }
        free(original);
    }

    fclose(fstab);

    printf("recovery filesystem table\n");
    printf("=========================\n");
    for (i = 0; i < num_volumes; ++i) {
        Volume* v = &device_volumes[i];
        printf("  %d %s %s %s %s %lld\n", i, v->mount_point, v->fs_type,
               v->device, v->device2, v->length);
    }
    printf("\n");
}
Example #24
0
/*
 *  send the damn thing
 */
char *
data(String *from, Biobuf *b)
{
	char *buf, *cp;
	int i, n, nbytes, bufsize, eof, r;
	String *fromline;
	char errmsg[Errlen];
	char id[40];

	/*
	 *  input the header.
	 */

	buf = malloc(1);
	if(buf == 0){
		s_append(s_restart(reply), "out of memory");
		return Retry;
	}
	n = 0;
	eof = 0;
	for(;;){
		cp = Brdline(b, '\n');
		if(cp == nil){
			eof = 1;
			break;
		}
		nbytes = Blinelen(b);
		buf = realloc(buf, n+nbytes+1);
		if(buf == 0){
			s_append(s_restart(reply), "out of memory");
			return Retry;
		}
		strncpy(buf+n, cp, nbytes);
		n += nbytes;
		if(nbytes == 1)		/* end of header */
			break;
	}
	buf[n] = 0;
	bufsize = n;

	/*
	 *  parse the header, turn all addresses into @ format
	 */
	yyinit(buf, n);
	yyparse();

	/*
	 *  print message observing '.' escapes and using \r\n for \n
	 */
	alarm(20*alarmscale);
	if(!filter){
		dBprint("DATA\r\n");
		switch(getreply()){
		case 3:
			break;
		case 5:
			free(buf);
			return Giveup;
		default:
			free(buf);
			return Retry;
		}
	}
	/*
	 *  send header.  add a message-id, a sender, and a date if there
	 *  isn't one
	 */
	nbytes = 0;
	fromline = convertheader(from);
	uneaten = buf;

	srand(truerand());
	if(messageid == 0){
		for(i=0; i<16; i++){
			r = rand()&0xFF;
			id[2*i] = hex[r&0xF];
			id[2*i+1] = hex[(r>>4)&0xF];
		}
		id[2*i] = '\0';
		nbytes += Bprint(&bout, "Message-ID: <%s@%s>\r\n", id, hostdomain);
		if(debug)
			Bprint(&berr, "Message-ID: <%s@%s>\r\n", id, hostdomain);
	}

	if(originator==0){
		nbytes += Bprint(&bout, "From: %s\r\n", s_to_c(fromline));
		if(debug)
			Bprint(&berr, "From: %s\r\n", s_to_c(fromline));
	}
	s_free(fromline);

	if(destination == 0 && toline)
		if(*s_to_c(toline) == '@'){	/* route addr */
			nbytes += Bprint(&bout, "To: <%s>\r\n", s_to_c(toline));
			if(debug)
				Bprint(&berr, "To: <%s>\r\n", s_to_c(toline));
		} else {
			nbytes += Bprint(&bout, "To: %s\r\n", s_to_c(toline));
			if(debug)
				Bprint(&berr, "To: %s\r\n", s_to_c(toline));
		}

	if(date==0 && udate)
		nbytes += printdate(udate);
	if (usys)
		uneaten = usys->end + 1;
	nbytes += printheader();
	if (*uneaten != '\n')
		putcrnl("\n", 1);

	/*
	 *  send body
	 */

	putcrnl(uneaten, buf+n - uneaten);
	nbytes += buf+n - uneaten;
	if(eof == 0){
		for(;;){
			n = Bread(b, buf, bufsize);
			if(n < 0){
				rerrstr(errmsg, sizeof(errmsg));
				s_append(s_restart(reply), errmsg);
				free(buf);
				return Retry;
			}
			if(n == 0)
				break;
			alarm(10*alarmscale);
			putcrnl(buf, n);
			nbytes += n;
		}
	}
	free(buf);
	if(!filter){
		if(last != '\n')
			dBprint("\r\n.\r\n");
		else
			dBprint(".\r\n");
		alarm(10*alarmscale);
		switch(getreply()){
		case 2:
			break;
		case 5:
			return Giveup;
		default:
			return Retry;
		}
		syslog(0, "smtp", "%s sent %d bytes to %s", s_to_c(from),
				nbytes, s_to_c(toline));/**/
	}
	return 0;
}
Example #25
0
APULSE_EXPORT
int
pa_mainloop_prepare(pa_mainloop *m, int timeout)
{
    trace_info("P %s m=%p, timeout=%d\n", __func__, m, timeout);

    m->timeout = timeout;
    if (m->recreate_fds) {
        GList *keys = g_hash_table_get_keys(m->events_ht);
        GList *it;
        struct pollfd *tmp;

        m->nfds = g_list_length(keys) + 1;
        tmp = realloc(m->fds, m->nfds * sizeof(*m->fds));
        if (!tmp)
            return -1;
        m->fds = tmp;

        m->fds[0].fd = m->wakeup_pipe[0];
        m->fds[0].events = POLLIN;
        m->fds[0].revents = 0;

        /* special case for alsa pollfds */
        int k = 1;
        m->alsa_special_cnt = 0;
        it = keys;
        while (it) {
            struct pa_io_event *ioe = it->data;
            if (ioe->events & 0x80000000u) {
                m->fds[k].fd = ioe->fd;
                m->fds[k].events = ioe->events & (~0x80000000u);
                m->fds[k].revents = 0;
                ioe->pollfd = &m->fds[k];
                k ++;
                m->alsa_special_cnt ++;
            }
            it = g_list_next(it);
        }

        /* normal file descriptors */
        it = keys;
        while (it) {
            struct pa_io_event *ioe = it->data;
            if ((ioe->events & 0x80000000u) == 0) {
                m->fds[k].fd = ioe->fd;
                m->fds[k].events = from_pa_io_event_flags(ioe->events);
                m->fds[k].revents = 0;
                ioe->pollfd = &m->fds[k];
                k ++;
            }
            it = g_list_next(it);
        }

        m->nfds = k;

        g_list_free(keys);
        m->recreate_fds = 0;
    }

    return 0;
}
Example #26
0
int main(int argc, char **argv, char **envp) {

    int capacidade = 4*1024;
    int contagem = 0;
    int* lista = (int*)malloc(capacidade*sizeof(int));

    // lista de parametros
    bool dbg = 0;
    bool use_quicksort = 0;
    bool use_mergesort = 0;
    int itarg;
    bool opt_items = 0;
    bool use_stdin = 1;
    for (itarg = 0; itarg < argc; itarg++) {
        char* arg = argv[itarg];

        if (opt_items) {
            char *ptr;
            long n = strtol(arg, &ptr, 10);
            if (ptr[0] != 0) {
                opt_items = 0;
            }
            else {
                dbg && printf("# %ld\n", n);

                // adicionando elemento na lista
                if (contagem == capacidade) {
                    capacidade *= 2;
                    lista = (int*)realloc(lista, capacidade*sizeof(int));
                }
                lista[contagem] = n;
                contagem++;

                continue;                
            }
        }

        // -i       sequencia de itens a usar (nao usar stdin)
        if (strcmp("-i", arg) == 0) {
            opt_items = 1;
            use_stdin = 0;
        }
        // -q       usar quicksort
        else if (strcmp("-q", arg) == 0) {
            use_quicksort = 1;
        }
        // -m       usar mergesort
        else if (strcmp("-m", arg) == 0) {
            use_mergesort = 1;
        }
        // -dbg     debug messages
        else if (strcmp("-dbg", arg) == 0) {
            dbg = 1;
        }
    }
    dbg && printf("# use_quicksort: %d\n", use_quicksort);
    dbg && printf("# use_mergesort: %d\n", use_mergesort);

    // lista de itens a serem ordenados
    // ********************************
    if (use_stdin) {
        const int MAX_LINE_SZ = 0x1000;
        char line[MAX_LINE_SZ];
        int i = 0;
        for (;; i++) {
            int n;
            if (fgets(line, MAX_LINE_SZ, stdin) == 0) break;
            if (line[0] == '#') {
                dbg && printf("%s", line);
            }
            else {
                sscanf(line, "%d\n", &n);
                dbg && printf("# %d\n", n);
            }

            // adicionando elemento na lista
            if (contagem == capacidade) {
                capacidade *= 2;
                lista = (int*)realloc(lista, capacidade*sizeof(int));
            }
            lista[contagem] = n;
            contagem++;
        }
    }


    // Programa de ordenacao
    // ************************

    if (use_mergesort) {
        printf("# mergesort\n");
        mergesort(lista, 0, contagem-1);

        int it = 0;
        for (; it < contagem; it++) {
            printf("%d\n", lista[it]);
        }
    }
    else if (use_quicksort) {
        printf("# quicksort\n");
        quicksort(lista, 0, contagem-1);

        int it = 0;
        for (; it < contagem; it++) {
            printf("%d\n", lista[it]);
        }
    }
}
Example #27
0
static void *_insert(void *ptr,long bytes,char *file,long line) {
    ((head *)ptr)->file=file;
    ((head *)ptr)->line=line;
    ((head *)ptr)->ptr=pinsert;
    ((head *)ptr)->bytes=bytes-HEAD_ALIGN;

    if(pinsert>=palloced) {
        palloced+=64;
        if(pointers) {
            pointers=(void **)realloc(pointers,sizeof(void **)*palloced);
            insertlist=(long *)realloc(insertlist,sizeof(long *)*palloced);
        } else {
            pointers=(void **)malloc(sizeof(void **)*palloced);
            insertlist=(long *)malloc(sizeof(long *)*palloced);
        }
    }

    pointers[pinsert]=ptr;

    if(pinsert==ptop)
        pinsert=++ptop;
    else
        pinsert=insertlist[pinsert];

#ifdef _VDBG_GRAPHFILE
    {
        FILE *out;
        struct timeval tv;
        static struct timezone tz;
        int i;
        char buffer[80];
        gettimeofday(&tv,&tz);

        for(i=0; i<filecount; i++)
            if(!strcmp(file,files[i]))break;

        if(i==filecount) {
            filecount++;
            if(!files) {
                files=malloc(filecount*sizeof(*files));
                file_bytes=malloc(filecount*sizeof(*file_bytes));
            } else {
                files=realloc(files,filecount*sizeof(*files));
                file_bytes=realloc(file_bytes,filecount*sizeof(*file_bytes));
            }
            files[i]=strdup(file);
            file_bytes[i]=0;
        }

        file_bytes[i]+=bytes-HEAD_ALIGN;

        if(start_time==-1)start_time=(tv.tv_sec*1000)+(tv.tv_usec/1000);

        snprintf(buffer,80,"%s",file);
        if(strchr(buffer,'.'))strchr(buffer,'.')[0]=0;
        strcat(buffer,_VDBG_GRAPHFILE);
        out=fopen(buffer,"a");
        fprintf(out,"%ld, %ld\n",-start_time+(tv.tv_sec*1000)+(tv.tv_usec/1000),
                file_bytes[i]-(bytes-HEAD_ALIGN));
        fprintf(out,"%ld, %ld # FILE %s LINE %ld\n",
                -start_time+(tv.tv_sec*1000)+(tv.tv_usec/1000),
                file_bytes[i],file,line);
        fclose(out);

        out=fopen("total"_VDBG_GRAPHFILE,"a");
        fprintf(out,"%ld, %ld\n",-start_time+(tv.tv_sec*1000)+(tv.tv_usec/1000),
                global_bytes);
        fprintf(out,"%ld, %ld\n",-start_time+(tv.tv_sec*1000)+(tv.tv_usec/1000),
                global_bytes+(bytes-HEAD_ALIGN));
        fclose(out);
    }
#endif

    global_bytes+=(bytes-HEAD_ALIGN);

    return(void *)(((char *)ptr)+HEAD_ALIGN);
}
Example #28
0
int
YYPARSE_DECL()
{
    int yym, yyn, yystate, yyresult;
#if YYBTYACC
    int yynewerrflag;
    YYParseState *yyerrctx = NULL;
#endif /* YYBTYACC */
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
    YYLTYPE  yyerror_loc_range[2]; /* position of error start & end */
#endif
#if YYDEBUG
    const char *yys;

    if ((yys = getenv("YYDEBUG")) != 0)
    {
        yyn = *yys;
        if (yyn >= '0' && yyn <= '9')
            yydebug = yyn - '0';
    }
    if (yydebug)
        fprintf(stderr, "%sdebug[<# of symbols on state stack>]\n", YYPREFIX);
#endif

#if YYBTYACC
    yyps = yyNewState(0); if (yyps == 0) goto yyenomem;
    yyps->save = 0;
#endif /* YYBTYACC */
    yym = 0;
    yyn = 0;
    yynerrs = 0;
    yyerrflag = 0;
    yychar = YYEMPTY;
    yystate = 0;

#if YYPURE
    memset(&yystack, 0, sizeof(yystack));
#endif

    if (yystack.s_base == NULL && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow;
    yystack.s_mark = yystack.s_base;
    yystack.l_mark = yystack.l_base;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
    yystack.p_mark = yystack.p_base;
#endif
    yystate = 0;
    *yystack.s_mark = 0;

yyloop:
    if ((yyn = yydefred[yystate]) != 0) goto yyreduce;
    if (yychar < 0)
    {
#if YYBTYACC
        do {
        if (yylvp < yylve)
        {
            /* we're currently re-reading tokens */
            yylval = *yylvp++;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            yylloc = *yylpp++;
#endif
            yychar = *yylexp++;
            break;
        }
        if (yyps->save)
        {
            /* in trial mode; save scanner results for future parse attempts */
            if (yylvp == yylvlim)
            {   /* Enlarge lexical value queue */
                size_t p = (size_t) (yylvp - yylvals);
                size_t s = (size_t) (yylvlim - yylvals);

                s += YYLVQUEUEGROWTH;
                if ((yylexemes = realloc(yylexemes, s * sizeof(YYINT))) == NULL) goto yyenomem;
                if ((yylvals   = realloc(yylvals, s * sizeof(YYSTYPE))) == NULL) goto yyenomem;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                if ((yylpsns   = realloc(yylpsns, s * sizeof(YYLTYPE))) == NULL) goto yyenomem;
#endif
                yylvp   = yylve = yylvals + p;
                yylvlim = yylvals + s;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                yylpp   = yylpe = yylpsns + p;
                yylplim = yylpsns + s;
#endif
                yylexp  = yylexemes + p;
            }
            *yylexp = (YYINT) YYLEX;
            *yylvp++ = yylval;
            yylve++;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            *yylpp++ = yylloc;
            yylpe++;
#endif
            yychar = *yylexp++;
            break;
        }
        /* normal operation, no conflict encountered */
#endif /* YYBTYACC */
        yychar = YYLEX;
#if YYBTYACC
        } while (0);
#endif /* YYBTYACC */
        if (yychar < 0) yychar = YYEOF;
#if YYDEBUG
        if (yydebug)
        {
            if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN];
            fprintf(stderr, "%s[%d]: state %d, reading token %d (%s)",
                            YYDEBUGSTR, yydepth, yystate, yychar, yys);
#ifdef YYSTYPE_TOSTRING
#if YYBTYACC
            if (!yytrial)
#endif /* YYBTYACC */
                fprintf(stderr, " <%s>", YYSTYPE_TOSTRING(yychar, yylval));
#endif
            fputc('\n', stderr);
        }
#endif
    }
#if YYBTYACC

    /* Do we have a conflict? */
    if (((yyn = yycindex[yystate]) != 0) && (yyn += yychar) >= 0 &&
        yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yychar)
    {
        YYINT ctry;

        if (yypath)
        {
            YYParseState *save;
#if YYDEBUG
            if (yydebug)
                fprintf(stderr, "%s[%d]: CONFLICT in state %d: following successful trial parse\n",
                                YYDEBUGSTR, yydepth, yystate);
#endif
            /* Switch to the next conflict context */
            save = yypath;
            yypath = save->save;
            save->save = NULL;
            ctry = save->ctry;
            if (save->state != yystate) YYABORT;
            yyFreeState(save);

        }
        else
        {

            /* Unresolved conflict - start/continue trial parse */
            YYParseState *save;
#if YYDEBUG
            if (yydebug)
            {
                fprintf(stderr, "%s[%d]: CONFLICT in state %d. ", YYDEBUGSTR, yydepth, yystate);
                if (yyps->save)
                    fputs("ALREADY in conflict, continuing trial parse.\n", stderr);
                else
                    fputs("Starting trial parse.\n", stderr);
            }
#endif
            save                  = yyNewState((unsigned)(yystack.s_mark - yystack.s_base + 1));
            if (save == NULL) goto yyenomem;
            save->save            = yyps->save;
            save->state           = yystate;
            save->errflag         = yyerrflag;
            save->yystack.s_mark  = save->yystack.s_base + (yystack.s_mark - yystack.s_base);
            memcpy (save->yystack.s_base, yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT));
            save->yystack.l_mark  = save->yystack.l_base + (yystack.l_mark - yystack.l_base);
            memcpy (save->yystack.l_base, yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE));
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            save->yystack.p_mark  = save->yystack.p_base + (yystack.p_mark - yystack.p_base);
            memcpy (save->yystack.p_base, yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE));
#endif
            ctry                  = yytable[yyn];
            if (yyctable[ctry] == -1)
            {
#if YYDEBUG
                if (yydebug && yychar >= YYEOF)
                    fprintf(stderr, "%s[%d]: backtracking 1 token\n", YYDEBUGSTR, yydepth);
#endif
                ctry++;
            }
            save->ctry = ctry;
            if (yyps->save == NULL)
            {
                /* If this is a first conflict in the stack, start saving lexemes */
                if (!yylexemes)
                {
                    yylexemes = malloc((YYLVQUEUEGROWTH) * sizeof(YYINT));
                    if (yylexemes == NULL) goto yyenomem;
                    yylvals   = (YYSTYPE *) malloc((YYLVQUEUEGROWTH) * sizeof(YYSTYPE));
                    if (yylvals == NULL) goto yyenomem;
                    yylvlim   = yylvals + YYLVQUEUEGROWTH;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                    yylpsns   = (YYLTYPE *) malloc((YYLVQUEUEGROWTH) * sizeof(YYLTYPE));
                    if (yylpsns == NULL) goto yyenomem;
                    yylplim   = yylpsns + YYLVQUEUEGROWTH;
#endif
                }
                if (yylvp == yylve)
                {
                    yylvp  = yylve = yylvals;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                    yylpp  = yylpe = yylpsns;
#endif
                    yylexp = yylexemes;
                    if (yychar >= YYEOF)
                    {
                        *yylve++ = yylval;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                        *yylpe++ = yylloc;
#endif
                        *yylexp  = (YYINT) yychar;
                        yychar   = YYEMPTY;
                    }
                }
            }
            if (yychar >= YYEOF)
            {
                yylvp--;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                yylpp--;
#endif
                yylexp--;
                yychar = YYEMPTY;
            }
            save->lexeme = (int) (yylvp - yylvals);
            yyps->save   = save;
        }
        if (yytable[yyn] == ctry)
        {
#if YYDEBUG
            if (yydebug)
                fprintf(stderr, "%s[%d]: state %d, shifting to state %d\n",
                                YYDEBUGSTR, yydepth, yystate, yyctable[ctry]);
#endif
            if (yychar < 0)
            {
                yylvp++;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                yylpp++;
#endif
                yylexp++;
            }
            if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM)
                goto yyoverflow;
            yystate = yyctable[ctry];
            *++yystack.s_mark = (YYINT) yystate;
            *++yystack.l_mark = yylval;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            *++yystack.p_mark = yylloc;
#endif
            yychar  = YYEMPTY;
            if (yyerrflag > 0) --yyerrflag;
            goto yyloop;
        }
        else
        {
            yyn = yyctable[ctry];
            goto yyreduce;
        }
    } /* End of code dealing with conflicts */
#endif /* YYBTYACC */
    if (((yyn = yysindex[yystate]) != 0) && (yyn += yychar) >= 0 &&
            yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yychar)
    {
#if YYDEBUG
        if (yydebug)
            fprintf(stderr, "%s[%d]: state %d, shifting to state %d\n",
                            YYDEBUGSTR, yydepth, yystate, yytable[yyn]);
#endif
        if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow;
        yystate = yytable[yyn];
        *++yystack.s_mark = yytable[yyn];
        *++yystack.l_mark = yylval;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
        *++yystack.p_mark = yylloc;
#endif
        yychar = YYEMPTY;
        if (yyerrflag > 0)  --yyerrflag;
        goto yyloop;
    }
    if (((yyn = yyrindex[yystate]) != 0) && (yyn += yychar) >= 0 &&
            yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yychar)
    {
        yyn = yytable[yyn];
        goto yyreduce;
    }
    if (yyerrflag != 0) goto yyinrecovery;
#if YYBTYACC

    yynewerrflag = 1;
    goto yyerrhandler;
    goto yyerrlab; /* redundant goto avoids 'unused label' warning */

yyerrlab:
    /* explicit YYERROR from an action -- pop the rhs of the rule reduced
     * before looking for error recovery */
    yystack.s_mark -= yym;
    yystate = *yystack.s_mark;
    yystack.l_mark -= yym;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
    yystack.p_mark -= yym;
#endif

    yynewerrflag = 0;
yyerrhandler:
    while (yyps->save)
    {
        int ctry;
        YYParseState *save = yyps->save;
#if YYDEBUG
        if (yydebug)
            fprintf(stderr, "%s[%d]: ERROR in state %d, CONFLICT BACKTRACKING to state %d, %d tokens\n",
                            YYDEBUGSTR, yydepth, yystate, yyps->save->state,
                    (int)(yylvp - yylvals - yyps->save->lexeme));
#endif
        /* Memorize most forward-looking error state in case it's really an error. */
        if (yyerrctx == NULL || yyerrctx->lexeme < yylvp - yylvals)
        {
            /* Free old saved error context state */
            if (yyerrctx) yyFreeState(yyerrctx);
            /* Create and fill out new saved error context state */
            yyerrctx                 = yyNewState((unsigned)(yystack.s_mark - yystack.s_base + 1));
            if (yyerrctx == NULL) goto yyenomem;
            yyerrctx->save           = yyps->save;
            yyerrctx->state          = yystate;
            yyerrctx->errflag        = yyerrflag;
            yyerrctx->yystack.s_mark = yyerrctx->yystack.s_base + (yystack.s_mark - yystack.s_base);
            memcpy (yyerrctx->yystack.s_base, yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT));
            yyerrctx->yystack.l_mark = yyerrctx->yystack.l_base + (yystack.l_mark - yystack.l_base);
            memcpy (yyerrctx->yystack.l_base, yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE));
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            yyerrctx->yystack.p_mark = yyerrctx->yystack.p_base + (yystack.p_mark - yystack.p_base);
            memcpy (yyerrctx->yystack.p_base, yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE));
#endif
            yyerrctx->lexeme         = (int) (yylvp - yylvals);
        }
        yylvp          = yylvals   + save->lexeme;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
        yylpp          = yylpsns   + save->lexeme;
#endif
        yylexp         = yylexemes + save->lexeme;
        yychar         = YYEMPTY;
        yystack.s_mark = yystack.s_base + (save->yystack.s_mark - save->yystack.s_base);
        memcpy (yystack.s_base, save->yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT));
        yystack.l_mark = yystack.l_base + (save->yystack.l_mark - save->yystack.l_base);
        memcpy (yystack.l_base, save->yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE));
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
        yystack.p_mark = yystack.p_base + (save->yystack.p_mark - save->yystack.p_base);
        memcpy (yystack.p_base, save->yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE));
#endif
        ctry           = ++save->ctry;
        yystate        = save->state;
        /* We tried shift, try reduce now */
        if ((yyn = yyctable[ctry]) >= 0) goto yyreduce;
        yyps->save     = save->save;
        save->save     = NULL;
        yyFreeState(save);

        /* Nothing left on the stack -- error */
        if (!yyps->save)
        {
#if YYDEBUG
            if (yydebug)
                fprintf(stderr, "%sdebug[%d,trial]: trial parse FAILED, entering ERROR mode\n",
                                YYPREFIX, yydepth);
#endif
            /* Restore state as it was in the most forward-advanced error */
            yylvp          = yylvals   + yyerrctx->lexeme;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            yylpp          = yylpsns   + yyerrctx->lexeme;
#endif
            yylexp         = yylexemes + yyerrctx->lexeme;
            yychar         = yylexp[-1];
            yylval         = yylvp[-1];
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            yylloc         = yylpp[-1];
#endif
            yystack.s_mark = yystack.s_base + (yyerrctx->yystack.s_mark - yyerrctx->yystack.s_base);
            memcpy (yystack.s_base, yyerrctx->yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT));
            yystack.l_mark = yystack.l_base + (yyerrctx->yystack.l_mark - yyerrctx->yystack.l_base);
            memcpy (yystack.l_base, yyerrctx->yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE));
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            yystack.p_mark = yystack.p_base + (yyerrctx->yystack.p_mark - yyerrctx->yystack.p_base);
            memcpy (yystack.p_base, yyerrctx->yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE));
#endif
            yystate        = yyerrctx->state;
            yyFreeState(yyerrctx);
            yyerrctx       = NULL;
        }
        yynewerrflag = 1;
    }
    if (yynewerrflag == 0) goto yyinrecovery;
#endif /* YYBTYACC */

    YYERROR_CALL("syntax error");
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
    yyerror_loc_range[0] = yylloc; /* lookahead position is error start position */
#endif

#if !YYBTYACC
    goto yyerrlab; /* redundant goto avoids 'unused label' warning */
yyerrlab:
#endif
    ++yynerrs;

yyinrecovery:
    if (yyerrflag < 3)
    {
        yyerrflag = 3;
        for (;;)
        {
            if (((yyn = yysindex[*yystack.s_mark]) != 0) && (yyn += YYERRCODE) >= 0 &&
                    yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) YYERRCODE)
            {
#if YYDEBUG
                if (yydebug)
                    fprintf(stderr, "%s[%d]: state %d, error recovery shifting to state %d\n",
                                    YYDEBUGSTR, yydepth, *yystack.s_mark, yytable[yyn]);
#endif
                if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow;
                yystate = yytable[yyn];
                *++yystack.s_mark = yytable[yyn];
                *++yystack.l_mark = yylval;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                /* lookahead position is error end position */
                yyerror_loc_range[1] = yylloc;
                YYLLOC_DEFAULT(yyloc, yyerror_loc_range, 2); /* position of error span */
                *++yystack.p_mark = yyloc;
#endif
                goto yyloop;
            }
            else
            {
#if YYDEBUG
                if (yydebug)
                    fprintf(stderr, "%s[%d]: error recovery discarding state %d\n",
                                    YYDEBUGSTR, yydepth, *yystack.s_mark);
#endif
                if (yystack.s_mark <= yystack.s_base) goto yyabort;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                /* the current TOS position is the error start position */
                yyerror_loc_range[0] = *yystack.p_mark;
#endif
#if defined(YYDESTRUCT_CALL)
#if YYBTYACC
                if (!yytrial)
#endif /* YYBTYACC */
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                    YYDESTRUCT_CALL("error: discarding state",
                                    yystos[*yystack.s_mark], yystack.l_mark, yystack.p_mark);
#else
                    YYDESTRUCT_CALL("error: discarding state",
                                    yystos[*yystack.s_mark], yystack.l_mark);
#endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */
#endif /* defined(YYDESTRUCT_CALL) */
                --yystack.s_mark;
                --yystack.l_mark;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                --yystack.p_mark;
#endif
            }
        }
    }
    else
    {
        if (yychar == YYEOF) goto yyabort;
#if YYDEBUG
        if (yydebug)
        {
            if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN];
            fprintf(stderr, "%s[%d]: state %d, error recovery discarding token %d (%s)\n",
                            YYDEBUGSTR, yydepth, yystate, yychar, yys);
        }
#endif
#if defined(YYDESTRUCT_CALL)
#if YYBTYACC
        if (!yytrial)
#endif /* YYBTYACC */
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
            YYDESTRUCT_CALL("error: discarding token", yychar, &yylval, &yylloc);
#else
            YYDESTRUCT_CALL("error: discarding token", yychar, &yylval);
#endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */
#endif /* defined(YYDESTRUCT_CALL) */
        yychar = YYEMPTY;
        goto yyloop;
    }

yyreduce:
    yym = yylen[yyn];
#if YYDEBUG
    if (yydebug)
    {
        fprintf(stderr, "%s[%d]: state %d, reducing by rule %d (%s)",
                        YYDEBUGSTR, yydepth, yystate, yyn, yyrule[yyn]);
#ifdef YYSTYPE_TOSTRING
#if YYBTYACC
        if (!yytrial)
#endif /* YYBTYACC */
            if (yym > 0)
            {
                int i;
                fputc('<', stderr);
                for (i = yym; i > 0; i--)
                {
                    if (i != yym) fputs(", ", stderr);
                    fputs(YYSTYPE_TOSTRING(yystos[yystack.s_mark[1-i]],
                                           yystack.l_mark[1-i]), stderr);
                }
                fputc('>', stderr);
            }
#endif
        fputc('\n', stderr);
    }
#endif
    if (yym > 0)
        yyval = yystack.l_mark[1-yym];
    else
        memset(&yyval, 0, sizeof yyval);
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)

    /* Perform position reduction */
    memset(&yyloc, 0, sizeof(yyloc));
#if YYBTYACC
    if (!yytrial)
#endif /* YYBTYACC */
    {
        YYLLOC_DEFAULT(yyloc, &yystack.p_mark[1-yym], yym);
        /* just in case YYERROR is invoked within the action, save
           the start of the rhs as the error start position */
        yyerror_loc_range[0] = yystack.p_mark[1-yym];
    }
#endif

    switch (yyn)
    {
case 3:
#line 35 "quote_calc3.y"
	{  yyerrok ; }
break;
case 4:
#line 39 "quote_calc3.y"
	{  printf("%d\n",yystack.l_mark[0]);}
break;
case 5:
#line 41 "quote_calc3.y"
	{  regs[yystack.l_mark[-2]] = yystack.l_mark[0]; }
break;
case 6:
#line 45 "quote_calc3.y"
	{  yyval = yystack.l_mark[-1]; }
break;
case 7:
#line 47 "quote_calc3.y"
	{  yyval = yystack.l_mark[-2] + yystack.l_mark[0]; }
break;
case 8:
#line 49 "quote_calc3.y"
	{  yyval = yystack.l_mark[-2] - yystack.l_mark[0]; }
break;
case 9:
#line 51 "quote_calc3.y"
	{  yyval = yystack.l_mark[-2] * yystack.l_mark[0]; }
break;
case 10:
#line 53 "quote_calc3.y"
	{  yyval = yystack.l_mark[-2] / yystack.l_mark[0]; }
break;
case 11:
#line 55 "quote_calc3.y"
	{  yyval = yystack.l_mark[-2] % yystack.l_mark[0]; }
break;
case 12:
#line 57 "quote_calc3.y"
	{  yyval = yystack.l_mark[-2] & yystack.l_mark[0]; }
break;
case 13:
#line 59 "quote_calc3.y"
	{  yyval = yystack.l_mark[-2] | yystack.l_mark[0]; }
break;
case 14:
#line 61 "quote_calc3.y"
	{  yyval = - yystack.l_mark[0]; }
break;
case 15:
#line 63 "quote_calc3.y"
	{  yyval = regs[yystack.l_mark[0]]; }
break;
case 17:
#line 68 "quote_calc3.y"
	{  yyval = yystack.l_mark[0]; base = (yystack.l_mark[0]==0) ? 8 : 10; }
break;
case 18:
#line 70 "quote_calc3.y"
	{  yyval = base * yystack.l_mark[-1] + yystack.l_mark[0]; }
break;
#line 1254 "quote_calc3.tab.c"
    default:
        break;
    }
    yystack.s_mark -= yym;
    yystate = *yystack.s_mark;
    yystack.l_mark -= yym;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
    yystack.p_mark -= yym;
#endif
    yym = yylhs[yyn];
    if (yystate == 0 && yym == 0)
    {
#if YYDEBUG
        if (yydebug)
        {
            fprintf(stderr, "%s[%d]: after reduction, ", YYDEBUGSTR, yydepth);
#ifdef YYSTYPE_TOSTRING
#if YYBTYACC
            if (!yytrial)
#endif /* YYBTYACC */
                fprintf(stderr, "result is <%s>, ", YYSTYPE_TOSTRING(yystos[YYFINAL], yyval));
#endif
            fprintf(stderr, "shifting from state 0 to final state %d\n", YYFINAL);
        }
#endif
        yystate = YYFINAL;
        *++yystack.s_mark = YYFINAL;
        *++yystack.l_mark = yyval;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
        *++yystack.p_mark = yyloc;
#endif
        if (yychar < 0)
        {
#if YYBTYACC
            do {
            if (yylvp < yylve)
            {
                /* we're currently re-reading tokens */
                yylval = *yylvp++;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                yylloc = *yylpp++;
#endif
                yychar = *yylexp++;
                break;
            }
            if (yyps->save)
            {
                /* in trial mode; save scanner results for future parse attempts */
                if (yylvp == yylvlim)
                {   /* Enlarge lexical value queue */
                    size_t p = (size_t) (yylvp - yylvals);
                    size_t s = (size_t) (yylvlim - yylvals);

                    s += YYLVQUEUEGROWTH;
                    if ((yylexemes = realloc(yylexemes, s * sizeof(YYINT))) == NULL)
                        goto yyenomem;
                    if ((yylvals   = realloc(yylvals, s * sizeof(YYSTYPE))) == NULL)
                        goto yyenomem;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                    if ((yylpsns   = realloc(yylpsns, s * sizeof(YYLTYPE))) == NULL)
                        goto yyenomem;
#endif
                    yylvp   = yylve = yylvals + p;
                    yylvlim = yylvals + s;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                    yylpp   = yylpe = yylpsns + p;
                    yylplim = yylpsns + s;
#endif
                    yylexp  = yylexemes + p;
                }
                *yylexp = (YYINT) YYLEX;
                *yylvp++ = yylval;
                yylve++;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
                *yylpp++ = yylloc;
                yylpe++;
#endif
                yychar = *yylexp++;
                break;
            }
            /* normal operation, no conflict encountered */
#endif /* YYBTYACC */
            yychar = YYLEX;
#if YYBTYACC
            } while (0);
#endif /* YYBTYACC */
            if (yychar < 0) yychar = YYEOF;
#if YYDEBUG
            if (yydebug)
            {
                if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN];
                fprintf(stderr, "%s[%d]: state %d, reading token %d (%s)\n",
                                YYDEBUGSTR, yydepth, YYFINAL, yychar, yys);
            }
#endif
        }
        if (yychar == YYEOF) goto yyaccept;
        goto yyloop;
    }
    if (((yyn = yygindex[yym]) != 0) && (yyn += yystate) >= 0 &&
            yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yystate)
        yystate = yytable[yyn];
    else
        yystate = yydgoto[yym];
#if YYDEBUG
    if (yydebug)
    {
        fprintf(stderr, "%s[%d]: after reduction, ", YYDEBUGSTR, yydepth);
#ifdef YYSTYPE_TOSTRING
#if YYBTYACC
        if (!yytrial)
#endif /* YYBTYACC */
            fprintf(stderr, "result is <%s>, ", YYSTYPE_TOSTRING(yystos[yystate], yyval));
#endif
        fprintf(stderr, "shifting from state %d to state %d\n", *yystack.s_mark, yystate);
    }
#endif
    if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow;
    *++yystack.s_mark = (YYINT) yystate;
    *++yystack.l_mark = yyval;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
    *++yystack.p_mark = yyloc;
#endif
    goto yyloop;
#if YYBTYACC

    /* Reduction declares that this path is valid. Set yypath and do a full parse */
yyvalid:
    if (yypath) YYABORT;
    while (yyps->save)
    {
        YYParseState *save = yyps->save;
        yyps->save = save->save;
        save->save = yypath;
        yypath = save;
    }
#if YYDEBUG
    if (yydebug)
        fprintf(stderr, "%s[%d]: state %d, CONFLICT trial successful, backtracking to state %d, %d tokens\n",
                        YYDEBUGSTR, yydepth, yystate, yypath->state, (int)(yylvp - yylvals - yypath->lexeme));
#endif
    if (yyerrctx)
    {
        yyFreeState(yyerrctx);
        yyerrctx = NULL;
    }
    yylvp          = yylvals + yypath->lexeme;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
    yylpp          = yylpsns + yypath->lexeme;
#endif
    yylexp         = yylexemes + yypath->lexeme;
    yychar         = YYEMPTY;
    yystack.s_mark = yystack.s_base + (yypath->yystack.s_mark - yypath->yystack.s_base);
    memcpy (yystack.s_base, yypath->yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT));
    yystack.l_mark = yystack.l_base + (yypath->yystack.l_mark - yypath->yystack.l_base);
    memcpy (yystack.l_base, yypath->yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE));
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
    yystack.p_mark = yystack.p_base + (yypath->yystack.p_mark - yypath->yystack.p_base);
    memcpy (yystack.p_base, yypath->yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE));
#endif
    yystate        = yypath->state;
    goto yyloop;
#endif /* YYBTYACC */

yyoverflow:
    YYERROR_CALL("yacc stack overflow");
#if YYBTYACC
    goto yyabort_nomem;
yyenomem:
    YYERROR_CALL("memory exhausted");
yyabort_nomem:
#endif /* YYBTYACC */
    yyresult = 2;
    goto yyreturn;

yyabort:
    yyresult = 1;
    goto yyreturn;

yyaccept:
#if YYBTYACC
    if (yyps->save) goto yyvalid;
#endif /* YYBTYACC */
    yyresult = 0;

yyreturn:
#if defined(YYDESTRUCT_CALL)
    if (yychar != YYEOF && yychar != YYEMPTY)
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
        YYDESTRUCT_CALL("cleanup: discarding token", yychar, &yylval, &yylloc);
#else
        YYDESTRUCT_CALL("cleanup: discarding token", yychar, &yylval);
#endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */

    {
        YYSTYPE *pv;
#if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED)
        YYLTYPE *pp;

        for (pv = yystack.l_base, pp = yystack.p_base; pv <= yystack.l_mark; ++pv, ++pp)
             YYDESTRUCT_CALL("cleanup: discarding state",
                             yystos[*(yystack.s_base + (pv - yystack.l_base))], pv, pp);
#else
        for (pv = yystack.l_base; pv <= yystack.l_mark; ++pv)
             YYDESTRUCT_CALL("cleanup: discarding state",
                             yystos[*(yystack.s_base + (pv - yystack.l_base))], pv);
#endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */
    }
#endif /* defined(YYDESTRUCT_CALL) */

#if YYBTYACC
    if (yyerrctx)
    {
        yyFreeState(yyerrctx);
        yyerrctx = NULL;
    }
    while (yyps)
    {
        YYParseState *save = yyps;
        yyps = save->save;
        save->save = NULL;
        yyFreeState(save);
    }
    while (yypath)
    {
        YYParseState *save = yypath;
        yypath = save->save;
        save->save = NULL;
        yyFreeState(save);
    }
#endif /* YYBTYACC */
    yyfreestack(&yystack);
    return (yyresult);
}
Example #29
0
#ifdef MCP_DEBUG
	fprintf(stderr, __FILE__ ": (samptomono)\n");
	fprintf(stderr, __FILE__ ": s->ptr=%p\n", s->ptr);
#endif
	s->type&=~mcpSampStereo;
	s->type|=mcpSampRedStereo;
	if (s->type&mcpSampFloat)
		for (i=0; i<l; i++)
			((float *)s->ptr)[i]=(((float *)s->ptr)[2*i]+((float *)s->ptr)[2*i+1])/2;
	else if (s->type&mcpSamp16Bit)
		for (i=0; i<l; i++)
			((int16_t *)s->ptr)[i]=(((int16_t *)s->ptr)[2*i]+((int16_t *)s->ptr)[2*i+1])>>1;
	else
		for (i=0; i<l; i++)
			((int8_t *)s->ptr)[i]=(((int8_t *)s->ptr)[2*i]+((int8_t *)s->ptr)[2*i+1])>>1;
	newptr=realloc(s->ptr,l<<sampsizefac(s->type));
#ifdef MCP_DEBUG
	fprintf(stderr, __FILE__ ": realloced buffer=%p\n", newptr);
#endif
	if (!newptr)
	{
		fprintf(stderr, __FILE__ " samptomono(): warning, realloc() failed\n"); /* safe to continue when buffer-shrink failes */
	} else
		s->ptr=newptr;
}


static int samptofloat(struct sampleinfo *s)
{
	int i;
	int l=s->length<<sampsizefac(s->type&mcpSampStereo);
Example #30
0
int main(int argc, char* argv[])
{
	if(argc < 4){
		usage();
		return -1;
	}

	struct sockaddr_in clientAdd;
	struct sockaddr_in serverAdd;
	struct hostent* h_s;

	char requete[1000];
	char reponse[65536];
	char* message;

	int lSocket, result;
	int byteCount;
	
	/*Socket du client*/
	lSocket = socket(AF_INET, SOCK_STREAM, 0);
	if(lSocket == -1){
		perror("Erreur lors de la création de la socket !\n");
		return 0;
	}

	clientAdd.sin_family = AF_INET;
	clientAdd.sin_port = htons(9000);
	clientAdd.sin_addr.s_addr = INADDR_ANY;
	memset(clientAdd.sin_zero, 0, 8);

	result = bind(lSocket, (struct sockaddr*) &clientAdd, sizeof(clientAdd));
	if(result == -1){
		perror("Erreur lors du bind!\n");
		return -1;
	}
		

	/*Adresse du serverAdd distant à joindre*/
	h_s = gethostbyname(argv[1]);
	if(h_s == NULL){
		perror("Erreur avec le résultat de gethostbyname()\n");
		return -1;
	}
	
	serverAdd.sin_family = AF_INET;
	memcpy(&serverAdd.sin_addr.s_addr, h_s->h_addr, 4);
	serverAdd.sin_port = htons(atoi(argv[2]));

	if(connect(lSocket, (struct sockaddr*) &serverAdd, sizeof(serverAdd)) == -1){
		perror("Echec lors de la connexion !");
		return -1;
	}

	sprintf(requete,"%s%s%s%s%s%s%s","GET /",argv[3]," HTTP/1.1\nHost: ",argv[1],":",argv[2],"\nConnection: Keep-Alive\n\n");	
	
	send(lSocket, (void*) requete, sizeof(requete),0);
	message = (char*) malloc(sizeof(char)*512);	
	while(byteCount = recv(lSocket, (void*) reponse, sizeof(reponse),0)){
		if(strlen(reponse) + strlen(message) > sizeof(message)){
			message = realloc(message, (strlen(reponse) + strlen(message))*512*sizeof(char));		
		}		
		sprintf(message,"%s%s",message,reponse);	
	}
	printf("Reponse du serveur : \n%s\n",message);
	close(lSocket);
	return 0;
}