コード例 #1
0
ファイル: scanner.c プロジェクト: dakov/ifj-13
int tokenInit(tToken * tk){
  tk->data = gcMalloc(sizeof(TString));

  if( tk-> data == NULL){
    //clean()
    return internalError();
  }

  tk->line = 0;
  tk->state = S_START;

  return EOK;
}
コード例 #2
0
ファイル: sampnt64.c プロジェクト: Azarien/open-watcom-v2
/*
 * loadProg - load the task to sample
 */
static void loadProg( char *exe, char *cmdline )
{
    STARTUPINFO         sinfo;
    PROCESS_INFORMATION pinfo;
    int                 rc;

    memset( &sinfo, 0, sizeof( sinfo ) );
    sinfo.cb = sizeof( sinfo );
    // set ShowWindow default value for nCmdShow parameter
    sinfo.dwFlags = STARTF_USESHOWWINDOW;
    sinfo.wShowWindow = SW_SHOWNORMAL;
    rc = CreateProcess( NULL,           /* application name */
                        cmdline,        /* command line */
                        NULL,           /* process attributes */
                        NULL,           /* thread attributes */
                        FALSE,          /* inherit handles */
                        DEBUG_ONLY_THIS_PROCESS, /* creation flags */
                        NULL,           /* environment block */
                        NULL,           /* starting directory */
                        &sinfo,         /* startup info */
                        &pinfo          /* process info */
                    );
    if( !rc ) {
        internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );
    }
    rc = WaitForDebugEvent( &debugEvent, INFINITE );
    if( !rc || (debugEvent.dwDebugEventCode != CREATE_PROCESS_DEBUG_EVENT) ||
                (debugEvent.dwProcessId != pinfo.dwProcessId) ) {
        internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );
    }
    taskPid = debugEvent.dwProcessId;
    processHandle = debugEvent.u.CreateProcessInfo.hProcess;
    newThread( debugEvent.dwThreadId, debugEvent.u.CreateProcessInfo.hThread );
    codeLoad( debugEvent.u.CreateProcessInfo.hFile,
                (DWORD) debugEvent.u.CreateProcessInfo.lpBaseOfImage,
                exe,
                SAMP_MAIN_LOAD );

} /* loadProg */
コード例 #3
0
ファイル: BaseVal.cpp プロジェクト: dakyri/qua
double
TypedValue::DoubleValue(QuasiStack *stack)
{
	if (refType == REF_STACK) {
		while (stack && stack->context != val.stackAddress.context) {
			stack = stack->lowerFrame;
		}
		if (stack && stack->mulch) {
			uchar *addr = stack->vars+val.stackAddress.offset;
			switch (type) {
			case S_DOUBLE:		return *((double *)addr);
			case S_BOOL:		return *((bool *)addr);
			case S_BYTE:		return *((uchar *)addr);
			case S_SHORT:		return *((int16 *)addr);
			case S_LONG:		return ((float)*((int64 *)addr));
			case S_INT:			return ((float)*((int32 *)addr));
			case S_FLOAT:		return *((float *)addr);
			case S_TIME:		return ((float)((Time*)addr)->ticks);
			case S_STRANGE_POINTER:	return 0;
			}
		} else {
			fprintf(stderr, "FloatValue: no stack matching ctxt %s\n", val.stackAddress.context?val.stackAddress.context->name.c_str() :"\"global\"");
			return 0;
		}
	} else if (refType == REF_INSTANCE) {
		internalError("double val of instance var???");
		return 0;
	} else if (refType == REF_POINTER) {
		internalError("double val of pointer var???");
		return 0;
	} else if (refType == REF_VALUE) {
		internalError("double val of value var???");
		return 0;
	} else {
		internalError("boo");
	}
	return 0;
}
コード例 #4
0
ファイル: ilist.c プロジェクト: dakov/ifj-13
int listInsertLast(tIlist *L, tInstr i) {
  tListItem *newItem;
  newItem = gcMalloc(sizeof (tListItem));

  if(newItem == NULL) return internalError();

  newItem->instr = i;
  newItem->nextItem = NULL;
  if (L->first == NULL)
     L->first = newItem;
  else
     L->last->nextItem=newItem;
  L->last=newItem;

  return EOK;
}
コード例 #5
0
void WebResourceLoader::didReceiveResource(const ShareableResource::Handle& handle, double finishTime)
{
    LOG(Network, "(WebProcess) WebResourceLoader::didReceiveResource for '%s'", m_coreLoader->url().string().utf8().data());

    RefPtr<SharedBuffer> buffer = handle.tryWrapInSharedBuffer();
    if (!buffer) {
        LOG_ERROR("Unable to create buffer from ShareableResource sent from the network process.");
        m_coreLoader->didFail(internalError(m_coreLoader->request().url()));
        return;
    }

    // Only send data to the didReceiveData callback if it exists.
    if (buffer->size())
        m_coreLoader->didReceiveBuffer(buffer.get(), buffer->size(), DataPayloadWholeResource);

    m_coreLoader->didFinishLoading(finishTime);
}
コード例 #6
0
ファイル: config.cpp プロジェクト: henrik1235/Kugelmatik
void setDefaultConfig() {
	config.stepMode = StepHalf;
	config.brakeMode = BrakeSmart;
	
	config.tickTime = 3500;
	config.homeTime = 3500;
	config.fixTime = 3500;
	
	config.maxSteps = 8000;
	config.homeSteps = 8000;
	config.fixSteps = 8000;
	
	config.brakeTicks = 10000;

	config.minStepDelta = 10;

	if (!checkConfig(&config))
		internalError(ERROR_INTERNAL_DEFAULT_CONFIG_FAULT);
}
コード例 #7
0
ファイル: interpret.c プロジェクト: xsokol08/IFJ15
int inter(MainData * data, tListOfInstr * instrList)
{
    listFirst(instrList);
    tInstr *instr;
    while (1)
    {
        instr = listGetData(ilist);         //vytáhnu instrukci
        if(instr == NULL)
            return internalError();
        TVarData *param1, *param2, *param3;
        int result;
        switch(instr->type)
        {
            /*******Aritmetické operace*******/

            case I_ADD:
                if((param2->type==tDouble) && (param3->type==tDouble))
                {
                    param1->type = tDouble;
                    param1->tDouble = param2->tDouble + param3->tDouble;
                }
                else if ((param2->type==tInteger) && (param3->type==tInteger))
                {
                    param1->type = tInteger;
                    param1->tInteger = param2->tInteger + param3->tInteger;
                }
                else if ((param2->type==tDouble) && (param3->type==tInteger))
                {
                    param1->type = tInteger;
                    param1->tInteger = param2->tDouble + param3->tInteger;
                }
                else if ((param2->type==tInteger) && (param3->type==tDouble))
                {
                    param1->type = tInteger;
                    param1->tInteger = param2->tInteger + param3->tDouble;
                }
                else return INTERPRET_ERR;
                break;

        }
    }
}
コード例 #8
0
ファイル: BaseVal.cpp プロジェクト: dakyri/qua
/*
* SetValue(*)
*   set the value of a BaseValueType according to its type
*/
void
TypedValue::SetTo(const string &strval)
{
	if (strval.size()) {
		switch (type) {
		case S_BOOL:		val.Bool = (atoi(strval.c_str()) != 0); break;
		case S_BYTE:		val.byte = atoi(strval.c_str()); break;
		case S_INT:			val.Int = atoi(strval.c_str()); break;
		case S_SHORT:		val.Short = atoi(strval.c_str()); break;
		case S_LONG:		val.Long = atoi(strval.c_str()); break;
		case S_FLOAT:		val.Float = atof(strval.c_str()); break;
		case S_POOL:		val.pool = findPool(strval.c_str()); break;
		case S_SAMPLE:		val.sample = findSample(strval.c_str()); break;
//		case S_STRING:		val.string = strval; break;
		default:
			internalError("can't set value to string, type = %d", type);
		}
		//		fprintf(stderr, "SetVal: %s %d %d\n", strval, type, val.Int);
	}
}
コード例 #9
0
ファイル: BaseVal.cpp プロジェクト: dakyri/qua
void
TypedValue::SetValue(Time &d, class QuasiStack *stack)
{
	if (type != S_TIME) {
		internalError("must be a valid time");
		return;
	}
	if (refType == REF_STACK) {
		if (stack == nullptr || stack->mulch == nullptr)
			return;
		uchar *addr = stack->vars + val.stackAddress.offset;
		switch (type) {
		case S_TIME:		*((Time*)addr) = d; return;
		default:			return;
		}
	} else if (refType == REF_VALUE) {
		val.time = d;
	} else if (refType == REF_POINTER) {
		if (val.timeP) *val.timeP = d;
	}
}
コード例 #10
0
void NetworkResourceLoader::startNetworkLoad(const ResourceRequest& request)
{
    RELEASE_LOG_IF_ALLOWED("startNetworkLoad: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());

    consumeSandboxExtensions();

    if (isSynchronous() || m_parameters.maximumBufferingTime > 0ms)
        m_bufferedData = SharedBuffer::create();

#if ENABLE(NETWORK_CACHE)
    if (canUseCache(request))
        m_bufferedDataForCache = SharedBuffer::create();
#endif

    NetworkLoadParameters parameters = m_parameters;
    parameters.defersLoading = m_defersLoading;
    parameters.request = request;

#if USE(NETWORK_SESSION)
    if (request.url().protocolIsBlob())
        parameters.blobFileReferences = NetworkBlobRegistry::singleton().filesInBlob(m_connection, originalRequest().url());

    auto* networkSession = SessionTracker::networkSession(parameters.sessionID);
    if (!networkSession) {
        WTFLogAlways("Attempted to create a NetworkLoad with a session (id=%" PRIu64 ") that does not exist.", parameters.sessionID.sessionID());
        RELEASE_LOG_ERROR_IF_ALLOWED("startNetworkLoad: Attempted to create a NetworkLoad with a session that does not exist (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", sessionID=%" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, parameters.sessionID.sessionID());
        NetworkProcess::singleton().logDiagnosticMessage(m_parameters.webPageID, WebCore::DiagnosticLoggingKeys::internalErrorKey(), WebCore::DiagnosticLoggingKeys::invalidSessionIDKey(), WebCore::ShouldSample::No);
        didFailLoading(internalError(request.url()));
        return;
    }
    m_networkLoad = std::make_unique<NetworkLoad>(*this, WTFMove(parameters), *networkSession);
#else
    m_networkLoad = std::make_unique<NetworkLoad>(*this, WTFMove(parameters));
#endif

    if (m_defersLoading) {
        RELEASE_LOG_IF_ALLOWED("startNetworkLoad: Created, but deferred (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")",
            m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
    }
}
コード例 #11
0
void WebResourceLoader::didReceiveResource(const ShareableResource::Handle& handle, double finishTime)
{
    LOG(Network, "(WebProcess) WebResourceLoader::didReceiveResource for '%s'", m_coreLoader->url().string().utf8().data());

    RefPtr<ShareableResource> resource = ShareableResource::create(handle);
    if (!resource) {
        LOG_ERROR("Unabled to recreate the ShareableResource sent from the network process.");
        m_coreLoader->didFail(internalError(m_coreLoader->request().url()));
        return;
    }

    // Only send data to the didReceiveData callback if it exists.
    if (resource->size()) {
        RetainPtr<CFAllocatorRef> deallocator(AdoptCF, createShareableResourceDeallocator(resource));
        RetainPtr<CFDataRef> data(AdoptCF, CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const UInt8*>(resource->data()), static_cast<CFIndex>(resource->size()), deallocator.get()));

        RefPtr<SharedBuffer> buffer = SharedBuffer::wrapCFData(data.get());
        m_coreLoader->didReceiveBuffer(buffer.get(), buffer->size(), DataPayloadWholeResource);
    }

    m_coreLoader->didFinishLoading(finishTime);
}
コード例 #12
0
bool ExtensionsParser::startElement(const QString& /*uri*/, const QString& elementName,
                                    const QString& /*qName*/, const QXmlAttributes& attributes)
{
  switch (stateStack.back())
  {
  case INITIAL_STATE :
    handleInitialState(elementName, attributes);
    break;
  case PLUGIN_STATE :
    handlePluginState(elementName, attributes);
    break;
  case PLUGIN_EXTENSION_POINT_STATE :
    handleExtensionPointState(elementName);
    break;
  case PLUGIN_EXTENSION_STATE :
  case CONFIGURATION_ELEMENT_STATE :
    handleExtensionState(elementName, attributes);
    break;
  default :
    stateStack.push(IGNORED_ELEMENT_STATE);
    internalError(QString("Unknown element \"%1\", found at the top level, ignored.").arg(elementName));
  }
  return true;
}
コード例 #13
0
void WebResourceLoader::didReceiveResource(const ShareableResource::Handle& handle, double finishTime)
{
    LOG(Network, "(WebProcess) WebResourceLoader::didReceiveResource for '%s'", m_coreLoader->url().string().latin1().data());
    RELEASE_LOG_IF_ALLOWED("WebResourceLoader::didReceiveResource, WebResourceLoader = %p", this);

    RefPtr<SharedBuffer> buffer = handle.tryWrapInSharedBuffer();

#if USE(QUICK_LOOK)
    if (QuickLookHandle* quickLookHandle = m_coreLoader->documentLoader()->quickLookHandle()) {
        if (buffer) {
            if (quickLookHandle->didReceiveData(buffer->existingCFData())) {
                quickLookHandle->didFinishLoading();
                return;
            }
        } else
            quickLookHandle->didFail();
    }
#endif

    if (!buffer) {
        LOG_ERROR("Unable to create buffer from ShareableResource sent from the network process.");
        m_coreLoader->didFail(internalError(m_coreLoader->request().url()));
        return;
    }

    Ref<WebResourceLoader> protect(*this);

    // Only send data to the didReceiveData callback if it exists.
    if (unsigned bufferSize = buffer->size())
        m_coreLoader->didReceiveBuffer(buffer.releaseNonNull(), bufferSize, DataPayloadWholeResource);

    if (!m_coreLoader)
        return;

    m_coreLoader->didFinishLoading(finishTime);
}
コード例 #14
0
void WebResourceLoader::networkProcessCrashed()
{
    ASSERT(m_coreLoader);
    m_coreLoader->didFail(internalError(m_coreLoader->url()));
}
コード例 #15
0
void BasicTaskScheduler::SingleStep(unsigned maxDelayTime) {
  fd_set readSet = fReadSet; // make a copy for this select() call
  fd_set writeSet = fWriteSet; // ditto
  fd_set exceptionSet = fExceptionSet; // ditto

  DelayInterval const& timeToDelay = fDelayQueue.timeToNextAlarm();
  struct timeval tv_timeToDelay;
  tv_timeToDelay.tv_sec = timeToDelay.seconds();
  tv_timeToDelay.tv_usec = timeToDelay.useconds();
  // Very large "tv_sec" values cause select() to fail.
  // Don't make it any larger than 1 million seconds (11.5 days)
  const long MAX_TV_SEC = MILLION;
  if (tv_timeToDelay.tv_sec > MAX_TV_SEC) {
    tv_timeToDelay.tv_sec = MAX_TV_SEC;
  }
  // Also check our "maxDelayTime" parameter (if it's > 0):
  if (maxDelayTime > 0 &&
      (tv_timeToDelay.tv_sec > (long)maxDelayTime/MILLION ||
       (tv_timeToDelay.tv_sec == (long)maxDelayTime/MILLION &&
	tv_timeToDelay.tv_usec > (long)maxDelayTime%MILLION))) {
    tv_timeToDelay.tv_sec = maxDelayTime/MILLION;
    tv_timeToDelay.tv_usec = maxDelayTime%MILLION;
  }

  int selectResult = select(fMaxNumSockets, &readSet, &writeSet, &exceptionSet, &tv_timeToDelay);
  if (selectResult < 0) {
#if defined(__WIN32__) || defined(_WIN32)
    int err = WSAGetLastError();
    // For some unknown reason, select() in Windoze sometimes fails with WSAEINVAL if
    // it was called with no entries set in "readSet".  If this happens, ignore it:
    if (err == WSAEINVAL && readSet.fd_count == 0) {
      err = EINTR;
      // To stop this from happening again, create a dummy socket:
      int dummySocketNum = socket(AF_INET, SOCK_DGRAM, 0);
      FD_SET((unsigned)dummySocketNum, &fReadSet);
    }
    if (err != EINTR) {
#else
    if (errno != EINTR && errno != EAGAIN) {
#endif
	// Unexpected error - treat this as fatal:
#if !defined(_WIN32_WCE)
	perror("BasicTaskScheduler::SingleStep(): select() fails");
#endif
	internalError();
      }
  }

  // Call the handler function for one readable socket:
  HandlerIterator iter(*fHandlers);
  HandlerDescriptor* handler;
  // To ensure forward progress through the handlers, begin past the last
  // socket number that we handled:
  if (fLastHandledSocketNum >= 0) {
    while ((handler = iter.next()) != NULL) {
      if (handler->socketNum == fLastHandledSocketNum) break;
    }
    if (handler == NULL) {
      fLastHandledSocketNum = -1;
      iter.reset(); // start from the beginning instead
    }
  }
  while ((handler = iter.next()) != NULL) {
    int sock = handler->socketNum; // alias
    int resultConditionSet = 0;
    if (FD_ISSET(sock, &readSet) && FD_ISSET(sock, &fReadSet)/*sanity check*/) resultConditionSet |= SOCKET_READABLE;
    if (FD_ISSET(sock, &writeSet) && FD_ISSET(sock, &fWriteSet)/*sanity check*/) resultConditionSet |= SOCKET_WRITABLE;
    if (FD_ISSET(sock, &exceptionSet) && FD_ISSET(sock, &fExceptionSet)/*sanity check*/) resultConditionSet |= SOCKET_EXCEPTION;
    if ((resultConditionSet&handler->conditionSet) != 0 && handler->handlerProc != NULL) {
      fLastHandledSocketNum = sock;
          // Note: we set "fLastHandledSocketNum" before calling the handler,
          // in case the handler calls "doEventLoop()" reentrantly.
      (*handler->handlerProc)(handler->clientData, resultConditionSet);
      break;
    }
  }
  if (handler == NULL && fLastHandledSocketNum >= 0) {
    // We didn't call a handler, but we didn't get to check all of them,
    // so try again from the beginning:
    iter.reset();
    while ((handler = iter.next()) != NULL) {
      int sock = handler->socketNum; // alias
      int resultConditionSet = 0;
      if (FD_ISSET(sock, &readSet) && FD_ISSET(sock, &fReadSet)/*sanity check*/) resultConditionSet |= SOCKET_READABLE;
      if (FD_ISSET(sock, &writeSet) && FD_ISSET(sock, &fWriteSet)/*sanity check*/) resultConditionSet |= SOCKET_WRITABLE;
      if (FD_ISSET(sock, &exceptionSet) && FD_ISSET(sock, &fExceptionSet)/*sanity check*/) resultConditionSet |= SOCKET_EXCEPTION;
      if ((resultConditionSet&handler->conditionSet) != 0 && handler->handlerProc != NULL) {
	fLastHandledSocketNum = sock;
	    // Note: we set "fLastHandledSocketNum" before calling the handler,
            // in case the handler calls "doEventLoop()" reentrantly.
	(*handler->handlerProc)(handler->clientData, resultConditionSet);
	break;
      }
    }
    if (handler == NULL) fLastHandledSocketNum = -1;//because we didn't call a handler
  }

  // Also handle any newly-triggered event (Note that we do this *after* calling a socket handler,
  // in case the triggered event handler modifies The set of readable sockets.)
  if (fTriggersAwaitingHandling != 0) {
    if (fTriggersAwaitingHandling == fLastUsedTriggerMask) {
      // Common-case optimization for a single event trigger:
      fTriggersAwaitingHandling = 0;
      if (fTriggeredEventHandlers[fLastUsedTriggerNum] != NULL) {
	(*fTriggeredEventHandlers[fLastUsedTriggerNum])(fTriggeredEventClientDatas[fLastUsedTriggerNum]);
      }
    } else {
      // Look for an event trigger that needs handling (making sure that we make forward progress through all possible triggers):
      unsigned i = fLastUsedTriggerNum;
      EventTriggerId mask = fLastUsedTriggerMask;

      do {
	i = (i+1)%MAX_NUM_EVENT_TRIGGERS;
	mask >>= 1;
	if (mask == 0) mask = 0x80000000;

	if ((fTriggersAwaitingHandling&mask) != 0) {
	  fTriggersAwaitingHandling &=~ mask;
	  if (fTriggeredEventHandlers[i] != NULL) {
	    (*fTriggeredEventHandlers[i])(fTriggeredEventClientDatas[i]);
	  }

	  fLastUsedTriggerMask = mask;
	  fLastUsedTriggerNum = i;
	  break;
	}
      } while (i != fLastUsedTriggerNum);
    }
  }

  // Also handle any delayed event that may have come due.
  fDelayQueue.handleAlarm();
}
コード例 #16
0
ファイル: Connection.cpp プロジェクト: ddddzzzz/mws
void Connection::respond(ev::io &w) {
    if (requestType < 0) {
        badRequest(w);
        return;
    }
    switch (requestType) {
        case GET:
                {
                    std::string filename = rootDir;
                    filename.append(filePath);
                    int fd = open(filename.c_str(), O_RDONLY);
                    if (fd == -1) {
                        switch (errno) {
                            case EACCES: {
                                             forbidden(w);
                                             break;
                                         }
                            default:
                                         {
                                             notFound(w);
                                             break;
                                         }
                        }
                        return;
                    }
                    struct stat stat_buf;
                    if (-1 == fstat(fd, &stat_buf)) {
                        close(fd);
                        internalError(w);
                    }
                    if (S_ISDIR(stat_buf.st_mode)) {
                        forbidden(w);
                        close(fd);
                        return;
                    }

                    std::ostringstream response;
                    response << "HTTP/1.0 200 OK\r\nContent-Length: ";
                    response << stat_buf.st_size << "\r\n";

                    char *point;
                    const char *contentType = "application/octet-stream";
                    if (NULL != (point = strrchr((char *)filePath.c_str(), '.'))) {
                        if (strcasecmp(point, ".gif") == 0) {
                            contentType = "image/gif";
                        } else if (strcasecmp(point, ".jpg") == 0 ||
                                   strcasecmp(point, ".jpeg") == 0) {
                            contentType = "image/jpeg";
                        } else if (strcasecmp(point, ".txt") == 0) {
                            contentType = "text/plain";
                        } else if (strcasecmp(point, ".html") == 0 ||
                                strcasecmp(point, ".htm") == 0) {
                            contentType = "text/html";
                        }
                    }
                    response << "Content-Type: " << contentType << "\r\n\r\n";

                    std::string headers = response.str();
                    send(w.fd, headers.c_str(), headers.size(), MSG_NOSIGNAL);

                    sendfile(w.fd, fd, NULL, stat_buf.st_size);
                    close(fd);
                    break;
                }
    }
    closeConnection = true;
}
コード例 #17
0
ファイル: cppcheck.cpp プロジェクト: HeisSpiter/cppcheck
unsigned int CppCheck::processFile(const std::string& filename, std::istream& fileStream)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (_settings.quiet == false) {
        std::string fixedpath = Path::simplifyPath(filename);
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("..."));
    }

    bool internalErrorFound(false);
    try {
        Preprocessor preprocessor(_settings, this);
        std::list<std::string> configurations;
        std::string filedata;

        {
            Timer t("Preprocessor::preprocess", _settings.showtime, &S_timerResults);
            preprocessor.preprocess(fileStream, filedata, configurations, filename, _settings.includePaths);
        }

        if (_settings.checkConfiguration) {
            return 0;
        }

        // Run define rules on raw code
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) {
            if (it->tokenlist == "define") {
                Tokenizer tokenizer2(&_settings, this);
                std::istringstream istr2(filedata);
                tokenizer2.list.createTokens(istr2, filename);

                for (const Token *tok = tokenizer2.list.front(); tok; tok = tok->next()) {
                    if (tok->str() == "#define") {
                        std::string code = std::string(tok->linenr()-1U, '\n');
                        for (const Token *tok2 = tok; tok2 && tok2->linenr() == tok->linenr(); tok2 = tok2->next())
                            code += " " + tok2->str();
                        Tokenizer tokenizer3(&_settings, this);
                        std::istringstream istr3(code);
                        tokenizer3.list.createTokens(istr3, tokenizer2.list.file(tok));
                        executeRules("define", tokenizer3);
                    }
                }
                break;
            }
        }

        if (!_settings.userDefines.empty() && _settings.maxConfigs==1U) {
            configurations.clear();
            configurations.push_back(_settings.userDefines);
        }

        if (!_settings.force && configurations.size() > _settings.maxConfigs) {
            if (_settings.isEnabled("information")) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        // write dump file xml prolog
        std::ofstream fdump;
        if (_settings.dump) {
            const std::string dumpfile(filename + ".dump");
            fdump.open(dumpfile.c_str());
            if (fdump.is_open()) {
                fdump << "<?xml version=\"1.0\"?>" << std::endl;
                fdump << "<dumps>" << std::endl;
            }
        }

        std::set<unsigned long long> checksums;
        unsigned int checkCount = 0;
        for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // bail out if terminated
            if (_settings.terminated())
                break;

            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings.force && ++checkCount > _settings.maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (_settings.quiet == false && it != configurations.begin()) {
                std::string fixedpath = Path::simplifyPath(filename);
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut("Checking " + fixedpath + ": " + cfg + "...");
            }

            if (!_settings.userDefines.empty()) {
                if (!cfg.empty())
                    cfg = ";" + cfg;
                cfg = _settings.userDefines + cfg;
            }

            Timer t("Preprocessor::getcode", _settings.showtime, &S_timerResults);
            std::string codeWithoutCfg = preprocessor.getcode(filedata, cfg, filename);
            t.Stop();

            codeWithoutCfg += _settings.append();

            if (_settings.preprocessOnly) {
                if (codeWithoutCfg.compare(0,5,"#file") == 0)
                    codeWithoutCfg.insert(0U, "//");
                std::string::size_type pos = 0;
                while ((pos = codeWithoutCfg.find("\n#file",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find("\n#endfile",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find(Preprocessor::macroChar,pos)) != std::string::npos)
                    codeWithoutCfg[pos] = ' ';
                reportOut(codeWithoutCfg);
                continue;
            }

            Tokenizer _tokenizer(&_settings, this);
            if (_settings.showtime != SHOWTIME_NONE)
                _tokenizer.setTimerResults(&S_timerResults);

            try {
                // Create tokens, skip rest of iteration if failed
                std::istringstream istr(codeWithoutCfg);
                Timer timer("Tokenizer::createTokens", _settings.showtime, &S_timerResults);
                bool result = _tokenizer.createTokens(istr, filename.c_str());
                timer.Stop();
                if (!result)
                    continue;

                // skip rest of iteration if just checking configuration
                if (_settings.checkConfiguration)
                    continue;

                // Check raw tokens
                checkRawTokens(_tokenizer);

                // Simplify tokens into normal form, skip rest of iteration if failed
                Timer timer2("Tokenizer::simplifyTokens1", _settings.showtime, &S_timerResults);
                result = _tokenizer.simplifyTokens1(cfg);
                timer2.Stop();
                if (!result)
                    continue;

                // dump xml if --dump
                if (_settings.dump && fdump.is_open()) {
                    fdump << "<dump cfg=\"" << cfg << "\">" << std::endl;
                    preprocessor.dump(fdump);
                    _tokenizer.dump(fdump);
                    fdump << "</dump>" << std::endl;
                }

                // Skip if we already met the same simplified token list
                if (_settings.force || _settings.maxConfigs > 1) {
                    const unsigned long long checksum = _tokenizer.list.calculateChecksum();
                    if (checksums.find(checksum) != checksums.end())
                        continue;
                    checksums.insert(checksum);
                }

                // Check normal tokens
                checkNormalTokens(_tokenizer);

                // simplify more if required, skip rest of iteration if failed
                if (_simplify) {
                    // if further simplification fails then skip rest of iteration
                    Timer timer3("Tokenizer::simplifyTokenList2", _settings.showtime, &S_timerResults);
                    result = _tokenizer.simplifyTokenList2();
                    timer3.Stop();
                    if (!result)
                        continue;

                    // Check simplified tokens
                    checkSimplifiedTokens(_tokenizer);
                }

            } catch (const InternalError &e) {
                if (_settings.isEnabled("information") && (_settings.debug || _settings.verbose))
                    purgedConfigurationMessage(filename, cfg);
                internalErrorFound=true;
                std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
                ErrorLogger::ErrorMessage::FileLocation loc;
                if (e.token) {
                    loc.line = e.token->linenr();
                    const std::string fixedpath = Path::toNativeSeparators(_tokenizer.list.file(e.token));
                    loc.setfile(fixedpath);
                } else {
                    ErrorLogger::ErrorMessage::FileLocation loc2;
                    loc2.setfile(Path::toNativeSeparators(filename.c_str()));
                    locationList.push_back(loc2);
                    loc.setfile(_tokenizer.list.getSourceFilePath());
                }
                locationList.push_back(loc);
                const ErrorLogger::ErrorMessage errmsg(locationList,
                                                       Severity::error,
                                                       e.errorMessage,
                                                       e.id,
                                                       false);

                reportErr(errmsg);
            }
        }

        // dumped all configs, close root </dumps> element now
        if (_settings.dump && fdump.is_open())
            fdump << "</dumps>" << std::endl;

    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
        exitcode=1; // e.g. reflect a syntax error
    }

    // In jointSuppressionReport mode, unmatched suppressions are
    // collected after all files are processed
    if (!_settings.jointSuppressionReport && (_settings.isEnabled("information") || _settings.checkConfiguration)) {
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename, unusedFunctionCheckIsEnabled()));
    }

    _errorList.clear();
    if (internalErrorFound && (exitcode==0)) {
        exitcode=1;
    }
    return exitcode;
}
コード例 #18
0
ファイル: cppcheck.cpp プロジェクト: Dmitry-Me/cppcheck
unsigned int CppCheck::processFile(const std::string& filename, const std::string &cfgname, std::istream& fileStream)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (!_settings.quiet) {
        std::string fixedpath = Path::simplifyPath(filename);
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + ' ' + cfgname + std::string("..."));

        if (_settings.verbose) {
            _errorLogger.reportOut("Defines: " + _settings.userDefines);
            std::string includePaths;
            for (std::list<std::string>::const_iterator I = _settings.includePaths.begin(); I != _settings.includePaths.end(); ++I)
                includePaths += " -I" + *I;
            _errorLogger.reportOut("Includes:" + includePaths);
            _errorLogger.reportOut(std::string("Platform:") + _settings.platformString());
        }
    }

    if (plistFile.is_open()) {
        plistFile << ErrorLogger::plistFooter();
        plistFile.close();
    }

    CheckUnusedFunctions checkUnusedFunctions(nullptr, nullptr, nullptr);

    bool internalErrorFound(false);
    try {
        Preprocessor preprocessor(_settings, this);
        std::set<std::string> configurations;

        simplecpp::OutputList outputList;
        std::vector<std::string> files;
        simplecpp::TokenList tokens1(fileStream, files, filename, &outputList);

        // If there is a syntax error, report it and stop
        for (simplecpp::OutputList::const_iterator it = outputList.begin(); it != outputList.end(); ++it) {
            bool err;
            switch (it->type) {
            case simplecpp::Output::ERROR:
            case simplecpp::Output::INCLUDE_NESTED_TOO_DEEPLY:
            case simplecpp::Output::SYNTAX_ERROR:
            case simplecpp::Output::UNHANDLED_CHAR_ERROR:
                err = true;
                break;
            case simplecpp::Output::WARNING:
            case simplecpp::Output::MISSING_HEADER:
            case simplecpp::Output::PORTABILITY_BACKSLASH:
                err = false;
                break;
            };

            if (err) {
                const ErrorLogger::ErrorMessage::FileLocation loc1(it->location.file(), it->location.line);
                std::list<ErrorLogger::ErrorMessage::FileLocation> callstack;
                callstack.push_back(loc1);

                ErrorLogger::ErrorMessage errmsg(callstack,
                                                 "",
                                                 Severity::error,
                                                 it->msg,
                                                 "syntaxError",
                                                 false);
                _errorLogger.reportErr(errmsg);
                return 1;
            }
        }

        preprocessor.loadFiles(tokens1, files);

        if (!_settings.plistOutput.empty()) {
            std::string filename2;
            if (filename.find('/') != std::string::npos)
                filename2 = filename.substr(filename.rfind('/') + 1);
            else
                filename2 = filename;
            filename2 = _settings.plistOutput + filename2.substr(0, filename2.find('.')) + ".plist";
            plistFile.open(filename2);
            plistFile << ErrorLogger::plistHeader(version(), files);
        }

        // write dump file xml prolog
        std::ofstream fdump;
        if (_settings.dump) {
            const std::string dumpfile(_settings.dumpFile.empty() ? (filename + ".dump") : _settings.dumpFile);
            fdump.open(dumpfile.c_str());
            if (fdump.is_open()) {
                fdump << "<?xml version=\"1.0\"?>" << std::endl;
                fdump << "<dumps>" << std::endl;
                fdump << "  <platform"
                      << " name=\"" << _settings.platformString() << '\"'
                      << " char_bit=\"" << _settings.char_bit << '\"'
                      << " short_bit=\"" << _settings.short_bit << '\"'
                      << " int_bit=\"" << _settings.int_bit << '\"'
                      << " long_bit=\"" << _settings.long_bit << '\"'
                      << " long_long_bit=\"" << _settings.long_long_bit << '\"'
                      << " pointer_bit=\"" << (_settings.sizeof_pointer * _settings.char_bit) << '\"'
                      << "/>\n";
                fdump << "  <rawtokens>" << std::endl;
                for (unsigned int i = 0; i < files.size(); ++i)
                    fdump << "    <file index=\"" << i << "\" name=\"" << ErrorLogger::toxml(files[i]) << "\"/>" << std::endl;
                for (const simplecpp::Token *tok = tokens1.cfront(); tok; tok = tok->next) {
                    fdump << "    <tok "
                          << "fileIndex=\"" << tok->location.fileIndex << "\" "
                          << "linenr=\"" << tok->location.line << "\" "
                          << "str=\"" << ErrorLogger::toxml(tok->str) << "\""
                          << "/>" << std::endl;
                }
                fdump << "  </rawtokens>" << std::endl;
            }
        }

        // Parse comments and then remove them
        preprocessor.inlineSuppressions(tokens1);
        tokens1.removeComments();
        preprocessor.removeComments();

        if (!_settings.buildDir.empty()) {
            // Get toolinfo
            std::string toolinfo;
            toolinfo += CPPCHECK_VERSION_STRING;
            toolinfo += _settings.isEnabled(Settings::WARNING) ? 'w' : ' ';
            toolinfo += _settings.isEnabled(Settings::STYLE) ? 's' : ' ';
            toolinfo += _settings.isEnabled(Settings::PERFORMANCE) ? 'p' : ' ';
            toolinfo += _settings.isEnabled(Settings::PORTABILITY) ? 'p' : ' ';
            toolinfo += _settings.isEnabled(Settings::INFORMATION) ? 'i' : ' ';
            toolinfo += _settings.userDefines;

            // Calculate checksum so it can be compared with old checksum / future checksums
            const unsigned int checksum = preprocessor.calculateChecksum(tokens1, toolinfo);
            std::list<ErrorLogger::ErrorMessage> errors;
            if (!analyzerInformation.analyzeFile(_settings.buildDir, filename, cfgname, checksum, &errors)) {
                while (!errors.empty()) {
                    reportErr(errors.front());
                    errors.pop_front();
                }
                return exitcode;  // known results => no need to reanalyze file
            }
        }

        // Get directives
        preprocessor.setDirectives(tokens1);
        preprocessor.simplifyPragmaAsm(&tokens1);

        preprocessor.setPlatformInfo(&tokens1);

        // Get configurations..
        if (_settings.userDefines.empty() || _settings.force) {
            Timer t("Preprocessor::getConfigs", _settings.showtime, &S_timerResults);
            configurations = preprocessor.getConfigs(tokens1);
        } else {
            configurations.insert(_settings.userDefines);
        }

        if (_settings.checkConfiguration) {
            for (std::set<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it)
                (void)preprocessor.getcode(tokens1, *it, files, true);

            return 0;
        }

        // Run define rules on raw code
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) {
            if (it->tokenlist != "define")
                continue;

            std::string code;
            const std::list<Directive> &directives = preprocessor.getDirectives();
            for (std::list<Directive>::const_iterator dir = directives.begin(); dir != directives.end(); ++dir) {
                if (dir->str.compare(0,8,"#define ") == 0)
                    code += "#line " + MathLib::toString(dir->linenr) + " \"" + dir->file + "\"\n" + dir->str + '\n';
            }
            Tokenizer tokenizer2(&_settings, this);
            std::istringstream istr2(code);
            tokenizer2.list.createTokens(istr2);
            executeRules("define", tokenizer2);
            break;
        }

        if (!_settings.force && configurations.size() > _settings.maxConfigs) {
            if (_settings.isEnabled(Settings::INFORMATION)) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        std::set<unsigned long long> checksums;
        unsigned int checkCount = 0;
        for (std::set<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // bail out if terminated
            if (_settings.terminated())
                break;

            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings.force && ++checkCount > _settings.maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (!_settings.quiet && (!cfg.empty() || it != configurations.begin())) {
                std::string fixedpath = Path::simplifyPath(filename);
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut("Checking " + fixedpath + ": " + cfg + "...");
            }

            if (!_settings.userDefines.empty()) {
                if (!cfg.empty())
                    cfg = ";" + cfg;
                cfg = _settings.userDefines + cfg;
            }

            if (_settings.preprocessOnly) {
                Timer t("Preprocessor::getcode", _settings.showtime, &S_timerResults);
                std::string codeWithoutCfg = preprocessor.getcode(tokens1, cfg, files, true);
                t.Stop();

                if (codeWithoutCfg.compare(0,5,"#file") == 0)
                    codeWithoutCfg.insert(0U, "//");
                std::string::size_type pos = 0;
                while ((pos = codeWithoutCfg.find("\n#file",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find("\n#endfile",pos)) != std::string::npos)
                    codeWithoutCfg.insert(pos+1U, "//");
                pos = 0;
                while ((pos = codeWithoutCfg.find(Preprocessor::macroChar,pos)) != std::string::npos)
                    codeWithoutCfg[pos] = ' ';
                reportOut(codeWithoutCfg);
                continue;
            }

            Tokenizer _tokenizer(&_settings, this);
            if (_settings.showtime != SHOWTIME_NONE)
                _tokenizer.setTimerResults(&S_timerResults);

            try {
                bool result;

                // Create tokens, skip rest of iteration if failed
                Timer timer("Tokenizer::createTokens", _settings.showtime, &S_timerResults);
                const simplecpp::TokenList &tokensP = preprocessor.preprocess(tokens1, cfg, files);
                _tokenizer.createTokens(&tokensP);
                timer.Stop();
                if (tokensP.empty())
                    continue;

                // skip rest of iteration if just checking configuration
                if (_settings.checkConfiguration)
                    continue;

                // Check raw tokens
                checkRawTokens(_tokenizer);

                // Simplify tokens into normal form, skip rest of iteration if failed
                Timer timer2("Tokenizer::simplifyTokens1", _settings.showtime, &S_timerResults);
                result = _tokenizer.simplifyTokens1(cfg);
                timer2.Stop();
                if (!result)
                    continue;

                // dump xml if --dump
                if (_settings.dump && fdump.is_open()) {
                    fdump << "<dump cfg=\"" << ErrorLogger::toxml(cfg) << "\">" << std::endl;
                    preprocessor.dump(fdump);
                    _tokenizer.dump(fdump);
                    fdump << "</dump>" << std::endl;
                }

                // Skip if we already met the same simplified token list
                if (_settings.force || _settings.maxConfigs > 1) {
                    const unsigned long long checksum = _tokenizer.list.calculateChecksum();
                    if (checksums.find(checksum) != checksums.end()) {
                        if (_settings.isEnabled(Settings::INFORMATION) && (_settings.debug || _settings.verbose))
                            purgedConfigurationMessage(filename, cfg);
                        continue;
                    }
                    checksums.insert(checksum);
                }

                // Check normal tokens
                checkNormalTokens(_tokenizer);

                // Analyze info..
                if (!_settings.buildDir.empty())
                    checkUnusedFunctions.parseTokens(_tokenizer, filename.c_str(), &_settings, false);

                // simplify more if required, skip rest of iteration if failed
                if (_simplify) {
                    // if further simplification fails then skip rest of iteration
                    Timer timer3("Tokenizer::simplifyTokenList2", _settings.showtime, &S_timerResults);
                    result = _tokenizer.simplifyTokenList2();
                    timer3.Stop();
                    if (!result)
                        continue;

                    // Check simplified tokens
                    checkSimplifiedTokens(_tokenizer);
                }

            } catch (const InternalError &e) {
                internalErrorFound=true;
                std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
                ErrorLogger::ErrorMessage::FileLocation loc;
                if (e.token) {
                    loc.line = e.token->linenr();
                    const std::string fixedpath = Path::toNativeSeparators(_tokenizer.list.file(e.token));
                    loc.setfile(fixedpath);
                } else {
                    ErrorLogger::ErrorMessage::FileLocation loc2;
                    loc2.setfile(Path::toNativeSeparators(filename));
                    locationList.push_back(loc2);
                    loc.setfile(_tokenizer.list.getSourceFilePath());
                }
                locationList.push_back(loc);
                ErrorLogger::ErrorMessage errmsg(locationList,
                                                 _tokenizer.list.getSourceFilePath(),
                                                 Severity::error,
                                                 e.errorMessage,
                                                 e.id,
                                                 false);

                reportErr(errmsg);
            }
        }

        // dumped all configs, close root </dumps> element now
        if (_settings.dump && fdump.is_open())
            fdump << "</dumps>" << std::endl;

    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const std::bad_alloc &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
        exitcode=1; // e.g. reflect a syntax error
    }

    analyzerInformation.setFileInfo("CheckUnusedFunctions", checkUnusedFunctions.analyzerInfo());
    analyzerInformation.close();

    // In jointSuppressionReport mode, unmatched suppressions are
    // collected after all files are processed
    if (!_settings.jointSuppressionReport && (_settings.isEnabled(Settings::INFORMATION) || _settings.checkConfiguration)) {
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename, isUnusedFunctionCheckEnabled()));
    }

    _errorList.clear();
    if (internalErrorFound && (exitcode==0)) {
        exitcode=1;
    }
    return exitcode;
}
コード例 #19
0
ファイル: text.c プロジェクト: apc-llc/cernlib
/***********************************************************************
DESCRIPTION:
    Read a name from a text widget with syntax error cheking.
    The value is read only if it have been changed since the last reading
    as indicated by status. If a syntax error have been found, the
    text field is visually marked and a warning message is popped up.
    An empty field is not considered an error by this function.

ARGUMENTS:
    text - text widget
    *status - current status of the field on input, new status on
        output (enum textstatus)
    name - the read value is copied if there was no syntax error and
        the field is not empty
    valueok - a function which given a pointer to the value read, returns
        1 if the application accepts it and 0 if not; if the field is
        empty, the pointer to the value is NULL

EXTERNALS: None
***********************************************************************/
void textReadName(Widget text, TextStatusInfo *status,
    char *name, int (*valueok)(char *name,int n))
{
    String textstr;
    TOKLOC nameloc;

    if (status->change != TEXTSTAT_CHANGED) {
        currErrorCode = TEXT_NOCHANGE;
        return;
    }
    currErrorCode = TEXT_OK;

    XtVaGetValues(text,XmNvalue, &textstr,NULL);

    /****** read and analyze the field *****/
    lx_load(textstr);
    lx_next();
    nameloc = lx_loc;
    if (lx_token.type == NEWLINE_T) { /* empty field */
        currErrorCode = TEXT_EMPTY;
        goto ok_proc;
    }

    if (lx_token.type == IDENT_T) {
        currErrorCode = TEXT_OK;
    }
    else {
        currErrorCode = TEXT_INVALID;
        goto endproc;
    }

    lx_next();
    if (lx_token.type != NEWLINE_T) {
        currErrorCode = TEXT_INVDAFTER;
    }

    /***** perform user check *****/
ok_proc:
    /* changes error code according to user preference */
    valueok(textstr+nameloc.pos,nameloc.inputlen);

    /***** return the name or signal the error *****/
endproc:
    status->change = TEXTSTAT_NOCHANGE;
    switch (currErrorCode) {
    case TEXT_OK:
    case TEXT_EMPTY:
        if (status->stat==TEXTSTAT_SYNTERROR) utl_markTextValid(text);
        status->stat = (status->stat&TEXTSTAT_SEMANTERROR)|TEXTSTAT_READOK;
        strncpy(name,textstr+nameloc.pos,nameloc.inputlen);
        name[nameloc.inputlen] = '\0';
    break;
    case TEXT_INVALID:
    case TEXT_INVDEMPTY:
    case TEXT_INVDAFTER:
        if (!(status->stat&TEXTSTAT_ANYERROR)) utl_markTextInvalid(text);
        status->stat = (status->stat&TEXTSTAT_SEMANTERROR)|TEXTSTAT_SYNTERROR;
    break;
    case TEXT_NOCHANGE:
    default:
        internalError();
    }
}
コード例 #20
0
ファイル: tools.c プロジェクト: FrankDMartinez/Typing
/* 
 * Compile the typing data from each of the given files into  a single file.
 * 
 * outfileName: The file to which the new typing data will be written.
 * filenames: The names of each file to be read.
 * multipliers: The multipliers corresponding with the filenames.
 * length: Length of filenames and multipliers.
 * unit: The unit size of the strings to be read (characters=1, digraphs=2, etc).
 * max: The maximum number of strings that can be put into the file.
 * 
 * Return Codes
 * 1: Null file.
 */
int compileTypingData(char *const outfileName,
                        char *const filenames[],
                        const int multipliers[],
                        const size_t length,
                        const int unit,
                        const size_t max)
{
	int aMultiplier;
	char *aFilename;
	Keystroke aKey;
	char *aValueString;
	int aValue;
	void outputTypingData(const KeystrokeValueTable *table, FILE *outfile, const size_t max);
	const int linelen = 100;
	char line[linelen];
    void includeKeyInTable(Keystroke aKey, Value aValue, KeystrokeValueTable *table);	

	FILE *outfile = fopen(outfileName, "w");
	if (outfile == NULL) {
		fprintf(stderr, "Error: null file %s.\n", outfileName);
		return 1;
	}
	KeystrokeValueTable *kvTable = createTable();
	if (kvTable == NULL) {
		internalError(014);
		fclose(outfile);
		return 1;
	}

	size_t i;
	for (i = 0; i < length; ++i) {
		aMultiplier = multipliers[i];
		aFilename = filenames[i];
		printf("file %s,  multiplier %d\n", aFilename, aMultiplier);

		
		if (aMultiplier == 0)
			continue;
		
		FILE *file = fopen(aFilename, "r");
		if (file == NULL) {
			fprintf(stderr, "Error: null file %s.\n", aFilename);
			fclose(outfile);
			free(kvTable->kvt_table);
			kvTable->kvt_table = NULL;
			free(kvTable);
			return 1;
		}
		
		while (fgets(line, linelen-1, file)) {			
			line[linelen-1] = '\0';
			line[unit] = 0;
			aKey = line;
			aValueString = line + unit + 1;
			aValue = atoi(aValueString);
			includeKeyInTable(aKey, aValue, kvTable);
		}
		
		fclose(file);
	}

	sortTable(kvTable, kvReverseComparingValues);
	outputTypingData(kvTable, outfile, max);
	fclose(outfile);
	free(kvTable);
	
	return 0;
}
コード例 #21
0
ファイル: tools.c プロジェクト: FrankDMartinez/Typing
/* 
 * Takes a string containing a name and a value. Sets the variable with the given name to
 * the given value.
 */
int setValue(char *const str)
{
	const size_t len = strlen(str);
	
	if (len == 0) {
		printf("No variable specified. Type \"variables\" for a complete listing of possible variables.\n\n");
		return 0;
	}
	
	char *const name = str;
	char *valstr = strchr(str, ' ');
	
	if( valstr == NULL )
		{
		internalError( 6 );
		return 0;
		}
	*valstr = '\0'; ++valstr;
	
	const int value = atoi(valstr);
	
	if (streq(name, "detailedOutput")) {
		detailedOutput = value;
	} else if (streq(name, "keepZXCV")) {
		keepZXCV = value;
	} else if (streq(name, "keepQWERTY")) {
		keepQWERTY = value;
	} else if (streq(name, "keepNumbers")) {
		keepNumbers = value;
	} else if (streq(name, "keepParentheses")) {
		keepParentheses = value;
	} else if (streq(name, "keepShiftPairs")) {
		keepShiftPairs = value;
	} else if (streq(name, "keepTab")) {
		keepTab = value;
	} else if (streq(name, "keepNumbersShifted")) {
		keepNumbersShifted = value;
	} else if (streq(name, "distance")) {
		distance = value;
	} else if (streq(name, "inRoll")) {
		inRoll = value;
	} else if (streq(name, "outRoll")) {
		outRoll = value;
	} else if (streq(name, "sameHand")) {
		sameHand = value;
	} else if (streq(name, "sameFingerP")) {
		sameFingerP = value;
	} else if (streq(name, "sameFingerR")) {
		sameFingerR = value;
	} else if (streq(name, "sameFingerM")) {
		sameFingerM = value;
	} else if (streq(name, "sameFingerI")) {
		sameFingerI = value;
	} else if (streq(name, "sameFingerT")) {
		sameFingerT = value;
	} else if (streq(name, "rowChangeUp")) {
		rowChangeUp = value;
	} else if (streq(name, "rowChangeDown")) {
		rowChangeDown = value;
	} else if (streq(name, "handWarp")) {
		handWarp = value;
	} else if (streq(name, "handSmooth")) {
		handSmooth = value;
	} else if (streq(name, "homeJump")) {
		homeJump = value;
	} else if (streq(name, "homeJumpIndex")) {
		homeJumpIndex = value;
	} else if (streq(name, "doubleJump")) {
		doubleJump = value;
	} else if (streq(name, "toCenter")) {
		toCenter = value;
	} else if (streq(name, "toOutside")) {
		toOutside = value;
	} else {
		printf("Unknown variable \"%s\". Type \"variables\" for a complete listing of possible variables.\n\n", name);
		return 1;
	}
	
	printf("%s set to %d.\n", name, value);
	
	return 0;
}
コード例 #22
0
/*
 * StartProg - start sampling a program
 */
void StartProg( const char *cmd, const char *prog, char *full_args, char *dos_args )
{
    DWORD       code;
    DWORD       tid;
    CONTEXT     con;
    BOOL        waiting_for_first_bp;
    DWORD       continue_how;
    BOOL        rc;
    DWORD       ttid;
    HANDLE      tth;
    uint_32     Fir;

    /* unused parameters */ (void)cmd;

    strcpy( utilBuff, prog );
    strcat( utilBuff, " " );
    strcat( utilBuff, full_args );

    loadProg( prog, utilBuff );
    tid = debugEvent.dwThreadId;

    tth = CreateThread( NULL, 2048, TimerThread, NULL, 0, &ttid );
    if( !tth ) {
        internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );
    }
    /* Attempt to ensure that we can record our samples in one shot */
    SetThreadPriority( tth, THREAD_PRIORITY_TIME_CRITICAL );

    Output( MsgArray[MSG_SAMPLE_1 - ERR_FIRST_MESSAGE] );
    Output( prog );
    Output( "\r\n" );

    waiting_for_first_bp = TRUE;
    continue_how = DBG_CONTINUE;

    for( ;; ) {
        ContinueDebugEvent( taskPid, tid, continue_how );
        rc = WaitForDebugEvent( &debugEvent, INFINITE );
        continue_how = DBG_CONTINUE;
        tid = debugEvent.dwThreadId;
        switch( debugEvent.dwDebugEventCode ) {
        case EXCEPTION_DEBUG_EVENT:
            code = debugEvent.u.Exception.ExceptionRecord.ExceptionCode;
            switch( code ) {
            case STATUS_SINGLE_STEP:
                if( timeOut ) {
                    myGetThreadContext( tid, &con );
                    Fir = LODWORD( con.Fir );
                    RecordSample( Fir, SEGMENT, tid );
                    timeOut = FALSE;
                }
                break;
            case STATUS_BREAKPOINT:
                /* Skip past the breakpoint in the startup code */
                if( waiting_for_first_bp ) {
                    SkipBreakpoint( tid );
                    waiting_for_first_bp = FALSE;
                }
                break;
            case STATUS_DATATYPE_MISALIGNMENT:
            case STATUS_ACCESS_VIOLATION:
            case STATUS_IN_PAGE_ERROR:
            case STATUS_NO_MEMORY:
            case STATUS_ILLEGAL_INSTRUCTION:
            case STATUS_NONCONTINUABLE_EXCEPTION:
            case STATUS_INVALID_DISPOSITION:
            case STATUS_ARRAY_BOUNDS_EXCEEDED:
            case STATUS_FLOAT_DENORMAL_OPERAND:
            case STATUS_FLOAT_DIVIDE_BY_ZERO:
            case STATUS_FLOAT_INVALID_OPERATION:
            case STATUS_FLOAT_OVERFLOW:
            case STATUS_FLOAT_STACK_CHECK:
            case STATUS_FLOAT_UNDERFLOW:
            case STATUS_INTEGER_DIVIDE_BY_ZERO:
            case STATUS_INTEGER_OVERFLOW:
            case STATUS_PRIVILEGED_INSTRUCTION:
            case STATUS_STACK_OVERFLOW:
            case STATUS_CONTROL_C_EXIT:
                if( debugEvent.u.Exception.dwFirstChance ) {
                    continue_how = DBG_EXCEPTION_NOT_HANDLED;
                } else {
                    Output( MsgArray[MSG_SAMPLE_4 - ERR_FIRST_MESSAGE] );
                    Output( "\r\n" );
                    doneSample = TRUE;
                    TerminateProcess( processHandle, 0 );
                    report();
                    return;
                }
                break;
            default:
                continue_how = DBG_EXCEPTION_NOT_HANDLED;
                break;
            }
            break;
        case LOAD_DLL_DEBUG_EVENT:
            if( GetDllName( &debugEvent.u.LoadDll, utilBuff, sizeof( utilBuff ) ) ) {
                codeLoad( debugEvent.u.LoadDll.hFile,
                            (DWORD) debugEvent.u.LoadDll.lpBaseOfDll,
                            utilBuff,
                            SAMP_CODE_LOAD );
            }
            break;
        case CREATE_THREAD_DEBUG_EVENT:
            newThread( debugEvent.dwThreadId, debugEvent.u.CreateThread.hThread );
            break;
        case EXIT_THREAD_DEBUG_EVENT:
            deadThread( debugEvent.dwThreadId );
            break;
        case EXIT_PROCESS_DEBUG_EVENT:
            doneSample = TRUE;
//          TerminateProcess( processHandle, 0 ); - already gone!!
            report();
            return;
        }
    }

} /* StartProg */
コード例 #23
0
ファイル: tools.c プロジェクト: FrankDMartinez/Typing
/* Reads typing data from allChars.txt and allDigraphs.txt.
 * 
 * Produces monographs and digraphs involving backspace by assuming that all 
 * characters are equally mistyped.
 */
void initTypingData()
{
	uint64_t i;
	FILE *file;
	
	file = fopen("allDigraphs.txt", "r");

	if( file == NULL ) {
		internalError( 7 );
		return;
	}
	if( digraphs == NULL ) {
		digraphs = createTable();
		if( digraphs == NULL ) {
			return;
		}
	}
	if( monographs == NULL ) {
		monographs = createTable();
		if( monographs == NULL ) {
			return;
		}
	}
	char key1;
	char key2;
	Value value;
	int c = '\0';
	i = 0;
	totalDi = 0;
	while (TRUE) {
		/* Skip any extra newlines. */
		while ((c = getc(file)) == '\n')
			;
		if (c == EOF) break;

		if (c == '\\') c = convertEscapeChar(getc(file));
		if (c == 0) {
			fprintf(stderr, "Error: In digraph file, unknown escape character \\%c.\n", c);
			fclose(file);
			return;
		}
		key1 = c;

		c = getc(file);
		if (c == '\\') c = convertEscapeChar(getc(file));
		if (c == 0) {
			fprintf(stderr, "Error: In digraph file, unknown escape character \\%c.\n", c);
			fclose(file);
			return;
		}
		key2 = c;
		
		c = getc(file); /* Skip the space between the digraph and the value. */
		
		if (strchr(keysToInclude, key1) && 
				strchr(keysToInclude, key2)) {
			value = 0;
			while ((c = getc(file)) != EOF && c >= '0' && c <= '9') {
				value *= 10;
				value += c - '0';
			}
			
			value /= DIVISOR;
			totalDi += value;

			char keys[3] = { key1, key2, '\0' };

			includeKeyInTable( keys, value, digraphs );
		}

		/* Skip all extra characters. */
		while (c != EOF && c != '\n')
			c = getc(file);
	}
	fclose(file);
	

	file = fopen("allChars.txt", "r");
	if( file == NULL ) {
		internalError( 8 );
		return;
	}
	c = '\0';
	i = 0;
	totalMon = 0;
	while (TRUE) {
		/* Skip any extra newlines. */
		while ((c = getc(file)) == '\n')
			;
		if (c == EOF) break;
		
		if (c == '\\') c = convertEscapeChar(getc(file));
		if (c == 0) {
			fprintf(stderr, "Error: In monograph file, unknown escape character \\%c.\n", c);
			return;
		}
		key1 = c;
		
		c = getc(file); /* Skip the space between the char and the value. */
		
		if (strchr(keysToInclude, key1)) {
			value = 0;
			while ((c = getc(file)) != EOF && c >= '0' && c <= '9') {
				value *= 10;
				value += c - '0';
			}
			
			value /= DIVISOR;
			totalMon += value;

			char keys[2] = { key1, '\0' };

			includeKeyInTable( keys, value, monographs );
		}

		/* Skip all extra characters. */
		while (c != EOF && c != '\n')
			c = getc(file);
	}
	
	fclose(file);
	
	/* If necessary, add the stats for backspace. */
	if (strchr(keysToInclude, '\b')) {
		const uint64_t used = monographs->kvt_used;
		KeystrokeValue *theTable = monographs->kvt_table;
		KeystrokeValue kv;
		Value theValue;
		Keystroke theStroke;
		char theStrokeToAdd[3] = { '\0', '\0', '\0' };
		char theKey;

		/* Add backpace to the digraph list. */
		for (i = 0; i < used; ++i) {
			kv = theTable[i];
			theValue = kv.theValue;
			theStroke = kv.theStroke;
			theKey = theStroke[0];
			value = theValue * ERROR_RATE_PERCENT / 100;
			theStrokeToAdd[0] = '\b';
			theStrokeToAdd[1] = theKey;
			includeKeyInTable(theStrokeToAdd, value, digraphs);
			theStrokeToAdd[0] = theKey;
			theStrokeToAdd[1] = '\b';
			includeKeyInTable(theStrokeToAdd, value, digraphs);
		}
	 
		/* Add backspace to the monograph list. */
   		theStrokeToAdd[0] = '\b';
   		theStrokeToAdd[1] = '\0';
		value = totalMon * ERROR_RATE_PERCENT / 100;
   		includeKeyInTable(theStrokeToAdd, value, monographs);
	}
	
	sortTable(digraphs, kvComparingValues);
	sortTable(monographs, kvComparingValues);
}
コード例 #24
0
ファイル: sampnt64.c プロジェクト: Azarien/open-watcom-v2
/*
 * StartProg - start sampling a program
 */
void StartProg( char *cmd, char *prog, char *full_args, char *dos_args )
{
    DWORD       code;
    DWORD       tid;
    CONTEXT     con;
    BOOL        waiting_for_first_bp;
    SIZE_T      len;
    DWORD       continue_how;
    BOOL        rc;
    seg_offset  where;
    DWORD       ttid;
    HANDLE      tth;

    cmd = cmd;

    strcpy( utilBuff, prog );
    strcat( utilBuff, " " );
    strcat( utilBuff, full_args );

    loadProg( prog, utilBuff );
    tid = debugEvent.dwThreadId;

    tth = CreateThread( NULL, 1024, TimerThread, NULL, 0, &ttid );
    if( !tth ) {
        internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );
    }
    /* attempt to ensure that we can get all of our samples in one shot */
    SetThreadPriority( tth, THREAD_PRIORITY_TIME_CRITICAL );

    Output( MsgArray[MSG_SAMPLE_1 - ERR_FIRST_MESSAGE] );
    Output( prog );
    Output( "\r\n" );

    waiting_for_first_bp = TRUE;
    continue_how = DBG_CONTINUE;

    for( ;; ) {
        ContinueDebugEvent( taskPid, tid, continue_how );
        rc = WaitForDebugEvent( &debugEvent, INFINITE );
        continue_how = DBG_CONTINUE;
        tid = debugEvent.dwThreadId;
        switch( debugEvent.dwDebugEventCode ) {
        case EXCEPTION_DEBUG_EVENT:
            code = debugEvent.u.Exception.ExceptionRecord.ExceptionCode;
            switch( code ) {
            case STATUS_SINGLE_STEP:
                if( timeOut ) {
                    myGetThreadContext( tid, &con );
                    RecordSample( con.Eip, con.SegCs, tid );
                    timeOut = FALSE;
                }
                break;
            case STATUS_BREAKPOINT:
                if( !waiting_for_first_bp ) {
                    myGetThreadContext( tid, &con );
                    con.Eip--;
                    if( (con.Edx & 0xffff) != 0 ) {    /* this is a mark */
                        ReadProcessMemory( processHandle, (LPVOID)con.Eax, utilBuff, BUFF_SIZE - 1, len );
                        utilBuff[len] = '\0';
                        where.segment = con.SegCs;
                        where.offset = con.Eip;
                        WriteMark( utilBuff, where );
                    } else {            /* this passes CommonAddr */
                        commonAddr.segment = con.Ecx & 0xffff;
                        commonAddr.offset = con.Ebx;
                    }
                } else {
                    waiting_for_first_bp = FALSE;
                }
                break;
            case STATUS_DATATYPE_MISALIGNMENT:
            case STATUS_ACCESS_VIOLATION:
            case STATUS_IN_PAGE_ERROR:
            case STATUS_NO_MEMORY:
            case STATUS_ILLEGAL_INSTRUCTION:
            case STATUS_NONCONTINUABLE_EXCEPTION:
            case STATUS_INVALID_DISPOSITION:
            case STATUS_ARRAY_BOUNDS_EXCEEDED:
            case STATUS_FLOAT_DENORMAL_OPERAND:
            case STATUS_FLOAT_DIVIDE_BY_ZERO:
            case STATUS_FLOAT_INVALID_OPERATION:
            case STATUS_FLOAT_OVERFLOW:
            case STATUS_FLOAT_STACK_CHECK:
            case STATUS_FLOAT_UNDERFLOW:
            case STATUS_INTEGER_DIVIDE_BY_ZERO:
            case STATUS_INTEGER_OVERFLOW:
            case STATUS_PRIVILEGED_INSTRUCTION:
            case STATUS_STACK_OVERFLOW:
            case STATUS_CONTROL_C_EXIT:
                if( debugEvent.u.Exception.dwFirstChance ) {
                    continue_how = DBG_EXCEPTION_NOT_HANDLED;
                } else {
                    Output( MsgArray[MSG_SAMPLE_4 - ERR_FIRST_MESSAGE] );
                    Output( "\r\n" );
                    doneSample = TRUE;
                    TerminateProcess( processHandle, 0 );
                    report();
                    return;
                }
                break;
            default:
                continue_how = DBG_EXCEPTION_NOT_HANDLED;
                break;
            }
            break;
        case LOAD_DLL_DEBUG_EVENT:
            if( GetDllName( &debugEvent.u.LoadDll, utilBuff, sizeof( utilBuff ) ) ) {
                codeLoad( debugEvent.u.LoadDll.hFile,
                            (DWORD) debugEvent.u.LoadDll.lpBaseOfDll,
                            utilBuff,
                            SAMP_CODE_LOAD );
            }
            break;
        case CREATE_THREAD_DEBUG_EVENT:
            newThread( debugEvent.dwThreadId, debugEvent.u.CreateThread.hThread );
            break;
        case EXIT_THREAD_DEBUG_EVENT:
            deadThread( debugEvent.dwThreadId );
            break;
        case EXIT_PROCESS_DEBUG_EVENT:
            doneSample = TRUE;
//          TerminateProcess( processHandle, 0 ); - already gone!!
            report();
            return;
        }
    }

} /* StartProg */
コード例 #25
0
/*
 * This is the memory allocator. When asked to allocate a buffer, allocate
 * it in such a way that the end of the buffer is followed by an inaccessable
 * memory page. If software overruns that buffer, it will touch the bad page
 * and get an immediate segmentation fault. It's then easy to zero in on the
 * offending code with a debugger.
 *
 * There are a few complications. If the user asks for an odd-sized buffer,
 * we would have to have that buffer start on an odd address if the byte after
 * the end of the buffer was to be on the inaccessable page. Unfortunately,
 * there is lots of software that asks for odd-sized buffers and then
 * requires that the returned address be word-aligned, or the size of the
 * buffer be a multiple of the word size. An example are the string-processing
 * functions on Sun systems, which do word references to the string memory
 * and may refer to memory up to three bytes beyond the end of the string.
 * For this reason, I take the alignment requests to memalign() and valloc()
 * seriously, and 
 * 
 * Electric Fence wastes lots of memory. I do a best-fit allocator here
 * so that it won't waste even more. It's slow, but thrashing because your
 * working set is too big for a system's RAM is even slower. 
 */
extern C_LINKAGE void *
ef_memalign(size_t alignment, size_t userSize)
{
	register Slot *	slot;
	register size_t	count;
	Slot *		fullSlot = 0;
	Slot *		emptySlots[2];
	size_t		internalSize;
	size_t		slack;
	char *		address;


	if ( userSize == 0 && !EF_ALLOW_MALLOC_0 )
		EF_Abort("Allocating 0 bytes, probably a bug.");

	/*
	 * If EF_PROTECT_BELOW is set, all addresses returned by malloc()
	 * and company will be page-aligned.
 	 */
	if ( !EF_PROTECT_BELOW && alignment > 1 ) {
		if ( (slack = userSize % alignment) != 0 )
			userSize += alignment - slack;
	}

	/*
	 * The internal size of the buffer is rounded up to the next page-size
	 * boudary, and then we add another page's worth of memory for the
	 * dead page.
	 */
	internalSize = userSize + bytesPerPage;
	if ( (slack = internalSize % bytesPerPage) != 0 )
		internalSize += bytesPerPage - slack;

	/*
	 * These will hold the addresses of two empty Slot structures, that
	 * can be used to hold information for any memory I create, and any
	 * memory that I mark free.
	 */
	emptySlots[0] = 0;
	emptySlots[1] = 0;

	/*
	 * The internal memory used by the allocator is currently
	 * inaccessable, so that errant programs won't scrawl on the
	 * allocator's arena. I'll un-protect it here so that I can make
	 * a new allocation. I'll re-protect it before I return.
 	 */
	if ( !noAllocationListProtection )
		Page_AllowAccess(allocationList, allocationListSize);

	/*
	 * If I'm running out of empty slots, create some more before
	 * I don't have enough slots left to make an allocation.
	 */
	if ( !internalUse && unUsedSlots < 7 ) {
		allocateMoreSlots();
	}
	
	/*
	 * Iterate through all of the slot structures. Attempt to find a slot
	 * containing free memory of the exact right size. Accept a slot with
	 * more memory than we want, if the exact right size is not available.
	 * Find two slot structures that are not in use. We will need one if
	 * we split a buffer into free and allocated parts, and the second if
	 * we have to create new memory and mark it as free.
	 *
	 */
	
	for ( slot = allocationList, count = slotCount ; count > 0; count-- ) {
		if ( slot->mode == FREE
		 && slot->internalSize >= internalSize ) {
			if ( !fullSlot
			 ||slot->internalSize < fullSlot->internalSize){
				fullSlot = slot;
				if ( slot->internalSize == internalSize
				 && emptySlots[0] )
					break;	/* All done, */
			}
		}
		else if ( slot->mode == NOT_IN_USE ) {
			if ( !emptySlots[0] )
				emptySlots[0] = slot;
			else if ( !emptySlots[1] )
				emptySlots[1] = slot;
			else if ( fullSlot
			 && fullSlot->internalSize == internalSize )
				break;	/* All done. */
		}
		slot++;
	}
	if ( !emptySlots[0] )
		internalError();

	if ( !fullSlot ) {
		/*
		 * I get here if I haven't been able to find a free buffer
		 * with all of the memory I need. I'll have to create more
		 * memory. I'll mark it all as free, and then split it into
		 * free and allocated portions later.
		 */
		size_t	chunkSize = MEMORY_CREATION_SIZE;

		if ( !emptySlots[1] )
			internalError();

		if ( chunkSize < internalSize )
			chunkSize = internalSize;

		if ( (slack = chunkSize % bytesPerPage) != 0 )
			chunkSize += bytesPerPage - slack;

		/* Use up one of the empty slots to make the full slot. */
		fullSlot = emptySlots[0];
		emptySlots[0] = emptySlots[1];
		fullSlot->internalAddress = Page_Create(chunkSize);
		fullSlot->internalSize = chunkSize;
		fullSlot->mode = FREE;
		unUsedSlots--;
	}

	/*
	 * If I'm allocating memory for the allocator's own data structures,
	 * mark it INTERNAL_USE so that no errant software will be able to
	 * free it.
	 */
	if ( internalUse )
		fullSlot->mode = INTERNAL_USE;
	else
		fullSlot->mode = ALLOCATED;

	/*
	 * If the buffer I've found is larger than I need, split it into
	 * an allocated buffer with the exact amount of memory I need, and
	 * a free buffer containing the surplus memory.
	 */
	if ( fullSlot->internalSize > internalSize ) {
		emptySlots[0]->internalSize
		 = fullSlot->internalSize - internalSize;
		emptySlots[0]->internalAddress
		 = ((char *)fullSlot->internalAddress) + internalSize;
		emptySlots[0]->mode = FREE;
		fullSlot->internalSize = internalSize;
		unUsedSlots--;
	}

	if ( !EF_PROTECT_BELOW ) {
		/*
		 * Arrange the buffer so that it is followed by an inaccessable
		 * memory page. A buffer overrun that touches that page will
		 * cause a segmentation fault.
		 */
		address = (char *)fullSlot->internalAddress;

		/* Set up the "live" page. */
		if ( internalSize - bytesPerPage > 0 )
				Page_AllowAccess(
				 fullSlot->internalAddress
				,internalSize - bytesPerPage);
			
		address += internalSize - bytesPerPage;

		/* Set up the "dead" page. */
		Page_DenyAccess(address, bytesPerPage);

		/* Figure out what address to give the user. */
		address -= userSize;
	}
	else {	/* EF_PROTECT_BELOW != 0 */
		/*
		 * Arrange the buffer so that it is preceded by an inaccessable
		 * memory page. A buffer underrun that touches that page will
		 * cause a segmentation fault.
		 */
		address = (char *)fullSlot->internalAddress;

		/* Set up the "dead" page. */
		Page_DenyAccess(address, bytesPerPage);
			
		address += bytesPerPage;

		/* Set up the "live" page. */
		if ( internalSize - bytesPerPage > 0 )
			Page_AllowAccess(address, internalSize - bytesPerPage);
	}

	fullSlot->userAddress = address;
	fullSlot->userSize = userSize;

	/*
	 * Make the pool's internal memory inaccessable, so that the program
	 * being debugged can't stomp on it.
	 */
	if ( !internalUse )
		Page_DenyAccess(allocationList, allocationListSize);

	return address;
}
コード例 #26
0
ファイル: cppcheck.cpp プロジェクト: 0x20e/cppcheck
unsigned int CppCheck::processFile(const std::string& filename)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (_settings._errorsOnly == false) {
        std::string fixedpath = Path::simplifyPath(filename.c_str());
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("..."));
    }

    try {
        Preprocessor preprocessor(&_settings, this);
        std::list<std::string> configurations;
        std::string filedata = "";

        if (!_fileContent.empty()) {
            // File content was given as a string
            std::istringstream iss(_fileContent);
            preprocessor.preprocess(iss, filedata, configurations, filename, _settings._includePaths);
        } else {
            // Only file name was given, read the content from file
            std::ifstream fin(filename.c_str());
            Timer t("Preprocessor::preprocess", _settings._showtime, &S_timerResults);
            preprocessor.preprocess(fin, filedata, configurations, filename, _settings._includePaths);
        }

        if (_settings.checkConfiguration) {
            return 0;
        }

        if (!_settings.userDefines.empty()) {
            configurations.clear();
            configurations.push_back(_settings.userDefines);
        }

        if (!_settings._force && configurations.size() > _settings._maxConfigs) {
            if (_settings.isEnabled("information")) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        unsigned int checkCount = 0;
        for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings._force && ++checkCount > _settings._maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (_settings._errorsOnly == false && it != configurations.begin()) {
                std::string fixedpath = Path::simplifyPath(filename.c_str());
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut(std::string("Checking ") + fixedpath + ": " + cfg + std::string("..."));
            }

            Timer t("Preprocessor::getcode", _settings._showtime, &S_timerResults);
            const std::string codeWithoutCfg = preprocessor.getcode(filedata, *it, filename, _settings.userDefines.empty());
            t.Stop();

            const std::string &appendCode = _settings.append();

            if (_settings.debugFalsePositive) {
                if (findError(codeWithoutCfg + appendCode, filename.c_str())) {
                    return exitcode;
                }
            } else {
                checkFile(codeWithoutCfg + appendCode, filename.c_str());
            }
        }
    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
    }

    if (!_settings._errorsOnly)
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename));

    _errorList.clear();
    return exitcode;
}
コード例 #27
0
bool ExtensionsParser::endElement(const QString& /*uri*/, const QString& elementName, const QString& /*qName*/)
{
  switch (stateStack.back())
  {
  case IGNORED_ELEMENT_STATE :
  {
    stateStack.pop();
    return true;
  }
  case INITIAL_STATE :
  {
    // shouldn't get here
    internalError(QString("Element/end element mismatch for element \"%1\".").arg(elementName));
    return false;
  }
  case PLUGIN_STATE :
  {
    stateStack.pop();

    QList<RegistryObject::Pointer>& extensionPoints = scratchVectors[EXTENSION_POINT_INDEX];
    QList<RegistryObject::Pointer>& extensions = scratchVectors[EXTENSION_INDEX];
    QList<int> namespaceChildren;
    namespaceChildren.push_back(0);
    namespaceChildren.push_back(0);
    // Put the extension points into this namespace
    if (extensionPoints.size() > 0)
    {
      namespaceChildren[RegistryContribution::EXTENSION_POINT] = extensionPoints.size();
      for (int i = 0; i < extensionPoints.size(); ++i)
      {
        namespaceChildren.push_back(extensionPoints[i]->GetObjectId());
      }
      extensionPoints.clear();
    }

    // Put the extensions into this namespace too
    if (extensions.size() > 0)
    {
      namespaceChildren[RegistryContribution::EXTENSION] = extensions.size();
      for (int i = 0; i < extensions.size(); ++i)
      {
        namespaceChildren.push_back(extensions[i]->GetObjectId());
      }
      extensions.clear();
    }
    contribution->SetRawChildren(namespaceChildren);
    return true;
  }
  case PLUGIN_EXTENSION_POINT_STATE :
  {
    if (elementName == EXTENSION_POINT)
    {
      stateStack.pop();
    }
    return true;
  }
  case PLUGIN_EXTENSION_STATE :
  {
    if (elementName == EXTENSION)
    {
      stateStack.pop();
      // Finish up extension object
      Extension::Pointer currentExtension = objectStack.pop().Cast<Extension>();
      if (currentExtension->GetNamespaceIdentifier().isEmpty())
        currentExtension->SetNamespaceIdentifier(contribution->GetDefaultNamespace());
      currentExtension->SetContributorId(contribution->GetContributorId());
      scratchVectors[EXTENSION_INDEX].push_back(currentExtension);
    }
    return true;
  }
  case CONFIGURATION_ELEMENT_STATE :
  {
    // We don't care what the element name was
    stateStack.pop();
    // Now finish up the configuration element object
    configurationElementValue.clear();
    ConfigurationElement::Pointer currentConfigElement = objectStack.pop().Cast<ConfigurationElement>();

    QString value = currentConfigElement->GetValueAsIs();
    if (!value.isEmpty())
    {
      currentConfigElement->SetValue(translate(value).trimmed());
    }

    RegistryObject::Pointer parent = objectStack.back().Cast<RegistryObject>();
    // Want to add this configuration element to the subelements of an extension
    QList<int> newValues = parent->GetRawChildren();
    newValues.push_back(currentConfigElement->GetObjectId());
    parent->SetRawChildren(newValues);
    currentConfigElement->SetParentId(parent->GetObjectId());
    currentConfigElement->SetParentType(parent.Cast<ConfigurationElement>() ?
                                          RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::EXTENSION);
    return true;
  }
  default:
    // should never get here
    return false;
  }
}
コード例 #28
0
ファイル: text.c プロジェクト: apc-llc/cernlib
/***********************************************************************
DESCRIPTION:
    Read a floating point value from a text widget with syntax error cheking.
    The value is read only if it have been changed since the last reading
    as indicated by status. If a syntax error have been found, the
    text field is visually marked and a warning message is popped up.
    An empty field is not considered an error by this function, and
    0.0 is returned as the value. If the value has been succesfully read,
    it is checked by a user-supplied function valueok, and if rejected,
    the error is signaled as before with a user-supplied message given
    in the argument msg.

ARGUMENTS:
    text - text widget
    *status - current status of the field on input, new status on
        output (enum textstatus)
    *dval - the read value is returned if there was no syntax error and
        the field is not empty
    valueok - a function which given a pointer to the value read, returns
        1 if the application accepts it and 0 if not; if the field is
        empty, the pointer to the value is NULL

EXTERNALS: None
***********************************************************************/
void textReadFloat(Widget text, TextStatusInfo *status,
    double *dp, int (*valueok)(double dval))
{
    String textstr;
    int sign = 1;
    double dval;

    if (status->change != TEXTSTAT_CHANGED) {
        currErrorCode = TEXT_NOCHANGE;
        return;
    }
    currErrorCode = TEXT_OK;

    XtVaGetValues(text,XmNvalue, &textstr,NULL);

    /****** read and analyze the field *****/
    lx_load(textstr);
    lx_next();
    if (lx_token.type == NEWLINE_T) { /* empty field */
        dval = 0.0;
        currErrorCode = TEXT_EMPTY;
        goto ok_proc;
    }

    if (lx_token.type == OPER_T+'+') lx_next();
    else if (lx_token.type == OPER_T+'-') {sign = -1; lx_next();}
    if (lx_token.type == DOUBLE_T) {
        dval = sign*lx_token.val.d;
        currErrorCode = TEXT_OK;
    }
    else if (lx_token.type == INT_T) {
        dval = sign*(double)lx_token.val.i;
        currErrorCode = TEXT_OK;
    }
    else {
        currErrorCode = TEXT_INVALID;
        goto endproc;
    }

    lx_next();
    if (lx_token.type != NEWLINE_T) {
        currErrorCode = TEXT_INVDAFTER;
        goto endproc;
    }

    /***** perform user check *****/
ok_proc:
    valueok(dval); /* changes error code according to user preference */

    /***** return the number or signal the error *****/
endproc:
    status->change = TEXTSTAT_NOCHANGE;
    switch (currErrorCode) {
    case TEXT_OK:
        if (status->stat==TEXTSTAT_SYNTERROR) utl_markTextValid(text);
        *dp = dval;
        status->stat = (status->stat&TEXTSTAT_SEMANTERROR)|TEXTSTAT_READOK;
    break;
    case TEXT_EMPTY:
        if (status->stat==TEXTSTAT_SYNTERROR) utl_markTextValid(text);
        *dp = dval;
        status->stat = (status->stat&TEXTSTAT_SEMANTERROR)|TEXTSTAT_EMPTY;
    break;
    case TEXT_INVALID:
    case TEXT_INVDAFTER:
    case TEXT_INVDEMPTY:
    case TEXT_INVDNONPOS:
        if (!(status->stat&TEXTSTAT_ANYERROR)) utl_markTextInvalid(text);
        status->stat = (status->stat&TEXTSTAT_SEMANTERROR)|TEXTSTAT_SYNTERROR;
    break;
    case TEXT_NOCHANGE:
    default:
        internalError();
    }
}
コード例 #29
0
ファイル: cppcheck.cpp プロジェクト: akalenuk/cppcheck
unsigned int CppCheck::processFile(const std::string& filename, const std::string& fileContent)
{
    exitcode = 0;

    // only show debug warnings for accepted C/C++ source files
    if (!Path::acceptFile(filename))
        _settings.debugwarnings = false;

    if (_settings.terminated())
        return exitcode;

    if (_settings._errorsOnly == false) {
        std::string fixedpath = Path::simplifyPath(filename);
        fixedpath = Path::toNativeSeparators(fixedpath);
        _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("..."));
    }

    try {
        Preprocessor preprocessor(&_settings, this);
        std::list<std::string> configurations;
        std::string filedata = "";

        if (!fileContent.empty()) {
            // File content was given as a string (democlient)
            std::istringstream iss(fileContent);
            preprocessor.preprocess(iss, filedata, configurations, filename, _settings._includePaths);
        } else {
            // Only file name was given, read the content from file
            std::ifstream fin(filename.c_str());
            Timer t("Preprocessor::preprocess", _settings._showtime, &S_timerResults);
            preprocessor.preprocess(fin, filedata, configurations, filename, _settings._includePaths);
        }

        if (_settings.checkConfiguration) {
            return 0;
        }

        // Run rules on this code
        for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) {
            if (it->tokenlist == "define") {
                Tokenizer tokenizer2(&_settings, this);
                std::istringstream istr2(filedata);
                tokenizer2.list.createTokens(istr2, filename);

                for (const Token *tok = tokenizer2.list.front(); tok; tok = tok->next()) {
                    if (tok->str() == "#define") {
                        std::string code = std::string(tok->linenr()-1U, '\n');
                        for (const Token *tok2 = tok; tok2 && tok2->linenr() == tok->linenr(); tok2 = tok2->next())
                            code += " " + tok2->str();
                        Tokenizer tokenizer3(&_settings, this);
                        std::istringstream istr3(code);
                        tokenizer3.list.createTokens(istr3, tokenizer2.list.file(tok));
                        executeRules("define", tokenizer3);
                    }
                }
                break;
            }
        }

        if (!_settings.userDefines.empty() && _settings._maxConfigs==1U) {
            configurations.clear();
            configurations.push_back(_settings.userDefines);
        }

        if (!_settings._force && configurations.size() > _settings._maxConfigs) {
            if (_settings.isEnabled("information")) {
                tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
            } else {
                tooManyConfigs = true;
            }
        }

        unsigned int checkCount = 0;
        for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
            // Check only a few configurations (default 12), after that bail out, unless --force
            // was used.
            if (!_settings._force && ++checkCount > _settings._maxConfigs)
                break;

            cfg = *it;

            // If only errors are printed, print filename after the check
            if (_settings._errorsOnly == false && it != configurations.begin()) {
                std::string fixedpath = Path::simplifyPath(filename);
                fixedpath = Path::toNativeSeparators(fixedpath);
                _errorLogger.reportOut(std::string("Checking ") + fixedpath + ": " + cfg + std::string("..."));
            }

            if (!_settings.userDefines.empty()) {
                if (!cfg.empty())
                    cfg = ";" + cfg;
                cfg = _settings.userDefines + cfg;
            }

            Timer t("Preprocessor::getcode", _settings._showtime, &S_timerResults);
            const std::string codeWithoutCfg = preprocessor.getcode(filedata, cfg, filename);
            t.Stop();

            const std::string &appendCode = _settings.append();

            if (_settings.debugFalsePositive) {
                if (findError(codeWithoutCfg + appendCode, filename.c_str())) {
                    return exitcode;
                }
            } else {
                checkFile(codeWithoutCfg + appendCode, filename.c_str());
            }
        }
    } catch (const std::runtime_error &e) {
        internalError(filename, e.what());
    } catch (const InternalError &e) {
        internalError(filename, e.errorMessage);
    }

    if (_settings.isEnabled("information") || _settings.checkConfiguration)
        reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename));

    _errorList.clear();
    return exitcode;
}
コード例 #30
0
ファイル: server_f.c プロジェクト: Jtfinlay/C379
int main(int argc, char * argv[])
{
	struct sockaddr_in sockname, client;
	struct sigaction sa;
	char *ep, *inbuff, *tmp;
	char outbuff[256];

	int clientlen, sd;

	u_short port;
	u_long p;
	pid_t pid;
	
		/* daemonize */
#ifndef DEBUG
	/* don't daemonize if we compile with -DDEBUG */
	if (daemon(1,1) == -1)
		err(1, "daemon() failed");
#endif

	/* check params */
	if (argc != 4)
		usage();

	errno = 0;
	p = strtoul(argv[1], &ep, 10);
	if (&argv[1] == '\0' || *ep != '\0'){
		/* parameter wasn't a number, or was empty */
		fprintf(stderr, "%s - not a number\n", argv[1]);
		usage();
	}
	if ((errno == ERANGE && p == ULONG_MAX) || (p > USHRT_MAX)) {
		/* It's a number, but it either can't fit in an unsigned
		 * long, or it is too big for an unsigned short */
		fprintf(stderr, "%s - value out of range\n", argv[1]);
		usage();
	}
	
	/* Ensure argv[2] is a valid directory */
	
	if (chdir(argv[2]) == -1)
		err(1, "chdir failed");
		
	/* TODO : Ensure argv[3] is a valid file */
	LOG_FILE = argv[3];

	/* now safe to do this */
	port = p;

	memset(&sockname, 0, sizeof(sockname));
	sockname.sin_family = AF_INET;
	sockname.sin_port = htons(port);
	sockname.sin_addr.s_addr = htonl(INADDR_ANY);
	sd = socket(AF_INET, SOCK_STREAM, 0);

	if (sd == -1)
		err(1, "socket failed");
	if (bind(sd, (struct sockaddr *) &sockname, sizeof(sockname)) == -1)
		err(1, "bind failed");
	if (listen(sd, 3) == -1)
		err(1, "listen failed");

	/* We are now bound and listening for connections on "sd" */

	/* Catch SIGCHLD to stop zombie children wandering around */
	sa.sa_handler = kidhandler;
	sigemptyset(&sa.sa_mask);

	/* allow system calls (accept) to restart if interrupted by SIGCHLD */
	sa.sa_flags = SA_RESTART;
	if (sigaction(SIGCHLD, &sa, NULL) == -1)
		err(1, "sigaction failed");

	/* main loop. Accept connections and do stuff */
	for(;;) {
		int clientsd;
		ssize_t written, w;
	
		clientlen = sizeof(&client);
		clientsd = accept(sd, (struct sockaddr *)&client, &clientlen);
		if (clientsd == -1)
			err(1, "accept failed");
		
		/* fork child to deal with each connection */
		pid = fork();
		if (pid == -1)
			internalError((struct sockaddr *)&client, 
				"fork failed", NULL);		

		if (pid == 0) {
			char * getLine, *fName;
			int valid, written;
			long lSize;
			FILE * fp;
			
			/* Parse GET */
			inbuff = malloc(12800*sizeof(char));
			fName = malloc(256*sizeof(char));
			if (inbuff == NULL || fName == NULL)
				internalError(&client, "malloc failed", NULL);

			readSocket(clientsd, inbuff, 12800);

			getLine = malloc(256*sizeof(char));
			if (getLine == NULL)
				internalError(&client, "malloc failed", NULL);
			
			valid = checkGET(inbuff, fName, getLine);
			fName++;


			if (valid == 0) {
				/* BAD REQUEST */
				sendBadRequestError(clientsd);
				logBadRequest(getIPString(&client), getLine);
			} else {
				/* GET is good. Try reading file & sending */

				fp = fopen(fName, "r");
				if (fp == NULL) {
					if (errno == ENOENT) {
						sendNotFoundError(clientsd);
						logNotFound(
							getIPString(&client),
							 getLine);
					} else if (errno == EACCES) {
						sendForbiddenError(clientsd);
						logForbidden(
							getIPString(&client), 
							getLine);
					} else 
						internalError(&client, 
							"fopen failed", 
							getLine);
				} else {
					
					/* get file size */
					fseek(fp, sizeof(char), SEEK_END);
					lSize = ftell(fp);
					rewind(fp);
					/* send OK and file */
				
					sendOK(clientsd, lSize);
					written = sendFile(fp, clientsd);
					logOK(getIPString(&client), getLine, 
						written, lSize-1);
				}		
				fclose(fp);
			}

			/* Clean up */
			fName--;
			free(getLine);
			free(inbuff);
			free(fName);
			fName = NULL;
			getLine = NULL;
			inbuff = NULL;

			exit(0);
		}
		close(clientsd);
	}
}