Beispiel #1
0
MYBOOL __WINAPI guess_basis(lprec *lp, REAL *guessvector, int *basisvector)
{
  MYBOOL status = FALSE;
  REAL   *values = NULL, *violation = NULL,
         *value, error, upB, loB, sortorder = 1.0;
  int    i, n, *rownr, *colnr;
  MATrec *mat = lp->matA;

  if(!mat_validate(lp->matA))
    return( status );

  /* Create helper arrays */
  if(!allocREAL(lp, &values, lp->sum+1, TRUE) ||
     !allocREAL(lp, &violation, lp->sum+1, TRUE))
    goto Finish;

  /* Compute values of slack variables for given guess vector */
  i = 0;
  n = get_nonzeros(lp);
  rownr = &COL_MAT_ROWNR(i);
  colnr = &COL_MAT_COLNR(i);
  value = &COL_MAT_VALUE(i);
  for(; i < n; i++, rownr += matRowColStep, colnr += matRowColStep, value += matValueStep)
    values[*rownr] += unscaled_mat(lp, my_chsign(is_chsign(lp, *rownr), *value), *rownr, *colnr) *
                      guessvector[*colnr];
  MEMMOVE(values+lp->rows+1, guessvector+1, lp->columns);

  /* Initialize constraint bound violation measures */
  for(i = 1; i <= lp->rows; i++) {
    upB = get_rh_upper(lp, i);
    loB = get_rh_lower(lp, i);
    error = values[i] - upB;
    if(error > lp->epsprimal)
      violation[i] = sortorder*error;
    else {
      error = loB - values[i];
      if(error > lp->epsprimal)
        violation[i] = sortorder*error;
      else if(is_infinite(lp, loB) && is_infinite(lp, upB))
        ;
      else if(is_infinite(lp, upB))
        violation[i] = sortorder*(loB - values[i]);
      else if(is_infinite(lp, loB))
        violation[i] = sortorder*(values[i] - upB);
      else
        violation[i] = - sortorder*MAX(upB - values[i], values[i] - loB);
    }
    basisvector[i] = i;
  }

  /* Initialize user variable bound violation measures */
  for(i = 1; i <= lp->columns; i++) {
    n = lp->rows+i;
    upB = get_upbo(lp, i);
    loB = get_lowbo(lp, i);
    error = guessvector[i] - upB;
    if(error > lp->epsprimal)
      violation[n] = sortorder*error;
    else {
      error = loB - values[n];
      if(error > lp->epsprimal)
        violation[n] = sortorder*error;
      else if(is_infinite(lp, loB) && is_infinite(lp, upB))
        ;
      else if(is_infinite(lp, upB))
        violation[n] = sortorder*(loB - values[n]);
      else if(is_infinite(lp, loB))
        violation[n] = sortorder*(values[n] - upB);
      else
        violation[n] = - sortorder*MAX(upB - values[n], values[n] - loB);
    }
    basisvector[n] = n;
  }

  /* Sort decending by violation; this means that variables with
     the largest violations will be designated as basic */
  sortByREAL(basisvector, violation, lp->sum, 1, FALSE);

  /* Adjust the non-basic indeces for the (proximal) bound state */
  error = lp->epsprimal;
  for(i = lp->rows+1, rownr = basisvector+i; i <= lp->sum; i++, rownr++) {
    if(*rownr <= lp->rows) {
      if(values[*rownr] <= get_rh_lower(lp, *rownr)+error)
        *rownr = -(*rownr);
    }
    else
      if(values[i] <= get_lowbo(lp, (*rownr)-lp->rows)+error)
        *rownr = -(*rownr);
  }

  /* Clean up and return status */
  status = (MYBOOL) (violation[1] == 0);
Finish:
  FREE(values);
  FREE(violation);


  return( status );
}
Beispiel #2
0
MYBOOL __WINAPI guess_basis(lprec *lp, REAL *guessvector, int *basisvector)
{
  MYBOOL *isnz, status = FALSE;
  REAL   *values = NULL, *violation = NULL,
         eps = lp->epsprimal,
         *value, error, upB, loB, sortorder = 1.0;
  int    i, j, jj, n, *rownr, *colnr, *slkpos,
         nrows = lp->rows, ncols = lp->columns;
  MATrec *mat = lp->matA;

  if(!mat_validate(mat))
    return( status );

  /* Create helper arrays */
  if(!allocREAL(lp, &values, lp->sum+1, TRUE) ||
     !allocREAL(lp, &violation, lp->sum+1, TRUE))
    goto Finish;

  /* Compute values of slack variables for given guess vector */
  i = 0;
  n = get_nonzeros(lp);
  rownr = &COL_MAT_ROWNR(i);
  colnr = &COL_MAT_COLNR(i);
  value = &COL_MAT_VALUE(i);
  for(; i < n; i++, rownr += matRowColStep, colnr += matRowColStep, value += matValueStep)
    values[*rownr] += unscaled_mat(lp, my_chsign(is_chsign(lp, *rownr), *value), *rownr, *colnr) *
                      guessvector[*colnr];
  MEMMOVE(values+nrows+1, guessvector+1, ncols);

  /* Initialize constraint bound violation measures (expressed as positive values) */
  for(i = 1; i <= nrows; i++) {
    upB = get_rh_upper(lp, i);
    loB = get_rh_lower(lp, i);
    error = values[i] - upB;
    if(error > -eps)
      violation[i] = sortorder*MAX(0,error);
    else {
      error = loB - values[i];
      if(error > -eps)
        violation[i] = sortorder*MAX(0,error);
      else if(my_infinite(lp, loB) && my_infinite(lp, upB))
        ;
      else if(my_infinite(lp, upB))
        violation[i] = sortorder*(loB - values[i]);
      else if(my_infinite(lp, loB))
        violation[i] = sortorder*(values[i] - upB);
      else
        violation[i] = -sortorder*MAX(upB - values[i], values[i] - loB);
    }
    basisvector[i] = i;
  }

  /* Initialize user variable bound violation measures (expressed as positive values) */
  for(i = 1; i <= ncols; i++) {
    n = nrows+i;
    upB = get_upbo(lp, i);
    loB = get_lowbo(lp, i);
    error = guessvector[i] - upB;
    if(error > -eps)
      violation[n] = sortorder*MAX(0,error);
    else {
      error = loB - values[n];
      if(error > -eps)
        violation[n] = sortorder*MAX(0,error);
      else if(my_infinite(lp, loB) && my_infinite(lp, upB))
        ;
      else if(my_infinite(lp, upB))
        violation[n] = sortorder*(loB - values[n]);
      else if(my_infinite(lp, loB))
        violation[n] = sortorder*(values[n] - upB);
      else
        violation[n] = -sortorder*MAX(upB - values[n], values[n] - loB);
    }
    basisvector[n] = n;
  }

  /* Sort decending by violation; this means that variables with
     the largest violations will be designated as basic */
  sortByREAL(basisvector, violation, lp->sum, 1, FALSE);
  error = violation[1];

  /* Adjust the non-basic indeces for the (proximal) bound state */
  for(i = nrows+1, rownr = basisvector+i; i <= lp->sum; i++, rownr++) {
    if(*rownr <= nrows) {
      values[*rownr] -= lp->orig_rhs[*rownr];
      if(values[*rownr] <= eps)
        *rownr = -(*rownr);
    }
    else
      if(values[i] <= get_lowbo(lp, (*rownr)-nrows)+eps)
        *rownr = -(*rownr);
  }

  /* Let us check for obvious row singularities and try to fix these;
     First assemble necessary basis statistics... */
  isnz = (MYBOOL *) values;
  MEMCLEAR(isnz, nrows+1);
  slkpos = (int *) violation;
  MEMCLEAR(slkpos, nrows+1);
  for(i = 1; i <= nrows; i++) {
    j = abs(basisvector[i]);
    if(j <= nrows) {
      isnz[j] = TRUE;
      slkpos[j] = i;
    }
    else {
      j-= nrows;
      jj = mat->col_end[j-1];
      isnz[COL_MAT_ROWNR(jj)] = TRUE;
/*      if(++jj < mat->col_end[j])
        isnz[COL_MAT_ROWNR(jj)] = TRUE; */
    }
  }
  for(; i <= lp->sum; i++) {
    j = abs(basisvector[i]);
    if(j <= nrows)
      slkpos[j] = i;
  }

  /* ...then set the corresponding slacks basic for row rank deficient positions */
  for(j = 1; j <= nrows; j++) {
#ifdef Paranoia
    if(slkpos[j] == 0)
      report(lp, SEVERE, "guess_basis: Internal error");
#endif
    if(!isnz[j]) {
      isnz[j] = TRUE;
      i = slkpos[j];
      swapINT(&basisvector[i], &basisvector[j]);
      basisvector[j] = abs(basisvector[j]);
    }
  }

  /* Lastly normalize all basic variables to be coded as lower-bounded */
  for(i = 1; i <= nrows; i++)
    basisvector[i] = -abs(basisvector[i]);

  /* Clean up and return status */
  status = (MYBOOL) (error <= eps);
Finish:
  FREE(values);
  FREE(violation);

  return( status );
}
Beispiel #3
0
/* ==================================================================
   lu7add  inserts the first nrank elements of the vector v(*)
   as column  jadd  of  U.  We assume that  U  does not yet have any
   entries in this column.
   Elements no larger than  parmlu(3)  are treated as zero.
   klast  will be set so that the last row to be affected
   (in pivotal order) is row  ip(klast).
   ------------------------------------------------------------------
   09 May 1988: First f77 version.
   ================================================================== */
void LU7ADD(LUSOLrec *LUSOL, int JADD, REAL V[], int LENL, int *LENU,
  int *LROW, int NRANK, int *INFORM, int *KLAST, REAL *VNORM)
{
  REAL SMALL;
  int  K, I, LENI, MINFRE, NFREE, LR1, LR2, L;
#ifndef LUSOLFastMove
  int J;
#endif

  SMALL = LUSOL->parmlu[LUSOL_RP_ZEROTOLERANCE];
  *VNORM = ZERO;
  *KLAST = 0;
  for(K = 1; K <= NRANK; K++) {
    I = LUSOL->ip[K];
    if(fabs(V[I])<=SMALL)
      continue;
    *KLAST = K;
    (*VNORM) += fabs(V[I]);
    LENI = LUSOL->lenr[I];
/*         Compress row file if necessary. */
    MINFRE = LENI+1;
    NFREE = LUSOL->lena - LENL - *LROW;
    if(NFREE<MINFRE) {
      LU1REC(LUSOL, LUSOL->m, TRUE,LROW,LUSOL->indr,LUSOL->lenr,LUSOL->locr);
      NFREE = LUSOL->lena - LENL - *LROW;
      if(NFREE<MINFRE)
        goto x970;
    }
/*         Move row  i  to the end of the row file,
           unless it is already there.
           No need to move if there is a gap already. */
    if(LENI==0)
      LUSOL->locr[I] = (*LROW) + 1;
    LR1 = LUSOL->locr[I];
    LR2 = (LR1+LENI)-1;
    if(LR2==*LROW)
      goto x150;
    if(LUSOL->indr[LR2+1]==0)
      goto x180;
    LUSOL->locr[I] = (*LROW) + 1;
#ifdef LUSOLFastMove
    L = LR2-LR1+1;
    if(L > 0) {
      LR2 = (*LROW)+1;
      MEMMOVE(LUSOL->a+LR2,    LUSOL->a+LR1, L);
      MEMMOVE(LUSOL->indr+LR2, LUSOL->indr+LR1, L);
      MEMCLEAR(LUSOL->indr+LR1, L);
      *LROW += L;
    }
#else
    for(L = LR1; L <= LR2; L++) {
      (*LROW)++;
      LUSOL->a[*LROW] = LUSOL->a[L];
      J = LUSOL->indr[L];
      LUSOL->indr[L] = 0;
      LUSOL->indr[*LROW] = J;
    }
#endif
x150:
    LR2 = *LROW;
    (*LROW)++;
/*         Add the element of  v. */
x180:
    LR2++;
    LUSOL->a[LR2] = V[I];
    LUSOL->indr[LR2] = JADD;
    LUSOL->lenr[I] = LENI+1;
    (*LENU)++;
  }
/*      Normal exit. */
  *INFORM = LUSOL_INFORM_LUSUCCESS;
  goto x990;
/*      Not enough storage. */
x970:
  *INFORM = LUSOL_INFORM_ANEEDMEM;
x990:
;
}
Beispiel #4
0
/* ==================================================================
   lu7for  (forward sweep) updates the LU factorization  A = L*U
   when row  iw = ip(klast)  of  U  is eliminated by a forward
   sweep of stabilized row operations, leaving  ip * U * iq  upper
   triangular.
   The row permutation  ip  is updated to preserve stability and/or
   sparsity.  The column permutation  iq  is not altered.
   kfirst  is such that row  ip(kfirst)  is the first row involved
   in eliminating row  iw.  (Hence,  kfirst  marks the first nonzero
   in row  iw  in pivotal order.)  If  kfirst  is unknown it may be
   input as  1.
   klast   is such that row  ip(klast)  is the row being eliminated.
   klast   is not altered.
   lu7for  should be called only if  kfirst .le. klast.
   If  kfirst = klast,  there are no nonzeros to eliminate, but the
   diagonal element of row  ip(klast)  may need to be moved to the
   front of the row.
   ------------------------------------------------------------------
   On entry,  locc(*)  must be zero.

   On exit:
   inform = 0  if row iw has a nonzero diagonal (could be small).
   inform = 1  if row iw has no diagonal.
   inform = 7  if there is not enough storage to finish the update.

   On a successful exit (inform le 1),  locc(*)  will again be zero.
   ------------------------------------------------------------------
      Jan 1985: Final f66 version.
   09 May 1988: First f77 version.
   ================================================================== */
void LU7FOR(LUSOLrec *LUSOL, int KFIRST, int KLAST, int *LENL, int *LENU,
                     int *LROW, int *INFORM, REAL *DIAG)
{
  MYBOOL SWAPPD;
  int    KBEGIN, IW, LENW, LW1, LW2, JFIRST, MINFRE, NFREE, L, J, KSTART, KSTOP, K,
         LFIRST, IV, LENV, LV1, JLAST, LV2, LV3, LV, JV, LW, LDIAG, LIMIT;
  REAL   AMULT, LTOL, USPACE, SMALL, VJ, WJ;

  LTOL   = LUSOL->parmlu[LUSOL_RP_UPDATEMAX_Lij];
  SMALL  = LUSOL->parmlu[LUSOL_RP_ZEROTOLERANCE];
  USPACE = LUSOL->parmlu[LUSOL_RP_COMPSPACE_U];
  KBEGIN = KFIRST;
  SWAPPD = FALSE;

/*      We come back here from below if a row interchange is performed. */
x100:
  IW = LUSOL->ip[KLAST];
  LENW = LUSOL->lenr[IW];
  if(LENW==0)
    goto x910;
  LW1 = LUSOL->locr[IW];
  LW2 = (LW1+LENW)-1;
  JFIRST = LUSOL->iq[KBEGIN];
  if(KBEGIN>=KLAST)
    goto x700;
/*      Make sure there is room at the end of the row file
        in case row  iw  is moved there and fills in completely. */
  MINFRE = LUSOL->n+1;
  NFREE = LUSOL->lena-(*LENL)-(*LROW);
  if(NFREE<MINFRE) {
    LU1REC(LUSOL, LUSOL->m,TRUE,LROW,LUSOL->indr,LUSOL->lenr,LUSOL->locr);
    LW1 = LUSOL->locr[IW];
    LW2 = (LW1+LENW)-1;
    NFREE = LUSOL->lena-(*LENL)-(*LROW);
    if(NFREE<MINFRE)
      goto x970;

  }
/*      Set markers on row  iw. */
  for(L = LW1; L <= LW2; L++) {
    J = LUSOL->indr[L];
    LUSOL->locc[J] = L;
  }
/*      ==================================================================
        Main elimination loop.
        ================================================================== */
  KSTART = KBEGIN;
  KSTOP = MIN(KLAST,LUSOL->n);
  for(K = KSTART; K <= KSTOP; K++) {
    JFIRST = LUSOL->iq[K];
    LFIRST = LUSOL->locc[JFIRST];
    if(LFIRST==0)
      goto x490;
/*         Row  iw  has its first element in column  jfirst. */
    WJ = LUSOL->a[LFIRST];
    if(K==KLAST)
      goto x490;
/*         ---------------------------------------------------------------
           We are about to use the first element of row  iv
                  to eliminate the first element of row  iw.
           However, we may wish to interchange the rows instead,
           to preserve stability and/or sparsity.
           --------------------------------------------------------------- */
    IV = LUSOL->ip[K];
    LENV = LUSOL->lenr[IV];
    LV1 = LUSOL->locr[IV];
    VJ = ZERO;
    if(LENV==0)
      goto x150;
    if(LUSOL->indr[LV1]!=JFIRST)
      goto x150;
    VJ = LUSOL->a[LV1];
    if(SWAPPD)
      goto x200;
    if(LTOL*fabs(WJ)<fabs(VJ))
      goto x200;
    if(LTOL*fabs(VJ)<fabs(WJ))
      goto x150;
    if(LENV<=LENW)
      goto x200;
/*         ---------------------------------------------------------------
           Interchange rows  iv  and  iw.
           --------------------------------------------------------------- */
x150:
    LUSOL->ip[KLAST] = IV;
    LUSOL->ip[K] = IW;
    KBEGIN = K;
    SWAPPD = TRUE;
    goto x600;
/*         ---------------------------------------------------------------
           Delete the eliminated element from row  iw
           by overwriting it with the last element.
           --------------------------------------------------------------- */
x200:
    LUSOL->a[LFIRST] = LUSOL->a[LW2];
    JLAST = LUSOL->indr[LW2];
    LUSOL->indr[LFIRST] = JLAST;
    LUSOL->indr[LW2] = 0;
    LUSOL->locc[JLAST] = LFIRST;
    LUSOL->locc[JFIRST] = 0;
    LENW--;
    (*LENU)--;
    if(*LROW==LW2)
      (*LROW)--;
    LW2 = LW2-1;
/*         ---------------------------------------------------------------
           Form the multiplier and store it in the  L  file.
           --------------------------------------------------------------- */
    if(fabs(WJ)<=SMALL)
      goto x490;
    AMULT = -WJ/VJ;
    L = LUSOL->lena-(*LENL);
    LUSOL->a[L] = AMULT;
    LUSOL->indr[L] = IV;
    LUSOL->indc[L] = IW;
    (*LENL)++;
/*         ---------------------------------------------------------------
           Add the appropriate multiple of row  iv  to row  iw.
           We use two different inner loops.  The first one is for the
           case where row  iw  is not at the end of storage.
           --------------------------------------------------------------- */
    if(LENV==1)
      goto x490;
    LV2 = LV1+1;
    LV3 = (LV1+LENV)-1;
    if(LW2==*LROW)
      goto x400;
/*         ...............................................................
           This inner loop will be interrupted only if
           fill-in occurs enough to bump into the next row.
           ............................................................... */
    for(LV = LV2; LV <= LV3; LV++) {
      JV = LUSOL->indr[LV];
      LW = LUSOL->locc[JV];
      if(LW>0) {
/*               No fill-in. */
        LUSOL->a[LW] += AMULT*LUSOL->a[LV];
        if(fabs(LUSOL->a[LW])<=SMALL) {
/*                  Delete small computed element. */
          LUSOL->a[LW] = LUSOL->a[LW2];
          J = LUSOL->indr[LW2];
          LUSOL->indr[LW] = J;
          LUSOL->indr[LW2] = 0;
          LUSOL->locc[J] = LW;
          LUSOL->locc[JV] = 0;
          (*LENU)--;
          LENW--;
          LW2--;
        }
      }
      else {
/*               Row  iw  doesn't have an element in column  jv  yet
                 so there is a fill-in. */
        if(LUSOL->indr[LW2+1]!=0)
          goto x360;
        (*LENU)++;
        LENW++;
        LW2++;
        LUSOL->a[LW2] = AMULT*LUSOL->a[LV];
        LUSOL->indr[LW2] = JV;
        LUSOL->locc[JV] = LW2;
      }
    }
    goto x490;
/*         Fill-in interrupted the previous loop.
           Move row  iw  to the end of the row file. */
x360:
    LV2 = LV;
    LUSOL->locr[IW] = (*LROW)+1;

#ifdef LUSOLFastMove
    L = LW2-LW1+1;
    if(L > 0) {
      int loci, *locp;
      for(loci = LW1, locp = LUSOL->indr+LW1;
          loci <= LW2; loci++, locp++) {
        (*LROW)++;
        LUSOL->locc[*locp] = *LROW;
      }
      LW2 = (*LROW)-L+1;
      MEMMOVE(LUSOL->a+LW2,    LUSOL->a+LW1, L);
      MEMMOVE(LUSOL->indr+LW2, LUSOL->indr+LW1, L);
      MEMCLEAR(LUSOL->indr+LW1, L);
    }
#else
    for(L = LW1; L <= LW2; L++) {
      (*LROW)++;
      LUSOL->a[*LROW] = LUSOL->a[L];
      J = LUSOL->indr[L];
      LUSOL->indr[L] = 0;
      LUSOL->indr[*LROW] = J;
      LUSOL->locc[J] = *LROW;
    }
#endif
    LW1 = LUSOL->locr[IW];
    LW2 = *LROW;
/*         ...............................................................
           Inner loop with row  iw  at the end of storage.
           ............................................................... */
x400:
    for(LV = LV2; LV <= LV3; LV++) {
      JV = LUSOL->indr[LV];
      LW = LUSOL->locc[JV];
      if(LW>0) {
/*               No fill-in. */
        LUSOL->a[LW] += AMULT*LUSOL->a[LV];
        if(fabs(LUSOL->a[LW])<=SMALL) {
/*                  Delete small computed element. */
          LUSOL->a[LW] = LUSOL->a[LW2];
          J = LUSOL->indr[LW2];
          LUSOL->indr[LW] = J;
          LUSOL->indr[LW2] = 0;
          LUSOL->locc[J] = LW;
          LUSOL->locc[JV] = 0;
          (*LENU)--;
          LENW--;
          LW2--;
        }
      }
      else {
/*               Row  iw  doesn't have an element in column  jv  yet
                 so there is a fill-in. */
        (*LENU)++;
        LENW++;
        LW2++;
        LUSOL->a[LW2] = AMULT*LUSOL->a[LV];
        LUSOL->indr[LW2] = JV;
        LUSOL->locc[JV] = LW2;
      }
    }
    *LROW = LW2;
/*         The  k-th  element of row  iw  has been processed.
           Reset  swappd  before looking at the next element. */
x490:
    SWAPPD = FALSE;
  }
/*      ==================================================================
        End of main elimination loop.
        ==================================================================

        Cancel markers on row  iw. */
x600:
  LUSOL->lenr[IW] = LENW;
  if(LENW==0)
    goto x910;
  for(L = LW1; L <= LW2; L++) {
    J = LUSOL->indr[L];
    LUSOL->locc[J] = 0;
  }
/*      Move the diagonal element to the front of row  iw.
        At this stage,  lenw gt 0  and  klast le n. */
x700:
  for(L = LW1; L <= LW2; L++) {
    LDIAG = L;
    if(LUSOL->indr[L]==JFIRST)
      goto x730;
  }
  goto x910;

x730:
  *DIAG = LUSOL->a[LDIAG];
  LUSOL->a[LDIAG] = LUSOL->a[LW1];
  LUSOL->a[LW1] = *DIAG;
  LUSOL->indr[LDIAG] = LUSOL->indr[LW1];
  LUSOL->indr[LW1] = JFIRST;
/*      If an interchange is needed, repeat from the beginning with the
        new row  iw,  knowing that the opposite interchange cannot occur. */
  if(SWAPPD)
    goto x100;
  *INFORM = LUSOL_INFORM_LUSUCCESS;
  goto x950;
/*      Singular. */
x910:
  *DIAG = ZERO;
  *INFORM = LUSOL_INFORM_LUSINGULAR;
/*      Force a compression if the file for  U  is much longer than the
        no. of nonzeros in  U  (i.e. if  lrow  is much bigger than  lenU).
        This should prevent memory fragmentation when there is far more
        memory than necessary  (i.e. when  lena  is huge). */
x950:
  LIMIT = (int) (USPACE*(*LENU))+LUSOL->m+LUSOL->n+1000;
  if(*LROW>LIMIT)
    LU1REC(LUSOL, LUSOL->m,TRUE,LROW,LUSOL->indr,LUSOL->lenr,LUSOL->locr);
  goto x990;
/*      Not enough storage. */
x970:
  *INFORM = LUSOL_INFORM_ANEEDMEM;
/*      Exit. */
x990:
;
}
Beispiel #5
0
/*
 * sscr_getprompt --
 *	Eat lines printed by the shell until a line with no trailing
 *	carriage return comes; set the prompt from that line.
 */
static int
sscr_getprompt(SCR *sp)
{
	struct timeval tv;
	CHAR_T *endp, *p, *t, buf[1024];
	SCRIPT *sc;
	fd_set fdset;
	db_recno_t lline;
	size_t llen, len;
	e_key_t value;
	int nr;

	FD_ZERO(&fdset);
	endp = buf;
	len = sizeof(buf);

	/* Wait up to a second for characters to read. */
	tv.tv_sec = 5;
	tv.tv_usec = 0;
	sc = sp->script;
	FD_SET(sc->sh_master, &fdset);
	switch (select(sc->sh_master + 1, &fdset, NULL, NULL, &tv)) {
	case -1:		/* Error or interrupt. */
		msgq(sp, M_SYSERR, "select");
		goto prompterr;
	case  0:		/* Timeout */
		msgq(sp, M_ERR, "Error: timed out");
		goto prompterr;
	case  1:		/* Characters to read. */
		break;
	}

	/* Read the characters. */
more:	len = sizeof(buf) - (endp - buf);
	switch (nr = read(sc->sh_master, endp, len)) {
	case  0:			/* EOF. */
		msgq(sp, M_ERR, "Error: shell: EOF");
		goto prompterr;
	case -1:			/* Error or interrupt. */
		msgq(sp, M_SYSERR, "shell");
		goto prompterr;
	default:
		endp += nr;
		break;
	}

	/* If any complete lines, push them into the file. */
	for (p = t = buf; p < endp; ++p) {
		value = KEY_VAL(sp, *p);
		if (value == K_CR || value == K_NL) {
			if (db_last(sp, &lline) ||
			    db_append(sp, 0, lline, t, p - t))
				goto prompterr;
			t = p + 1;
		}
	}
	if (p > buf) {
		MEMMOVE(buf, t, endp - t);
		endp = buf + (endp - t);
	}
	if (endp == buf)
		goto more;

	/* Wait up 1/10 of a second to make sure that we got it all. */
	tv.tv_sec = 0;
	tv.tv_usec = 100000;
	switch (select(sc->sh_master + 1, &fdset, NULL, NULL, &tv)) {
	case -1:		/* Error or interrupt. */
		msgq(sp, M_SYSERR, "select");
		goto prompterr;
	case  0:		/* Timeout */
		break;
	case  1:		/* Characters to read. */
		goto more;
	}

	/* Timed out, so theoretically we have a prompt. */
	llen = endp - buf;
	endp = buf;

	/* Append the line into the file. */
	if (db_last(sp, &lline) || db_append(sp, 0, lline, buf, llen)) {
prompterr:	sscr_end(sp);
		return (1);
	}

	return (sscr_setprompt(sp, buf, llen));
}
Beispiel #6
0
VoidMemBlock::VoidMemBlock(int _size, const void *data) {
  mem = NULL;
  size = 0;
  setSize(_size);
  if (data != NULL && size > 0) MEMMOVE(mem, data, size); // Using memmove because data might be in the middle of our buffer, who knows
}
Beispiel #7
0
/* xlgetkeyarg - get a keyword argument */
int xlgetkeyarg P2C(LVAL, key, LVAL *, pval)
{
#if 0
    LVAL *argv=xlargv;
    int argc=xlargc;
    for (argv = xlargv, argc = xlargc; (argc -= 2) >= 0; argv += 2) {
	if (*argv == key) {
	    *pval = *++argv;

	    /* delete the used argument */
	    if (argc>0) MEMMOVE(argv-1, argv+1, argc*sizeof(LVAL));
	    xlargc -=2;

	    return (TRUE);
	}
    }
    return (FALSE);
#else
    int argc = xlargc;
    int result = FALSE;
    int i, first;
    LVAL *argv = xlargv;

    /* First check if we have an even number of arguments remaining */
    if (( argc & 1 )) {
        xlfail( "keyword value missing" );
        return FALSE;
    }
    /*
     * Argument count is ok, now we traverse the remaining key-value-pairs to
     * search for the requested key. During the traversal, we move the
     * matching argument to the front of the remaining arguments, so used
     * arguments get popped off the stack only at the front, no entries are
     * overwritten. 
     * Tricky: keyword processing is specified to take only the leftmost
     * occurence of a key-value-pair in the argument list and ignore the
     * others - to allow the C-macro xllastarg to work correctly, we search
     * all remaining arguments and move the unused pairs to the front of the
     * remaining arguments but just behind the used one. This method allows the
     * function xlbaktrace to print a correct arguments during a backtrace as
     * no arguments are overwritten (this has been the case in the old
     * implementation above) but only their order gets changed. Remind: the
     * sorting is stable (the leftmost key od a duplicate remains the
     * leftmost).
     * FIXME:
     * Still untreated is the occurence of :allow_other_keys in the argument
     * list: xllastarg should be in closer contact with this function to do
     * the correct thing. However: I do not expect functions having so complex
     * argument-lists implemented in C, so the provided macros will work fine.
     * From: [email protected] (Wolfgang Kechel - Patzschke + Rasp GmbH)
     */
     for ( i = first = 0; i < argc; i += 2 ) {
         if ( argv[i] == key ) {
             if ( ! result ) {
                 *pval = xlargv[i+1];
                 result = TRUE;
             }
             if ( i != first ) {
                 LVAL temp[2];
                 int j;

                 temp[0] = argv[i];
                 temp[1] = argv[i+1];
                 for ( j = i+1; j > first; --j )
                     argv[j] = argv[j-2];
                 argv[first] = temp[0];
                 argv[first+1] = temp[1];
             }
             first += 2;
         }
     }
     xlargc -= first;
     xlargv += first;
     return result;
#endif
}
Beispiel #8
0
static inline VALUE
vm_call_method(rb_thread_t *th, rb_control_frame_t *cfp,
               int num, const rb_block_t *blockptr, VALUE flag,
               ID id, const rb_method_entry_t *me, VALUE recv)
{
    VALUE val;

start_method_dispatch:

    if (me != 0) {
        if ((me->flag == 0)) {
normal_method_dispatch:
            switch (me->def->type) {
            case VM_METHOD_TYPE_ISEQ: {
                vm_setup_method(th, cfp, recv, num, blockptr, flag, me);
                return Qundef;
            }
            case VM_METHOD_TYPE_NOTIMPLEMENTED:
            case VM_METHOD_TYPE_CFUNC: {
                val = vm_call_cfunc(th, cfp, num, recv, blockptr, me);
                break;
            }
            case VM_METHOD_TYPE_ATTRSET: {
                if (num != 1) {
                    rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", num);
                }
                val = rb_ivar_set(recv, me->def->body.attr.id, *(cfp->sp - 1));
                cfp->sp -= 2;
                break;
            }
            case VM_METHOD_TYPE_IVAR: {
                if (num != 0) {
                    rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", num);
                }
                val = rb_attr_get(recv, me->def->body.attr.id);
                cfp->sp -= 1;
                break;
            }
            case VM_METHOD_TYPE_MISSING: {
                VALUE *argv = ALLOCA_N(VALUE, num+1);
                argv[0] = ID2SYM(me->def->original_id);
                MEMCPY(argv+1, cfp->sp - num, VALUE, num);
                cfp->sp += - num - 1;
                val = rb_funcall2(recv, rb_intern("method_missing"), num+1, argv);
                break;
            }
            case VM_METHOD_TYPE_BMETHOD: {
                VALUE *argv = ALLOCA_N(VALUE, num);
                MEMCPY(argv, cfp->sp - num, VALUE, num);
                cfp->sp += - num - 1;
                val = vm_call_bmethod(th, recv, num, argv, blockptr, me);
                break;
            }
            case VM_METHOD_TYPE_ZSUPER: {
                VALUE klass = RCLASS_SUPER(me->klass);
                me = rb_method_entry(klass, id);

                if (me != 0) {
                    goto normal_method_dispatch;
                }
                else {
                    goto start_method_dispatch;
                }
            }
            case VM_METHOD_TYPE_OPTIMIZED: {
                switch (me->def->body.optimize_type) {
                case OPTIMIZED_METHOD_TYPE_SEND: {
                    rb_control_frame_t *reg_cfp = cfp;
                    rb_num_t i = num - 1;
                    VALUE sym;

                    if (num == 0) {
                        rb_raise(rb_eArgError, "no method name given");
                    }

                    sym = TOPN(i);
                    id = SYMBOL_P(sym) ? SYM2ID(sym) : rb_to_id(sym);
                    /* shift arguments */
                    if (i > 0) {
                        MEMMOVE(&TOPN(i), &TOPN(i-1), VALUE, i);
                    }
                    me = rb_method_entry(CLASS_OF(recv), id);
                    num -= 1;
                    DEC_SP(1);
                    flag |= VM_CALL_FCALL_BIT | VM_CALL_OPT_SEND_BIT;

                    goto start_method_dispatch;
                }
                case OPTIMIZED_METHOD_TYPE_CALL: {
                    rb_proc_t *proc;
                    int argc = num;
                    VALUE *argv = ALLOCA_N(VALUE, num);
                    GetProcPtr(recv, proc);
                    MEMCPY(argv, cfp->sp - num, VALUE, num);
                    cfp->sp -= num + 1;

                    val = rb_vm_invoke_proc(th, proc, proc->block.self, argc, argv, blockptr);
                    break;
                }
                default:
                    rb_bug("eval_invoke_method: unsupported optimized method type (%d)",
                           me->def->body.optimize_type);
                }
                break;
            }
            default: {
                rb_bug("eval_invoke_method: unsupported method type (%d)", me->def->type);
                break;
            }
            }
        }
        else {
            int noex_safe;

            if (!(flag & VM_CALL_FCALL_BIT) &&
                    (me->flag & NOEX_MASK) & NOEX_PRIVATE) {
                int stat = NOEX_PRIVATE;

                if (flag & VM_CALL_VCALL_BIT) {
                    stat |= NOEX_VCALL;
                }
                val = vm_method_missing(th, id, recv, num, blockptr, stat);
            }
            else if (!(flag & VM_CALL_OPT_SEND_BIT) && (me->flag & NOEX_MASK) & NOEX_PROTECTED) {
                VALUE defined_class = me->klass;

                if (RB_TYPE_P(defined_class, T_ICLASS)) {
                    defined_class = RBASIC(defined_class)->klass;
                }

                if (!rb_obj_is_kind_of(cfp->self, defined_class)) {
                    val = vm_method_missing(th, id, recv, num, blockptr, NOEX_PROTECTED);
                }
                else {
                    goto normal_method_dispatch;
                }
            }
            else if ((noex_safe = NOEX_SAFE(me->flag)) > th->safe_level &&
                     (noex_safe > 2)) {
                rb_raise(rb_eSecurityError, "calling insecure method: %s", rb_id2name(id));
            }
            else {
                goto normal_method_dispatch;
            }
        }
    }
    else {
        /* method missing */
        int stat = 0;
        if (flag & VM_CALL_VCALL_BIT) {
            stat |= NOEX_VCALL;
        }
        if (flag & VM_CALL_SUPER_BIT) {
            stat |= NOEX_SUPER;
        }
        if (id == idMethodMissing) {
            VALUE *argv = ALLOCA_N(VALUE, num);
            vm_method_missing_args(th, argv, num - 1, 0, stat);
            rb_raise_method_missing(th, num, argv, recv, stat);
        }
        else {
            val = vm_method_missing(th, id, recv, num, blockptr, stat);
        }
    }

    RUBY_VM_CHECK_INTS();
    return val;
}
Beispiel #9
0
integer ExeX()			/* execute an X command */
{
	ptrdiff_t TmpSiz;

	DBGFEN(1,"ExeX",NULL);
	if (EStTop == EStBot) {			/* if no numeric argument */
		NArgmt = 1;			/* default is 1X */
	} else {
		UMinus();			/* if it's -X, make it -1X */
		if (GetNmA() == FAILURE) {	/* get numeric argument */
			DBGFEX(1,DbgFNm,"FAILURE, GetNmA() failed");
			return FAILURE;
		}
	}


	if (IncCBP() == FAILURE) {		/* move to char after X */
		DBGFEX(1,DbgFNm,"FAILURE, IncCBP() failed");
		return FAILURE;
	}

	if (FindQR() == FAILURE) {		/* find q-register values */
		DBGFEX(1,DbgFNm,"FAILURE, FindQR() failed");
		return FAILURE;
	}

	if (!(CmdMod & COLON)) {		/* if no colon modifier */
		if (QR->Start != NULL) {	/* if text area not empty */
			ZFree((voidptr)QR->Start);/* free allocated memory */
			QR->Start = QR->End_P1 = NULL;
		}
	}

	if ((CmdMod & MARGIS) == '\0') {	/* if it's nXq (not m,nXq) */
		NArgmt = Ln2Chr(NArgmt);
		if (NArgmt > 0) {
			if (MakRom((size_t)NArgmt) == FAILURE) {
				DBGFEX(1,DbgFNm,"FAILURE, MakRom() failed");
				return FAILURE;
			}
			MEMMOVE(QR->End_P1, GapEnd+1, (size_t)NArgmt);
			QR->End_P1 += NArgmt;
		} else if (NArgmt < 0) {
			if (MakRom((size_t)-NArgmt) == FAILURE) {
				DBGFEX(1,DbgFNm,"FAILURE, MakRom() failed");
				return FAILURE;
			}
			MEMMOVE(QR->End_P1, GapBeg+NArgmt, (size_t)-NArgmt);
			QR->End_P1 -= NArgmt;
		}
	} else if (NArgmt != MArgmt) {		/* else (it's m,nXq) */
		MEMMOVE(ErrTxt, "m,nX", 5);
		if (GetAra() == FAILURE) {
			DBGFEX(1,DbgFNm,"FAILURE, GetAra() failed");
			return FAILURE;
		}
		if ((AraBeg < GapBeg) && (AraEnd > GapEnd)) {
			TmpSiz = (GapBeg-AraBeg) + (AraEnd-GapEnd);
			if (TmpSiz > 0) {
				if (MakRom((size_t)TmpSiz) == FAILURE) {
					DBGFEX(1,DbgFNm,"FAILURE, MakRom() failed");
					return FAILURE;
				}
				MEMMOVE(QR->End_P1,
					AraBeg,
					(size_t)(GapBeg - AraBeg));
				QR->End_P1 += GapBeg-AraBeg;
				MEMMOVE(QR->End_P1,
					GapEnd+1,
					(size_t)(AraEnd - GapEnd));
				QR->End_P1 += AraEnd-GapEnd;
			}
		} else {			/* else area is contiguous */
			TmpSiz = (AraEnd - AraBeg) + 1;
			if (TmpSiz > 0) {
				if (MakRom((size_t)TmpSiz) == FAILURE) {
					DBGFEX(1,DbgFNm,"FAILURE, MakRom() failed");
					return FAILURE;
				}
				MEMMOVE(QR->End_P1, AraBeg, (size_t)TmpSiz);
				QR->End_P1 += TmpSiz;
			}
		}
	}

	CmdMod = '\0';			/* clear modifiers flags */

	DBGFEX(1,DbgFNm,"SUCCESS");
	return SUCCESS;
}
Beispiel #10
0
INT32 insert_timer(TYPE_TIMER type,TIMER_SET_CONTENT  *t_insert, UINT32 pos)
{
	SYSTEM_DATA * sys_data = sys_data_get();
	TIMER_SET_CONTENT * tmp = NULL;
	UINT32 highpos =0;
	INT32 ret=0;
	
	date_time insert,other;
	
	insert.year = t_insert->wakeup_year;
	insert.month = t_insert->wakeup_month;
	insert.day = t_insert->wakeup_day;

	
	
	if(type == TIMER_TYPE_EPG)
	{
		tmp= &sys_data->timer_set.TimerContent[0];
		highpos = MAX_EPG_TIMER_NUM;
	}
	else if(type ==TIMER_TYPE_NVOD)
	{
		tmp= &sys_data->timer_set.TimerContent[32];
		highpos = MAX_NVOD_TIMER_NUM;
	}

	UINT32 idx = 0;
	
	if(pos>=highpos)
	{
		show_pop_up_info(RS_BOOK_FULL);
		return !SUCCESS;
	}

	for(idx =0; idx<pos;idx++)
	{
		other.year = tmp[idx].wakeup_year;
		other.month = tmp[idx].wakeup_month;
		other.day = tmp[idx].wakeup_day;
		
		ret = api_compare_day(&other,&insert);

		if(ret > 0)
			break;
		else if(ret ==0)
		{
			if(t_insert->wakeup_time < tmp[idx].wakeup_time)
				break;	
		}
	}
	
	if(idx==pos)
	{
		MEMCPY(&tmp[pos],t_insert,sizeof(TIMER_SET_CONTENT));
		return SUCCESS;
	}
	else
	{
		MEMMOVE(&tmp[idx+1],&tmp[idx],((UINT32)&tmp[pos]-(UINT32)&tmp[idx]));
		MEMCPY(&tmp[idx],t_insert,sizeof(TIMER_SET_CONTENT));
		return SUCCESS;
	}
}
Beispiel #11
0
/**
 * @brief This function builds an openSAFETY frame and provides it to the HNF, which is in charge of transmission.
 *
 * The calling function has to request the memory block by using {SFS_GetMemBlock()}. The memory block has
 * to be of size of the complete openSAFETY frame and data to be transmitted is stored at the place inside the
 * memory block where payload data of sub frame one is located. The memory block is provided by reference
 * to this function. The calling function also has to provide the header info by reference. The data structure
 * must be of type EPLS_t_FRM_HDR and assembles all necessary header info to build the openSAFETY frame.
 * All frame header info is checked before is is put into the right order and stored into sub frame one and two.
 * Frame data, already stored in sub frame one, is copied into sub frame two. To pass the openSAFETY frame to the
 * SHNF and so transmitting it the function SHNF_MarkTxMemBlock() is used.
 *
 * @see          EPLS_t_FRM_HDR
 *
 * @param        b_instNum         instance number (not checked, called with EPLS_k_SCM_INST_NUM or checked in
 *                    SSC_ProcessSNMTSSDOFrame() or SPDO_BuildTxSpdo())) valid range: 0 .. &lt;EPLS_cfg_MAX_INSTANCES&gt; - 1
 *
 * @param        ps_hdrInfo        reference to header info, stored into an internal data structure (not checked,
 *                    only called with reference to struct), valid range: <> NULL
 *
 * @param        pb_frame          reference to an openSAFETY frame (payload data is already stored in sub frame ONE).
 *                    Reference is provided by function SFS_GetMemBlock() (not checked, checked in transmitRequest()
 *                    or SNMTM_SnErrorAck() or SNMTS_TxRespRstGuardScm() or SendTxSpdo() processStateSer() or
 *                    reqBufferSend()), valid range: <> NULL
 *
 * @return
 * - TRUE            - openSAFETY frame serialized and passed to the SHNF successfully
 * - FALSE           - error during marking the memory block openSAFETY frame passing failed
 */
BOOLEAN SFS_FrmSerialize(BYTE_B_INSTNUM_ const EPLS_t_FRM_HDR *ps_hdrInfo,
                         UINT8 *pb_frame)
{
    BOOLEAN o_return = FALSE;     /* predefined return value */
    UINT8 b_subFrm1Id = 0u;       /* variable to build the value of the ID field
                                   in sub frame 1 */
    UINT8 b_subFrm2Id = 0u;       /* variable to build the value of the ID field
                                   in sub frame 2 */
    UINT8 b_subFrm2Adr = 0u;      /* variable to build the value of ADR field */
    UINT8 b_subFrm2Tr = 0u;       /* variable to build the value of TR field */

    UINT8 b_calcCrc1Short = 0u;   /* calculated 8 bit CRC, provided by SHNF */
    UINT8 b_calcCrc2Short = 0u;   /* calculated 8 bit CRC, provided by SHNF */
    UINT16 w_calcCrc1Long = 0u;   /* calculated 16 bit CRC, provided by SHNF */
    UINT16 w_calcCrc2Long = 0u;   /* calculated 16 bit CRC, provided by SHNF */

    UINT16 w_subFrm1Len = 0u;     /* number of bytes of sub frame ONE */
    UINT16 w_subFrm2Len = 0u;     /* number of bytes of sub frame ONE */
    UINT8 *pb_subFrm1Crc = 0u;    /* pointer to CRC in sub frame ONE */
    UINT8 *pb_subFrm2Crc = 0u;    /* pointer to CRC in sub frame TWO */

    /* reference to sub frame ONE within received openSAFETY frame
       NOTE:
       sub frame ONE and TWO are twisted within the openSAFETY frame in tx dir. !!! */
    UINT8 *pb_subFrm1 = (UINT8 *)NULL;


    /* if the header info provided by the calling function is correct */
    if(checkTxFrameHeader(B_INSTNUM_ ps_hdrInfo))
    {
        /* Build 8 bit value of openSAFETY frame ID field in sub frame ONE */
        b_subFrm1Id = ps_hdrInfo->b_id;                            /* 00XX|XXXX */
        b_subFrm1Id = (UINT8)(b_subFrm1Id << 2u);                  /* XXXX|XX00 */
        b_subFrm1Id = (UINT8)(b_subFrm1Id |
                              (HIGH8(ps_hdrInfo->w_adr) & k_ADR_MASK_AND)); /* XXXX|XXYY */

        /* Build 8 bit value of openSAFETY frame ADR field in sub frame TWO */
        b_subFrm2Adr = LOW8(ps_hdrInfo->w_adr);
        b_subFrm2Adr = (UINT8)(b_subFrm2Adr ^ LOW8(ps_hdrInfo->w_sdn));

        /* Build 8 bit value of openSAFETY frame ID field in sub frame TWO,
        *     ID field = 6bit frame ID, ((2bit sadr) XOR (2bit domain number))
        *
        *       HIGH8(w_sdn) : SSSS|SSZZ
        * AND  k_ID_MASK_AND : 0000|0011
        * -------------------> 0000|00ZZ
        * XOR    b_subFrm1Id : XXXX|XXYY
        * -------------------> XXXX|XXQQ   ( Q = Y xor Z )
        */
        b_subFrm2Id  = (UINT8)(b_subFrm1Id ^
                               (HIGH8(ps_hdrInfo->w_sdn) & k_SDN_HB_MASK_AND));

        /* Build 8 bit value of openSAFETY frame TR field in sub frame TWO */
        b_subFrm2Tr = ps_hdrInfo->b_tr;                            /* 00XX|XXXX */
        b_subFrm2Tr = (UINT8)(b_subFrm2Tr << 2u);                  /* XXXX|XX00 */
        b_subFrm2Tr = (UINT8)(b_subFrm2Tr | (HIGH8(ps_hdrInfo->w_tadr)
                                             & k_TADR_MASK_AND));                        /* XXXX|XXYY */

        /* check if payload data is doubled */
        if ( k_SERVICE_REQ_FAST == (ps_hdrInfo->b_id & k_SERVICE_REQ_FAST))
        {
            /* no double payload data */
            /* if payload data length is larger than 8 bytes, 2 byte CRC is used */
            if(ps_hdrInfo->b_le > k_MAX_DATA_LEN_SHORT)
            {
                /* calculate reference to start of sub frame ONE header (2 byte CRC)
                    NOTE: sub frame ONE and TWO are twisted within the openSAFETY frame in
                          tx dir. !!! */
                pb_subFrm1 =
                    &pb_frame[(k_SFRM2_HDR_LEN + k_CRC_LEN_LONG)];
            }
            else  /* payload data length is 8 byte or less and 1 byte CRC is used */
            {
                /* calculate reference to start of sub frame ONE header (1 byte CRC)
                    NOTE: sub frame ONE and TWO are twisted within the openSAFETY frame in
                          tx dir. !!! */
                pb_subFrm1 =
                    &pb_frame[(k_SFRM2_HDR_LEN + k_CRC_LEN_SHORT)];
            }
            /* calculate length of sub frames and
                calculate reference to CRC field of sub frames TWO and sub frame ONE */
            w_subFrm1Len  = (UINT16)(k_SFRM1_HDR_LEN + ps_hdrInfo->b_le);
            w_subFrm2Len  = (UINT16)(k_SFRM2_HDR_LEN);

            pb_subFrm1Crc = &pb_subFrm1[k_SFRM1_DATA + ps_hdrInfo->b_le];
            pb_subFrm2Crc = &pb_frame[k_SFRM2_DATA];
        }
        else
        {
            /* if payload data length is larger than 8 bytes, 2 byte CRC is used */
            if(ps_hdrInfo->b_le > k_MAX_DATA_LEN_SHORT)
            {
                /* calculate reference to start of sub frame ONE header (2 byte CRC)
                    NOTE: sub frame ONE and TWO are twisted within the openSAFETY frame in
                          tx dir. !!! */
                pb_subFrm1 =
                    &pb_frame[(k_SFRM2_HDR_LEN + ps_hdrInfo->b_le + k_CRC_LEN_LONG)];
            }
            else  /* payload data length is 8 byte or less and 1 byte CRC is used */
            {
                /* calculate reference to start of sub frame ONE header (1 byte CRC)
                    NOTE: sub frame ONE and TWO are twisted within the openSAFETY frame in
                          tx dir. !!! */
                pb_subFrm1 =
                    &pb_frame[(k_SFRM2_HDR_LEN + ps_hdrInfo->b_le + k_CRC_LEN_SHORT)];
            }
            /* calculate length of sub frames and
                calculate reference to CRC field of sub frames TWO and sub frame ONE */
            w_subFrm1Len  = (UINT16)(k_SFRM1_HDR_LEN + ps_hdrInfo->b_le);
            w_subFrm2Len  = (UINT16)(k_SFRM2_HDR_LEN + ps_hdrInfo->b_le);

            pb_subFrm1Crc = &pb_subFrm1[k_SFRM1_DATA + ps_hdrInfo->b_le];
            pb_subFrm2Crc = &pb_frame[k_SFRM2_DATA + ps_hdrInfo->b_le];
        }

        /* copy payload data from sub frame TWO into sub frame ONE */
        /*lint -save -e119 -e746 -i830: the prototype is not really missing but there is a problem with the
         * standard lib*/
        (void)MEMMOVE(&pb_subFrm1[k_SFRM1_DATA], &pb_frame[k_SFRM2_DATA],
                      (UINT32)ps_hdrInfo->b_le);
        /*lint -restore */

        /* fill header bytes and data bytes of sub frame ONE into the memory
            block of serialized openSAFETY frame. */
        SFS_NET_CPY8(&(pb_subFrm1[k_SFRM1_HDR_ADR]),&LOW8(ps_hdrInfo->w_adr));
        SFS_NET_CPY8(&(pb_subFrm1[k_SFRM1_HDR_ID]), &b_subFrm1Id);
        SFS_NET_CPY8(&(pb_subFrm1[k_SFRM1_HDR_LE]), &ps_hdrInfo->b_le);
        SFS_NET_CPY8(&(pb_subFrm1[k_SFRM1_HDR_CT]), &LOW8(ps_hdrInfo->w_ct));

        /* fill header bytes and data bytes of sub frame TWO into the memory
            block of serialized openSAFETY frame. */
        SFS_NET_CPY8(&(pb_frame[k_SFRM2_HDR_ADR]), &b_subFrm2Adr);
        SFS_NET_CPY8(&(pb_frame[k_SFRM2_HDR_ID]), &b_subFrm2Id);
        SFS_NET_CPY8(&(pb_frame[k_SFRM2_HDR_CT]), &(HIGH8(ps_hdrInfo->w_ct)));
        SFS_NET_CPY8(&(pb_frame[k_SFRM2_HDR_TADR]), &(LOW8(ps_hdrInfo->w_tadr)));
        SFS_NET_CPY8(&(pb_frame[k_SFRM2_HDR_TR]), &b_subFrm2Tr);

        /* NOTE: payload data is already written into sub frame TWO
            by the calling function and for special frame types already overwritten */


        /* if payload data length is larger than 8 bytes */
        if(ps_hdrInfo->b_le > k_MAX_DATA_LEN_SHORT)
        {
            if ( k_SERVICE_REQ_FAST == (ps_hdrInfo->b_id & k_SERVICE_REQ_FAST))
            {
                /* get 16 bit CRC as reference for sub frame TWO/ONE from unit SHNF */
                w_calcCrc1Long = SHNF_Crc16CalcSlim(0U, (INT32)w_subFrm1Len,
                                                    (void *)pb_subFrm1);
                w_calcCrc2Long = SHNF_Crc16CalcSlim(0U, (INT32)w_subFrm2Len,
                                                    (void *)pb_frame);
            }
            else
            {
                /* get 16 bit CRC as reference for sub frame TWO/ONE from unit SHNF */
                w_calcCrc1Long = SHNF_Crc16Calc(0U, (INT32)w_subFrm1Len,
                                                (void *)pb_subFrm1);
                w_calcCrc2Long = SHNF_Crc16Calc(0U, (INT32)w_subFrm2Len,
                                                (void *)pb_frame);
            }

            SFS_NET_CPY16(pb_subFrm1Crc, &w_calcCrc1Long);
            SFS_NET_CPY16(pb_subFrm2Crc, &w_calcCrc2Long);
        }
        else  /* payload data length is 8 byte or less */
        {
            /* get 8 bit CRC as reference for sub frame TWO/ONE from unit SHNF */
            b_calcCrc1Short = SHNF_Crc8Calc(0U, (INT32)w_subFrm1Len,
                                            (void *)pb_subFrm1);
            b_calcCrc2Short = SHNF_Crc8Calc(0U, (INT32)w_subFrm2Len,
                                            (void *)pb_frame);
            SFS_NET_CPY8(pb_subFrm1Crc, &b_calcCrc1Short);
            SFS_NET_CPY8(pb_subFrm2Crc, &b_calcCrc2Short);
        }

        /* the UDID of the SCM encoding */
        SFS_ScmUdidCode(B_INSTNUM_ ps_hdrInfo->b_id, pb_frame);

        /* if openSAFETY frame cannot be passed to SHNF */
        if(!(SHNF_MarkTxMemBlock(B_INSTNUM_ pb_frame)))
        {
            /* error: SHNF cannot mark openSAFETY frame as "ready to process" */
            SERR_SetError(B_INSTNUM_ SFS_k_ERR_SHNF_CANNOT_MARK_MEM_BLK,
                          SERR_k_NO_ADD_INFO);
        }
        else  /* openSAFETY frame processed successfully from SHNF */
        {
            o_return = TRUE;
        }
    }
    /* else the header info provided by the calling function is incorrect */
    SCFM_TACK_PATH();
    return o_return;
}
Beispiel #12
0
int
arp_flood (void * pio)
{
   PACKET arppkt;
   struct ethhdr *   ethhdr;
   struct arp_hdr *  arphdr;
   NET net;
   long  i;
   int   e;
   ip_addr ipaddr;

#ifdef MULTI_HOMED
   ip_addr phost;    /* phoney host for pass to iproute */
   net = iproute(activehost, &phost);
#else
   net = nets[0];
#endif

   if (!net)
   {
      ns_printf(pio, "ARP flood: no route");
      return -1;
   }

   ns_printf(pio, "sending ARP flood of %ld pkts to %u.%u.%u.%u..", 
    pktcount, PUSH_IPADDR(activehost) );


   for (i = 0; i < pktcount; i++)
   {
      if (pktwait("ARP", pio))
         return -1;

      /******** code cribbed from et_arp.c: ********/
      LOCK_NET_RESOURCE(FREEQ_RESID);
      arppkt = pk_alloc(arpsize);
      UNLOCK_NET_RESOURCE(FREEQ_RESID);
      if (!arppkt)
         return ENP_RESOURCE;
      arppkt->nb_prot = arppkt->nb_buff;
      arppkt->nb_plen = arpsize;
      arppkt->net = net;

      /* build arp request packet */
      ethhdr = (struct ethhdr *)(arppkt->nb_buff + ETHHDR_BIAS);     /* ethernet header at start of buffer */
      arphdr = (struct arp_hdr *)(arppkt->nb_buff + ETHHDR_SIZE); /* arp header follows */
      arphdr->ar_hd = ARPHW;     /* net endian arp hardware type (ethernet) */
      arphdr->ar_pro = ARPIP;
      arphdr->ar_hln = 6;
      arphdr->ar_pln = 4;
      arphdr->ar_op = ARREQ;
      arphdr->ar_tpa = activehost;        /* target's IP address */

      /* FLOOD TEST MOD: just for grins, rotate our IP address so we 
       * flood everybody's arp tables. Remember that we store IP 
       * addresses 
       */
      ipaddr = i & (0x00FFFFFE & htonl(~net->snmask));   /* make host portion */
      arphdr->ar_spa = (net->n_ipaddr | htonl(ipaddr));  /* add net portion */

      MEMCPY(arphdr->ar_sha, net->n_mib->ifPhysAddress, 6);
      MEMSET(&(ethhdr->e_dst[0]), 0xFF, 6);     /* destination to broadcast (all FFs) */
      MEMCPY(ethhdr->e_src, net->n_mib->ifPhysAddress, 6);
      ethhdr->e_type = ET_ARP;   /* 0x0806 - ARP type on ethernet */

#ifdef NO_CC_PACKING    /* move ARP fields to proper network boundaries */
      {
         struct arp_wire * arwp  =  (struct  arp_wire *)arphdr;
         MEMMOVE(&arwp->data[AR_SHA], arphdr->ar_sha, 6);
         MEMMOVE(&arwp->data[AR_SPA], &arphdr->ar_spa, 4);
         MEMMOVE(&arwp->data[AR_THA], arphdr->ar_tha, 6);
         MEMMOVE(&arwp->data[AR_TPA], &arphdr->ar_tpa, 4);
      }
#endif   /* NO_CC_PACKING */

      /* send arp request - if a packet oriented send exists, use it: */
      if (net->pkt_send)
         e = net->pkt_send(arppkt);    /* driver should free arppkt later */
      else  /* use old raw send */
      {
         e = net->raw_send(arppkt->net, arppkt->nb_buff, arpsize);
         LOCK_NET_RESOURCE(FREEQ_RESID);
         pk_free(arppkt);
         UNLOCK_NET_RESOURCE(FREEQ_RESID);
      }

      arpReqsOut++;
      /******** end of code cribbed from et_arp.c: ********/

      if (e < 0)
      {
         ns_printf(pio, "ARP flood send error %d on pkt %ld\n",e,i);
         return -1;
      }
      if ((i & 0x0f) == 0x0f)
         ns_printf(pio, ".");
   }

   return 0;
}
Beispiel #13
0
/*
 * sscr_insert --
 *	Take a line from the shell and insert it into the file.
 */
static int
sscr_insert(SCR *sp)
{
	struct timeval tv;
	CHAR_T *endp, *p, *t;
	SCRIPT *sc;
	fd_set rdfd;
	db_recno_t lno;
	size_t blen, len = 0, tlen;
	e_key_t value;
	int nr, rval;
	CHAR_T *bp;

	/* Find out where the end of the file is. */
	if (db_last(sp, &lno))
		return (1);

#define	MINREAD	1024
	GET_SPACE_RETW(sp, bp, blen, MINREAD);
	endp = bp;

	/* Read the characters. */
	rval = 1;
	sc = sp->script;
more:	switch (nr = read(sc->sh_master, endp, MINREAD)) {
	case  0:			/* EOF; shell just exited. */
		sscr_end(sp);
		rval = 0;
		goto ret;
	case -1:			/* Error or interrupt. */
		msgq(sp, M_SYSERR, "shell");
		goto ret;
	default:
		endp += nr;
		break;
	}

	/* Append the lines into the file. */
	for (p = t = bp; p < endp; ++p) {
		value = KEY_VAL(sp, *p);
		if (value == K_CR || value == K_NL) {
			len = p - t;
			if (db_append(sp, 1, lno++, t, len))
				goto ret;
			t = p + 1;
		}
	}
	if (p > t) {
		len = p - t;
		/*
		 * If the last thing from the shell isn't another prompt, wait
		 * up to 1/10 of a second for more stuff to show up, so that
		 * we don't break the output into two separate lines.  Don't
		 * want to hang indefinitely because some program is hanging,
		 * confused the shell, or whatever.
		 */
		if (!sscr_matchprompt(sp, t, len, &tlen) || tlen != 0) {
			tv.tv_sec = 0;
			tv.tv_usec = 100000;
			FD_ZERO(&rdfd);
			FD_SET(sc->sh_master, &rdfd);
			if (select(sc->sh_master + 1,
			    &rdfd, NULL, NULL, &tv) == 1) {
				MEMMOVE(bp, t, len);
				endp = bp + len;
				goto more;
			}
		}
		if (sscr_setprompt(sp, t, len))
			return (1);
		if (db_append(sp, 1, lno++, t, len))
			goto ret;
	}

	/* The cursor moves to EOF. */
	sp->lno = lno;
	sp->cno = len ? len - 1 : 0;
	rval = vs_refresh(sp, 1);

ret:	FREE_SPACEW(sp, bp, blen);
	return (rval);
}
Beispiel #14
0
MYBOOL __WINAPI guess_basis(lprec *lp, REAL *guessvector, int *basisvector)
{
  MYBOOL *isnz = NULL, status = FALSE;
  REAL   *values = NULL, *violation = NULL,
         eps = lp->epsprimal,
         *value, error, upB, loB, sortorder = -1.0;
  int    i, j, jj, n, *rownr, *colnr, *slkpos = NULL,
         nrows = lp->rows, ncols = lp->columns, nsum = lp->sum;
  int    *basisnr;
  MATrec *mat = lp->matA;

  if(!mat_validate(mat))
    return( status );

  /* Create helper arrays, providing for multiple use of the violation array */
  if(!allocREAL(lp, &values, nsum+1, TRUE) ||
     !allocREAL(lp, &violation, nsum+1, TRUE))
    goto Finish;

  /* Compute the values of the constraints for the given guess vector */
  i = 0;
  n = get_nonzeros(lp);
  rownr = &COL_MAT_ROWNR(i);
  colnr = &COL_MAT_COLNR(i);
  value = &COL_MAT_VALUE(i);
  for(; i < n; i++, rownr += matRowColStep, colnr += matRowColStep, value += matValueStep)
    values[*rownr] += unscaled_mat(lp, my_chsign(is_chsign(lp, *rownr), *value), *rownr, *colnr) *
                      guessvector[*colnr];
  MEMMOVE(values+nrows+1, guessvector+1, ncols);

  /* Initialize bound "violation" or primal non-degeneracy measures, expressed
     as the absolute value of the differences from the closest bound. */
  for(i = 1; i <= nsum; i++) {
    if(i <= nrows) {
      loB = get_rh_lower(lp, i);
      upB = get_rh_upper(lp, i);
    }
    else {
      loB = get_lowbo(lp, i-nrows);
      upB = get_upbo(lp, i-nrows);
    }

    /* Free constraints/variables */
    if(my_infinite(lp, loB) && my_infinite(lp, upB))
      error = 0;
    /* Violated constraints/variable bounds */
    else if(values[i]+eps < loB)
      error = loB-values[i];
    else if(values[i]-eps > upB)
      error = values[i]-upB;
    /* Non-violated constraints/variables bounds */
    else if(my_infinite(lp, upB))
      error = MAX(0, values[i]-loB);
    else if(my_infinite(lp, loB))
      error = MAX(0, upB-values[i]);
    else
      error = MIN(upB-values[i], values[i]-loB); /* MAX(upB-values[i], values[i]-loB); */
    if(error != 0)
      violation[i] = sortorder*error;
    basisvector[i] = i;
  }

  /* Sort decending , meaning that variables with the largest
     "violations" will be designated basic. Effectively, we are performing a
     greedy type algorithm, but start at the "least interesting" end. */
  sortByREAL(basisvector, violation, nsum, 1, FALSE);
  error = violation[1]; /* Used for setting the return value */

  /* Let us check for obvious row singularities and try to fix these.
     Note that we reuse the memory allocated to the violation array.
     First assemble necessary basis statistics... */
  slkpos = (int *) violation;
  n = nrows+1;
  MEMCLEAR(slkpos, n);
  isnz = (MYBOOL *) (slkpos+n+1);
  MEMCLEAR(isnz, n);
  for(i = 1; i <= nrows; i++) {
    j = abs(basisvector[i]);
    if(j <= nrows) {
      isnz[j] = TRUE;
      slkpos[j] = i;
    }
    else {
      j-= nrows;
      jj = mat->col_end[j-1];
      jj = COL_MAT_ROWNR(jj);
      isnz[jj] = TRUE;
    }
  }
  for(; i <= nsum; i++) {
    j = abs(basisvector[i]);
    if(j <= nrows)
      slkpos[j] = i;
  }

  /* ...then set the corresponding slacks basic for row rank deficient positions */
  for(j = 1; j <= nrows; j++) {
    if(slkpos[j] == 0)
      report(lp, SEVERE, "guess_basis: Internal error");
    if(!isnz[j]) {
      isnz[j] = TRUE;
      i = slkpos[j];
      swapINT(&basisvector[i], &basisvector[j]);
      basisvector[j] = abs(basisvector[j]);
    }
  }

  /* Adjust the non-basic indeces for the (proximal) bound state */
  for(i = nrows+1, basisnr = basisvector+i; i <= nsum; i++, basisnr++) {
    n = *basisnr;
    if(n <= nrows) {
      values[n] -= get_rh_lower(lp, n);
      if(values[n] <= eps)
        *basisnr = -(*basisnr);
    }
    else
      if(values[n]-eps <= get_lowbo(lp, n-nrows))
        *basisnr = -(*basisnr);
  }

/* Lastly normalize all basic variables to be coded as lower-bounded,
   or effectively zero-based in the case of free variables. */
  for(i = 1; i <= nrows; i++)
    basisvector[i] = -abs(basisvector[i]);

  /* Clean up and return status */
  status = (MYBOOL) (error <= eps);
Finish:
  FREE(values);
  FREE(violation);

  return( status );
}
Beispiel #15
0
/* EXTPROTO */
void           *
memcpy(void *s1, const void *s2, size_t len)
{
    /* has extra stack and time but less code space */
    return MEMMOVE(s1, s2, len);
}
Beispiel #16
0
/*
 * v_increment -- [count]#[#+-]
 *	Increment/decrement a keyword number.
 *
 * PUBLIC: int v_increment __P((SCR *, VICMD *));
 */
int
v_increment(SCR *sp, VICMD *vp)
{
	enum nresult nret;
	u_long ulval;
	long change, ltmp, lval;
	size_t beg, blen, end, len, nlen, wlen;
	int base, isempty, rval;
	CHAR_T *ntype, nbuf[100];
	CHAR_T *bp, *p, *t;

	/* Validate the operator. */
	if (vp->character == '#')
		vp->character = '+';
	if (vp->character != '+' && vp->character != '-') {
		v_emsg(sp, vp->kp->usage, VIM_USAGE);
		return (1);
	}

	/* If new value set, save it off, but it has to fit in a long. */
	if (F_ISSET(vp, VC_C1SET)) {
		if (vp->count > LONG_MAX) {
			inc_err(sp, NUM_OVER);
			return (1);
		}
		change = vp->count;
	} else
		change = 1;

	/* Get the line. */
	if (db_eget(sp, vp->m_start.lno, &p, &len, &isempty)) {
		if (isempty)
			goto nonum;
		return (1);
	}

	/*
	 * Skip any leading space before the number.  Getting a cursor word
	 * implies moving the cursor to its beginning, if we moved, refresh
	 * now.
	 */
	for (beg = vp->m_start.cno; beg < len && ISSPACE(p[beg]); ++beg);
	if (beg >= len)
		goto nonum;
	if (beg != vp->m_start.cno) {
		sp->cno = beg;
		(void)vs_refresh(sp, 0);
	}

#undef	ishex
#define	ishex(c)	(ISXDIGIT(c))
#undef	isoctal
#define	isoctal(c)	((c) >= '0' && (c) <= '7')

	/*
	 * Look for 0[Xx], or leading + or - signs, guess at the base.
	 * The character after that must be a number.  Wlen is set to
	 * the remaining characters in the line that could be part of
	 * the number.
	 */
	wlen = len - beg;
	if (p[beg] == '0' && wlen > 2 &&
	    (p[beg + 1] == 'X' || p[beg + 1] == 'x')) {
		base = 16;
		end = beg + 2;
		if (!ishex(p[end]))
			goto decimal;
		ntype = p[beg + 1] == 'X' ? fmt[HEXC] : fmt[HEXL];
	} else if (p[beg] == '0' && wlen > 1) {
		base = 8;
		end = beg + 1;
		if (!isoctal(p[end]))
			goto decimal;
		ntype = fmt[OCTAL];
	} else if (wlen >= 1 && (p[beg] == '+' || p[beg] == '-')) {
		base = 10;
		end = beg + 1;
		ntype = fmt[SDEC];
		if (!isdigit(p[end]))
			goto nonum;
	} else {
decimal:	base = 10;
		end = beg;
		ntype = fmt[DEC];
		if (!isdigit(p[end])) {
nonum:			msgq(sp, M_ERR, "181|Cursor not in a number");
			return (1);
		}
	}

	/* Find the end of the word, possibly correcting the base. */
	while (++end < len) {
		switch (base) {
		case 8:
			if (isoctal(p[end]))
				continue;
			if (p[end] == '8' || p[end] == '9') {
				base = 10;
				ntype = fmt[DEC];
				continue;
			}
			break;
		case 10:
			if (isdigit(p[end]))
				continue;
			break;
		case 16:
			if (ishex(p[end]))
				continue;
			break;
		default:
			abort();
			/* NOTREACHED */
		}
		break;
	}
	wlen = (end - beg);

	/*
	 * XXX
	 * If the line was at the end of the buffer, we have to copy it
	 * so we can guarantee that it's NULL-terminated.  We make the
	 * buffer big enough to fit the line changes as well, and only
	 * allocate once.
	 */
	GET_SPACE_RETW(sp, bp, blen, len + 50);
	if (end == len) {
		MEMMOVE(bp, &p[beg], wlen);
		bp[wlen] = '\0';
		t = bp;
	} else
		t = &p[beg];

	/*
	 * Octal or hex deal in unsigned longs, everything else is done
	 * in signed longs.
	 */
	if (base == 10) {
		if ((nret = nget_slong(&lval, t, NULL, 10)) != NUM_OK)
			goto err;
		ltmp = vp->character == '-' ? -change : change;
		if (lval > 0 && ltmp > 0 && !NPFITS(LONG_MAX, lval, ltmp)) {
			nret = NUM_OVER;
			goto err;
		}
		if (lval < 0 && ltmp < 0 && !NNFITS(LONG_MIN, lval, ltmp)) {
			nret = NUM_UNDER;
			goto err;
		}
		lval += ltmp;
		/* If we cross 0, signed numbers lose their sign. */
		if (lval == 0 && ntype == fmt[SDEC])
			ntype = fmt[DEC];
		nlen = SPRINTF(nbuf, sizeof(nbuf), ntype, lval);
	} else {
		if ((nret = nget_uslong(&ulval, t, NULL, base)) != NUM_OK)
			goto err;
		if (vp->character == '+') {
			if (!NPFITS(ULONG_MAX, ulval, change)) {
				nret = NUM_OVER;
				goto err;
			}
			ulval += change;
		} else {
			if (ulval < change) {
				nret = NUM_UNDER;
				goto err;
			}
			ulval -= change;
		}

		/* Correct for literal "0[Xx]" in format. */
		if (base == 16)
			wlen -= 2;

		nlen = SPRINTF(nbuf, sizeof(nbuf), ntype, wlen, ulval);
	}

	/* Build the new line. */
	MEMMOVE(bp, p, beg);
	MEMMOVE(bp + beg, nbuf, nlen);
	MEMMOVE(bp + beg + nlen, p + end, len - beg - (end - beg));
	len = beg + nlen + (len - beg - (end - beg));

	nret = NUM_OK;
	rval = db_set(sp, vp->m_start.lno, bp, len);

	if (0) {
err:		rval = 1;
		inc_err(sp, nret);
	}
	if (bp != NULL)
		FREE_SPACEW(sp, bp, blen);
	return (rval);
}
Beispiel #17
0
/*
 * v_replace -- [count]r<char>
 *
 * !!!
 * The r command in historic vi was almost beautiful in its badness.  For
 * example, "r<erase>" and "r<word erase>" beeped the terminal and deleted
 * a single character.  "Nr<carriage return>", where N was greater than 1,
 * inserted a single carriage return.  "r<escape>" did cancel the command,
 * but "r<literal><escape>" erased a single character.  To enter a literal
 * <literal> character, it required three <literal> characters after the
 * command.  This may not be right, but at least it's not insane.
 *
 * PUBLIC: int v_replace(SCR *, VICMD *);
 */
int
v_replace(SCR *sp, VICMD *vp)
{
	EVENT ev;
	VI_PRIVATE *vip;
	TEXT *tp;
	size_t blen, len;
	u_long cnt;
	int quote, rval;
	CHAR_T *bp;
	CHAR_T *p;

	vip = VIP(sp);

	/*
	 * If the line doesn't exist, or it's empty, replacement isn't
	 * allowed.  It's not hard to implement, but:
	 *
	 *	1: It's historic practice (vi beeped before the replacement
	 *	   character was even entered).
	 *	2: For consistency, this change would require that the more
	 *	   general case, "Nr", when the user is < N characters from
	 *	   the end of the line, also work, which would be a bit odd.
	 *	3: Replacing with a <newline> has somewhat odd semantics.
	 */
	if (db_get(sp, vp->m_start.lno, DBG_FATAL, &p, &len))
		return (1);
	if (len == 0) {
		msgq(sp, M_BERR, "186|No characters to replace");
		return (1);
	}

	/*
	 * Figure out how many characters to be replace.  For no particular
	 * reason (other than that the semantics of replacing the newline
	 * are confusing) only permit the replacement of the characters in
	 * the current line.  I suppose we could append replacement characters
	 * to the line, but I see no compelling reason to do so.  Check this
	 * before we get the character to match historic practice, where Nr
	 * failed immediately if there were less than N characters from the
	 * cursor to the end of the line.
	 */
	cnt = F_ISSET(vp, VC_C1SET) ? vp->count : 1;
	vp->m_stop.lno = vp->m_start.lno;
	vp->m_stop.cno = vp->m_start.cno + cnt - 1;
	if (vp->m_stop.cno > len - 1) {
		v_eol(sp, &vp->m_start);
		return (1);
	}

	/*
	 * If it's not a repeat, reset the current mode and get a replacement
	 * character.
	 */
	quote = 0;
	if (!F_ISSET(vp, VC_ISDOT)) {
		sp->showmode = SM_REPLACE;
		if (vs_refresh(sp, 0))
			return (1);
next:		if (v_event_get(sp, &ev, 0, 0))
			return (1);

		switch (ev.e_event) {
		case E_CHARACTER:
			/*
			 * <literal_next> means escape the next character.
			 * <escape> means they changed their minds.
			 */
			if (!quote) {
				if (ev.e_value == K_VLNEXT) {
					quote = 1;
					goto next;
				}
				if (ev.e_value == K_ESCAPE)
					return (0);
			}
			vip->rlast = ev.e_c;
			vip->rvalue = ev.e_value;
			break;
		case E_ERR:
		case E_EOF:
			F_SET(sp, SC_EXIT_FORCE);
			return (1);
		case E_INTERRUPT:
			/* <interrupt> means they changed their minds. */
			return (0);
		case E_WRESIZE:
			/* <resize> interrupts the input mode. */
			v_emsg(sp, NULL, VIM_WRESIZE);
			return (0);
		case E_REPAINT:
			if (vs_repaint(sp, &ev))
				return (1);
			goto next;
		default:
			v_event_err(sp, &ev);
			return (0);
		}
	}

	/* Copy the line. */
	GET_SPACE_RETW(sp, bp, blen, len);
	MEMMOVE(bp, p, len);
	p = bp;

	/*
	 * Versions of nvi before 1.57 created N new lines when they replaced
	 * N characters with <carriage-return> or <newline> characters.  This
	 * is different from the historic vi, which replaced N characters with
	 * a single new line.  Users complained, so we match historic practice.
	 */
	if ((!quote && vip->rvalue == K_CR) || vip->rvalue == K_NL) {
		/* Set return line. */
		vp->m_stop.lno = vp->m_start.lno + 1;
		vp->m_stop.cno = 0;

		/* The first part of the current line. */
		if (db_set(sp, vp->m_start.lno, p, vp->m_start.cno))
			goto err_ret;

		/*
		 * The rest of the current line.  And, of course, now it gets
		 * tricky.  If there are characters left in the line and if
		 * the autoindent edit option is set, white space after the
		 * replaced character is discarded, autoindent is applied, and
		 * the cursor moves to the last indent character.
		 */
		p += vp->m_start.cno + cnt;
		len -= vp->m_start.cno + cnt;
		if (len != 0 && O_ISSET(sp, O_AUTOINDENT))
			for (; len && isblank(*p); --len, ++p);

		if ((tp = text_init(sp, p, len, len)) == NULL)
			goto err_ret;

		if (len != 0 && O_ISSET(sp, O_AUTOINDENT)) {
			if (v_txt_auto(sp, vp->m_start.lno, NULL, 0, tp))
				goto err_ret;
			vp->m_stop.cno = tp->ai ? tp->ai - 1 : 0;
		} else
			vp->m_stop.cno = 0;

		vp->m_stop.cno = tp->ai ? tp->ai - 1 : 0;
		if (db_append(sp, 1, vp->m_start.lno, tp->lb, tp->len))
err_ret:		rval = 1;
		else {
			text_free(tp);
			rval = 0;
		}
	} else {
		STRSET(bp + vp->m_start.cno, vip->rlast, cnt);
		rval = db_set(sp, vp->m_start.lno, bp, len);
	}
	FREE_SPACEW(sp, bp, blen);

	vp->m_final = vp->m_stop;
	return (rval);
}
static void deviceInformationResponseHandler(const EmberEUI64 source,
                                             uint32_t transaction,
                                             uint8_t numberOfSubDevices,
                                             uint8_t startIndex,
                                             uint8_t deviceInformationRecordCount,
                                             uint8_t *deviceInformationRecordList)
{
  uint16_t deviceInformationRecordListLen = (deviceInformationRecordCount
                                           * ZLL_DEVICE_INFORMATION_RECORD_SIZE);
  uint16_t deviceInformationRecordListIndex = 0;
  uint8_t i;
  bool validResponse = (emberEventControlGetActive(emberAfPluginZllCommissioningTouchLinkEventControl)
                           && (network.securityAlgorithm.transactionId == transaction)
                           && MEMCOMPARE(network.eui64, source, EUI64_SIZE) == 0);

  emberAfZllCommissioningClusterFlush();
  emberAfZllCommissioningClusterPrint("RX: DeviceInformationResponse 0x%4x, 0x%x, 0x%x, 0x%x,",
                                      transaction,
                                      numberOfSubDevices,
                                      startIndex,
                                      deviceInformationRecordCount);
  emberAfZllCommissioningClusterFlush();
  for (i = 0; i < deviceInformationRecordCount; i++) {
    uint8_t *ieeeAddress;
    uint8_t endpointId;
    uint16_t profileId;
    uint16_t deviceId;
    uint8_t version;
    uint8_t groupIdCount;
    uint8_t sort;
    ieeeAddress = &deviceInformationRecordList[deviceInformationRecordListIndex];
    deviceInformationRecordListIndex += EUI64_SIZE;
    endpointId = emberAfGetInt8u(deviceInformationRecordList, deviceInformationRecordListIndex, deviceInformationRecordListLen);
    deviceInformationRecordListIndex++;
    profileId = emberAfGetInt16u(deviceInformationRecordList, deviceInformationRecordListIndex, deviceInformationRecordListLen);
    deviceInformationRecordListIndex += 2;
    deviceId = emberAfGetInt16u(deviceInformationRecordList, deviceInformationRecordListIndex, deviceInformationRecordListLen);
    deviceInformationRecordListIndex += 2;
    version = emberAfGetInt8u(deviceInformationRecordList, deviceInformationRecordListIndex, deviceInformationRecordListLen);
    deviceInformationRecordListIndex++;
    groupIdCount = emberAfGetInt8u(deviceInformationRecordList, deviceInformationRecordListIndex, deviceInformationRecordListLen);
    deviceInformationRecordListIndex++;
    sort = emberAfGetInt8u(deviceInformationRecordList, deviceInformationRecordListIndex, deviceInformationRecordListLen);
    deviceInformationRecordListIndex++;
    emberAfZllCommissioningClusterPrint(" [");
    emberAfZllCommissioningClusterDebugExec(emberAfPrintBigEndianEui64(ieeeAddress));
    emberAfZllCommissioningClusterPrint(" 0x%x 0x%2x 0x%2x 0x%x 0x%x 0x%x",
                                        endpointId,
                                        profileId,
                                        deviceId,
                                        version,
                                        groupIdCount,
                                        sort);
    emberAfZllCommissioningClusterFlush();

    if (validResponse
        && (subDeviceCount
            < EMBER_AF_PLUGIN_ZLL_COMMISSIONING_SUB_DEVICE_TABLE_SIZE)) {
      MEMMOVE(subDevices[subDeviceCount].ieeeAddress, ieeeAddress, EUI64_SIZE);
      subDevices[subDeviceCount].endpointId = endpointId;
      subDevices[subDeviceCount].profileId = profileId;
      subDevices[subDeviceCount].deviceId = deviceId;
      subDevices[subDeviceCount].version = version;
      subDevices[subDeviceCount].groupIdCount = groupIdCount;
      subDeviceCount++;
    } else {
      emberAfZllCommissioningClusterPrint(" (ignored)");
    }
    emberAfZllCommissioningClusterPrint("]");
    emberAfZllCommissioningClusterFlush();
  }
  emberAfZllCommissioningClusterPrintln("");

  if (validResponse
      && (subDeviceCount
          < EMBER_AF_PLUGIN_ZLL_COMMISSIONING_SUB_DEVICE_TABLE_SIZE)
      && subDeviceCount < numberOfSubDevices) {
    sendDeviceInformationRequest(startIndex + deviceInformationRecordCount);
  }
}
Beispiel #19
0
unsigned int isread(char UUFAR *buffer,
                    unsigned int wanted,
                    unsigned int timeout)
{
   union REGS rcvregs, outregs;
   time_t quit = time( NULL ) + timeout;

   size_t commBufferCached = commBufferUsed;

   if ( wanted > commBufferLength )
   {
      printmsg(0,"nsread: Overlength read, wanted %u bytes into %u buffer!",
                     (unsigned int) wanted,
                     (unsigned int) commBufferLength );
      panic();
   }

#ifdef ARTICOMM_INT14   /* Richard H. Gumpertz ([email protected]), 28 Sep 1993 */
   union REGS timregs;          /* Scratch area for interrupt calls. */

   timregs.x.ax = 0x8009;               /* Set timeouts */
   timregs.x.cx = timeout * 91 / 5;     /* Receive timeout in ticks */
   timregs.x.bx = 0x7FFF/*???*/;        /* Send timeout in ticks */
   timregs.x.dx = portNum;              /* Port number */
   int86(0x14, &timregs, &outregs);
#endif /* ARTICOMM_INT14 */

   rcvregs.h.ah = FS_RECV1;
   rcvregs.h.al = 0;
   rcvregs.x.dx = portNum;              /* Port number */
   rcvregs.x.bx = 0;

   while (commBufferUsed < wanted)
   {
      if ( terminate_processing )
      {
         static KWBoolean recurse = KWFalse;
         if ( ! recurse )
         {
            printmsg(2,"isread: User aborted processing");
            recurse = KWTrue;
         }
         commBufferUsed = 0;
         return commBufferUsed;
      }

      int86(0x14, &rcvregs, &outregs);
      if (!(outregs.h.ah & 0x80))
         commBuffer[commBufferUsed++] = (char) outregs.h.al;
      else {                                 /* the read timed out */
         if (timeout == 0)              /* If not interested in waiting */
            return commBufferUsed;      /* then get out of here fast */

         ShowModem();                   /* Report modem status */

         if ( time(NULL) >= quit )
         {
            printmsg(20, "isread: Timeout (timeout=%u, want=%u, have=%u)",
                          timeout, wanted, commBufferUsed);
            return commBufferUsed;
         }

#ifdef ARTICOMM_INT14 /* Richard H. Gumpertz ([email protected]), 28 Sep 1993 */
         timregs.x.cx = (unsigned short)(quit - now) * 91 / 5; /* Receive timeout in ticks */
         int86(0x14, &timregs, &outregs);
#endif /* ARTICOMM_INT14 */

      } /* else */
   } /* while (commBufferUsed < wanted) */

   traceData( commBuffer + commBufferCached,
              commBufferUsed - commBufferCached,
              KWFalse );

   if ( buffer != NULL )
   {
      MEMCPY(buffer, commBuffer, wanted);
      commBufferUsed -= wanted;
      if (commBufferUsed)
         MEMMOVE(commBuffer, commBuffer + wanted, commBufferUsed);
   }

   return wanted + commBufferUsed;

} /* isread */