Пример #1
0
ACCExpr *invertExpr(ACCExpr *expr)
{
    if (!expr)
        return allocExpr("1");
    ACCExpr *lhs = expr->operands.front();
    std::string v = expr->value;
    if (checkInteger(expr, "1"))
        return allocExpr("0");
    if (checkInteger(expr, "0"))
        return allocExpr("1");
    if (v == "!")
        return lhs;
    if (v == "^" && checkInteger(getRHS(expr), "1"))
        return lhs;
    if (v == "==") {
        if (expr->operands.size() == 1)
            return allocExpr("0");
        return allocExpr("!=", lhs, getRHS(expr));
    }
    if (v == "!=") {
        if (expr->operands.size() == 1)
            return allocExpr("1");
        return allocExpr("==", lhs, getRHS(expr));
    }
    if (v == "&" || v == "|") {
        ACCExpr *temp = allocExpr(v == "&" ? "|" : "&");
        for (auto item: expr->operands)
            temp->operands.push_back(invertExpr(item));
        return temp;
    }
    return allocExpr("^", expr, allocExpr("1"));
}
Пример #2
0
bool
DcModel::feasibleSolution(int & numberIntegerInfeasibilities)
{
    bool feasible = true;
    numberIntegerInfeasibilities = 0;
    int i = -1;
    const int numCols = getNumCols();

    if (currentSolution_ != 0) {
	delete [] currentSolution_;
	currentSolution_ = 0;
    }

    currentSolution_ = new double [numCols];
    memcpy(currentSolution_, solver_->getColSolution(),sizeof(double)*numCols);

    for (i = 0; i < numberIntegers_; ++i) {
	if ( ! checkInteger(currentSolution_[integerVariable_[i]]) ) {
	    ++numberIntegerInfeasibilities;
	    feasible = false;
	}
    }

    return feasible;
}
Пример #3
0
// todo implement substitution
Object * parsePattern(Collector * c, Tokenizer * tt) {
	if (tokenizerNext(tt) != TOK_NUMBER) goto fail;
	double dcol = tt->c.number;
	if (tokenizerNext(tt) != TOK_COMMA) goto fail;
	if (tokenizerNext(tt) != TOK_NUMBER) goto fail;
	double drow = tt->c.number;
	if (tokenizerNext(tt) != TOK_RBRACKET) goto fail;

	if (!checkInteger(dcol)) goto fail;
	if (!checkInteger(drow)) goto fail;
	Object * pattern = (Object *) newPattern(c, (int) dcol, (int) drow);
	if (!pattern) goto fail;
	return pattern;

fail:
	return NULL;
}
Пример #4
0
void walkReplaceBuiltin(ACCExpr *expr)
{
    while(1) {
    if (expr->value == "__bitconcat") {
        ACCExpr *list = expr->operands.front();
        if (list->value == PARAMETER_MARKER)
            list->value = "{";
        expr->value = list->value;
        expr->operands = list->operands;
    }
    else if (expr->value == "__bitsubstr") {
        ACCExpr *list = expr->operands.front();
        ACCExpr *bitem = list->operands.front();
        if (!isIdChar(bitem->value[0])) {  // can only do bit select on net or reg (not expressions)
            printf("[%s:%d] can only do __bitsubstr on elementary items\n", __FUNCTION__, __LINE__);
            dumpExpr("BITSUB", expr);
            exit(-1);
        }
        bitem->operands.push_back(allocExpr("[", allocExpr(":", getRHS(list), getRHS(list, 2))));
        expr->value = bitem->value;
        expr->operands = bitem->operands;
    }
    else if (expr->value == "__phi") {
        ACCExpr *list = expr->operands.front(); // get "(" list of [":", cond, value] items
        int size = list->operands.size();
        ACCExpr *firstInList = getRHS(list, 0), *secondInList = getRHS(list);
        ACCExpr *newe = nullptr;
        if (size == 2 && matchExpr(getRHS(firstInList, 0), invertExpr(getRHS(secondInList, 0))))
            newe = allocExpr("?", getRHS(firstInList, 0), getRHS(firstInList), getRHS(secondInList));
        else if (size == 2 && getRHS(firstInList, 0)->value == "__default" && exprWidth(getRHS(secondInList)) == 1)
            newe = allocExpr("&", getRHS(secondInList, 0), getRHS(secondInList));
        else if (size == 1)
            newe = getRHS(firstInList);
        else {
            //dumpExpr("PHI", list);
            newe = allocExpr("|");
            for (auto item: list->operands) {
                dumpExpr("PHIELEMENTBEF", item);
                if (checkInteger(getRHS(item), "0"))
                    continue;    // default value is already '0'
                item->value = "?"; // Change from ':' -> '?'
                item->operands.push_back(allocExpr("0"));
                updateWidth(item, exprWidth(getRHS(item)));
                newe->operands.push_back(item);
                if (trace_expr)
                    dumpExpr("PHIELEMENT", item);
            }
        }
        expr->value = newe->value;
        expr->operands = newe->operands;
    }
    else
        break;
    }
    for (auto item: expr->operands)
        walkReplaceBuiltin(item);
}
Пример #5
0
int Sandbox::universal_jump(string name, int linenum, JumpType type, Var* pvar1, Var* pvar2){
	int retline;
	bool retlineSet = false;
	map<string, int>::iterator rj;

	if(checkInteger(name)){
		int line = parseInteger(name);
		retline = line + linenum;
		retlineSet = true;
	}else{
		if((rj=jmap.find(name))==jmap.end()){
			errAbort(Error_JptNotFound);
		}
	}

	if(type==Jump_DIRECT){
		if(retlineSet) return retline;
		return (*rj).second;	// direct jump
	}

	int *p1 = pvar1->p();
	int *p2 = pvar2->p();
	if(pvar1->len()>1) p1 = pvar1->arrayp();
	if(pvar2->len()>1) p2 = pvar2->arrayp();

	// conditional jump
	bool jumpSuccess = false;
	switch(type){
	case Jump_E:
		if(*p1 == *p2) jumpSuccess = true;
		break;
	case Jump_NE:
		if(*p1 != *p2) jumpSuccess = true;
		break;
	case Jump_L:
		if(*p1 < *p2) jumpSuccess = true;
		break;
	case Jump_LE:
		if(*p1 <= *p2) jumpSuccess = true;
		break;
	case Jump_G:
		if(*p1 > *p2) jumpSuccess = true;
		break;
	case Jump_GE:
		if(*p1 >= *p2) jumpSuccess = true;
		break;
	}
	if(jumpSuccess){
		if(retlineSet) return retline;
		return (*rj).second;
	}
	return JUMPNCON;
}
Пример #6
0
int Numbers::getInteger( string str )
{
    int res_num = 0;
	bool isNegative = false;

    if (!checkInteger(str)) return 0; // Check if proper integer.

    for(int cnt = 0;cnt < str.length( );cnt++)
    {
        if (cnt == 0 && str[cnt] == '-') isNegative = true;
        res_num = res_num * 10 + (str[cnt] - '0');
    }

	return (isNegative) ? -res_num : res_num;
}
Пример #7
0
int CheckParameter(int paramId, char *data)
{
  int error;
  switch(PARAMTYPE_LIST[paramId])
    {
    case PARAM_INTEGER:
      error = checkInteger(data);
      if(!error) error = checkBounds(paramId, data);
      break;
    case PARAM_FLOAT:
      error = checkFloatingPoint(data);
      if(!error) error = checkBounds(paramId, data);
      break;
    case PARAM_SPEEDUP_TYPE:
      error = checkSpeedup(data);
      break;
    case PARAM_CURVE_TYPE:
      error = checkCurveType(paramId, data);
      break;
    }
  return error;
} 
Пример #8
0
//-----------------------------------------------------------------------------
int ctkErrorLogModelTest1(int argc, char * argv [])
{
  QCoreApplication app(argc, argv);
  Q_UNUSED(app);
  ctkErrorLogModel model;
  ctkModelTester modelTester;
  modelTester.setVerbose(false);
  QString errorMsg;

  QStringList enabledMessageHandlers = model.msgHandlerEnabled();
  int currentEnabledMessageHandlersCount = enabledMessageHandlers.count();
  errorMsg = checkInteger(__LINE__, "EnabledMessageHandlersCount", currentEnabledMessageHandlersCount, 0);
  if (!errorMsg.isEmpty())
    {
    model.disableAllMsgHandler();
    printErrorMessage(errorMsg);
    return EXIT_FAILURE;
    }

  try
    {
    modelTester.setModel(&model);

    // --------------------------------------------------------------------------
    // Monitor Qt messages
      {
      model.registerMsgHandler(new ctkErrorLogQtMessageHandler);
      model.setMsgHandlerEnabled(ctkErrorLogQtMessageHandler::HandlerName, true);

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ 0);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        return EXIT_FAILURE;
        }

      QString qtMessage0("This is a qDebug message");
      qDebug().nospace() << qPrintable(qtMessage0);

      QString qtMessage1("This is a qWarning message");
      qWarning().nospace() << qPrintable(qtMessage1);

      QString qtMessage2("This is a qCritical message");
      qCritical().nospace() << qPrintable(qtMessage2);

      QStringList expectedQtMessages;
      expectedQtMessages << qtMessage0 << qtMessage1 << qtMessage2;

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ expectedQtMessages.count());
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        printTextMessages(model);
        return EXIT_FAILURE;
        }

      errorMsg = checkTextMessages(__LINE__, model, expectedQtMessages);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        return EXIT_FAILURE;
        }

      // Check if msgHandlerEnabled() works as expected
      enabledMessageHandlers = model.msgHandlerEnabled();
      currentEnabledMessageHandlersCount = enabledMessageHandlers.count();
      errorMsg = checkInteger(__LINE__, "EnabledMessageHandlersCount", currentEnabledMessageHandlersCount, 1);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        return EXIT_FAILURE;
        }

      // Clear
      model.clear();

      // Disable Qt messages monitoring
      model.setMsgHandlerEnabled(ctkErrorLogQtMessageHandler::HandlerName, false);

      qDebug() << "This qDebug message should appear in the console";
      qWarning() << "This qWarning message should appear in the console";
      qCritical() << "This qCritical message should appear in the console";

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ 0);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        printTextMessages(model);
        return EXIT_FAILURE;
        }
      }

    // --------------------------------------------------------------------------
    // Monitor Stream messages
      {
      model.registerMsgHandler(new ctkErrorLogStreamMessageHandler);
      model.setMsgHandlerEnabled(ctkErrorLogStreamMessageHandler::HandlerName, true);

      // Make sure Qt message handler is still disabled
      if (model.msgHandlerEnabled(ctkErrorLogQtMessageHandler::HandlerName))
        {
        model.disableAllMsgHandler();
        errorMsg = QLatin1String("Line %1 - Qt message handler should be disabled");
        printErrorMessage(errorMsg.arg(__LINE__));
        return EXIT_FAILURE;
        }

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ 0);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        printTextMessages(model);
        return EXIT_FAILURE;
        }

      QString streamMessage0("This is a Cout message");
      std::cout << qPrintable(streamMessage0) << std::endl;

      QString streamMessage1("This is a Cerr message");
      std::cerr << qPrintable(streamMessage1) << std::endl;

      QStringList expectedStreamMessages;
      expectedStreamMessages << streamMessage0 << streamMessage1;

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ expectedStreamMessages.count());
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        printTextMessages(model);
        return EXIT_FAILURE;
        }

      errorMsg = checkTextMessages(__LINE__, model, expectedStreamMessages);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        return EXIT_FAILURE;
        }

      // Clear
      model.clear();

      // Disable Stream messages monitoring
      model.setMsgHandlerEnabled(ctkErrorLogStreamMessageHandler::HandlerName, false);

      std::cout << "This std::cout message should appear in the console" << std::endl;
      std::cerr << "This std::cerr message should appear in the console" << std::endl;

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ 0);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        printTextMessages(model);
        return EXIT_FAILURE;
        }
      }

    // --------------------------------------------------------------------------
    // Monitor FD messages
      {
      model.registerMsgHandler(new ctkErrorLogFDMessageHandler);
      model.setMsgHandlerEnabled(ctkErrorLogFDMessageHandler::HandlerName, true);

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ 0);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        printTextMessages(model);
        return EXIT_FAILURE;
        }

      QString fdMessage0("This is a stdout");
      fprintf(stdout, "%s", qPrintable(fdMessage0));
      QString fdMessage0b(" message");
      fprintf(stdout, "%s\n", qPrintable(fdMessage0b));
      fdMessage0.append(fdMessage0b);
      fflush(stdout);

//      QString fdMessage1("This is a 2nd stdout message");
//      fprintf(stdout, "%s\n", qPrintable(fdMessage1));
//      fflush(stdout);

      QString fdMessage2("This is a stderr");
      fprintf(stderr, "%s", qPrintable(fdMessage2));
      QString fdMessage2b(" message");
      fprintf(stderr, "%s\n", qPrintable(fdMessage2b));
      fdMessage2.append(fdMessage2b);
      fflush(stderr);

//      QString fdMessage3("This is a 2nd stderr message");
//      fprintf(stderr, "%s\n", qPrintable(fdMessage3));
//      fflush(stderr);

      QStringList expectedFDMessages;
      expectedFDMessages << fdMessage0 /*<< fdMessage1*/ << fdMessage2 /*<< fdMessage3*/;

      // Give enough time to the QFileSystemWatcher used internally by ctkErrorLogFDMessageHandler
      // to consider the updated files.
      QTimer timer;
      timer.setSingleShot(true);
      timer.start(1000);
      while(timer.isActive())
        {
        QCoreApplication::processEvents();
        }

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ expectedFDMessages.count());
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        printTextMessages(model);
        return EXIT_FAILURE;
        }

      errorMsg = checkTextMessages(__LINE__, model, expectedFDMessages);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        return EXIT_FAILURE;
        }

      // Clear
      model.clear();

      // Disable FD messages monitoring
      model.setMsgHandlerEnabled(ctkErrorLogFDMessageHandler::HandlerName, false);

      fprintf(stdout, "%s", "This stdout message should appear in the console\n");
      fprintf(stderr, "%s", "This stderr message should appear in the console\n");
      fflush(stderr);

      errorMsg = checkRowCount(__LINE__, model.rowCount(), /* expected = */ 0);
      if (!errorMsg.isEmpty())
        {
        model.disableAllMsgHandler();
        printErrorMessage(errorMsg);
        printTextMessages(model);
        return EXIT_FAILURE;
        }
      }

    }
  catch (const char* error)
    {
    model.disableAllMsgHandler();
    std::cerr << error << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
void ColumnPreferencesFrame::on_columnTreeWidget_itemActivated(QTreeWidgetItem *item, int column)
{
    if (!item || cur_line_edit_ || cur_combo_box_) return;

    QWidget *editor = NULL;
    cur_column_ = column;
    saved_combo_idx_ = item->data(type_col_, Qt::UserRole).toInt();

    switch (column) {
    case title_col_:
    {
        cur_line_edit_ = new QLineEdit();
        cur_column_ = column;
        saved_col_string_ = item->text(title_col_);
        connect(cur_line_edit_, SIGNAL(editingFinished()), this, SLOT(columnTitleEditingFinished()));
        editor = cur_line_edit_;
        break;
    }
    case type_col_:
    {
        cur_combo_box_ = new QComboBox();
        for (int i = 0; i < NUM_COL_FMTS; i++) {
            cur_combo_box_->addItem(col_format_desc(i), QVariant(i));
            if (i == saved_combo_idx_) {
                cur_combo_box_->setCurrentIndex(i);
            }
        }
        connect(cur_combo_box_, SIGNAL(currentIndexChanged(int)), this, SLOT(columnTypeCurrentIndexChanged(int)));
        editor = cur_combo_box_;
        break;
    }
    case custom_field_col_:
    {
        SyntaxLineEdit *syntax_edit = new SyntaxLineEdit();
        saved_col_string_ = item->text(custom_field_col_);
        connect(syntax_edit, SIGNAL(textChanged(QString)),
                syntax_edit, SLOT(checkFieldName(QString)));
        connect(syntax_edit, SIGNAL(editingFinished()), this, SLOT(customFieldEditingFinished()));
        editor = cur_line_edit_ = syntax_edit;

        saved_combo_idx_ = item->data(type_col_, Qt::UserRole).toInt();
        item->setText(type_col_, col_format_desc(COL_CUSTOM));
        item->setData(type_col_, Qt::UserRole, QVariant(COL_CUSTOM));
        break;
    }
    case custom_occurrence_col_:
    {
        SyntaxLineEdit *syntax_edit = new SyntaxLineEdit();
        saved_col_string_ = item->text(custom_occurrence_col_);
        connect(syntax_edit, SIGNAL(textChanged(QString)),
                syntax_edit, SLOT(checkInteger(QString)));
        connect(syntax_edit, SIGNAL(editingFinished()), this, SLOT(customOccurrenceEditingFinished()));
        editor = cur_line_edit_ = syntax_edit;

        saved_combo_idx_ = item->data(type_col_, Qt::UserRole).toInt();
        item->setText(type_col_, col_format_desc(COL_CUSTOM));
        item->setData(type_col_, Qt::UserRole, QVariant(COL_CUSTOM));
        break;
    }
    default:
        return;
    }

    if (cur_line_edit_) {
        cur_line_edit_->setText(saved_col_string_);
        cur_line_edit_->selectAll();
        connect(cur_line_edit_, SIGNAL(destroyed()), this, SLOT(lineEditDestroyed()));
    }
    if (cur_combo_box_) {
        connect(cur_combo_box_, SIGNAL(destroyed()), this, SLOT(comboDestroyed()));
    }
    if (editor) {
        QFrame *edit_frame = new QFrame();
        QHBoxLayout *hb = new QHBoxLayout();
        QSpacerItem *spacer = new QSpacerItem(5, 10);

        hb->addWidget(editor, 0);
        hb->addSpacerItem(spacer);
        hb->setStretch(1, 1);
        hb->setContentsMargins(0, 0, 0, 0);

        edit_frame->setLineWidth(0);
        edit_frame->setFrameStyle(QFrame::NoFrame);
        // The documentation suggests setting autoFillbackground. That looks silly
        // so we clear the item text instead.
        item->setText(cur_column_, "");
        edit_frame->setLayout(hb);
        ui->columnTreeWidget->setItemWidget(item, cur_column_, edit_frame);
        editor->setFocus();
    }
}
Пример #10
0
int main(int argc, char **argv)
{
    int verbose=0, force=0;
    int ascii=0, issuerAscii=0;
    char *progName=0;
    PRFileDesc *inFile=0, *issuerCertFile=0;
    SECItem derCert, derIssuerCert;
    PLArenaPool *arena=0;
    CERTSignedData *signedData=0;
    CERTCertificate *cert=0, *issuerCert=0;
    SECKEYPublicKey *rsapubkey=0;
    SECAlgorithmID md5WithRSAEncryption, md2WithRSAEncryption;
    SECAlgorithmID sha1WithRSAEncryption, rsaEncryption;
    SECItem spk;
    int selfSigned=0;
    int invalid=0;
    char *inFileName = NULL, *issuerCertFileName = NULL;
    PLOptState *optstate;
    PLOptStatus status;
    SECStatus rv;

    PORT_Memset(&md5WithRSAEncryption, 0, sizeof(md5WithRSAEncryption));
    PORT_Memset(&md2WithRSAEncryption, 0, sizeof(md2WithRSAEncryption));
    PORT_Memset(&sha1WithRSAEncryption, 0, sizeof(sha1WithRSAEncryption));
    PORT_Memset(&rsaEncryption, 0, sizeof(rsaEncryption));

    progName = strrchr(argv[0], '/');
    progName = progName ? progName+1 : argv[0];

    optstate = PL_CreateOptState(argc, argv, "aAvf");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case 'v':
	    verbose = 1;
	    break;

	  case 'f':
	    force = 1;
	    break;

	  case 'a':
	    ascii = 1;
	    break;

	  case 'A':
	    issuerAscii = 1;
	    break;

	  case '\0':
	    if (!inFileName)
		inFileName = PL_strdup(optstate->value);
	    else if (!issuerCertFileName)
		issuerCertFileName = PL_strdup(optstate->value);
	    else
		Usage(progName);
	    break;
	}
    }

    if (!inFileName || !issuerCertFileName || status == PL_OPT_BAD) {
	/* insufficient or excess args */
	Usage(progName);
    }

    inFile = PR_Open(inFileName, PR_RDONLY, 0);
    if (!inFile) {
	fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
	                 progName, inFileName);
	exit(1);
    }

    issuerCertFile = PR_Open(issuerCertFileName, PR_RDONLY, 0);
    if (!issuerCertFile) {
	fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
	                 progName, issuerCertFileName);
	exit(1);
    }

    if (SECU_ReadDERFromFile(&derCert, inFile, ascii, PR_FALSE) != SECSuccess) {
	printf("Couldn't read input certificate as DER binary or base64\n");
	exit(1);
    }

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    if (arena == 0) {
	fprintf(stderr,"%s: can't allocate scratch arena!", progName);
	exit(1);
    }

    if (issuerCertFile) {
	CERTSignedData *issuerCertSD=0;
	if (SECU_ReadDERFromFile(&derIssuerCert, issuerCertFile, issuerAscii,
	                         PR_FALSE) != SECSuccess) {
	    printf("Couldn't read issuer certificate as DER binary or base64.\n");
	    exit(1);
	}
	issuerCertSD = PORT_ArenaZNew(arena, CERTSignedData);
	if (!issuerCertSD) {
	    fprintf(stderr,"%s: can't allocate issuer signed data!", progName);
	    exit(1);
	}
	rv = SEC_ASN1DecodeItem(arena, issuerCertSD, 
	                        SEC_ASN1_GET(CERT_SignedDataTemplate),
				&derIssuerCert);
	if (rv) {
	    fprintf(stderr, "%s: Issuer cert isn't X509 SIGNED Data?\n",
		    progName);
	    exit(1);
	}
	issuerCert = createEmptyCertificate();
	if (!issuerCert) {
	    printf("%s: can't allocate space for issuer cert.", progName);
	    exit(1);
	}
	rv = SEC_ASN1DecodeItem(arena, issuerCert, 
	                    SEC_ASN1_GET(CERT_CertificateTemplate),
			    &issuerCertSD->data);
	if (rv) {
	    printf("%s: Does not appear to be an X509 Certificate.\n",
		   progName);
	    exit(1);
	}
    }

    signedData =  PORT_ArenaZNew(arena,CERTSignedData);
    if (!signedData) {
	fprintf(stderr,"%s: can't allocate signedData!", progName);
	exit(1);
    }

    rv = SEC_ASN1DecodeItem(arena, signedData, 
                            SEC_ASN1_GET(CERT_SignedDataTemplate), 
			    &derCert);
    if (rv) {
	fprintf(stderr, "%s: Does not appear to be X509 SIGNED Data.\n",
		progName);
	exit(1);
    }

    if (verbose) {
	printf("Decoded ok as X509 SIGNED data.\n");
    }

    cert = createEmptyCertificate();
    if (!cert) {
	fprintf(stderr, "%s: can't allocate cert", progName);
	exit(1);
    }

    rv = SEC_ASN1DecodeItem(arena, cert, 
                        SEC_ASN1_GET(CERT_CertificateTemplate), 
			&signedData->data);
    if (rv) {
	fprintf(stderr, "%s: Does not appear to be an X509 Certificate.\n",
		progName);
	exit(1);
    }


    if (verbose) {
	printf("Decoded ok as an X509 certificate.\n");
    }

    SECU_RegisterDynamicOids();
    rv = SECU_PrintSignedData(stdout, &derCert, "Certificate", 0,
			      (SECU_PPFunc)SECU_PrintCertificate);

    if (rv) {
	fprintf(stderr, "%s: Unable to pretty print cert. Error: %d\n",
		progName, PORT_GetError());
	if (!force) {
	    exit(1);
	}
    }


    /* Do various checks on the cert */

    printf("\n");

    /* Check algorithms */
    rv = SECOID_SetAlgorithmID(arena, &md5WithRSAEncryption,
		       SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, NULL);
    if (rv) {
	fprintf(stderr, "%s: failed to set algorithm ID for SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION.\n",
                progName);
	exit(1);
    }

    rv = SECOID_SetAlgorithmID(arena, &md2WithRSAEncryption,
		       SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION, NULL);
    if (rv) {
	fprintf(stderr, "%s: failed to set algorithm ID for SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION.\n",
                progName);
	exit(1);
    }

    rv = SECOID_SetAlgorithmID(arena, &sha1WithRSAEncryption,
		       SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION, NULL);
    if (rv) {
	fprintf(stderr, "%s: failed to set algorithm ID for SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION.\n",
                progName);
	exit(1);
    }

    rv = SECOID_SetAlgorithmID(arena, &rsaEncryption,
		       SEC_OID_PKCS1_RSA_ENCRYPTION, NULL);
    if (rv) {
	fprintf(stderr, "%s: failed to set algorithm ID for SEC_OID_PKCS1_RSA_ENCRYPTION.\n",
                progName);
	exit(1);
    }

    {
	int isMD5RSA = (SECOID_CompareAlgorithmID(&cert->signature,
					       &md5WithRSAEncryption) == 0);
	int isMD2RSA = (SECOID_CompareAlgorithmID(&cert->signature,
					       &md2WithRSAEncryption) == 0);
	int isSHA1RSA = (SECOID_CompareAlgorithmID(&cert->signature,
					       &sha1WithRSAEncryption) == 0);

	if (verbose) {
	    printf("\nDoing algorithm checks.\n");
	}

	if (!(isMD5RSA || isMD2RSA || isSHA1RSA)) {
	    printf("PROBLEM: Signature not PKCS1 MD5, MD2, or SHA1 + RSA.\n");
	} else if (!isMD5RSA) {
	    printf("WARNING: Signature not PKCS1 MD5 with RSA Encryption\n");
	}

	if (SECOID_CompareAlgorithmID(&cert->signature,
				   &signedData->signatureAlgorithm)) {
	    printf("PROBLEM: Algorithm in sig and certInfo don't match.\n");
	}
    }

    if (SECOID_CompareAlgorithmID(&cert->subjectPublicKeyInfo.algorithm,
			       &rsaEncryption)) {
	printf("PROBLEM: Public key algorithm is not PKCS1 RSA Encryption.\n");
    }

    /* Check further public key properties */
    spk = cert->subjectPublicKeyInfo.subjectPublicKey;
    DER_ConvertBitString(&spk);

    if (verbose) {
	printf("\nsubjectPublicKey DER\n");
	rv = DER_PrettyPrint(stdout, &spk, PR_FALSE);
	printf("\n");
    }

    rsapubkey = (SECKEYPublicKey *) 
	             PORT_ArenaZAlloc(arena,sizeof(SECKEYPublicKey));
    if (!rsapubkey) {
	fprintf(stderr, "%s: rsapubkey allocation failed.\n", progName);
	exit(1);
    }

    rv = SEC_ASN1DecodeItem(arena, rsapubkey, 
                            SEC_ASN1_GET(SECKEY_RSAPublicKeyTemplate), &spk);
    if (rv) {
	printf("PROBLEM: subjectPublicKey is not a DER PKCS1 RSAPublicKey.\n");
    } else {
	int mlen;
	int pubexp;
	if (verbose) {
	    printf("Decoded RSA Public Key ok.  Doing key checks.\n");
	}
	PORT_Assert(rsapubkey->keyType == rsaKey); /* XXX RSA */
	mlen = checkInteger(&rsapubkey->u.rsa.modulus, "Modulus", verbose);
	printf("INFO: Public Key modulus length in bits: %d\n", mlen);
	if (mlen > MAX_MODULUS) {
	    printf("PROBLEM: Modulus length exceeds %d bits.\n",
		   MAX_MODULUS);
	}
	if (mlen < 512) {
	    printf("WARNING: Short modulus.\n");
	}
	if (mlen != (1 << (ffs(mlen)-1))) {
	    printf("WARNING: Unusual modulus length (not a power of two).\n");
	}
	checkInteger(&rsapubkey->u.rsa.publicExponent, "Public Exponent",
                     verbose);
	pubexp = DER_GetInteger(&rsapubkey->u.rsa.publicExponent);
	if (pubexp != 17 && pubexp != 3 && pubexp != 65537) {
	    printf("WARNING: Public exponent not any of: 3, 17, 65537\n");
	}
    }


    /* Name checks */
    checkName(&cert->issuer, "Issuer Name", verbose);
    checkName(&cert->subject, "Subject Name", verbose);

    if (issuerCert) {
	SECComparison c =
	    CERT_CompareName(&cert->issuer, &issuerCert->subject);
	if (c) {
         printf("PROBLEM: Issuer Name and Subject in Issuing Cert differ\n");
        }
    }

    /* Check if self-signed */
    selfSigned = (CERT_CompareName(&cert->issuer, &cert->subject) == 0);
    if (selfSigned) {
	printf("INFO: Certificate is self signed.\n");
    } else {
	printf("INFO: Certificate is NOT self-signed.\n");
    }


    /* Validity time check */
    if (CERT_CertTimesValid(cert) == SECSuccess) {
	printf("INFO: Inside validity period of certificate.\n");
    } else {
	printf("PROBLEM: Not in validity period of certificate.\n");
	invalid = 1;
    }

    /* Signature check if self-signed */
    if (selfSigned && !invalid) {
	if (rsapubkey->u.rsa.modulus.len) {
	    SECStatus ver;
	    if (verbose) {
		printf("Checking self signature.\n");
	    }
	    ver = OurVerifySignedData(signedData, cert);
	    if (ver != SECSuccess) {
		printf("PROBLEM: Verification of self-signature failed!\n");
	    } else {
		printf("INFO: Self-signature verifies ok.\n");
	    }
	} else {
	    printf("INFO: Not checking signature due to key problems.\n");
	}
    } else if (!selfSigned && !invalid && issuerCert) {
	SECStatus ver;
	ver = OurVerifySignedData(signedData, issuerCert);
	if (ver != SECSuccess) {
	    printf("PROBLEM: Verification of issuer's signature failed!\n");
	} else {
	    printf("INFO: Issuer's signature verifies ok.\n");
	}
    } else {
	printf("INFO: Not checking signature.\n");
    }

    return 0;    
}
Пример #11
0
/**
 * Older generic interface to DCDLIB's cdf functions.
 * @param fname scilab caller's function name
 * @param inarg number of inputs to the scilab call
 * @param oarg number of outputs begged by the scilab call
 * @param shift tells how much arglist has to be shifted in DCDFLIB funcall
 * @param which of the arguments is to be deduced from the others
 * @param fun actual computation function
 * @return error code
 */
int CdfBase(char const * const fname, void* pvApiCtx, int inarg, int oarg, int shift, int which, int (*fun)(int*, ...))
{
#define MAXARG 6
    double *data[MAXARG];
    int rows[MAXARG], cols[MAXARG];
#undef MAXARG

    double bound = 0;
    int errlevel = 0;
    int i = 0;
    int *p = NULL;
    int siz = strlen(fname);
    int *df;
    int row, col;
    double *datas;
    int resc;
    int pos = 0;
    int pos1 = 0;

    char *option = create_string(pvApiCtx, 1);

    if ( Rhs != inarg + 1 )
    {
        Scierror(999, _("%s: Wrong number of input argument(s): %d expected.\n"), fname, inarg + 1);
        return 1;
    }

    for (i = 0; i < inarg; ++i)
    {
        int j = 0;
        getVarAddressFromPosition(pvApiCtx, i + 2, &p);
        getMatrixOfDouble(pvApiCtx, p, &rows[i], &cols[i], &data[i]);
    }

    for (i = 1; i < inarg ; ++i)
    {
        if (rows[i] != rows[i - 1] || cols[i] != cols[i - 1])
        {
            Scierror(999, _("%s: Incompatible input arguments #%d and #%d': Same sizes expected.\n"), fname, i + 1, i + 2);
            return 1;
        }
    }

    for (i = 0; i < oarg; ++i)
    {
        allocMatrixOfDouble(pvApiCtx, Rhs + i + 1, rows[0], cols[0], &data[i + inarg]);
    }

    //check which scilab function is called
    switch (siz)
    {
    case 4:
        //cdff
        if (fname[3] == 'f')
        {
            if (strcmp(option, "PQ") == 0)
            {
                pos = 3;
                pos1 = 4;
            }
            else if (strcmp(option, "F") == 0)
            {
                pos = 2;
                pos1 = 3;
            }
            else if (strcmp(option, "Dfn") == 0)
            {
                pos = 2;
            }
            else if (strcmp(option, "Dfd") == 0)
            {
                pos = 5;
            }
        }
        //cdft
        else
        {
            if (strcmp(option, "PQ") == 0)
            {
                pos = 3;
            }
            else if (strcmp(option, "T") == 0)
            {
                pos = 2;
            }
        }
        break;
    case 6 :
        //cdfbet
        if (fname[4] == 'e')
        {

        }
        //cdfbin
        else if (fname[4] == 'i')
        {

        }
        //cdffnc
        else if (fname[4] == 'n')
        {
            if (strcmp(option, "PQ") == 0)
            {
                pos = 3;
                pos1 = 4;
            }
            else if (strcmp(option, "F") == 0)
            {
                pos = 2;
                pos1 = 3;
            }
            else if (strcmp(option, "Dfn") == 0)
            {
                pos = 2;
            }
            else if (strcmp(option, "Dfd") == 0)
            {
                pos = 6;
            }
            else if (strcmp(option, "Pnonc") == 0)
            {
                pos = 5;
                pos1 = 6;
            }
        }
        //cdfgam
        else if (fname[4] == 'a')
        {

        }
        //cdfnbn
        else if (fname[4] == 'b')
        {

        }
        else if (fname[4] == 'h')
        {
            //cdfchi
            if (fname[5] == 'i')
            {
                if (strcmp(option, "PQ") == 0)
                {
                    pos = 3;
                }
                else if (strcmp(option, "X") == 0)
                {
                    pos = 2;
                }
            }
            //cdfchn
            else
            {
                if (strcmp(option, "PQ") == 0)
                {
                    pos = 3;
                }
                else if (strcmp(option, "X") == 0)
                {
                    pos = 2;
                }
                else if (strcmp(option, "Pnonc") == 0)
                {
                    pos = 5;
                }
            }
        }
        else
        {
            //cdfnor
            if (fname[5] == 'r')
            {

            }
            //cdfpoi
            else
            {

            }
        }
        break;
    }

    if (pos != 0)
    {
        getVarAddressFromPosition(pvApiCtx, pos, &df);
        getMatrixOfDouble(pvApiCtx, df, &row, &col, &datas);
        resc = checkInteger(row, col, datas, pos, fname);
        if (resc == 1)
        {
            Sciwarning(_("%s: Warning: using non integer values for argument #%d may lead to incorrect results.\n"), fname, pos);
        }
    }
    if (pos1 != 0)
    {
        getVarAddressFromPosition(pvApiCtx, pos1, &df);
        getMatrixOfDouble(pvApiCtx, df, &row, &col, &datas);
        resc = checkInteger(row, col, datas, pos1, fname);
        if (resc == 1)
        {
            Sciwarning(_("%s: Warning: using non integer values for argument #%d may lead to incorrect results.\n"), fname, pos1);
        }
    }
#define callpos(i) rotate(i, shift, inarg + oarg)
    for (i = 0; i < rows[0] * cols[0]; ++i)
    {
        switch (inarg + oarg)
        {
        case 4: /* cdfchi, cdfpoi, cdft */
            (*fun)(&which, &(data[callpos(0)][i]), &(data[callpos(1)][i]), &(data[callpos(2)][i]), &(data[callpos(3)][i]), &errlevel, &bound);
            break;
        case 5: /* cdfchn, cdff, cdfgam, cdfnor */
            (*fun)(&which, &(data[callpos(0)][i]), &(data[callpos(1)][i]), &(data[callpos(2)][i]), &(data[callpos(3)][i]), &(data[callpos(4)][i]), &errlevel, &bound);
            break;
        case 6: /* cdfbet, cdfbin, cdffnc, cdfnbn, */
            (*fun)(&which, &(data[callpos(0)][i]), &(data[callpos(1)][i]), &(data[callpos(2)][i]), &(data[callpos(3)][i]), &(data[callpos(4)][i]), &(data[callpos(5)][i]), &errlevel, &bound);
            break;
        }
        if (errlevel != 0)
        {
            cdf_error(fname, errlevel, bound);
            return 1;
        }
    }
#undef callpos
    for (i = 0; i < oarg; ++i)
    {
        LhsVar(i + 1) = Rhs + i + 1;
    }

    PutLhsVar();
    return 0;
}
Пример #12
0
static DdNode *tree2BDD(DdManager *mgr, ACCExpr *expr, VarMap &varMap)
{
    std::string op = expr->value;
    DdNode *ret = nullptr;
    if (op == "&&")
        op = "&";
    else if (op == "||")
        op = "|";
    if (checkInteger(expr, "1"))
        ret = Cudd_ReadOne(mgr);
    else if (checkInteger(expr, "0"))
        ret = Cudd_ReadLogicZero(mgr);
    else if (op == "!")
        return Cudd_Not(tree2BDD(mgr, expr->operands.front(), varMap)); // Not passes through ref count
    else if (op != "&" && op != "|" && op != "^") {
        if ((op == "!=" || op == "==")) {
            ACCExpr *lhs = getRHS(expr, 0);
            if (boolPossible(lhs) && boolPossible(getRHS(expr,1)))
                goto next; // we can analyze relops on booleans
            if (trace_bool)
                printf("[%s:%d] boolnot %d %d = %s\n", __FUNCTION__, __LINE__, boolPossible(getRHS(expr,0)), boolPossible(getRHS(expr,1)), tree2str(expr).c_str());
            if (isIdChar(lhs->value[0])) {
                if (trace_bool)
                    printf("[%s:%d] name %s type %s\n", __FUNCTION__, __LINE__, lhs->value.c_str(), refList[lhs->value].type.c_str());
            }
        }
        if (op == "!=")    // normalize comparison strings
            expr->value = "==";
        std::string name = "( " + tree2str(expr) + " )";
        if (!varMap[name]) {
            varMap[name] = new MapItem;
            varMap[name]->index = varMap.size();
            varMap[name]->node = Cudd_bddIthVar(mgr, varMap[name]->index);
        }
        ret = varMap[name]->node;
        if (op == "!=") {   // normalize comparison strings
            expr->value = op; // restore
            ret = Cudd_Not(ret);
        }
    }
    if (ret) {
        Cudd_Ref(ret);
        return ret;
    }
next:;
    for (auto item: expr->operands) {
         DdNode *operand = tree2BDD(mgr, item, varMap), *next;
         if (!ret)
             ret = operand;
         else {
             if (op == "&")
                 next = Cudd_bddAnd(mgr, ret, operand);
             else if (op == "|")
                 next = Cudd_bddOr(mgr, ret, operand);
             else if (op == "^" || op == "!=")
                 next = Cudd_bddXor(mgr, ret, operand);
             else if (op == "==")
                 next = Cudd_bddXnor(mgr, ret, operand);
             else {
                 printf("[%s:%d] unknown operator\n", __FUNCTION__, __LINE__);
                 exit(-1);
             }
             Cudd_Ref(next);
             Cudd_RecursiveDeref(mgr, operand);
             Cudd_RecursiveDeref(mgr, ret);
             ret = next;
         }
    }
    return ret;
}