예제 #1
0
파일: jevents.c 프로젝트: nikai3d/pmu-tools
/**
 * json_events - Read JSON event file from disk and call event callback.
 * @fn: File name to read or NULL for default.
 * @func: Callback to call for each event
 * @data: Abstract pointer to pass to func.
 *
 * The callback gets the data pointer, the event name, the event
 * in perf format and a description passed.
 *
 * Call func with each event in the json file
 * Return: -1 on failure, otherwise 0.
 */
int json_events(const char *fn,
                int (*func)(void *data, char *name, char *event, char *desc),
                void *data)
{
    int err = -EIO;
    size_t size;
    jsmntok_t *tokens, *tok;
    int i, j, len;
    char *map;

    if (!fn)
        fn = json_default_name();
    tokens = parse_json(fn, &map, &size, &len);
    if (!tokens)
        return -EIO;
    EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
    tok = tokens + 1;
    for (i = 0; i < tokens->size; i++) {
        char *event = NULL, *desc = NULL, *name = NULL;
        struct msrmap *msr = NULL;
        jsmntok_t *msrval = NULL;
        jsmntok_t *precise = NULL;
        jsmntok_t *obj = tok++;

        EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
        for (j = 0; j < obj->size; j += 2) {
            jsmntok_t *field, *val;
            int nz;

            field = tok + j;
            EXPECT(field->type == JSMN_STRING, tok + j,
                   "Expected field name");
            val = tok + j + 1;
            EXPECT(val->type == JSMN_STRING, tok + j + 1,
                   "Expected string value");

            nz = !json_streq(map, val, "0");
            if (match_field(map, field, nz, &event, val)) {
                /* ok */
            } else if (json_streq(map, field, "EventName")) {
                addfield(map, &name, "", "", val);
            } else if (json_streq(map, field, "BriefDescription")) {
                addfield(map, &desc, "", "", val);
                fixdesc(desc);
            } else if (json_streq(map, field, "PEBS") && nz && desc &&
                       !strstr(desc, "(Precise Event)")) {
                precise = val;
            } else if (json_streq(map, field, "MSRIndex") && nz) {
                msr = lookup_msr(map, val);
            } else if (json_streq(map, field, "MSRValue")) {
                msrval = val;
            } else if (json_streq(map, field, "Errata") &&
                       !json_streq(map, val, "null")) {
                addfield(map, &desc, ". ",
                         " Spec update: ", val);
            } else if (json_streq(map, field, "Data_LA") && nz) {
                addfield(map, &desc, ". ",
                         " Supports address when precise",
                         NULL);
            }
            /* ignore unknown fields */
        }
        if (precise) {
            if (json_streq(map, precise, "2"))
                addfield(map, &desc, " ", "(Must be precise)",
                         NULL);
            else
                addfield(map, &desc, " ",
                         "(Precise event)", NULL);
        }
        if (msr != NULL)
            addfield(map, &event, ",", msr->pname, msrval);
        err = -EIO;
        if (name && event) {
            fixname(name);
            err = func(data, name, event, desc);
        }
        free(event);
        free(desc);
        free(name);
        if (err)
            break;
        tok += j;
    }
    EXPECT(tok - tokens == len, tok, "unexpected objects at end");
    err = 0;
out_free:
    free_json(map, size, tokens);
    return err;
}
예제 #2
0
파일: test_tcp_oos.c 프로젝트: 0xc0170/mbed
/* this test uses 4 packets:
 * - data (len=TCP_MSS)
 * - FIN
 * - data after FIN (len=1) (invalid)
 * - 2nd FIN (invalid)
 *
 * the parameter 'delay_packet' is a bitmask that choses which on these packets is ooseq
 */
static void test_tcp_recv_ooseq_double_FINs(int delay_packet)
{
  int i, k;
  struct test_tcp_counters counters;
  struct tcp_pcb* pcb;
  struct pbuf *p_normal_fin, *p_data_after_fin, *p, *p_2nd_fin_ooseq;
  struct netif netif;
  u32_t exp_rx_calls = 0, exp_rx_bytes = 0, exp_close_calls = 0, exp_oos_pbufs = 0, exp_oos_tcplen = 0;
  int first_dropped = 0xff;

  for(i = 0; i < (int)sizeof(data_full_wnd); i++) {
    data_full_wnd[i] = (char)i;
  }

  /* initialize local vars */
  test_tcp_init_netif(&netif, NULL, &test_local_ip, &test_netmask);
  /* initialize counter struct */
  memset(&counters, 0, sizeof(counters));
  counters.expected_data_len = TCP_WND;
  counters.expected_data = data_full_wnd;

  /* create and initialize the pcb */
  pcb = test_tcp_new_counters_pcb(&counters);
  EXPECT_RET(pcb != NULL);
  tcp_set_state(pcb, ESTABLISHED, &test_local_ip, &test_remote_ip, TEST_LOCAL_PORT, TEST_REMOTE_PORT);
  pcb->rcv_nxt = 0x8000;

  /* create segments */
  p = tcp_create_rx_segment(pcb, &data_full_wnd[0], TCP_MSS, 0, 0, TCP_ACK);
  p_normal_fin = tcp_create_rx_segment(pcb, NULL, 0, TCP_MSS, 0, TCP_ACK|TCP_FIN);
  k = 1;
  p_data_after_fin = tcp_create_rx_segment(pcb, &data_full_wnd[TCP_MSS+1], k, TCP_MSS+1, 0, TCP_ACK);
  p_2nd_fin_ooseq = tcp_create_rx_segment(pcb, NULL, 0, TCP_MSS+1+k, 0, TCP_ACK|TCP_FIN);

  if(delay_packet & 1) {
    /* drop normal data */
    first_dropped = 1;
  } else {
    /* send normal data */
    test_tcp_input(p, &netif);
    exp_rx_calls++;
    exp_rx_bytes += TCP_MSS;
  }
  /* check if counters are as expected */
  check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen);

  if(delay_packet & 2) {
    /* drop FIN */
    if(first_dropped > 2) {
      first_dropped = 2;
    }
  } else {
    /* send FIN */
    test_tcp_input(p_normal_fin, &netif);
    if (first_dropped < 2) {
      /* already dropped packets, this one is ooseq */
      exp_oos_pbufs++;
      exp_oos_tcplen++;
    } else {
      /* inseq */
      exp_close_calls++;
    }
  }
  /* check if counters are as expected */
  check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen);

  if(delay_packet & 4) {
    /* drop data-after-FIN */
    if(first_dropped > 3) {
      first_dropped = 3;
    }
  } else {
    /* send data-after-FIN */
    test_tcp_input(p_data_after_fin, &netif);
    if (first_dropped < 3) {
      /* already dropped packets, this one is ooseq */
      if (delay_packet & 2) {
        /* correct FIN was ooseq */
        exp_oos_pbufs++;
        exp_oos_tcplen += k;
      }
    } else {
      /* inseq: no change */
    }
  }
  /* check if counters are as expected */
  check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen);

  if(delay_packet & 8) {
    /* drop 2nd-FIN */
    if(first_dropped > 4) {
      first_dropped = 4;
    }
  } else {
    /* send 2nd-FIN */
    test_tcp_input(p_2nd_fin_ooseq, &netif);
    if (first_dropped < 3) {
      /* already dropped packets, this one is ooseq */
      if (delay_packet & 2) {
        /* correct FIN was ooseq */
        exp_oos_pbufs++;
        exp_oos_tcplen++;
      }
    } else {
      /* inseq: no change */
    }
  }
  /* check if counters are as expected */
  check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen);

  if(delay_packet & 1) {
    /* dropped normal data before */
    test_tcp_input(p, &netif);
    exp_rx_calls++;
    exp_rx_bytes += TCP_MSS;
    if((delay_packet & 2) == 0) {
      /* normal FIN was NOT delayed */
      exp_close_calls++;
      exp_oos_pbufs = exp_oos_tcplen = 0;
    }
  }
  /* check if counters are as expected */
  check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen);

  if(delay_packet & 2) {
    /* dropped normal FIN before */
    test_tcp_input(p_normal_fin, &netif);
    exp_close_calls++;
    exp_oos_pbufs = exp_oos_tcplen = 0;
  }
  /* check if counters are as expected */
  check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen);

  if(delay_packet & 4) {
    /* dropped data-after-FIN before */
    test_tcp_input(p_data_after_fin, &netif);
  }
  /* check if counters are as expected */
  check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen);

  if(delay_packet & 8) {
    /* dropped 2nd-FIN before */
    test_tcp_input(p_2nd_fin_ooseq, &netif);
  }
  /* check if counters are as expected */
  check_rx_counters(pcb, &counters, exp_close_calls, exp_rx_calls, exp_rx_bytes, 0, exp_oos_pbufs, exp_oos_tcplen);

  /* check that ooseq data has been dumped */
  EXPECT(pcb->ooseq == NULL);

  /* make sure the pcb is freed */
  EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1);
  tcp_abort(pcb);
  EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0);
}
예제 #3
0
static int TestAdvance( int mode, PaDeviceIndex deviceID, double sampleRate,
                        int numChannels, PaSampleFormat format )
{
    PaStreamParameters inputParameters, outputParameters, *ipp, *opp;
    PaStream *stream = NULL;
    PaError result = paNoError;
    PaQaData myData;
    #define FRAMES_PER_BUFFER  (64)
    
    /* Setup data for synthesis thread. */
    myData.framesLeft = (unsigned long) (sampleRate * 100); /* 100 seconds */
    myData.numChannels = numChannels;
    myData.mode = mode;
    myData.format = format;
    switch( format )
    {
    case paFloat32:
    case paInt32:
    case paInt24:
        myData.bytesPerSample = 4;
        break;
/*  case paPackedInt24:
        myData.bytesPerSample = 3;
        break; */
    default:
        myData.bytesPerSample = 2;
        break;
    }

    if( mode == MODE_INPUT )
    {
        inputParameters.device       = deviceID;
        inputParameters.channelCount = numChannels;
        inputParameters.sampleFormat = format;
        inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
        inputParameters.hostApiSpecificStreamInfo = NULL;
        ipp = &inputParameters;
    }
    else
        ipp = NULL;
    if( mode == MODE_OUTPUT )           /* Pa_GetDeviceInfo(paNoDevice) COREDUMPS!!! */
    {
        outputParameters.device       = deviceID;
        outputParameters.channelCount = numChannels;
        outputParameters.sampleFormat = format;
        outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
        outputParameters.hostApiSpecificStreamInfo = NULL;
        opp = &outputParameters;
    }
    else
        opp = NULL;

    if(paFormatIsSupported == Pa_IsFormatSupported( ipp, opp, sampleRate ))
    {
        printf("------ TestAdvance: %s, device = %d, rate = %g, numChannels = %d, format = %lu -------\n",
                ( mode == MODE_INPUT ) ? "INPUT" : "OUTPUT",
                deviceID, sampleRate, numChannels, (unsigned long)format);
        EXPECT( ((result = Pa_OpenStream( &stream,
                                          ipp,
                                          opp,
                                          sampleRate,
                                          FRAMES_PER_BUFFER,
                                          paClipOff,  /* we won't output out of range samples so don't bother clipping them */
                                          QaCallback,
                                          &myData ) ) == 0) );
        if( stream )
        {
            PaTime oldStamp, newStamp;
            unsigned long oldFrames;
            int minDelay = ( mode == MODE_INPUT ) ? 1000 : 400;
            /* Was:
            int minNumBuffers = Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate );
            int msec = (int) ((minNumBuffers * 3 * 1000.0 * FRAMES_PER_BUFFER) / sampleRate);
            */
            int msec = (int)( 3.0 *
                       (( mode == MODE_INPUT ) ? inputParameters.suggestedLatency : outputParameters.suggestedLatency ));
            if( msec < minDelay ) msec = minDelay;
            printf("msec = %d\n", msec);  /**/
            EXPECT( ((result=Pa_StartStream( stream )) == 0) );
            /* Check to make sure PortAudio is advancing timeStamp. */
            oldStamp = Pa_GetStreamTime(stream);
            Pa_Sleep(msec);
            newStamp = Pa_GetStreamTime(stream);
            printf("oldStamp = %g,newStamp = %g\n", oldStamp, newStamp ); /**/
            EXPECT( (oldStamp < newStamp) );
            /* Check to make sure callback is decrementing framesLeft. */
            oldFrames = myData.framesLeft;
            Pa_Sleep(msec);
            printf("oldFrames = %lu, myData.framesLeft = %lu\n", oldFrames,  myData.framesLeft ); /**/
            EXPECT( (oldFrames > myData.framesLeft) );
            EXPECT( ((result=Pa_CloseStream( stream )) == 0) );
            stream = NULL;
        }
    }
error:
    if( stream != NULL ) Pa_CloseStream( stream );
    return result;
}
예제 #4
0
void test_queue (void){
  struct queue queue;
  struct foo buf[5];

  init_queue(&queue, &buf, sizeof(struct foo), 5);
  ((struct foo *) enqueue(&queue))->a = 1;
  ((struct foo *) enqueue(&queue))->a = 2;
  ((struct foo *) enqueue(&queue))->a = 3;
  ((struct foo *) enqueue(&queue))->a = 4;
  ((struct foo *) enqueue(&queue))->a = 5;
  EXPECT(!enqueue(&queue));
  EXPECT(!enqueue(&queue));
  EXPECT(((struct foo *) dequeue(&queue))->a == 1);
  EXPECT(((struct foo *) dequeue(&queue))->a == 2);
  ((struct foo *) enqueue(&queue))->a = 6;
  ((struct foo *) enqueue(&queue))->a = 7;
  EXPECT(((struct foo *) dequeue(&queue))->a == 3);
  EXPECT(((struct foo *) dequeue(&queue))->a == 4);
  EXPECT(((struct foo *) dequeue(&queue))->a == 5);
  EXPECT(((struct foo *) dequeue(&queue))->a == 6);
  EXPECT(((struct foo *) dequeue(&queue))->a == 7);
  EXPECT(!dequeue(&queue));
  EXPECT(!dequeue(&queue));
}
예제 #5
0
파일: test_tcp_oos.c 프로젝트: 0xc0170/mbed
END_TEST

/** similar to above test, except seqno starts near the max rxwin */
START_TEST(test_tcp_recv_ooseq_overrun_rxwin_edge)
{
#if !TCP_OOSEQ_MAX_BYTES && !TCP_OOSEQ_MAX_PBUFS
  int i, k;
  struct test_tcp_counters counters;
  struct tcp_pcb* pcb;
  struct pbuf *pinseq, *p_ovr;
  struct netif netif;
  int datalen = 0;
  int datalen2;

  for(i = 0; i < (int)sizeof(data_full_wnd); i++) {
    data_full_wnd[i] = (char)i;
  }

  /* initialize local vars */
  test_tcp_init_netif(&netif, NULL, &test_local_ip, &test_netmask);
  /* initialize counter struct */
  memset(&counters, 0, sizeof(counters));
  counters.expected_data_len = TCP_WND;
  counters.expected_data = data_full_wnd;

  /* create and initialize the pcb */
  pcb = test_tcp_new_counters_pcb(&counters);
  EXPECT_RET(pcb != NULL);
  tcp_set_state(pcb, ESTABLISHED, &test_local_ip, &test_remote_ip, TEST_LOCAL_PORT, TEST_REMOTE_PORT);
  pcb->rcv_nxt = 0xffffffff - (TCP_WND / 2);

  /* create segments */
  /* pinseq is sent as last segment! */
  pinseq = tcp_create_rx_segment(pcb, &data_full_wnd[0],  TCP_MSS, 0, 0, TCP_ACK);

  for(i = TCP_MSS, k = 0; i < TCP_WND; i += TCP_MSS, k++) {
    int count, expected_datalen;
    struct pbuf *p = tcp_create_rx_segment(pcb, &data_full_wnd[TCP_MSS*(k+1)],
                                           TCP_MSS, TCP_MSS*(k+1), 0, TCP_ACK);
    EXPECT_RET(p != NULL);
    /* pass the segment to tcp_input */
    test_tcp_input(p, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 0);
    EXPECT(counters.recved_bytes == 0);
    EXPECT(counters.err_calls == 0);
    /* check ooseq queue */
    count = tcp_oos_count(pcb);
    EXPECT_OOSEQ(count == k+1);
    datalen = tcp_oos_tcplen(pcb);
    if (i + TCP_MSS < TCP_WND) {
      expected_datalen = (k+1)*TCP_MSS;
    } else {
      expected_datalen = TCP_WND - TCP_MSS;
    }
    if (datalen != expected_datalen) {
      EXPECT_OOSEQ(datalen == expected_datalen);
    }
  }

  /* pass in one more segment, cleary overrunning the rxwin */
  p_ovr = tcp_create_rx_segment(pcb, &data_full_wnd[TCP_MSS*(k+1)], TCP_MSS, TCP_MSS*(k+1), 0, TCP_ACK);
  EXPECT_RET(p_ovr != NULL);
  /* pass the segment to tcp_input */
  test_tcp_input(p_ovr, &netif);
  /* check if counters are as expected */
  EXPECT(counters.close_calls == 0);
  EXPECT(counters.recv_calls == 0);
  EXPECT(counters.recved_bytes == 0);
  EXPECT(counters.err_calls == 0);
  /* check ooseq queue */
  EXPECT_OOSEQ(tcp_oos_count(pcb) == k);
  datalen2 = tcp_oos_tcplen(pcb);
  EXPECT_OOSEQ(datalen == datalen2);

  /* now pass inseq */
  test_tcp_input(pinseq, &netif);
  EXPECT(pcb->ooseq == NULL);

  /* make sure the pcb is freed */
  EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1);
  tcp_abort(pcb);
  EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0);
#endif /* !TCP_OOSEQ_MAX_BYTES && !TCP_OOSEQ_MAX_PBUFS */
  LWIP_UNUSED_ARG(_i);
}
예제 #6
0
파일: string.c 프로젝트: stoyannk/dynamorio
void
unit_test_string(void)
{
    static const char test_path[] = "/path/to/file";
    const char *ret;
    char buf[MAXIMUM_PATH];
    unsigned long num;

    print_file(STDERR, "testing string\n");

    /* strchr */
    ret = strchr(identity(test_path), '/');
    EXPECT(ret == test_path, true);
    ret = strchr(identity(test_path), '\0');
    EXPECT(ret != NULL, true);
    EXPECT(*ret, '\0');

    /* strrchr */
    ret = strrchr(identity(test_path), '/');
    EXPECT(strcmp(ret, "/file"), 0);
    ret = strrchr(identity(test_path), '\0');
    EXPECT(ret != NULL, true);
    EXPECT(*ret, '\0');

    /* strncpy, strncat */
    strncpy(buf, test_path, sizeof(buf));
    EXPECT(is_region_memset_to_char((byte *) buf + strlen(test_path),
                                    sizeof(buf) - strlen(test_path), '\0'),
           true);
    strncat(buf, "/foo_wont_copy", 4);
    EXPECT(strcmp(buf, "/path/to/file/foo"), 0);

    /* strtoul */
    num = strtoul(identity("-10"), NULL, 0);
    EXPECT((long)num, -10);  /* negative */
    num = strtoul(identity("0777"), NULL, 0);
    EXPECT(num, 0777);  /* octal */
    num = strtoul(identity("0xdeadBEEF"), NULL, 0);
    EXPECT(num, 0xdeadbeef);  /* hex */
    num = strtoul(identity("deadBEEF next"), (char **) &ret, 16);
    EXPECT(num, 0xdeadbeef);  /* non-0x prefixed hex */
    EXPECT(strcmp(ret, " next"), 0);  /* end */
    num = strtoul(identity("1001a"), NULL, 2);
    EXPECT(num, 9);  /* binary */
    num = strtoul(identity("1aZ"), NULL, 36);
    EXPECT(num, 1 * 36 * 36 + 10 * 36 + 35);  /* weird base */
    num = strtoul(identity("1aZ"), (char **) &ret, 37);
    EXPECT(num, ULONG_MAX);  /* invalid base */
    EXPECT(ret == NULL, true);

    /* memmove */
    strncpy(buf, test_path, sizeof(buf));
    memmove(buf + 4, buf, strlen(buf) + 1);
    strncpy(buf, "/foo", 4);
    EXPECT(strcmp(buf, "/foo/path/to/file"), 0);

    print_file(STDERR, "done testing string\n");
}
예제 #7
0
/* finalized when this finalizer is invoked.			*/
GC_API void GC_register_finalizer_inner(void * obj,
					GC_finalization_proc fn, void *cd,
					GC_finalization_proc *ofn, void **ocd,
					finalization_mark_proc mp)
{
    ptr_t base;
    struct finalizable_object * curr_fo, * prev_fo;
    size_t index;
    struct finalizable_object *new_fo;
    hdr *hhdr;
    DCL_LOCK_STATE;

#   ifdef THREADS
	LOCK();
#   endif
    if (log_fo_table_size == -1
        || GC_fo_entries > ((word)1 << log_fo_table_size)) {
    	GC_grow_table((struct hash_chain_entry ***)(&fo_head),
    		      &log_fo_table_size);
	if (GC_print_stats) {
	    GC_log_printf("Grew fo table to %u entries\n",
	    	          (1 << log_fo_table_size));
	}
    }
    /* in the THREADS case signals are disabled and we hold allocation	*/
    /* lock; otherwise neither is true.  Proceed carefully.		*/
    base = (ptr_t)obj;
    index = HASH2(base, log_fo_table_size);
    prev_fo = 0; curr_fo = fo_head[index];
    while (curr_fo != 0) {
        GC_ASSERT(GC_size(curr_fo) >= sizeof(struct finalizable_object));
        if (curr_fo -> fo_hidden_base == HIDE_POINTER(base)) {
            /* Interruption by a signal in the middle of this	*/
            /* should be safe.  The client may see only *ocd	*/
            /* updated, but we'll declare that to be his	*/
            /* problem.						*/
            if (ocd) *ocd = (void *) (curr_fo -> fo_client_data);
            if (ofn) *ofn = curr_fo -> fo_fn;
            /* Delete the structure for base. */
                if (prev_fo == 0) {
                  fo_head[index] = fo_next(curr_fo);
                } else {
                  fo_set_next(prev_fo, fo_next(curr_fo));
                }
            if (fn == 0) {
                GC_fo_entries--;
                  /* May not happen if we get a signal.  But a high	*/
                  /* estimate will only make the table larger than	*/
                  /* necessary.						*/
#		if !defined(THREADS) && !defined(DBG_HDRS_ALL)
                  GC_free((void *)curr_fo);
#		endif
            } else {
                curr_fo -> fo_fn = fn;
                curr_fo -> fo_client_data = (ptr_t)cd;
                curr_fo -> fo_mark_proc = mp;
		/* Reinsert it.  We deleted it first to maintain	*/
		/* consistency in the event of a signal.		*/
		if (prev_fo == 0) {
                  fo_head[index] = curr_fo;
                } else {
                  fo_set_next(prev_fo, curr_fo);
                }
            }
#	    ifdef THREADS
                UNLOCK();
#	    endif
            return;
        }
        prev_fo = curr_fo;
        curr_fo = fo_next(curr_fo);
    }
    if (ofn) *ofn = 0;
    if (ocd) *ocd = 0;
    if (fn == 0) {
#	ifdef THREADS
            UNLOCK();
#	endif
        return;
    }
    GET_HDR(base, hhdr);
    if (0 == hhdr) {
      /* We won't collect it, hence finalizer wouldn't be run. */
#     ifdef THREADS
          UNLOCK();
#     endif
      return;
    }
    new_fo = (struct finalizable_object *)
    	GC_INTERNAL_MALLOC(sizeof(struct finalizable_object),NORMAL);
    if (EXPECT(0 == new_fo, FALSE)) {
#     ifdef THREADS
	UNLOCK();
#     endif
      new_fo = (struct finalizable_object *)
	      GC_oom_fn(sizeof(struct finalizable_object));
      if (0 == new_fo) {
	GC_finalization_failures++;
	return;
      }
      /* It's not likely we'll make it here, but ... */
#     ifdef THREADS
	LOCK();
#     endif
    }
    GC_ASSERT(GC_size(new_fo) >= sizeof(struct finalizable_object));
    new_fo -> fo_hidden_base = (word)HIDE_POINTER(base);
    new_fo -> fo_fn = fn;
    new_fo -> fo_client_data = (ptr_t)cd;
    new_fo -> fo_object_size = hhdr -> hb_sz;
    new_fo -> fo_mark_proc = mp;
    fo_set_next(new_fo, fo_head[index]);
    GC_fo_entries++;
    fo_head[index] = new_fo;
#   ifdef THREADS
        UNLOCK();
#   endif
}
status_t Harness::testSeek(
        const char *componentName, const char *componentRole) {
    bool isEncoder =
        !strncmp(componentRole, "audio_encoder.", 14)
        || !strncmp(componentRole, "video_encoder.", 14);

    if (isEncoder) {
        // Not testing seek behaviour for encoders.

        printf("  * Not testing seek functionality for encoders.\n");
        return OK;
    }

    const char *mime = GetMimeFromComponentRole(componentRole);

    if (!mime) {
        LOGI("Cannot perform seek test with this componentRole (%s)",
             componentRole);

        return OK;
    }

    sp<MediaSource> source = CreateSourceForMime(mime);

    sp<MediaSource> seekSource = CreateSourceForMime(mime);
    if (source == NULL || seekSource == NULL) {
        return UNKNOWN_ERROR;
    }

    CHECK_EQ(seekSource->start(), OK);

    sp<MediaSource> codec = OMXCodec::Create(
            mOMX, source->getFormat(), false /* createEncoder */,
            source, componentName);

    CHECK(codec != NULL);

    CHECK_EQ(codec->start(), OK);

    int64_t durationUs;
    CHECK(source->getFormat()->findInt64(kKeyDuration, &durationUs));

    LOGI("stream duration is %lld us (%.2f secs)",
         durationUs, durationUs / 1E6);

    static const int32_t kNumIterations = 5000;

    // We are always going to seek beyond EOS in the first iteration (i == 0)
    // followed by a linear read for the second iteration (i == 1).
    // After that it's all random.
    for (int32_t i = 0; i < kNumIterations; ++i) {
        int64_t requestedSeekTimeUs;
        int64_t actualSeekTimeUs;
        MediaSource::ReadOptions options;

        double r = uniform_rand();

        if ((i == 1) || (i > 0 && r < 0.5)) {
            // 50% chance of just continuing to decode from last position.

            requestedSeekTimeUs = -1;

            LOGI("requesting linear read");
        } else {
            if (i == 0 || r < 0.55) {
                // 5% chance of seeking beyond end of stream.

                requestedSeekTimeUs = durationUs;

                LOGI("requesting seek beyond EOF");
            } else {
                requestedSeekTimeUs =
                    (int64_t)(uniform_rand() * durationUs);

                LOGI("requesting seek to %lld us (%.2f secs)",
                     requestedSeekTimeUs, requestedSeekTimeUs / 1E6);
            }

            MediaBuffer *buffer = NULL;
            options.setSeekTo(
                    requestedSeekTimeUs, MediaSource::ReadOptions::SEEK_NEXT_SYNC);

            if (seekSource->read(&buffer, &options) != OK) {
                CHECK_EQ(buffer, NULL);
                actualSeekTimeUs = -1;
            } else {
                CHECK(buffer != NULL);
                CHECK(buffer->meta_data()->findInt64(kKeyTime, &actualSeekTimeUs));
                CHECK(actualSeekTimeUs >= 0);

                buffer->release();
                buffer = NULL;
            }

            LOGI("nearest keyframe is at %lld us (%.2f secs)",
                 actualSeekTimeUs, actualSeekTimeUs / 1E6);
        }

        status_t err;
        MediaBuffer *buffer;
        for (;;) {
            err = codec->read(&buffer, &options);
            options.clearSeekTo();
            if (err == INFO_FORMAT_CHANGED) {
                CHECK_EQ(buffer, NULL);
                continue;
            }
            if (err == OK) {
                CHECK(buffer != NULL);
                if (buffer->range_length() == 0) {
                    buffer->release();
                    buffer = NULL;
                    continue;
                }
            } else {
                CHECK_EQ(buffer, NULL);
            }

            break;
        }

        if (requestedSeekTimeUs < 0) {
            // Linear read.
            if (err != OK) {
                CHECK_EQ(buffer, NULL);
            } else {
                CHECK(buffer != NULL);
                buffer->release();
                buffer = NULL;
            }
        } else if (actualSeekTimeUs < 0) {
            EXPECT(err != OK,
                   "We attempted to seek beyond EOS and expected "
                   "ERROR_END_OF_STREAM to be returned, but instead "
                   "we got a valid buffer.");
            EXPECT(err == ERROR_END_OF_STREAM,
                   "We attempted to seek beyond EOS and expected "
                   "ERROR_END_OF_STREAM to be returned, but instead "
                   "we found some other error.");
            CHECK_EQ(err, ERROR_END_OF_STREAM);
            CHECK_EQ(buffer, NULL);
        } else {
            EXPECT(err == OK,
                   "Expected a valid buffer to be returned from "
                   "OMXCodec::read.");
            CHECK(buffer != NULL);

            int64_t bufferTimeUs;
            CHECK(buffer->meta_data()->findInt64(kKeyTime, &bufferTimeUs));
            if (!CloseEnough(bufferTimeUs, actualSeekTimeUs)) {
                printf("\n  * Attempted seeking to %lld us (%.2f secs)",
                       requestedSeekTimeUs, requestedSeekTimeUs / 1E6);
                printf("\n  * Nearest keyframe is at %lld us (%.2f secs)",
                       actualSeekTimeUs, actualSeekTimeUs / 1E6);
                printf("\n  * Returned buffer was at %lld us (%.2f secs)\n\n",
                       bufferTimeUs, bufferTimeUs / 1E6);

                buffer->release();
                buffer = NULL;

                CHECK_EQ(codec->stop(), OK);

                return UNKNOWN_ERROR;
            }

            buffer->release();
            buffer = NULL;
        }
    }

    CHECK_EQ(codec->stop(), OK);

    return OK;
}
예제 #9
0
파일: http.c 프로젝트: vidarr/eldritchd
/*----------------------------------------------------------------------------*/
int http_readRequest(HttpRequest* request)
{
    /*
     * Request constitutes of
     * request-lineCRLF
     * Header1: *Value1CRLF
     * ...CRLF
     * CRLF
     * Body
     */
    enum {None, Cr1, Lf1, Cr2, Lf2} crLfReadingState;
    int numCrLf = 0;
    signed char c = 0;
    signed char c2 = 0;
    enum { BEFORE, READING, DONE }  readingState = BEFORE;
    /* Read method */
    while(DONE != readingState)
    {
        NEXT_CHAR(c);
        switch( toupper(c) )
        {
            case LF:
            case CR:
                if(BEFORE != readingState)
                {
                    LOG_CON(ERROR, socketFd, "Premature end of HTTP request\n");
                    return -1;
                }
                break;
            case 'G':
                request->type = GET;
                EXPECT('E', c);
                EXPECT('T', c);
                EXPECT(SPACE, c);
                readingState = DONE;
                LOG_CON(INFO, socketFd, "Got GET request");
                break;
            case 'H':
                request->type = HEAD;
                EXPECT('E', c);
                EXPECT('A', c);
                EXPECT('D', c);
                EXPECT(SPACE, c);
                readingState = DONE;
                LOG_CON(INFO, socketFd, "Got HEAD request");
                break;
            default:
                LOG_CON(ERROR, socketFd,
                        "Could not parse HTTP request - "
                        " Unsupported HTTP method?\n");
                return -1;
        };
    };
    if(SPACE != getToken(request->url, &request->urlMaxLength) )
    {
        LOG_CON(ERROR, socketFd, "Could not read URL for HTTP requst\n");
        return -1;
    }
    LOG_CON(INFO, socketFd, "Read URL");
    EXPECT('H', c);
    EXPECT('T', c);
    EXPECT('T', c);
    EXPECT('P', c);
    EXPECT('/', c);
    NEXT_CHAR(request->majVersion);
    EXPECT('.', c);
    NEXT_CHAR(request->minVersion);
    EXPECT(CR, c);
    EXPECT(LF, c);
    crLfReadingState = Lf1;
    /* Read until end of header */
    while(Lf2 != crLfReadingState)
    {
        NEXT_CHAR(c);
        if(CR == c)
        {
            if(Lf1 == crLfReadingState)
            {
                crLfReadingState = Cr2;
            }
            else
            {
                crLfReadingState = Cr1;
            }
        }
        else if(LF == c)
        {
            if(Cr1 == crLfReadingState)
            {
                crLfReadingState = Lf1;
            }
            else if(Cr2 == crLfReadingState)
            {
                crLfReadingState = Lf2;
            }
            else
            {
                crLfReadingState = None;
            }
        }
        else
        {
            crLfReadingState = None;
        }
    }
    /* Line should be terminated by CRLF, but LF might be missing */
    return 0;
}
예제 #10
0
static int
RPCNametoOutletList(struct pluginDevice* bt, const char * name
,		int outletlist[])
{
	char	NameMapping[128];
	int	sockno;
	char	sockname[32];
	int	maxfound = 0;



	/* Verify that we're in the top-level menu */
	SEND(bt->wrfd, "\r");

	/* Expect "RPC-x Menu" */
	EXPECT(bt->rdfd, RPC, 5);
	EXPECT(bt->rdfd, Menu, 5);


	/* OK.  Request sub-menu 1 (Outlet Control) */
	SEND(bt->wrfd, "1\r");

	/* Verify that we're in the sub-menu */

	/* Expect: "RPC-x>" */
	EXPECT(bt->rdfd, RPC, 5);
	EXPECT(bt->rdfd, GTSign, 5);

	/* The status command output contains mapping of hosts to outlets */
	SEND(bt->wrfd, "STATUS\r");

	/* Expect: "emperature:" so we can skip over it... */
 	EXPECT(bt->rdfd, bt->modelinfo->expect, 5);
 	EXPECT(bt->rdfd, CRNL, 5);

	/* Looks Good!  Parse the status output */

	do {
		char *	last;
		NameMapping[0] = EOS;
		SNARF(bt->rdfd, NameMapping, 5);

		if (!parse_socket_line(bt, NameMapping, &sockno, sockname)) {
			continue;
		}

		last = sockname+bt->modelinfo->socklen;
		*last = EOS;
		--last;

		/* Strip off trailing blanks */
		for(; last > sockname; --last) {
			if (*last == ' ') {
				*last = EOS;
			}else{
				break;
			}
		}
		if (strcasecmp(name, sockname) == 0) {
			outletlist[maxfound] = sockno;
			++maxfound;
		}
	} while (strlen(NameMapping) > 2  && maxfound < MAXOUTLET);

	/* Pop back out to the top level menu */
	SEND(bt->wrfd, "MENU\r");
	return(maxfound);
}
status_t Harness::testStateTransitions(
        const char *componentName, const char *componentRole) {
    if (strncmp(componentName, "OMX.", 4)) {
        // Non-OMX components, i.e. software decoders won't execute this
        // test.
        return OK;
    }

    sp<MemoryDealer> dealer = new MemoryDealer(16 * 1024 * 1024, "OMXHarness");
    IOMX::node_id node;

    status_t err =
        mOMX->allocateNode(componentName, this, &node);
    EXPECT_SUCCESS(err, "allocateNode");

    NodeReaper reaper(this, node);

    err = setRole(node, componentRole);
    EXPECT_SUCCESS(err, "setRole");

    // Initiate transition Loaded->Idle
    err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateIdle);
    EXPECT_SUCCESS(err, "sendCommand(go-to-Idle)");

    omx_message msg;
    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    // Make sure node doesn't just transition to idle before we are done
    // allocating all input and output buffers.
    EXPECT(err == TIMED_OUT,
            "Component must not transition from loaded to idle before "
            "all input and output buffers are allocated.");

    // Now allocate buffers.
    Vector<Buffer> inputBuffers;
    err = allocatePortBuffers(dealer, node, 0, &inputBuffers);
    EXPECT_SUCCESS(err, "allocatePortBuffers(input)");

    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    CHECK_EQ(err, TIMED_OUT);

    Vector<Buffer> outputBuffers;
    err = allocatePortBuffers(dealer, node, 1, &outputBuffers);
    EXPECT_SUCCESS(err, "allocatePortBuffers(output)");

    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    EXPECT(err == OK
            && msg.type == omx_message::EVENT
            && msg.u.event_data.event == OMX_EventCmdComplete
            && msg.u.event_data.data1 == OMX_CommandStateSet
            && msg.u.event_data.data2 == OMX_StateIdle,
           "Component did not properly transition to idle state "
           "after all input and output buffers were allocated.");

    // Initiate transition Idle->Executing
    err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateExecuting);
    EXPECT_SUCCESS(err, "sendCommand(go-to-Executing)");

    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    EXPECT(err == OK
            && msg.type == omx_message::EVENT
            && msg.u.event_data.event == OMX_EventCmdComplete
            && msg.u.event_data.data1 == OMX_CommandStateSet
            && msg.u.event_data.data2 == OMX_StateExecuting,
           "Component did not properly transition from idle to "
           "executing state.");

    for (size_t i = 0; i < outputBuffers.size(); ++i) {
        err = mOMX->fillBuffer(node, outputBuffers[i].mID);
        EXPECT_SUCCESS(err, "fillBuffer");

        outputBuffers.editItemAt(i).mFlags |= kBufferBusy;
    }

    err = mOMX->sendCommand(node, OMX_CommandFlush, 1);
    EXPECT_SUCCESS(err, "sendCommand(flush-output-port)");

    err = dequeueMessageForNodeIgnoringBuffers(
            node, &inputBuffers, &outputBuffers, &msg, DEFAULT_TIMEOUT);
    EXPECT(err == OK
            && msg.type == omx_message::EVENT
            && msg.u.event_data.event == OMX_EventCmdComplete
            && msg.u.event_data.data1 == OMX_CommandFlush
            && msg.u.event_data.data2 == 1,
           "Component did not properly acknowledge flushing the output port.");

    for (size_t i = 0; i < outputBuffers.size(); ++i) {
        EXPECT((outputBuffers[i].mFlags & kBufferBusy) == 0,
               "Not all output buffers have been returned to us by the time "
               "we received the flush-complete notification.");
    }

    for (size_t i = 0; i < outputBuffers.size(); ++i) {
        err = mOMX->fillBuffer(node, outputBuffers[i].mID);
        EXPECT_SUCCESS(err, "fillBuffer");

        outputBuffers.editItemAt(i).mFlags |= kBufferBusy;
    }

    // Initiate transition Executing->Idle
    err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateIdle);
    EXPECT_SUCCESS(err, "sendCommand(go-to-Idle)");

    err = dequeueMessageForNodeIgnoringBuffers(
            node, &inputBuffers, &outputBuffers, &msg, DEFAULT_TIMEOUT);
    EXPECT(err == OK
            && msg.type == omx_message::EVENT
            && msg.u.event_data.event == OMX_EventCmdComplete
            && msg.u.event_data.data1 == OMX_CommandStateSet
            && msg.u.event_data.data2 == OMX_StateIdle,
           "Component did not properly transition to from executing to "
           "idle state.");

    for (size_t i = 0; i < inputBuffers.size(); ++i) {
        EXPECT((inputBuffers[i].mFlags & kBufferBusy) == 0,
                "Not all input buffers have been returned to us by the "
                "time we received the transition-to-idle complete "
                "notification.");
    }

    for (size_t i = 0; i < outputBuffers.size(); ++i) {
        EXPECT((outputBuffers[i].mFlags & kBufferBusy) == 0,
                "Not all output buffers have been returned to us by the "
                "time we received the transition-to-idle complete "
                "notification.");
    }

    // Initiate transition Idle->Loaded
    err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateLoaded);
    EXPECT_SUCCESS(err, "sendCommand(go-to-Loaded)");

    // Make sure node doesn't just transition to loaded before we are done
    // freeing all input and output buffers.
    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    CHECK_EQ(err, TIMED_OUT);

    for (size_t i = 0; i < inputBuffers.size(); ++i) {
        err = mOMX->freeBuffer(node, 0, inputBuffers[i].mID);
        EXPECT_SUCCESS(err, "freeBuffer");
    }

    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    CHECK_EQ(err, TIMED_OUT);

    for (size_t i = 0; i < outputBuffers.size(); ++i) {
        err = mOMX->freeBuffer(node, 1, outputBuffers[i].mID);
        EXPECT_SUCCESS(err, "freeBuffer");
    }

    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    EXPECT(err == OK
            && msg.type == omx_message::EVENT
            && msg.u.event_data.event == OMX_EventCmdComplete
            && msg.u.event_data.data1 == OMX_CommandStateSet
            && msg.u.event_data.data2 == OMX_StateLoaded,
           "Component did not properly transition to from idle to "
           "loaded state after freeing all input and output buffers.");

    err = mOMX->freeNode(node);
    EXPECT_SUCCESS(err, "freeNode");

    reaper.disarm();

    node = 0;

    return OK;
}
예제 #12
0
/* Reset (power-cycle) the given outlet number */
static int
RPCReset(struct pluginDevice* bt, int unitnum, const char * rebootid)
{
	char		unum[32];


	SEND(bt->wrfd, "\r");

	/* Make sure we're in the top level menu */

	/* Expect "RPC-x Menu" */
	EXPECT(bt->rdfd, RPC, 5);
	EXPECT(bt->rdfd, Menu, 5);

	/* OK.  Request sub-menu 1 (Outlet Control) */
	SEND(bt->wrfd, "1\r");

	/* Verify that we're in the sub-menu */

	/* Expect: "RPC-x>" */
	EXPECT(bt->rdfd, RPC, 5);
	EXPECT(bt->rdfd, GTSign, 5);


	/* Send REBOOT command for given outlet */
	snprintf(unum, sizeof(unum), "REBOOT %d\r", unitnum);
	SEND(bt->wrfd, unum);

	/* Expect "ebooting "... or "(Y/N)" (if confirmation turned on) */

	retry:
	switch (StonithLookFor(bt->rdfd, Rebooting, 5)) {
		case 0: /* Got "Rebooting" Do nothing */
			break;

		case 1: /* Got that annoying command confirmation :-( */
			SEND(bt->wrfd, "Y\r");
			goto retry;

		case 2:	/* Outlet is turned off */
			LOG(PIL_CRIT, "Host is OFF: %s.", rebootid);
			return(S_ISOFF);

		default:
			return(errno == ETIMEDOUT ? S_RESETFAIL : S_OOPS);
	}
	LOG(PIL_INFO,	"Host %s (outlet %d) being rebooted."
	,	rebootid, unitnum);
	
	/* Expect "ower applied to outlet" */
	if (StonithLookFor(bt->rdfd, PowerApplied, 30) < 0) {
		return(errno == ETIMEDOUT ? S_RESETFAIL : S_OOPS);
	}

	/* All Right!  Power is back on.  Life is Good! */
	
	LOG(PIL_INFO,	"Power restored to host %s (outlet %d)."
	,	rebootid, unitnum);

	/* Expect: "RPC-x>" */
	EXPECT(bt->rdfd, RPC,5);
	EXPECT(bt->rdfd, GTSign, 5);

	/* Pop back to main menu */
	SEND(bt->wrfd, "MENU\r");
	return(S_OK);
}
예제 #13
0
static int
RPCLogin(struct pluginDevice * bt)
{
	char		IDinfo[128];
	static char	IDbuf[128];
	char *		idptr = IDinfo;
	char *		delim;
	int		j;

	EXPECT(bt->rdfd, RPC, 10);

	/* Look for the unit type info */
	if (EXPECT_TOK(bt->rdfd, BayTechAssoc, 2, IDinfo
	,	sizeof(IDinfo), Debug) < 0) {
		LOG(PIL_CRIT, "No initial response from %s.", bt->idinfo);
		return(errno == ETIMEDOUT ? S_TIMEOUT : S_OOPS);
	}
	idptr += strspn(idptr, WHITESPACE);
	/*
	 * We should be looking at something like this:
         *	RPC-5 Telnet Host
    	 *	Revision F 4.22, (C) 1999
    	 *	Bay Technical Associates
	 */

	/* Truncate the result after the RPC-5 part */
	if ((delim = strchr(idptr, ' ')) != NULL) {
		*delim = EOS;
	}
	snprintf(IDbuf, sizeof(IDbuf), "BayTech RPC%s", idptr);
	REPLSTR(bt->idinfo, IDbuf);
	if (bt->idinfo == NULL) {
		return(S_OOPS);
	}

	bt->modelinfo = &ModelInfo[0];

	for (j=0; ModelInfo[j].type != NULL; ++j) {
		/*
		 * TIMXXX - 
		 * Look at device ID as this really describes the model.
		 */
		if (strcasecmp(ModelInfo[j].type, IDbuf) == 0) {
			bt->modelinfo = &ModelInfo[j];
			break;
		}
	}

	/* Look for the unit id info */
	EXPECT(bt->rdfd, UnitId, 10);
	SNARF(bt->rdfd, IDbuf, 2);
	delim = IDbuf + strcspn(IDbuf, WHITESPACE);
	*delim = EOS;
	REPLSTR(bt->unitid, IDbuf);
	if (bt->unitid == NULL) {
		return(S_OOPS);
	}

	/* Expect "username>" */
	EXPECT(bt->rdfd, login, 2);

	SEND(bt->wrfd, bt->user);
	SEND(bt->wrfd, "\r");

	/* Expect "password>" */

	switch (StonithLookFor(bt->rdfd, password, 5)) {
		case 0:	/* Good! */
			break;

		case 1:	/* OOPS!  got another username prompt */
			LOG(PIL_CRIT, "Invalid username for %s.", bt->idinfo);
			return(S_ACCESS);

		default:
			return(errno == ETIMEDOUT ? S_TIMEOUT : S_OOPS);
	}

	SEND(bt->wrfd, bt->passwd);
	SEND(bt->wrfd, "\r");

	/* Expect "RPC-x Menu" */

	switch (StonithLookFor(bt->rdfd, LoginOK, 5)) {

		case 0:	/* Good! */
			break;

		case 1:	/* Uh-oh - bad password */
			LOG(PIL_CRIT, "Invalid password for %s.", bt->idinfo);
			return(S_ACCESS);

		default:
			return(errno == ETIMEDOUT ? S_TIMEOUT : S_OOPS);
	}
	EXPECT(bt->rdfd, Menu, 2);

	return(S_OK);
}
예제 #14
0
파일: init.c 프로젝트: mduwalsh/SA
int read_config(char *file_name)
{
  FILE *f;

  if (!(f = fopen(file_name,"r"))) return 1;
  EXPECT(1, "unsigned Seed      = %u;", &Seed);
  EXPECT(1, "int      Runs      = %d;", &Runs);
  EXPECT(1, "int      N         = %d;", &N);
  EXPECT(1, "int      G         = %d;", &G);  
  EXPECT(1, "double   T         = %lf;", &T);
  
  EXPECT(1, "double   PE[0]     = %lf;", PE+0);
  EXPECT(1, "double   PE[1]     = %lf;", PE+1);
  EXPECT(1, "double   PE[2]     = %lf;", PE+2);
  
  EXPECT(1, "double   F0        = %lf;", &F0);
  EXPECT(1, "double   B         = %lf;", &B);
  EXPECT(1, "double   C         = %lf;", &C);
  EXPECT(1, "double   X0        = %lf;", &X0);
  EXPECT(1, "double   Discount  = %lf;", &Discount);
  EXPECT(1, "double   Omega     = %lf;", &Omega);
  
  EXPECT(1, "double   Alpha     = %lf;", &Alpha);
  EXPECT(1, "double   Beta      = %lf;", &Beta);
  EXPECT(1, "double   Gamma     = %lf;", &Gamma);
  
  EXPECT(1, "double   Delta     = %lf;", &Delta);
    
  EXPECT(1, "int      PROTOCOL  = %d;", &PROTOCOL);
  EXPECT(1, "int      K         = %d;", &K);
  EXPECT(1, "double   Eta       = %lf;", &Eta);  
  
  EXPECT(1, "double   E         = %lf;", &E);
  EXPECT(1, "double   S0        = %lf;", &S0);
  EXPECT(1, "double   Phi       = %lf;", &Phi);
  EXPECT(1, "double   e         = %lf;", &e);
  
  EXPECT(1, "double   Mu        = %lf;", &Mu);
  EXPECT(1, "double   Sigma     = %lf;", &Sigma);
  EXPECT(1, "double   Sigma_B   = %lf;", &Sigma_B);
  EXPECT(1, "double   Sigma_dxi = %lf;", &Sigma_dxi);
  EXPECT(1, "double   Sigma_dsi = %lf;", &Sigma_dsi);  

  fclose(f); return 0;
}
예제 #15
0
파일: unit-rct.c 프로젝트: DynamoRIO/drk
static void
test_self_direct(dcontext_t *dcontext)
{
    app_pc base_pc;
    size_t size;
    uint found;
    uint newfound;

#ifdef WINDOWS
    /* this will get both code and data FIXME: data2data reference
     * will be the majority
     */
    size = get_allocation_size((app_pc)test_self_direct, &base_pc);
#else
    /* platform agnostic but only looks for current CODE section, and
     * on windows is not quite what we want - since base_pc will just
     * be just page aligned
     */
    get_memory_info((app_pc)test_self_direct, &base_pc, &size, NULL);
#endif

    mutex_lock(&rct_module_lock);
    found = find_address_references(dcontext,
                                    base_pc, base_pc+size,
                                    base_pc, base_pc+size);
    mutex_unlock(&rct_module_lock);

    /* guesstimate */
    EXPECT_RELATION(found, >, 140);
#ifdef WINDOWS
    /* FIXME: note data2data have a huge part here */
    EXPECT_RELATION(found, <, 20000);
#else
    EXPECT_RELATION(found, <, 1000);
#endif
    EXPECT(is_address_taken(dcontext, (app_pc)f3), true);
    EXPECT(is_address_taken(dcontext, (app_pc)f2), true);
    EXPECT(is_address_taken(dcontext, (app_pc)f7), true); /* array reference only */


    /* it is pretty hard to produce the address of a static
     * (e.g. test_self) without making it address taken ;) so we just
     * add a number to known to be good one's */
    EXPECT(is_address_taken(dcontext, (app_pc)f3 + 1), false);
    EXPECT(is_address_taken(dcontext, (app_pc)f3 + 2), false);
    EXPECT(is_address_taken(dcontext, (app_pc)f2 + 1), false);
    EXPECT(is_address_taken(dcontext, (app_pc)f7 + 1), false);

    mutex_lock(&rct_module_lock);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           found);
    EXPECT_RELATION(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1)
                    , == , 0);  /* nothing missed */
    mutex_unlock(&rct_module_lock);

    /* now try manually rct_analyze_module_at_violation */

    mutex_lock(&rct_module_lock);
    EXPECT(rct_analyze_module_at_violation(dcontext, (app_pc)test_self_direct), true);

    /* should be all found */
    /* FIXME: with the data2data in fact a few noisy entries show up
     * since second lookup in data may differ from original
     */
    newfound = find_address_references(dcontext,
                                       base_pc, base_pc+size,
                                       base_pc, base_pc+size);
    EXPECT_RELATION(newfound, <, 4);
    EXPECT_RELATION(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1)
                    , > , found + newfound - 5); /* FIXME: data references uncomparable */

    EXPECT_RELATION(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1)
                    , == , 0);  /* nothing missed */
    mutex_unlock(&rct_module_lock);
}
예제 #16
0
파일: main.c 프로젝트: unixdj/depcb
static int
load_project(char *filename)
{
	char	buf[PATH_MAX];
	char	*tok[PCB_MAX_TOKENS];
	FILE	*f;
	char	*s;
	int	tokens = 0;
	int	state = 0, line = 1, layer = 0;

#define EXPECT(t, s)							\
	if (t != tokens) {						\
		g_error("%s line %d: Expected %d tokens, got %d\n",	\
		   filename, line, t, tokens);				\
		goto Error;						\
	}								\
	if (strcmp(tok[0], s)) {					\
		g_error("%s line %d: Expected %s, got %s\n",		\
		   filename, line, s, tok[0]);				\
		goto Error;						\
	}
#define PARSE_ERROR()							\
	do {								\
		g_error("%s line %d: Parse error\n", filename, line);	\
		goto Error;						\
	} while (0)
#define GET_LAYER(l, s)							\
	l = strtoull(s, NULL, 16);					\
	if (!l || (l & ~ALL_LAYERS()))					\
		PARSE_ERROR();
#define GET_COORD(c, x0, y0)						\
	(c).x = atof(x0);						\
	(c).y = atof(y0);						\
	if ((c).x < 0 || (c).x > pcb.width ||				\
	    (c).y < 0 || (c).y > pcb.height)				\
		PARSE_ERROR();

	pcb.filename = filename;
	if (!(f = fopen(pcb.filename, "r"))) {
		g_error("Can't open file: %s: %s\n", pcb.filename,
		    strerror(errno));
		return -1;
	}
	while (fgets(buf, sizeof(buf), f)) {
		if (state != 0 && state != 4)
			tokenize(buf, tok, &tokens);
		switch (state) {
		case 0:
			if (strcmp(buf, "depcb-project-0\n")) {
				g_error("Not a project file: %s\n%s%s",
				    pcb.filename, "depcb-project-0\n", buf);
				goto Error;
			}
			state++;
			break;
		case 1:
			EXPECT(2, "layers");
			pcb.layers = atoi(tok[1]);
			if (pcb.layers < 1 || pcb.layers > 64)
				PARSE_ERROR();
			pcb.layer = g_malloc0(pcb.layers * sizeof(*pcb.layer));
			pcb.action = g_malloc0(sizeof(PcbAction));
			state++;
			break;
		case 2:
			EXPECT(2, "curlayer");
			pcb.curlayer = atoi(tok[1]);
			if (pcb.curlayer < 0 || pcb.curlayer >= pcb.layers)
				PARSE_ERROR();
			state++;
			break;
		case 3:
			EXPECT(3, "size");
			pcb.width = atof(tok[1]);
			pcb.height = atof(tok[2]);
			state++;
			break;
		case 4:
			if (strncmp(buf, "imagefile ", 10)) {
				g_error("expected imagefile, got %s", buf);
				goto Error;
			}
			s = buf + strlen(buf) - 1;
			if (*s == '\n')
				*s = 0;
			pcb.layer[layer].filename = strdup(buf + 10);
			if (++layer == pcb.layers)
				state++;
			break;
		case 5:
			if (tokens == 5 && !strcmp(tok[0], "point")) {
				pcb.action->act = PCB_ADD | PCB_POINT;
				GET_LAYER(pcb.action->layers, tok[1]);
				GET_COORD(pcb.action->c, tok[2], tok[3]);
				pcb.action->flags = strtol(tok[4], NULL, 16);
				if (!play_action(PCB_DO))
					PARSE_ERROR();
				break;
			}
			if (tokens == 6 && !strcmp(tok[0], "line")) {
				pcb.action->act = PCB_ADD | PCB_LINE;
				GET_LAYER(pcb.action->layers, tok[1]);
				GET_COORD(pcb.action->c, tok[2], tok[3]);
				GET_COORD(pcb.action->l, tok[4], tok[5]);
				if (!play_action(PCB_DO))
					PARSE_ERROR();
				break;
			}
			bzero(pcb.action, sizeof(*pcb.action));
			state++;
			/* FALLTHRU */
		case 6:
			g_error("garbage at eof");
			break;
		}
		line++;
	}
	return 0;
Error:
	fclose(f);
	return -1;
}
예제 #17
0
파일: unit-rct.c 프로젝트: DynamoRIO/drk
static void
test_rct_ind_branch_check(void)
{
    uint found;

    linkstub_t l;
    fragment_t f;

    /* to pass args security_violation assumes present */
    dcontext_t *dcontext = create_new_dynamo_context(true/*initial*/, NULL);

    f.tag = (app_pc)0xbeef;
    l.fragment = &f;
    l.flags = LINK_INDIRECT | LINK_CALL;
    set_last_exit(dcontext, &l);
    dcontext->logfile = GLOBAL;

    /* this should auto call rct_analyze_module_at_violation((app_pc)test_self) */
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f3),
           1);
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f3),
           1);

    /* running in -detect_mode we should get -1 */
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f3+1),
           -1);

    /* not code */
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)0xbad),
           2);

    /* starting over */
    mutex_lock(&rct_module_lock);
    invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1);
    mutex_unlock(&rct_module_lock);

    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f3), 1);
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f2), 1);
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f7), 1); /* array reference only */

    /* it is pretty hard to produce the address of a static
      * (e.g. test_self) without making it address taken ;) so we just
      * add a number to known to be good one's */
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f3 + 1), -1);
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f3 + 2), -1);
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f2 + 1), -1);
    EXPECT(rct_ind_branch_check(dcontext, (app_pc)f7 + 1), -1);

    mutex_lock(&rct_module_lock);
    found = invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1);
    mutex_unlock(&rct_module_lock);

    EXPECT_RELATION(found, >, 140);
}
예제 #18
0
    TEST_EX(::selftest, _ResultSuite, _ResultCorrect)
    {
        // Test correct initial result
        auto iter1 = getResult().getAssertions();
        EXPECT_EQ(iter1.begin(), iter1.end());
        EXPECT(getResult());
        EXPECT(getResult().succeeded());
        EXPECT_EQ(getResult().getFirstFailure(), nullptr);
        EXPECT_EQ(getResult().getFinalFailure(), nullptr);

        // Add a failed assertion
        EXPECT(false);
        ASSERT_NEQ(getResult().getFinalFailure(), nullptr);
        const Assertion* fail1 = getResult().getFinalFailure();

        // Test that result now indicates failure
        EXPECT(!getResult());
        EXPECT(!getResult().succeeded());
        EXPECT_NEQ(getResult().getFirstFailure(), nullptr);
        EXPECT_NEQ(getResult().getFinalFailure(), nullptr);
        EXPECT_EQ(getResult().getFirstFailure(), getResult().getFinalFailure());

        // Test assertion iteration
        auto iter2 = getResult().getAssertions();
        {
            auto current = iter2.begin();
            auto end = iter2.end();
            EXPECT_NEQ(current, end);

            // The first and only incorrect assertion is the 6th
            for (uint8_t i = 0; i < 5 && current != end; i++, current++) {
                EXPECT((*current).passed());
            }
            ASSERT_NEQ(current, end);

            EXPECT_EQ(&*current, getResult().getFirstFailure());
            EXPECT_EQ(&*current, getResult().getFinalFailure());
            EXPECT(!(*current).passed());

            current++;
            bool allPassed = true;
            for (uint8_t i = 0; i < 22-6 && current != end; i++, current++) {
                if (!(*current).passed()) { allPassed = false; break; }
            }
            bool atEnd = (current == end);
            EXPECT(atEnd);
            EXPECT(allPassed);
        }

        // Test that result still indicates failure
        EXPECT(!getResult());
        EXPECT(!getResult().succeeded());
        EXPECT_NEQ(getResult().getFirstFailure(), nullptr);
        EXPECT_NEQ(getResult().getFinalFailure(), nullptr);
        EXPECT_EQ(getResult().getFirstFailure(), getResult().getFinalFailure());

        // Add an additional failure
        EXPECT_EQ(1, 2);
        ASSERT_NEQ(getResult().getFinalFailure(), nullptr);
        const Assertion* fail2 = getResult().getFinalFailure();

        // Test that result still indicates failure
        EXPECT(!getResult());
        EXPECT(!getResult().succeeded());
        EXPECT_NEQ(getResult().getFirstFailure(), nullptr);
        EXPECT_NEQ(getResult().getFinalFailure(), nullptr);
        EXPECT_NEQ(getResult().getFirstFailure(), getResult().getFinalFailure());

        // Test copying result object
        TestResult result1{getResult()};
        EXPECT_EQ(result1.succeeded(), getResult().succeeded());
        EXPECT_EQ(result1.getFirstFailure(), getResult().getFirstFailure());
        EXPECT_EQ(result1.getFinalFailure(), getResult().getFinalFailure());
        EXPECT_EQ(result1.getAssertions().begin(), getResult().getAssertions().begin());
        EXPECT_EQ(result1.getAssertions().end(), getResult().getAssertions().end());

        TestResult result2{};
        result2 = getResult();
        EXPECT_EQ(result2.succeeded(), getResult().succeeded());
        EXPECT_EQ(result2.getFirstFailure(), getResult().getFirstFailure());
        EXPECT_EQ(result2.getFinalFailure(), getResult().getFinalFailure());
        EXPECT_EQ(result2.getAssertions().begin(), getResult().getAssertions().begin());
        EXPECT_EQ(result2.getAssertions().end(), getResult().getAssertions().end());

        // Test move constructor
        TestResult emptyResult{};
        TestResult result3{reinterpret_cast<TestResult&&>(result1)};

        // Original result must now be reset
        EXPECT_EQ(result1.succeeded(), emptyResult.succeeded());
        EXPECT_EQ(result1.getFirstFailure(), emptyResult.getFirstFailure());
        EXPECT_EQ(result1.getFinalFailure(), emptyResult.getFinalFailure());
        EXPECT_EQ(result1.getAssertions().begin(), emptyResult.getAssertions().begin());
        EXPECT_EQ(result1.getAssertions().end(), emptyResult.getAssertions().end());

        EXPECT_EQ(result3.succeeded(), result2.succeeded());
        EXPECT_EQ(result3.getFirstFailure(), result2.getFirstFailure());
        EXPECT_EQ(result3.getFinalFailure(), result2.getFinalFailure());
        EXPECT_EQ(result3.getAssertions().begin(), result2.getAssertions().begin());
        EXPECT_EQ(result3.getAssertions().end(), result2.getAssertions().end());

        // Test move assignment
        TestResult result4{};
        result4 = reinterpret_cast<TestResult&&>(result2);

        // Original result must now be reset
        EXPECT_EQ(result2.succeeded(), emptyResult.succeeded());
        EXPECT_EQ(result2.getFirstFailure(), emptyResult.getFirstFailure());
        EXPECT_EQ(result2.getFinalFailure(), emptyResult.getFinalFailure());
        EXPECT_EQ(result2.getAssertions().begin(), emptyResult.getAssertions().begin());
        EXPECT_EQ(result2.getAssertions().end(), emptyResult.getAssertions().end());

        EXPECT_EQ(result4.succeeded(), result3.succeeded());
        EXPECT_EQ(result4.getFirstFailure(), result3.getFirstFailure());
        EXPECT_EQ(result4.getFinalFailure(), result3.getFinalFailure());
        EXPECT_EQ(result4.getAssertions().begin(), result3.getAssertions().begin());
        EXPECT_EQ(result4.getAssertions().end(), result3.getAssertions().end());

        // Create array of tests expected to fail. Terminate with nullptr.
        static const Assertion* fails[] = { fail1, fail2, nullptr };
        static Metadata<TestExpect> _1(*this, "expect", TestExpect::SomeFail);
        static Metadata<const Assertion**> _2(*this, "fails", static_cast<const Assertion**>(fails));
    }
예제 #19
0
파일: jevents.c 프로젝트: nkurz/pmu-tools
/**
 * json_events - Read JSON event file from disk and call event callback.
 * @fn: File name to read or NULL for default.
 * @func: Callback to call for each event
 * @data: Abstract pointer to pass to func.
 *
 * The callback gets the data pointer, the event name, the event 
 * in perf format and a description passed.
 *
 * Call func with each event in the json file 
 * Return: -1 on failure, otherwise 0.
 */
int json_events(const char *fn,
	  int (*func)(void *data, char *name, char *event, char *desc, char *pmu),
	  void *data)
{
	int err = -EIO;
	size_t size;
	jsmntok_t *tokens, *tok;
	int i, j, len;
	char *map;
	char buf[128];
	const char *orig_fn = fn;

	if (!fn)
		fn = json_default_name("-core");
	tokens = parse_json(fn, &map, &size, &len);
	if (!tokens)
		return -EIO;
	EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
	tok = tokens + 1;
	for (i = 0; i < tokens->size; i++) {
		char *event = NULL, *desc = NULL, *name = NULL;
		char *pmu = NULL;
		char *filter = NULL;
		unsigned long long eventcode = 0;
		struct msrmap *msr = NULL;
		jsmntok_t *msrval = NULL;
		jsmntok_t *precise = NULL;
		jsmntok_t *obj = tok++;

		EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
		for (j = 0; j < obj->size; j += 2) {
			jsmntok_t *field, *val;
			int nz;

			field = tok + j;
			EXPECT(field->type == JSMN_STRING, tok + j,
			       "Expected field name");
			val = tok + j + 1;
			EXPECT(val->type == JSMN_STRING, tok + j + 1,
			       "Expected string value");

			nz = !json_streq(map, val, "0");
			if (match_field(map, field, nz, &event, val)) {
				/* ok */
			} else if (json_streq(map, field, "EventCode")) {
				char *code = NULL;
				addfield(map, &code, "", "", val);
				eventcode |= strtoul(code, NULL, 0);
				free(code);
			} else if (json_streq(map, field, "ExtSel")) {
				char *code = NULL;
				addfield(map, &code, "", "", val);
				eventcode |= strtoul(code, NULL, 0) << 21;
				free(code);
			} else if (json_streq(map, field, "EventName")) {
				addfield(map, &name, "", "", val);
			} else if (json_streq(map, field, "BriefDescription")) {
				addfield(map, &desc, "", "", val);
				fixdesc(desc);
			} else if (json_streq(map, field, "PEBS") && nz && desc &&
				   !strstr(desc, "(Precise Event)")) {
				precise = val;
			} else if (json_streq(map, field, "MSRIndex") && nz) {
				msr = lookup_msr(map, val);
			} else if (json_streq(map, field, "MSRValue")) {
				msrval = val;
			} else if (json_streq(map, field, "Errata") &&
				   !json_streq(map, val, "null")) {
				addfield(map, &desc, ". ",
					" Spec update: ", val);
			} else if (json_streq(map, field, "Data_LA") && nz) {
				addfield(map, &desc, ". ",
					" Supports address when precise",
					NULL);
			} else if (json_streq(map, field, "Unit")) {
				const char *ppmu;
				char *s;

				ppmu = field_to_perf(unit_to_pmu, map, val);
				if (ppmu) {
					pmu = strdup(ppmu);
				} else {
					addfield(map, &pmu, "", "", val);
					for (s = pmu; *s; s++)
						*s = tolower(*s);
				}
				addfield(map, &desc, ". ", "Unit: ", NULL);
				addfield(map, &desc, "", pmu, NULL);
			} else if (json_streq(map, field, "Filter")) {
				addfield(map, &filter, "", "", val);
			}
			/* ignore unknown fields */
		}
		if (precise) {
			if (json_streq(map, precise, "2"))
				addfield(map, &desc, " ", "(Must be precise)",
						NULL);
			else
				addfield(map, &desc, " ",
						"(Precise event)", NULL);
		}
		snprintf(buf, sizeof buf, "event=%#llx", eventcode);
		addfield(map, &event, ",", buf, NULL);
		if (filter)
			addfield(map, &event, ",", filter, NULL);
		if (msr != NULL)
			addfield(map, &event, ",", msr->pname, msrval);
		if (!pmu)
			pmu = strdup("cpu");
		err = -EIO;
		if (name && event) {
			fixname(name);
			err = func(data, name, event, desc, pmu);
		}
		free(event);
		free(desc);
		free(name);
		free(pmu);
		free(filter);
		if (err)
			break;
		tok += j;
	}
	EXPECT(tok - tokens == len, tok, "unexpected objects at end");
	err = 0;
out_free:
	free_json(map, size, tokens);
	if (!orig_fn && !err) {
		fn = json_default_name("-uncore");
		err = json_events(fn, func, data);
		/* Ignore open error */
		if (err == -EIO)
			return 0;
	}
	if (!orig_fn)
		free((char *)fn);
	return err;
}
예제 #20
0
파일: test_tcp.c 프로젝트: bb2048er/lwip
END_TEST

/** Check that we handle malformed tcp headers, and discard the pbuf(s) */
START_TEST(test_tcp_malformed_header)
{
  struct test_tcp_counters counters;
  struct tcp_pcb* pcb;
  struct pbuf* p;
  char data[] = {1, 2, 3, 4};
  ip_addr_t remote_ip, local_ip, netmask;
  u16_t data_len, chksum;
  u16_t remote_port = 0x100, local_port = 0x101;
  struct netif netif;
  struct test_tcp_txcounters txcounters;
  struct tcp_hdr *hdr;
  LWIP_UNUSED_ARG(_i);

  /* initialize local vars */
  memset(&netif, 0, sizeof(netif));
  IP_ADDR4(&local_ip, 192, 168, 1, 1);
  IP_ADDR4(&remote_ip, 192, 168, 1, 2);
  IP_ADDR4(&netmask,   255, 255, 255, 0);
  test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask);
  data_len = sizeof(data);
  /* initialize counter struct */
  memset(&counters, 0, sizeof(counters));
  counters.expected_data_len = data_len;
  counters.expected_data = data;

  /* create and initialize the pcb */
  pcb = test_tcp_new_counters_pcb(&counters);
  EXPECT_RET(pcb != NULL);
  tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port);

  /* create a segment */
  p = tcp_create_rx_segment(pcb, counters.expected_data, data_len, 0, 0, 0);

  pbuf_header(p, -(s16_t)sizeof(struct ip_hdr));

  hdr = (struct tcp_hdr *)p->payload;
  TCPH_HDRLEN_FLAGS_SET(hdr, 15, 0x3d1);

  hdr->chksum = 0;

  chksum = ip_chksum_pseudo(p, IP_PROTO_TCP, p->tot_len,
                             &remote_ip, &local_ip);

  hdr->chksum = chksum;

  pbuf_header(p, sizeof(struct ip_hdr));

  EXPECT(p != NULL);
  EXPECT(p->next == NULL);
  if (p != NULL) {
    /* pass the segment to tcp_input */
    test_tcp_input(p, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 0);
    EXPECT(counters.recved_bytes == 0);
    EXPECT(counters.err_calls == 0);
  }

  /* make sure the pcb is freed */
  EXPECT(lwip_stats.memp[MEMP_TCP_PCB].used == 1);
  tcp_abort(pcb);
  EXPECT(lwip_stats.memp[MEMP_TCP_PCB].used == 0);
}
예제 #21
0
void test(void)
{
	DECL_OUTPUT(regIn, 0, 16);
	DECL_OUTPUT(clock, 16, 1);
	DECL_OUTPUT(notLoad, 17, 1);
	DECL_OUTPUT(notOE, 18, 1);
	
	DECL_INPUT(regOut, 0, 16);
	
	for(;;)
	{
		OUT(clock, 0);
		OUT(notLoad, 1);
		OUT(notOE, 1);
		FLUSH_OUTPUTS;
	
		size_t i;
		for(i = 0; i < 16; ++i)
		{
			uint16_t v = 1 << i;
		
			WRITE(v);
			Delay(10000);
		
			EXPECT(regOut, v);
		
			OUT(notOE, 0);
			FLUSH_OUTPUTS;
			Delay(10000);
			TEST_INPUTS;
			OUT(notOE, 1);
			FLUSH_OUTPUTS;
			Delay(10000);
		}
	
		WRITE(0x68EB);
		FLUSH_OUTPUTS;
	
		OUT(regIn, 0x1BC9);
		FLUSH_OUTPUTS;
		Delay(10000);
		CLOCK_PULSE;
		Delay(10000);
	
		OUT(notOE, 0);
		FLUSH_OUTPUTS;
		Delay(10000);
		
		EXPECT(regOut, 0x68EB);
		TEST_INPUTS;
		
		WRITE(0xFFFF);
		Delay(10000);
	
		EXPECT(regOut, 0xFFFF);
	
		OUT(notOE, 0);
		FLUSH_OUTPUTS;
		Delay(10000);
		TEST_INPUTS;
		OUT(notOE, 1);
		FLUSH_OUTPUTS;
		Delay(10000);
		
		WRITE(0x0);
		Delay(10000);
	
		EXPECT(regOut, 0x0);
	
		OUT(notOE, 0);
		FLUSH_OUTPUTS;
		Delay(10000);
		TEST_INPUTS;
		OUT(notOE, 1);
		FLUSH_OUTPUTS;
		Delay(10000);
	}
}
예제 #22
0
파일: test_tcp.c 프로젝트: bb2048er/lwip
END_TEST

/** Send data with sequence numbers that wrap around the u32_t range.
 * Then, provoke RTO retransmission and check that all
 * segment lists are still properly sorted. */
START_TEST(test_tcp_rto_rexmit_wraparound)
{
  struct netif netif;
  struct test_tcp_txcounters txcounters;
  struct test_tcp_counters counters;
  struct tcp_pcb* pcb;
  ip_addr_t remote_ip, local_ip, netmask;
  u16_t remote_port = 0x100, local_port = 0x101;
  err_t err;
#define SEQNO1 (0xFFFFFF00 - TCP_MSS)
#define ISS    6510
  u16_t i, sent_total = 0;
  u32_t seqnos[] = {
    SEQNO1,
    SEQNO1 + (1 * TCP_MSS),
    SEQNO1 + (2 * TCP_MSS),
    SEQNO1 + (3 * TCP_MSS),
    SEQNO1 + (4 * TCP_MSS),
    SEQNO1 + (5 * TCP_MSS)};
  LWIP_UNUSED_ARG(_i);

  for (i = 0; i < sizeof(tx_data); i++) {
    tx_data[i] = (u8_t)i;
  }

  /* initialize local vars */
  IP_ADDR4(&local_ip,  192, 168,   1, 1);
  IP_ADDR4(&remote_ip, 192, 168,   1, 2);
  IP_ADDR4(&netmask,   255, 255, 255, 0);
  test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask);
  memset(&counters, 0, sizeof(counters));

  /* create and initialize the pcb */
  tcp_ticks = 0;
  tcp_ticks = 0 - tcp_next_iss();
  tcp_ticks = SEQNO1 - tcp_next_iss();
  pcb = test_tcp_new_counters_pcb(&counters);
  EXPECT_RET(pcb != NULL);
  EXPECT(pcb->lastack == SEQNO1);
  tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port);
  pcb->mss = TCP_MSS;
  /* disable initial congestion window (we don't send a SYN here...) */
  pcb->cwnd = 2*TCP_MSS;

  /* send 6 mss-sized segments */
  for (i = 0; i < 6; i++) {
    err = tcp_write(pcb, &tx_data[sent_total], TCP_MSS, TCP_WRITE_FLAG_COPY);
    EXPECT_RET(err == ERR_OK);
    sent_total += TCP_MSS;
  }
  check_seqnos(pcb->unsent, 6, seqnos);
  EXPECT(pcb->unacked == NULL);
  err = tcp_output(pcb);
  EXPECT(txcounters.num_tx_calls == 2);
  EXPECT(txcounters.num_tx_bytes == 2 * (TCP_MSS + 40U));
  memset(&txcounters, 0, sizeof(txcounters));

  check_seqnos(pcb->unacked, 2, seqnos);
  check_seqnos(pcb->unsent, 4, &seqnos[2]);

  /* call the tcp timer some times */
  for (i = 0; i < 10; i++) {
    test_tcp_tmr();
    EXPECT(txcounters.num_tx_calls == 0);
  }
  /* 11th call to tcp_tmr: RTO rexmit fires */
  test_tcp_tmr();
  EXPECT(txcounters.num_tx_calls == 1);
  check_seqnos(pcb->unacked, 1, seqnos);
  check_seqnos(pcb->unsent, 5, &seqnos[1]);

  /* fake greater cwnd */
  pcb->cwnd = pcb->snd_wnd;
  /* send more data */
  err = tcp_output(pcb);
  EXPECT(err == ERR_OK);
  /* check queues are sorted */
  EXPECT(pcb->unsent == NULL);
  check_seqnos(pcb->unacked, 6, seqnos);

  /* make sure the pcb is freed */
  EXPECT_RET(lwip_stats.memp[MEMP_TCP_PCB].used == 1);
  tcp_abort(pcb);
  EXPECT_RET(lwip_stats.memp[MEMP_TCP_PCB].used == 0);
}
예제 #23
0
파일: test_tcp_oos.c 프로젝트: 0xc0170/mbed
END_TEST


/** create multiple segments and pass them to tcp_input in a wrong
 * order to see if ooseq-caching works correctly
 * FIN is received IN-SEQUENCE at the end */
START_TEST(test_tcp_recv_ooseq_FIN_INSEQ)
{
  struct test_tcp_counters counters;
  struct tcp_pcb* pcb;
  struct pbuf *p_1_2, *p_4_8, *p_3_11, *p_2_12, *p_15_1, *p_15_1a, *pinseq, *pinseqFIN;
  char data[] = {
     1,  2,  3,  4,
     5,  6,  7,  8,
     9, 10, 11, 12,
    13, 14, 15, 16};
  u16_t data_len;
  struct netif netif;
  LWIP_UNUSED_ARG(_i);

  /* initialize local vars */
  test_tcp_init_netif(&netif, NULL, &test_local_ip, &test_netmask);
  data_len = sizeof(data);
  /* initialize counter struct */
  memset(&counters, 0, sizeof(counters));
  counters.expected_data_len = data_len;
  counters.expected_data = data;

  /* create and initialize the pcb */
  pcb = test_tcp_new_counters_pcb(&counters);
  EXPECT_RET(pcb != NULL);
  tcp_set_state(pcb, ESTABLISHED, &test_local_ip, &test_remote_ip, TEST_LOCAL_PORT, TEST_REMOTE_PORT);

  /* create segments */
  /* p1: 7 bytes - 2 before FIN */
  /*     seqno: 1..2 */
  p_1_2  = tcp_create_rx_segment(pcb, &data[1],  2, 1, 0, TCP_ACK);
  /* p2: 4 bytes before p1, including the first 4 bytes of p1 (partly duplicate) */
  /*     seqno: 4..11 */
  p_4_8  = tcp_create_rx_segment(pcb, &data[4],  8, 4, 0, TCP_ACK);
  /* p3: same as p2 but 2 bytes longer and one byte more at the front */
  /*     seqno: 3..13 */
  p_3_11 = tcp_create_rx_segment(pcb, &data[3], 11, 3, 0, TCP_ACK);
  /* p4: 13 bytes - 2 before FIN - should be ignored as contained in p1 and p3 */
  /*     seqno: 2..13 */
  p_2_12 = tcp_create_rx_segment(pcb, &data[2], 12, 2, 0, TCP_ACK);
  /* pinseq is the first segment that is held back to create ooseq! */
  /*     seqno: 0..3 */
  pinseq = tcp_create_rx_segment(pcb, &data[0],  4, 0, 0, TCP_ACK);
  /* p5: last byte before FIN */
  /*     seqno: 15 */
  p_15_1 = tcp_create_rx_segment(pcb, &data[15], 1, 15, 0, TCP_ACK);
  /* p6: same as p5, should be ignored */
  p_15_1a= tcp_create_rx_segment(pcb, &data[15], 1, 15, 0, TCP_ACK);
  /* pinseqFIN: last 2 bytes plus FIN */
  /*     only segment containing seqno 14 and FIN */
  pinseqFIN = tcp_create_rx_segment(pcb,  &data[14], 2, 14, 0, TCP_ACK|TCP_FIN);
  EXPECT(pinseq != NULL);
  EXPECT(p_1_2 != NULL);
  EXPECT(p_4_8 != NULL);
  EXPECT(p_3_11 != NULL);
  EXPECT(p_2_12 != NULL);
  EXPECT(p_15_1 != NULL);
  EXPECT(p_15_1a != NULL);
  EXPECT(pinseqFIN != NULL);
  if ((pinseq != NULL) && (p_1_2 != NULL) && (p_4_8 != NULL) && (p_3_11 != NULL) && (p_2_12 != NULL)
    && (p_15_1 != NULL) && (p_15_1a != NULL) && (pinseqFIN != NULL)) {
    /* pass the segment to tcp_input */
    test_tcp_input(p_1_2, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 0);
    EXPECT(counters.recved_bytes == 0);
    EXPECT(counters.err_calls == 0);
    /* check ooseq queue */
    EXPECT_OOSEQ(tcp_oos_count(pcb) == 1);
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 1);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 2);

    /* pass the segment to tcp_input */
    test_tcp_input(p_4_8, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 0);
    EXPECT(counters.recved_bytes == 0);
    EXPECT(counters.err_calls == 0);
    /* check ooseq queue */
    EXPECT_OOSEQ(tcp_oos_count(pcb) == 2);
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 1);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 2);
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 1) == 4);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 1) == 8);

    /* pass the segment to tcp_input */
    test_tcp_input(p_3_11, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 0);
    EXPECT(counters.recved_bytes == 0);
    EXPECT(counters.err_calls == 0);
    /* check ooseq queue */
    EXPECT_OOSEQ(tcp_oos_count(pcb) == 2);
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 1);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 2);
    /* p_3_11 has removed p_4_8 from ooseq */
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 1) == 3);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 1) == 11);

    /* pass the segment to tcp_input */
    test_tcp_input(p_2_12, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 0);
    EXPECT(counters.recved_bytes == 0);
    EXPECT(counters.err_calls == 0);
    /* check ooseq queue */
    EXPECT_OOSEQ(tcp_oos_count(pcb) == 2);
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 1);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 1);
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 1) == 2);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 1) == 12);

    /* pass the segment to tcp_input */
    test_tcp_input(pinseq, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 1);
    EXPECT(counters.recved_bytes == 14);
    EXPECT(counters.err_calls == 0);
    EXPECT(pcb->ooseq == NULL);

    /* pass the segment to tcp_input */
    test_tcp_input(p_15_1, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 1);
    EXPECT(counters.recved_bytes == 14);
    EXPECT(counters.err_calls == 0);
    /* check ooseq queue */
    EXPECT_OOSEQ(tcp_oos_count(pcb) == 1);
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 15);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 1);

    /* pass the segment to tcp_input */
    test_tcp_input(p_15_1a, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 1);
    EXPECT(counters.recved_bytes == 14);
    EXPECT(counters.err_calls == 0);
    /* check ooseq queue: unchanged */
    EXPECT_OOSEQ(tcp_oos_count(pcb) == 1);
    EXPECT_OOSEQ(tcp_oos_seg_seqno(pcb, 0) == 15);
    EXPECT_OOSEQ(tcp_oos_seg_tcplen(pcb, 0) == 1);

    /* pass the segment to tcp_input */
    test_tcp_input(pinseqFIN, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 1);
    EXPECT(counters.recv_calls == 2);
    EXPECT(counters.recved_bytes == data_len);
    EXPECT(counters.err_calls == 0);
    EXPECT(pcb->ooseq == NULL);
  }

  /* make sure the pcb is freed */
  EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1);
  tcp_abort(pcb);
  EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0);
}
예제 #24
0
파일: test_tcp.c 프로젝트: bb2048er/lwip
END_TEST

/** Provoke fast retransmission by duplicate ACKs and then recover by ACKing all sent data.
 * At the end, send more data. */
static void test_tcp_tx_full_window_lost(u8_t zero_window_probe_from_unsent)
{
  struct netif netif;
  struct test_tcp_txcounters txcounters;
  struct test_tcp_counters counters;
  struct tcp_pcb* pcb;
  struct pbuf *p;
  ip_addr_t remote_ip, local_ip, netmask;
  u16_t remote_port = 0x100, local_port = 0x101;
  err_t err;
  u16_t sent_total, i;
  u8_t expected = 0xFE;

  for (i = 0; i < sizeof(tx_data); i++) {
    u8_t d = (u8_t)i;
    if (d == 0xFE) {
      d = 0xF0;
    }
    tx_data[i] = d;
  }
  if (zero_window_probe_from_unsent) {
    tx_data[TCP_WND] = expected;
  } else {
    tx_data[0] = expected;
  }

  /* initialize local vars */
  IP_ADDR4(&local_ip,  192, 168,   1, 1);
  IP_ADDR4(&remote_ip, 192, 168,   1, 2);
  IP_ADDR4(&netmask,   255, 255, 255, 0);
  test_tcp_init_netif(&netif, &txcounters, &local_ip, &netmask);
  memset(&counters, 0, sizeof(counters));
  memset(&txcounters, 0, sizeof(txcounters));

  /* create and initialize the pcb */
  pcb = test_tcp_new_counters_pcb(&counters);
  EXPECT_RET(pcb != NULL);
  tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, local_port, remote_port);
  pcb->mss = TCP_MSS;
  /* disable initial congestion window (we don't send a SYN here...) */
  pcb->cwnd = pcb->snd_wnd;

  /* send a full window (minus 1 packets) of TCP data in MSS-sized chunks */
  sent_total = 0;
  if ((TCP_WND - TCP_MSS) % TCP_MSS != 0) {
    u16_t initial_data_len = (TCP_WND - TCP_MSS) % TCP_MSS;
    err = tcp_write(pcb, &tx_data[sent_total], initial_data_len, TCP_WRITE_FLAG_COPY);
    EXPECT_RET(err == ERR_OK);
    err = tcp_output(pcb);
    EXPECT_RET(err == ERR_OK);
    EXPECT(txcounters.num_tx_calls == 1);
    EXPECT(txcounters.num_tx_bytes == initial_data_len + 40U);
    memset(&txcounters, 0, sizeof(txcounters));
    sent_total += initial_data_len;
  }
  for (; sent_total < (TCP_WND - TCP_MSS); sent_total += TCP_MSS) {
    err = tcp_write(pcb, &tx_data[sent_total], TCP_MSS, TCP_WRITE_FLAG_COPY);
    EXPECT_RET(err == ERR_OK);
    err = tcp_output(pcb);
    EXPECT_RET(err == ERR_OK);
    EXPECT(txcounters.num_tx_calls == 1);
    EXPECT(txcounters.num_tx_bytes == TCP_MSS + 40U);
    memset(&txcounters, 0, sizeof(txcounters));
  }
  EXPECT(sent_total == (TCP_WND - TCP_MSS));

  /* now ACK the packet before the first */
  p = tcp_create_rx_segment(pcb, NULL, 0, 0, 0, TCP_ACK);
  test_tcp_input(p, &netif);
  /* ensure this didn't trigger a retransmission */
  EXPECT(txcounters.num_tx_calls == 0);
  EXPECT(txcounters.num_tx_bytes == 0);

  EXPECT(pcb->persist_backoff == 0);
  /* send the last packet, now a complete window has been sent */
  err = tcp_write(pcb, &tx_data[sent_total], TCP_MSS, TCP_WRITE_FLAG_COPY);
  sent_total += TCP_MSS;
  EXPECT_RET(err == ERR_OK);
  err = tcp_output(pcb);
  EXPECT_RET(err == ERR_OK);
  EXPECT(txcounters.num_tx_calls == 1);
  EXPECT(txcounters.num_tx_bytes == TCP_MSS + 40U);
  memset(&txcounters, 0, sizeof(txcounters));
  EXPECT(pcb->persist_backoff == 0);

  if (zero_window_probe_from_unsent) {
    /* ACK all data but close the TX window */
    p = tcp_create_rx_segment_wnd(pcb, NULL, 0, 0, TCP_WND, TCP_ACK, 0);
    test_tcp_input(p, &netif);
    /* ensure this didn't trigger any transmission */
    EXPECT(txcounters.num_tx_calls == 0);
    EXPECT(txcounters.num_tx_bytes == 0);
    EXPECT(pcb->persist_backoff == 1);
  }

  /* send one byte more (out of window) -> persist timer starts */
  err = tcp_write(pcb, &tx_data[sent_total], 1, TCP_WRITE_FLAG_COPY);
  EXPECT_RET(err == ERR_OK);
  err = tcp_output(pcb);
  EXPECT_RET(err == ERR_OK);
  EXPECT(txcounters.num_tx_calls == 0);
  EXPECT(txcounters.num_tx_bytes == 0);
  memset(&txcounters, 0, sizeof(txcounters));
  if (!zero_window_probe_from_unsent) {
    /* no persist timer unless a zero window announcement has been received */
    EXPECT(pcb->persist_backoff == 0);
  } else {
    EXPECT(pcb->persist_backoff == 1);

    /* call tcp_timer some more times to let persist timer count up */
    for (i = 0; i < 4; i++) {
      test_tcp_tmr();
      EXPECT(txcounters.num_tx_calls == 0);
      EXPECT(txcounters.num_tx_bytes == 0);
    }

    /* this should trigger the zero-window-probe */
    txcounters.copy_tx_packets = 1;
    test_tcp_tmr();
    txcounters.copy_tx_packets = 0;
    EXPECT(txcounters.num_tx_calls == 1);
    EXPECT(txcounters.num_tx_bytes == 1 + 40U);
    EXPECT(txcounters.tx_packets != NULL);
    if (txcounters.tx_packets != NULL) {
      u8_t sent;
      u16_t ret;
      ret = pbuf_copy_partial(txcounters.tx_packets, &sent, 1, 40U);
      EXPECT(ret == 1);
      EXPECT(sent == expected);
    }
    if (txcounters.tx_packets != NULL) {
      pbuf_free(txcounters.tx_packets);
      txcounters.tx_packets = NULL;
    }
  }

  /* make sure the pcb is freed */
  EXPECT_RET(lwip_stats.memp[MEMP_TCP_PCB].used == 1);
  tcp_abort(pcb);
  EXPECT_RET(lwip_stats.memp[MEMP_TCP_PCB].used == 0);
}
예제 #25
0
파일: test_tcp_oos.c 프로젝트: 0xc0170/mbed
END_TEST

START_TEST(test_tcp_recv_ooseq_max_pbufs)
{
#if TCP_OOSEQ_MAX_PBUFS && (TCP_OOSEQ_MAX_PBUFS < ((TCP_WND / TCP_MSS) + 1)) && (PBUF_POOL_BUFSIZE >= (TCP_MSS + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN))
  int i;
  struct test_tcp_counters counters;
  struct tcp_pcb* pcb;
  struct pbuf *p_ovr;
  struct netif netif;
  int datalen = 0;
  int datalen2;

  for(i = 0; i < sizeof(data_full_wnd); i++) {
    data_full_wnd[i] = (char)i;
  }

  /* initialize local vars */
  test_tcp_init_netif(&netif, NULL, &test_local_ip, &test_netmask);
  /* initialize counter struct */
  memset(&counters, 0, sizeof(counters));
  counters.expected_data_len = TCP_WND;
  counters.expected_data = data_full_wnd;

  /* create and initialize the pcb */
  pcb = test_tcp_new_counters_pcb(&counters);
  EXPECT_RET(pcb != NULL);
  tcp_set_state(pcb, ESTABLISHED, &local_ip, &remote_ip, TEST_LOCAL_PORT, TEST_REMOTE_PORT);
  pcb->rcv_nxt = 0x8000;

  /* don't 'recv' the first segment (1 byte) so that all other segments will be ooseq */

  /* create segments and 'recv' them */
  for(i = 1; i <= TCP_OOSEQ_MAX_PBUFS; i++) {
    int count;
    struct pbuf *p = tcp_create_rx_segment(pcb, &data_full_wnd[i],
                                           1, i, 0, TCP_ACK);
    EXPECT_RET(p != NULL);
    EXPECT_RET(p->next == NULL);
    /* pass the segment to tcp_input */
    test_tcp_input(p, &netif);
    /* check if counters are as expected */
    EXPECT(counters.close_calls == 0);
    EXPECT(counters.recv_calls == 0);
    EXPECT(counters.recved_bytes == 0);
    EXPECT(counters.err_calls == 0);
    /* check ooseq queue */
    count = tcp_oos_pbuf_count(pcb);
    EXPECT_OOSEQ(count == i);
    datalen = tcp_oos_tcplen(pcb);
    EXPECT_OOSEQ(datalen == i);
  }

  /* pass in one more segment, overrunning the limit */
  p_ovr = tcp_create_rx_segment(pcb, &data_full_wnd[i+1], 1, i+1, 0, TCP_ACK);
  EXPECT_RET(p_ovr != NULL);
  /* pass the segment to tcp_input */
  test_tcp_input(p_ovr, &netif);
  /* check if counters are as expected */
  EXPECT(counters.close_calls == 0);
  EXPECT(counters.recv_calls == 0);
  EXPECT(counters.recved_bytes == 0);
  EXPECT(counters.err_calls == 0);
  /* check ooseq queue (ensure the new segment was not accepted) */
  EXPECT_OOSEQ(tcp_oos_count(pcb) == (i-1));
  datalen2 = tcp_oos_tcplen(pcb);
  EXPECT_OOSEQ(datalen2 == (i-1));

  /* make sure the pcb is freed */
  EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 1);
  tcp_abort(pcb);
  EXPECT(MEMP_STATS_GET(used, MEMP_TCP_PCB) == 0);
#endif /* TCP_OOSEQ_MAX_PBUFS && (TCP_OOSEQ_MAX_BYTES < (TCP_WND + 1)) && (PBUF_POOL_BUFSIZE >= (TCP_MSS + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN)) */
  LWIP_UNUSED_ARG(_i);
}
예제 #26
0
파일: cn_set_str.c 프로젝트: nu4nu/sobun
static int pass1(cn_t cn, const char *str){
  int ix;
  int cnt;

  if(str[0] != '('){
    return CN_NOT_CN;
  }
  if(strcmp(str, CNFILE_TERMINATOR) == 0){
    return CN_NOT_CN;
  }
  ix = 1;

  EXPECT(str[ix] >= '0' && str[ix] <= '9');
  ix += read_int(str+ix, &cn->n);

  EXPECT(str[ix] == ' ');
  ix++;

  EXPECT(str[ix] >= '0' && str[ix] <= '9');
  ix += read_int(str+ix, &cn->x);

  EXPECT(str[ix] == ' ');
  ix++;

  EXPECT(str[ix] == '(');
  ix++;

  cnt = 2;
  while(1){
    EXPECT(str[ix] >= '0' && str[ix] <= '9');
    while(str[ix] >= '0' && str[ix] <= '9') ix++;
    EXPECT(str[ix] == ' ' || str[ix] == ')');
    if(str[ix] == ')') break;
    ix++;
    cnt++;
  }
  ix++;

  EXPECT(str[ix] == ' ');
  ix++;

  EXPECT(str[ix] == '(');
  ix++;

  EXPECT(str[ix] == 'C' || str[ix] == 'P');
  cn->flag = str[ix];
  ix++;

  EXPECT(str[ix] == ' ');
  ix++;

  EXPECT(str[ix] >= '0' && str[ix] <= '9');
  ix += read_int(str+ix, &cn->lf_digit);

  EXPECT(str[ix] == ')');
  ix++;

  EXPECT(str[ix] == ')');
  ix++;

  EXPECT(str[ix] == '\0');

  cn->factor = malloc(cnt * sizeof(mpz_t));
  if(cn->factor == NULL){
    return CN_MEMORY_ERROR;
  }
  return CN_OK;
}
예제 #27
0
int main(int argc, char * argv[])
{
    SETLOGMASK();

    {
        int sock;
        int rc;

        TEST();

        sock = socket(AF_INET6, SOCK_STREAM, 0);
        ASSERT(sock >= 0);

        rc = diminuto_ipc_set_nonblocking(sock, !0);
        EXPECT(rc >= 0);
        rc = diminuto_ipc_set_nonblocking(sock, 0);
        EXPECT(rc >= 0);

        rc = diminuto_ipc_set_reuseaddress(sock, !0);
        EXPECT(rc >= 0);
        rc = diminuto_ipc_set_reuseaddress(sock, 0);
        EXPECT(rc >= 0);

        rc = diminuto_ipc_set_keepalive(sock, !0);
        EXPECT(rc >= 0);
        rc = diminuto_ipc_set_keepalive(sock, 0);
        EXPECT(rc >= 0);

        if (geteuid() == 0) {
            rc = diminuto_ipc_set_debug(sock, !0);
            EXPECT(rc >= 0);
            rc = diminuto_ipc_set_debug(sock, 0);
            EXPECT(rc >= 0);
        }

        rc = diminuto_ipc_set_linger(sock, diminuto_frequency());
        EXPECT(rc >= 0);
        rc = diminuto_ipc_set_linger(sock, 0);
        EXPECT(rc >= 0);


        rc = diminuto_ipc_set_debug(sock, 0);
        EXPECT(rc >= 0);

        rc = diminuto_ipc_set_nodelay(sock, !0);
        EXPECT(rc >= 0);
        rc = diminuto_ipc_set_nodelay(sock, 0);
        EXPECT(rc >= 0);

        rc = diminuto_ipc_set_quickack(sock, !0);
        EXPECT(rc >= 0);
        rc = diminuto_ipc_set_quickack(sock, 0);
        EXPECT(rc >= 0);

        rc = diminuto_ipc_set_send(sock, 512);
        EXPECT(rc >= 0);

        rc = diminuto_ipc_set_receive(sock, 512);
        EXPECT(rc >= 0);

        rc = diminuto_ipc_stream_get_available(sock);
        EXPECT(rc == 0);

        rc = diminuto_ipc_stream_get_pending(sock);
        EXPECT(rc == 0);

        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    {
        int sock;
        int rc;
        int value;

        TEST();

        sock = socket(AF_INET6, SOCK_STREAM, 0);
        ASSERT(sock >= 0);

        value = !0;
        rc = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &value, sizeof(value));
        if (rc < 0) { diminuto_perror("setsockopt: IPPROTO_IPV6 IPV6_V6ONLY"); }
        EXPECT(rc >= 0);

        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    {
        int sock;
        int rc;
        int value;

        TEST();

        sock = socket(AF_INET6, SOCK_STREAM, 0);
        ASSERT(sock >= 0);

        value = !0;
        rc = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &value, sizeof(value));
        if (rc < 0) { diminuto_perror("setsockopt: IPPROTO_IP IPV6_V6ONLY"); }
        EXPECT(rc >= 0);

        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    {
        int sock;
        int rc;
        int value;

        TEST();

        sock = socket(AF_INET6, SOCK_STREAM, 0);
        ASSERT(sock >= 0);

        value = AF_INET;
        rc = setsockopt(sock, IPPROTO_TCP, IPV6_ADDRFORM, &value, sizeof(value));
        if (rc < 0) { diminuto_perror("setsockopt: IPPROTO_TCP IPV6_ADDRFORM"); }
        EXPECT(rc >= 0);

        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    {
        int sock;
        int rc;
        int value;

        TEST();

        sock = socket(AF_INET6, SOCK_DGRAM, 0);
        ASSERT(sock >= 0);

        value = AF_INET;
        rc = setsockopt(sock, IPPROTO_UDP, IPV6_ADDRFORM, &value, sizeof(value));
        if (rc < 0) { diminuto_perror("setsockopt: IPPROTO_UDP IPV6_ADDRFORM"); }
        EXPECT(rc >= 0);

        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    {
        int sock;
        int rc;

        TEST();

        sock = socket(AF_INET6, SOCK_STREAM, 0);
        ASSERT(sock >= 0);
        rc = diminuto_ipc6_set_ipv6only(sock, !0);
        EXPECT(rc >= 0);
        rc = diminuto_ipc6_set_ipv6only(sock, 0);
        EXPECT(rc >= 0);
        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    {
        int sock;
        int rc;

        TEST();

        sock = socket(AF_INET6, SOCK_DGRAM, 0);
        ASSERT(sock >= 0);
        rc = diminuto_ipc6_set_ipv6only(sock, !0);
        EXPECT(rc >= 0);
        rc = diminuto_ipc6_set_ipv6only(sock, 0);
        EXPECT(rc >= 0);
        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    {
        int sock;
        int rc;

        TEST();

        sock = socket(AF_INET6, SOCK_STREAM, 0);
        ASSERT(sock >= 0);
        rc = diminuto_ipc6_stream_set_ipv6toipv4(sock);
        EXPECT(rc >= 0);
        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    {
        int sock;
        int rc;

        TEST();

        sock = socket(AF_INET6, SOCK_DGRAM, 0);
        ASSERT(sock >= 0);
        rc = diminuto_ipc6_datagram_set_ipv6toipv4(sock);
        EXPECT(rc >= 0);
        rc = close(sock);
        EXPECT(rc >= 0);

        STATUS();
    }

    EXIT();
}
예제 #28
0
파일: unit-rct.c 프로젝트: DynamoRIO/drk
/* work on a small arrays of carefully planted values
 *
 * TODO: verify end
 * of region conditions - and add this at the end of a page to verify
 * not reaching out to bad memory out of the array
 */
static int
test_small_array(dcontext_t *dcontext)
{
    /*
     * [0 1 2 3 4 5 6 7] 8)
     * [4 3 2 1 5 3 2 1]
     */

    char arr[100];

    arr[0]=4;
    arr[1]=3;
    arr[2]=2;
    arr[3]=1;

    arr[4+0]=5;
    arr[4+1]=3;
    arr[4+2]=2;
    arr[4+3]=1;

    mutex_lock(&rct_module_lock); /* around whole sequence */

    EXPECT(find_address_references(dcontext, (app_pc)arr, (app_pc)(arr+8),
                                   (app_pc)0x01020304, (app_pc)0x01020304),
           0);
    /* clean up to start over */
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           0);

    EXPECT(find_address_references(dcontext, arr, arr+8,
                            (app_pc)0x01020304, (app_pc)0x01020305),
           1);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           1);

    /* repetition */
    EXPECT(find_address_references(dcontext, arr, arr+8,
                            (app_pc)0x01020304, (app_pc)0x01020305),
           1);
    EXPECT(find_address_references(dcontext, arr, arr+8,
                            (app_pc)0x01020304, (app_pc)0x01020305),
           0);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           1);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           0);


    EXPECT(find_address_references(dcontext,arr, arr+8,
                                   (app_pc)0x01020304, (app_pc)0x01020309),
           2);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           2);


    EXPECT(find_address_references(dcontext,arr, arr+8,
                                   (app_pc)0x01020304, (app_pc)0x01020309),
           2);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)0x01020304),
           0);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)0x01020305),
           1);
    EXPECT(invalidate_ind_branch_target_range(dcontext, (app_pc)0x01020306, (app_pc)0x01020309),
           0);
    EXPECT(invalidate_ind_branch_target_range(dcontext, (app_pc)0x01020305, (app_pc)0x01020306),
           1);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           0);


    EXPECT(find_address_references(dcontext,arr+1, arr+8,
                                   (app_pc)0x01020304, (app_pc)0x01020309),
           1);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           1);


    EXPECT(find_address_references(dcontext,arr+1, arr+8,
                                   (app_pc)0x01020305, (app_pc)0x01020309),
           1);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           1);


    EXPECT(find_address_references(dcontext,arr+1, arr+8,
                            (app_pc)0x01020306, (app_pc)0x01020309),
           0);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           0);

    EXPECT(find_address_references(dcontext,arr+4, arr+8,
                            (app_pc)0x01020300, (app_pc)0x01020309),
           1);
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           1);

    EXPECT(find_address_references(dcontext,arr+5, arr+8,
                            (app_pc)0x01020300, (app_pc)0x01020309),
           0);

    /* unreadable */
    EXPECT(find_address_references(dcontext, (app_pc)5, (app_pc)8,
                            (app_pc)0x01020300, (app_pc)0x01020309),
           0);

    /* all address space for code */
    EXPECT(find_address_references(dcontext,arr, arr+8,
                            (app_pc)0, (app_pc)-1),
           5); /* all match */

    EXPECT(find_address_references(dcontext,arr, arr+8,
                            (app_pc)0, (app_pc)-1),
           0); /* all duplicates of last search */

    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           5);


    arr[0]=4;
    arr[1]=3;
    arr[2]=2;
    arr[3]=1;

    arr[4+0]=4;                 /* duplicate entry */
    arr[4+1]=3;
    arr[4+2]=2;
    arr[4+3]=1;

    /* all address space for code */
    EXPECT(find_address_references(dcontext,arr, arr+8,
                            (app_pc)0, (app_pc)-1),
           4); /* all match but we have a duplicate */
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           4);

    EXPECT(find_address_references(dcontext,arr, arr+8,
                            (app_pc)0x01020300, (app_pc)0x01020305),
           1); /* two matches but with a duplicate */
    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           1);

    EXPECT(invalidate_ind_branch_target_range(dcontext, 0, (app_pc)-1),
           0);

    mutex_unlock(&rct_module_lock);

    return 1;
}
BOOLEAN GetFlowMatchFromArguments(_Inout_ OVS_FLOW_MATCH* pFlowMatch, _In_ const OVS_ARGUMENT_GROUP* pPIGroup, const OVS_ARGUMENT_GROUP* pPIMaskGroup)
{
    BOOLEAN encapIsValid = FALSE;
    BOOLEAN ok = TRUE;
    OVS_ARGUMENT* pEthTypeArg = NULL, *pEthAddrArg = NULL;
    OVS_PI_RANGE* pPiRange = NULL;
    OVS_OFPACKET_INFO* pPacketInfo = NULL;

    OVS_CHECK(pFlowMatch);

    if (!pFlowMatch)
    {
        return FALSE;
    }

    pEthTypeArg = FindArgument(pPIGroup, OVS_ARGTYPE_PI_ETH_TYPE);
#if OVS_VERSION == OVS_VERSION_1_11
    EXPECT(pEthAddrArg);
#endif

    pEthAddrArg = FindArgument(pPIGroup, OVS_ARGTYPE_PI_ETH_ADDRESS);
    EXPECT(pEthAddrArg);

    if (pEthTypeArg && RtlUshortByteSwap(OVS_ETHERTYPE_QTAG) == GET_ARG_DATA(pEthTypeArg, BE16))
    {
        if (!_PIFromArgs_HandleEncap(pPIGroup, pEthAddrArg, &encapIsValid))
        {
            return FALSE;
        }
    }

    pPiRange = &pFlowMatch->piRange;
    pPacketInfo = pFlowMatch->pPacketInfo;

    ok = GetPacketInfoFromArguments(pPacketInfo, pPiRange, pPIGroup, /*isMask*/ FALSE);
    if (!ok)
    {
        return FALSE;
    }

    if (!pPIMaskGroup)
    {
        if (pFlowMatch->pFlowMask)
        {
            UINT8* pStart = (UINT8*)&pFlowMatch->pFlowMask->packetInfo + pPiRange->startRange;
            UINT16 range = (UINT16)(pPiRange->endRange - pPiRange->startRange);

            pFlowMatch->pFlowMask->piRange = *pPiRange;
            memset(pStart, OVS_PI_MASK_MATCH_EXACT(UINT8), range);
        }
    }
    else
    {
        OVS_ARGUMENT* pEncapArg = NULL;

        pEncapArg = FindArgument(pPIMaskGroup, OVS_ARGTYPE_PI_ENCAP_GROUP);

        if (pEncapArg)
        {
            if (!encapIsValid)
            {
                DEBUGP(LOG_ERROR, "Tryed to set encapsulation to non-vlan frame!\n");
                return FALSE;
            }

            if (!pEthTypeArg || !_MasksFromArgs_HandleEncap(pPIMaskGroup, pEncapArg, pEthTypeArg))
            {
                return FALSE;
            }
        }

        OVS_CHECK(pFlowMatch->pFlowMask);
        pPiRange = &pFlowMatch->pFlowMask->piRange;
        pPacketInfo = &pFlowMatch->pFlowMask->packetInfo;

        ok = GetPacketInfoFromArguments(pPacketInfo, pPiRange, pPIMaskGroup, /*is mask*/TRUE);
        if (!ok)
        {
            return FALSE;
        }
    }

    //if the userspace gives us bad / unexpected args, we cannot simply deny the flow:
    //a) this might not be a bug (i.e. the userspace intends to set flows like this)
    //b) if it is a bug, we can do little in the kernel to help it.
#if __VERIFY_MASKS
    if (!_VerifyMasks(pFlowMatch, pPIGroup, pPIMaskGroup))
    {
        return FALSE;
    }
#endif

    return TRUE;
}
예제 #30
0
파일: mark_rts.c 프로젝트: GWRon/brl.mod-NG
  /* this function is called repeatedly by GC_register_map_entries.     */
  GC_INNER void GC_remove_roots_subregion(ptr_t b, ptr_t e)
  {
    int i;
    GC_bool rebuild = FALSE;

    GC_ASSERT(I_HOLD_LOCK());
    GC_ASSERT((word)b % sizeof(word) == 0 && (word)e % sizeof(word) == 0);
    for (i = 0; i < n_root_sets; i++) {
      ptr_t r_start, r_end;

      if (GC_static_roots[i].r_tmp) {
        /* The remaining roots are skipped as they are all temporary. */
#       ifdef GC_ASSERTIONS
          int j;
          for (j = i + 1; j < n_root_sets; j++) {
            GC_ASSERT(GC_static_roots[j].r_tmp);
          }
#       endif
        break;
      }
      r_start = GC_static_roots[i].r_start;
      r_end = GC_static_roots[i].r_end;
      if (!EXPECT((word)e <= (word)r_start || (word)r_end <= (word)b, TRUE)) {
#       ifdef DEBUG_ADD_DEL_ROOTS
          GC_log_printf("Removing %p .. %p from root section %d (%p .. %p)\n",
                        (void *)b, (void *)e,
                        i, (void *)r_start, (void *)r_end);
#       endif
        if ((word)r_start < (word)b) {
          GC_root_size -= r_end - b;
          GC_static_roots[i].r_end = b;
          /* No need to rebuild as hash does not use r_end value. */
          if ((word)e < (word)r_end) {
            int j;

            if (rebuild) {
              GC_rebuild_root_index();
              rebuild = FALSE;
            }
            GC_add_roots_inner(e, r_end, FALSE); /* updates n_root_sets */
            for (j = i + 1; j < n_root_sets; j++)
              if (GC_static_roots[j].r_tmp)
                break;
            if (j < n_root_sets-1 && !GC_static_roots[n_root_sets-1].r_tmp) {
              /* Exchange the roots to have all temporary ones at the end. */
              ptr_t tmp_r_start = GC_static_roots[j].r_start;
              ptr_t tmp_r_end = GC_static_roots[j].r_end;

              GC_static_roots[j].r_start =
                                GC_static_roots[n_root_sets-1].r_start;
              GC_static_roots[j].r_end = GC_static_roots[n_root_sets-1].r_end;
              GC_static_roots[j].r_tmp = FALSE;
              GC_static_roots[n_root_sets-1].r_start = tmp_r_start;
              GC_static_roots[n_root_sets-1].r_end = tmp_r_end;
              GC_static_roots[n_root_sets-1].r_tmp = TRUE;
              rebuild = TRUE;
            }
          }
        } else {
          if ((word)e < (word)r_end) {
            GC_root_size -= e - r_start;
            GC_static_roots[i].r_start = e;
          } else {
            GC_remove_root_at_pos(i);
            i--;
          }
          rebuild = TRUE;
        }
      }
    }
    if (rebuild)
      GC_rebuild_root_index();
  }