示例#1
0
文件: tilek.cpp 项目: imace/rose-1
SgFunctionParameterList * Kernel<Annotation, Runtime>::createParameterList() const {
  const std::list<SgVariableSymbol *> & params = getArguments().parameters;
  const std::list<SgVariableSymbol *> & scalars = getArguments().scalars;
  const std::list<Data<DLX::KLT::Annotation<DLX::TileK::language_t> > *> & datas = getArguments().datas;

  std::list<SgVariableSymbol *>::const_iterator it_var_sym;
  std::list<Data<DLX::KLT::Annotation<DLX::TileK::language_t> > *>::const_iterator it_data;

  SgFunctionParameterList * result = SageBuilder::buildFunctionParameterList();

  result->append_arg(SageBuilder::buildInitializedName("param",  SageBuilder::buildPointerType(SageBuilder::buildIntType()), NULL));
  result->append_arg(SageBuilder::buildInitializedName("data",   SageBuilder::buildPointerType(SageBuilder::buildPointerType(SageBuilder::buildVoidType())), NULL));
  result->append_arg(SageBuilder::buildInitializedName("scalar", SageBuilder::buildPointerType(SageBuilder::buildPointerType(SageBuilder::buildVoidType())), NULL));

  result->append_arg(Runtime::kernel_api.createContext());

  return result;
}
示例#2
0
void AdaptivePath::update() {
  double weight2 = -1.*mypathv->dx;
  double weight1 = 1.0 + mypathv->dx;
  if( weight1>1.0 ) {
    weight1=1.0; weight2=0.0;
  } else if( weight2>1.0 ) {
    weight1=0.0; weight2=1.0;
  }
  // Add projections to dispalcement accumulators
  ReferenceConfiguration* myref = getReferenceConfiguration( mypathv->iclose1 );
  myref->extractDisplacementVector( getPositions(), getArguments(), mypathv->cargs, false, displacement );
  getReferenceConfiguration( mypathv->iclose2 )->extractDisplacementVector( myref->getReferencePositions(), getArguments(), myref->getReferenceArguments(), false, displacement2 );
  displacement.addDirection( -mypathv->dx, displacement2 );
  pdisplacements[mypathv->iclose1].addDirection( weight1, displacement );
  pdisplacements[mypathv->iclose2].addDirection( weight2, displacement );
  // Update weight accumulators
  wsum[mypathv->iclose1] *= fadefact;
  wsum[mypathv->iclose2] *= fadefact;
  wsum[mypathv->iclose1] += weight1;
  wsum[mypathv->iclose2] += weight2;

  // This does the update of the path if it is time to
  if( (getStep()>0) && (getStep()%update_str==0) ) {
    wsum[fixedn[0]]=wsum[fixedn[1]]=0.;
    for(unsigned inode=0; inode<getNumberOfReferencePoints(); ++inode) {
      if( wsum[inode]>0 ) {
        // First displace the node by the weighted direction
        getReferenceConfiguration( inode )->displaceReferenceConfiguration( 1./wsum[inode], pdisplacements[inode] );
        // Reset the displacement
        pdisplacements[inode].zeroDirection();
      }
    }
    // Now ensure all the nodes of the path are equally spaced
    PathReparameterization myspacings( getPbc(), getArguments(), getAllReferenceConfigurations() );
    myspacings.reparameterize( fixedn[0], fixedn[1], tolerance );
  }
  if( (getStep()>0) && (getStep()%wstride==0) ) {
    pathfile.printf("# PATH AT STEP %d TIME %f \n", getStep(), getTime() );
    std::vector<ReferenceConfiguration*>& myconfs=getAllReferenceConfigurations();
    for(unsigned i=0; i<myconfs.size(); ++i) myconfs[i]->print( pathfile, ofmt, atoms.getUnits().getLength()/0.1 );
    pathfile.flush();
  }
}
示例#3
0
vector<wstring> ConnectedShortcut::getLArgs() const
{
	CommandLineParser cli;
	cli.allowAllKeys();
	try {
		cli.parse(getArguments());
		return cli.getLArgs();
	}
	catch (CLIException&) {
		return {};
	}
}
示例#4
0
/* Simulates a shell, i.e., gets command names and executes them */
int main(int argc, char *argv[])
{

  char commandLine[COMMAND_LINE_LENGTH+1]; 
  char *arguments[MAX_NUM_ARGS];
  
  printf("Welcome to Extremely Simple Shell\n");

  int exit= 0;
  do { 
      int status;
      char *temp;
      
      /* Prints the command prompt */
      printf("\n$ ");
      
      /* Reads the command line and stores it in array commandLine */
      getLine(commandLine,COMMAND_LINE_LENGTH+1);

      /* The user did not enter any commands */
      if (!strcmp(commandLine,""))
         continue;
      
      /* Breaks the command line into arguments and stores the arguments in arguments array */
      int numArgs = getArguments(commandLine,arguments);
      
      /* Terminates the program when the user types exit or quit */
      if (!strcmp(arguments[0],"quit") || !strcmp(arguments[0],"exit"))
         break;
         
      /* Creates a child process */   
      int pid = fork();
      
      switch (pid)
      {
          case 0: /* Executed by the child process only */ 
                  execvp(arguments[0],arguments);
                  perror("Exec error\n");
                  break;
          case -1: /* Executed only when the fork system call fails */
                  perror("Fork error\n");
                  break;
          default: /* Executed by parent process only  */
                  wait(&status);
                  break;        
      }
  }
  while (1); /* Use int values to represent boolean in C language: 0 denotes false, non-zero denotes true */


  return 0;
}
示例#5
0
文件: NEModule.cpp 项目: kniz/World
	NEBinaryFileSaver& NEModule::serialize(NEBinaryFileSaver& saver) const
	{
		NENamedUnit::serialize(saver);

		/*
			Argument의 저장:
				NEKeyNameBinder::serialize를 참고 해보면 상위클래스인 NEKeyBinder를 호출하지 않는다.
				이는 의도적인 행동으로, 바인딩 결과물인 NEKeyBinder 객체의 데이터를 공유하지 않기 위함이다.
					"상위클래스의 바인딩결과 정보는 공유(저장 및 로드)할 수 없다" 
				에 따라, 매 로드시마다 바인딩을 시도 하게 된다.
		*/
		return saver << getArguments();
	}
示例#6
0
void Tree::lookupAndSetTypeDefinitionInCurrentTree(
    Type* type,
    const NameBindings& scope,
    const Location& location) {

    auto definition = scope.lookupType(type->getName());
    if (definition == nullptr) {
        Trace::error("Unknown type: " + type->getName(), location);
    }

    type->setDefinition(definition);

    auto classDefinition = definition->dynCast<ClassDefinition>();
    if (classDefinition != nullptr && classDefinition == getCurrentClass()) {
        classDefinition->setRecursive(true);
    }

    if (type->isFunction()) {
        auto signature = type->getFunctionSignature();
        lookupAndSetTypeDefinitionInCurrentTree(signature->getReturnType(),
                                                scope,
                                                location);
        for (auto argumentType: signature->getArguments()) {
            lookupAndSetTypeDefinitionInCurrentTree(argumentType,
                                                    scope,
                                                    location);
        }
    }

    if (type->hasGenericTypeParameters()) {
        // The type has generic type parameters. This means the type must refer
        // to a generic class.
        if (classDefinition == nullptr) {
            Trace::error("Only classes can take type parameters: " +
                          type->getName(),
                          location);
        }

        if (!classDefinition->isGeneric()) {
            Trace::error("Only generic classes can take type parameters: " +
                          type->getName(),
                          location);
        }

        for (auto typeParameter: type->getGenericTypeParameters()) {
            lookupAndSetTypeDefinitionInCurrentTree(typeParameter,
                                                    scope,
                                                    location);
        }
    }
}
示例#7
0
static TCHAR *parseAddAlias(ARGUMENTSINFO *ai)
{
	int res;
	char *szHelp, *szArgsA;

	if (ai->argc != 3)
		return NULL;

	TCHAR *cur = ai->targv[1];
	while (isValidTokenChar(*cur))
		cur++;

	ptrT alias(mir_tstrndup(ai->targv[1], cur - ai->targv[1]));

	int argc;
	TCHAR **argv;
	getArguments(cur, &argv, &argc);
	deRegisterToken(alias);
	addToAliasRegister(alias, argc, argv, ai->targv[2]);
	TCHAR *szArgs = NULL;
	for (int i = 0; i < argc; i++) {
		if (i == 0)
			szArgs = (TCHAR*)mir_calloc((_tcslen(argv[i]) + 2)*sizeof(TCHAR));
		else
			szArgs = (TCHAR*)mir_realloc(szArgs, (_tcslen(szArgs) + _tcslen(argv[i]) + 2)*sizeof(TCHAR));

		_tcscat(szArgs, argv[i]);
		if (i != argc - 1)
			_tcscat(szArgs, _T(","));
	}
	if (szArgs != NULL && argc > 0) {
		szArgsA = mir_t2a(szArgs);

		size_t size = 32 + strlen(szArgsA);
		szHelp = (char *)mir_alloc(size);
		memset(szHelp, '\0', 32 + strlen(szArgsA));
		mir_snprintf(szHelp, size, LPGEN("Alias")"\t(%s)\t"LPGEN("user defined"), szArgsA);
		res = registerIntToken(alias, parseTranslateAlias, TRF_FUNCTION | TRF_UNPARSEDARGS, szHelp);
		mir_free(szArgsA);
	}
	else {
		szHelp = (char*)mir_alloc(32);
		memset(szHelp, '\0', 32);
		mir_snprintf(szHelp, 32, LPGEN("Alias")"\t\t"LPGEN("user defined"));
		res = registerIntToken(alias, parseTranslateAlias, TRF_FIELD | TRF_UNPARSEDARGS, szHelp);
	}
	mir_free(szArgs);
	mir_free(szHelp);
	return (res == 0) ? mir_tstrdup(_T("")) : NULL;
}
示例#8
0
void CheckFunctions::memsetInvalid2ndParam()
{
// FIXME:
//  Replace this with library configuration.
//  For instance:
//     <arg nr="2">
//       <not-float/>
//       <warn possibleIntValue=":-129,256:" severity="warning" msg="..."/>
//     </arg>

    const bool printPortability = _settings->isEnabled(Settings::PORTABILITY);
    const bool printWarning = _settings->isEnabled(Settings::WARNING);
    if (!printWarning && !printPortability)
        return;

    const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
    const std::size_t functions = symbolDatabase->functionScopes.size();
    for (std::size_t i = 0; i < functions; ++i) {
        const Scope * scope = symbolDatabase->functionScopes[i];
        for (const Token* tok = scope->classStart->next(); tok && (tok != scope->classEnd); tok = tok->next()) {
            if (!Token::simpleMatch(tok, "memset ("))
                continue;

            const std::vector<const Token *> args = getArguments(tok);
            if (args.size() != 3)
                continue;

            // Second parameter is zero literal, i.e. 0.0f
            const Token * const secondParamTok = args[1];
            if (Token::Match(secondParamTok, "%num% ,") && MathLib::isNullValue(secondParamTok->str()))
                continue;

            // Check if second parameter is a float variable or a float literal != 0.0f
            if (printPortability && astIsFloat(secondParamTok,false)) {
                memsetFloatError(secondParamTok, secondParamTok->expressionString());
            }

            if (printWarning && secondParamTok->isNumber()) { // Check if the second parameter is a literal and is out of range
                const long long int value = MathLib::toLongNumber(secondParamTok->str());
                if (value < -128 || value > 255) // FIXME: Use platform char_bits
                    memsetValueOutOfRangeError(secondParamTok, secondParamTok->str());
            }
        }
    }
}
void Car::evaluate() {
	// Car should only get a list as input so if arguments has more than one
	// element something is wrong and we will return ""
	if (arguments.size() > 1 || arguments.size() == 0){
		result = "";
	} else {
		// My arguments are only lists so we can treat them as functions to
		// get their arguments
		Expression* myArgumentArgument;
		Function* firstArg = ((Function*)(getArguments().front()));
		if (firstArg->getArguments().size() != 0){
			// Get the first element of my argument
			myArgumentArgument = firstArg->getArguments().front();
			firstArg = (Function*)myArgumentArgument;
		}
		firstArg->evaluate();
		result = firstArg->getResult();
	}
}
示例#10
0
   INT32 iPmdDMNChildProc::start()
   {
      INT32 rc = SDB_OK;
      ossResultCode result;
#if defined  (_LINUX)
      OSSPID childPid = OSS_INVALID_PID;
      childPid = fork();
      PD_CHECK( childPid >= 0, SDB_SYS, error, PDERROR,
               "fork() error!" );
      if ( 0 == childPid )
      {
#endif
      rc = ossExec( getExecuteFile(), getArguments(), NULL,
                    0, _pid, result, NULL, NULL );
#if defined  (_LINUX)
      if ( SDB_OK != rc )
      {
         PD_LOG( PDERROR, "failed to start service(rc=%d)", rc );
      }
      exit(0);
      }
      else if ( -1 == childPid )
      {
         rc = SDB_SYS;
         PD_LOG( PDERROR, "Failed to fork!" );
      }
      else
      {
         waitpid( childPid, NULL, 0 );
      }
#endif

      PD_RC_CHECK( rc, PDERROR, "failed to start service(rc=%d)", rc );
   done:
      return rc;
   error:
      goto done;
   }
示例#11
0
文件: test.c 项目: luoken/cs370
int main(int argc, char** argv)
{
  // MPI_Status status;
  // Initialize the MPI environment
  MPI_Init(NULL, NULL);

  // Get the number of processes
  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  MPI_Get_processor_name(processor_name, &name_len);

  int proceed_flag = 0;
  int n = 0;
  int z = 0;
  int seed = 0;

  if (my_rank == 0) {
    proceed_flag = getArguments(argc, argv, &n, &z, &seed);
  }

  // broadcast instruction
  MPI_Bcast(&proceed_flag, 1, MPI_INT, 0, MPI_COMM_WORLD);

  if (proceed_flag == TRUE) {
    if (my_rank == 0) {
      doManager(n, z, seed);
    } else {
      doWorker();
    }
  }

  printf("[%s.%d] program completed\n", processor_name, my_rank);

  // Finalize the MPI environment.
  MPI_Finalize();

  return 0;
}
示例#12
0
void ConnectedShortcut::connect(const wstring& settingsArgs)
{
	if (isConnected())
		return;
	
	wstring args = getArguments();
	wstring target = CommandLineParser::escapeArgument(getPath());
	wstring description = SHORT_APP_NAME L" + " + getDescription();
	wstring workingDirectory = getWorkingDirectory();

	if (!args.empty())
		target.push_back(L' ');
	if (!settingsArgs.empty() && settingsArgs.back() != L' ')
		target.insert(target.begin(), L' ');

	// SetPath seems to change the working directory, too.
	// We want to keep the original directory, however.
	m_pLink->SetPath(getSelfPath().data());
	m_pLink->SetArguments((settingsArgs + target + args).data());
	m_pLink->SetDescription(description.data());
	m_pLink->SetWorkingDirectory(workingDirectory.data());

	m_isConnectedCachedResult = true;
}
	/*
	* Main command handler. This will be executed, before any of the sub command handlers.
	* It uses polymorphism to map the commands.
	*/
	static bool handlePremiumCommand(ChatHandler* handler, const char* args)
	{
		Player* player = handler->GetSession()->GetPlayer();

			if (PREM::IsPlayerPremium(player))
				return_type = true;
			else
				return false;

		std::vector<char*> arguments = getArguments(args);
		if (arguments.size() == 0)
			return false;

		std::string command = arguments[0];
		arguments.erase(arguments.begin());

		PremCommand* commandHandler = command_map[command];
		if (commandHandler == NULL)
			return false;

		commandHandler->handleCommand(handler, player);

		return true;
	}
示例#14
0
ActionWithAveraging::ActionWithAveraging( const ActionOptions& ao ):
  Action(ao),
  ActionPilot(ao),
  ActionAtomistic(ao),
  ActionWithArguments(ao),
  ActionWithValue(ao),
  ActionWithVessel(ao),
  myaverage(NULL),
  useRunAllTasks(false),
  clearstride(0),
  lweight(0),cweight(0)
{
  if( keywords.exists("CLEAR") ) {
    parse("CLEAR",clearstride);
    if( clearstride>0 ) {
      if( clearstride%getStride()!=0 ) error("CLEAR parameter must be a multiple of STRIDE");
      log.printf("  clearing grid every %u steps \n",clearstride);
    }
  }
  if( keywords.exists("LOGWEIGHTS") ) {
    std::vector<std::string> wwstr; parseVector("LOGWEIGHTS",wwstr);
    if( wwstr.size()>0 ) log.printf("  reweighting using weights from ");
    std::vector<Value*> arg( getArguments() );
    for(unsigned i=0; i<wwstr.size(); ++i) {
      ActionWithValue* val = plumed.getActionSet().selectWithLabel<ActionWithValue*>(wwstr[i]);
      if( !val ) error("could not find value named");
      weights.push_back( val->copyOutput(val->getLabel()) );
      arg.push_back( val->copyOutput(val->getLabel()) );
      log.printf("%s ",wwstr[i].c_str() );
    }
    if( wwstr.size()>0 ) log.printf("\n");
    else log.printf("  weights are all equal to one\n");
    requestArguments( arg );
  }
  if( keywords.exists("UNORMALIZED") ) parseFlag("UNORMALIZED",unormalised);
}
示例#15
0
//
//  MAIN program
//
int __cdecl main(int argc, char *argv[]) {
    short    rexxrc = 0;                 /* return code from rexx             */
    int   i;                             /* loop counter                      */
    int  rc;                             /* actually running program RC       */
    const char *program_name;            /* name to run                       */
    char  arg_buffer[8192];              /* starting argument buffer          */
    char *cp;                            /* option character pointer          */
    CONSTRXSTRING arguments;             /* rexxstart argument                */
    size_t argcount;
    RXSTRING rxretbuf;                   // program return buffer
    BOOL from_string = FALSE;            /* running from command line string? */
    BOOL real_argument = TRUE;           /* running from command line string? */
    RXSTRING instore[2];

    RexxInstance        *pgmInst;
    RexxThreadContext   *pgmThrdInst;
    RexxArrayObject      rxargs, rxcargs;
    RexxDirectoryObject  dir;
    RexxObjectPtr        result;

    rc = 0;                              /* set default return                */

    /*
     * Convert the input array into a single string for the Object REXX
     * argument string. Initialize the RXSTRING variable to point to this
     * string. Keep the string null terminated so we can print it for debug.
     * First argument is name of the REXX program
     * Next argument(s) are parameters to be passed
    */

    arg_buffer[0] = '\0';                /* default to no argument string     */
    program_name = NULL;                 /* no program to run yet             */

    for (i = 1; i < argc; i++)           /* loop through the arguments        */
    {
        /* is this an option switch?         */
        if ((*(cp=*(argv+i)) == '-' || *cp == '/')) {
            switch (*++cp) {
                case 'e':
                case 'E':                /* execute from string               */
                    if (from_string == FALSE) {  /* only treat 1st -e differently */
                        from_string = TRUE;
                        if ( argc == i+1 ) {
                            break;
                        }
                        program_name = "INSTORE";
                        instore[0].strptr = argv[i+1];
                        instore[0].strlength = strlen(instore[0].strptr);
                        instore[1].strptr = NULL;
                        instore[1].strlength = 0;
                        real_argument = FALSE;
                    }
                    break;
                case 'v':
                case 'V': {                                /* version display */
                    char *ptr = RexxGetVersionInformation();
                    if (ptr)
                    {
                        fprintf(stdout, ptr);
                        fprintf(stdout, "\n");
                        RexxFreeMemory(ptr);
                    }
                    return 0;
                }
                default:                       /* ignore other switches       */
                    break;
            }
        }
        else                             /* convert into an argument string   */
        {
            if (program_name == NULL) {       /* no name yet?                  */
                program_name = argv[i];        /* program is first non-option  */
                break;     /* end parsing after program_name has been resolved */
            }
            else if ( real_argument )  {  /* part of the argument string       */
                if (arg_buffer[0] != '\0')  {   /* not the first one?          */
                    strcat(arg_buffer, " ");     /* add an blank               */
                }
                strcat(arg_buffer, argv[i]);  /* add this to the argument string */
            }
            real_argument = TRUE;
        }
    }

    if (program_name == NULL) {
        /* give a simple error message       */
#undef printf
        printf("\n");
        fprintf(stderr,"Syntax is \"rexx filename [arguments]\"\n");
        fprintf(stderr,"or        \"rexx -e program_string [arguments]\"\n");
        fprintf(stderr,"or        \"rexx -v\".\n");
        return -1;
    }
    else {                              /* real program execution              */
        getArguments(NULL, GetCommandLine(), &argcount, &arguments);
        rxretbuf.strlength = 0L;                 /* initialize return to empty */

#ifdef REXXC_DEBUG
        printf("program_name = %s\n", program_name);
        printf("argv 0 = %s\n", argv[0]);
        printf("argv 1 = %s\n", argv[1]);
        printf("argv 2 = %s\n", argv[2]);
        printf("argument.strptr = %s\n", argument.strptr);
        printf("argument.strlenth = %lu\n", argument.strlength);
#endif


        if (from_string) {
            /* Here we call the interpreter.  We don't really need to use      */
            /* all the casts in this call; they just help illustrate           */
            /* the data types used.                                            */
            rc=REXXSTART(argcount,                    /* number of arguments   */
                         &arguments,                   /* array of arguments   */
                         program_name,                /* name of REXX file     */
                         instore,               /* rexx code from command line */
                         "CMD",                       /* Command env. name     */
                         RXCOMMAND,                   /* Code for how invoked  */
                         NULL,
                         &rexxrc,                     /* Rexx program output   */
                         &rxretbuf );                 /* Rexx program output   */
            /* rexx procedure executed*/
            if ((rc==0) && rxretbuf.strptr) {
                RexxFreeMemory(rxretbuf.strptr);    /* Release storage only if */
            }
            freeArguments(NULL, &arguments);
        }
        else {
            RexxCreateInterpreter(&pgmInst, &pgmThrdInst, NULL);
            // configure the traditional single argument string

            if ( arguments.strptr != NULL )
            {
                rxargs = pgmThrdInst->NewArray(1);
                pgmThrdInst->ArrayPut(rxargs, pgmThrdInst->String(arguments.strptr), 1);
            }
            else
            {
                rxargs = pgmThrdInst->NewArray(0);
            }

            // set up the C args into the .local environment
            dir = (RexxDirectoryObject)pgmThrdInst->GetLocalEnvironment();
            if ( argc > 2 )
            {
                rxcargs = pgmThrdInst->NewArray(argc - 2);
            }
            else
            {
                rxcargs = pgmThrdInst->NewArray(0);
            }
            for (i = 2; i < argc; i++)
            {
                pgmThrdInst->ArrayPut(rxcargs,
                                      pgmThrdInst->NewStringFromAsciiz(argv[i]),
                                      i - 1);
            }
            pgmThrdInst->DirectoryPut(dir, rxcargs, "SYSCARGS");
            // call the interpreter
            result = pgmThrdInst->CallProgram(program_name, rxargs);
            // display any error message if there is a condition.
            // if there was an error, then that will be our return code.
            // Although the return is a wholenumber_t we know there is no error
            // code too big to fit in an int.
            rc = (int)pgmThrdInst->DisplayCondition();
            if (rc != 0)
            {
                pgmInst->Terminate();
                return -rc;   // well, the negation of the error number is the return code
            }
            // now handle any potential return value
            if (result != NULL) {
                pgmThrdInst->ObjectToInt32(result, &rc);
            }

            pgmInst->Terminate();

            return rc;
        }
    }
    return rc ? rc : rexxrc;                    // rexx program return cd
}
示例#16
0
//==============================================================================
ObjectHandle CommandInstance::getCommandDescription() const
{
	auto command = this->getCommand();

	auto description = command->getCommandDescription(getArguments());
	if (description != nullptr)
	{
        return setCommandDescription(std::move(description));
	}

	if (undoRedoData_.empty())
	{
		return nullptr;
	}

	// Single command
	// OR
	// Batch command with one child
	// OR
	// Macro command
	// - getCommandDescription() returns the same as a single command

	const auto commandCount = undoRedoData_.size();
	auto batchCommand = dynamic_cast<const BatchCommand*>(command);
	if ((commandCount == 1) || (commandCount == 2))
	{
        return setCommandDescription(undoRedoData_.begin()->get()->getCommandDescription());
	}

	// Batch command with multiple children
	// This is expected to have a "Children" collection attached
	auto itr = undoRedoData_.begin();

	// First item is the batch itself
	auto batchHandle = itr->get()->getCommandDescription();
    auto pBatchDescription = batchHandle.getHandleT();
	TF_ASSERT(pBatchDescription != nullptr);

	// Get copy of children
    typedef std::vector<ManagedObjectPtr> ContainerType;
	Collection childrenCollection;
	const bool success = pBatchDescription->get("Children", childrenCollection);
    auto container = childrenCollection.container<ContainerType>();
    if (!success || !container)
    {
        TF_ASSERT(!"Children must be in container of Managed Objects");
        return nullptr;
    }

	// Latter items are children of the batch
    ++itr;
    for (; itr != undoRedoData_.end(); ++itr)
    {
        auto childObject = itr->get()->getCommandDescription();
        container->push_back(std::make_unique<ManagedObject<GenericObject>>(std::move(childObject)));
    }

	// Copy back to batch
	const auto setCollection = pBatchDescription->set("Children", childrenCollection);
	TF_ASSERT(setCollection);

    return setCommandDescription(std::move(batchHandle));
}
示例#17
0
/** Dereferencing null constant (simplified token list) */
void CheckNullPointer::nullConstantDereference()
{
    const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();

    for (const Scope * scope : symbolDatabase->functionScopes) {
        if (scope->function == nullptr || !scope->function->hasBody()) // We only look for functions with a body
            continue;

        const Token *tok = scope->bodyStart;

        if (scope->function->isConstructor())
            tok = scope->function->token; // Check initialization list

        for (; tok != scope->bodyEnd; tok = tok->next()) {
            if (Token::Match(tok, "sizeof|decltype|typeid|typeof ("))
                tok = tok->next()->link();

            else if (Token::simpleMatch(tok, "* 0")) {
                if (Token::Match(tok->previous(), "return|throw|;|{|}|:|[|(|,") || tok->previous()->isOp()) {
                    nullPointerError(tok);
                }
            }

            else if (Token::Match(tok, "0 [") && (tok->previous()->str() != "&" || !Token::Match(tok->next()->link()->next(), "[.(]")))
                nullPointerError(tok);

            else if (Token::Match(tok->previous(), "!!. %name% (") && (tok->previous()->str() != "::" || tok->strAt(-2) == "std")) {
                if (Token::Match(tok->tokAt(2), "0|NULL|nullptr )") && tok->varId()) { // constructor call
                    const Variable *var = tok->variable();
                    if (var && !var->isPointer() && !var->isArray() && var->isStlStringType())
                        nullPointerError(tok);
                } else { // function call
                    std::list<const Token *> var;
                    parseFunctionCall(*tok, var, &mSettings->library);

                    // is one of the var items a NULL pointer?
                    for (const Token *vartok : var) {
                        if (Token::Match(vartok, "0|NULL|nullptr [,)]")) {
                            nullPointerError(vartok);
                        }
                    }
                }
            } else if (Token::Match(tok, "std :: string|wstring ( 0|NULL|nullptr )"))
                nullPointerError(tok);

            else if (Token::Match(tok->previous(), "::|. %name% (")) {
                const std::vector<const Token *> &args = getArguments(tok);
                for (int argnr = 0; argnr < args.size(); ++argnr) {
                    const Token *argtok = args[argnr];
                    if (!argtok->hasKnownIntValue())
                        continue;
                    if (argtok->values().front().intvalue != 0)
                        continue;
                    if (mSettings->library.isnullargbad(tok, argnr+1))
                        nullPointerError(argtok);
                }
            }

            else if (Token::Match(tok->previous(), ">> 0|NULL|nullptr")) { // Only checking input stream operations is safe here, because otherwise 0 can be an integer as well
                const Token* tok2 = tok->previous(); // Find start of statement
                for (; tok2; tok2 = tok2->previous()) {
                    if (Token::Match(tok2->previous(), ";|{|}|:|("))
                        break;
                }
                if (tok2 && tok2->previous() && tok2->previous()->str()=="(")
                    continue;
                if (Token::simpleMatch(tok2, "std :: cin"))
                    nullPointerError(tok);
                if (tok2 && tok2->varId() != 0) {
                    const Variable *var = tok2->variable();
                    if (var && var->isStlType(stl_istream))
                        nullPointerError(tok);
                }
            }

            const Variable *ovar = nullptr;
            const Token *tokNull = nullptr;
            if (Token::Match(tok, "0|NULL|nullptr ==|!=|>|>=|<|<= %var%")) {
                if (!Token::Match(tok->tokAt(3),".|[")) {
                    ovar = tok->tokAt(2)->variable();
                    tokNull = tok;
                }
            } else if (Token::Match(tok, "%var% ==|!=|>|>=|<|<= 0|NULL|nullptr") ||
                       Token::Match(tok, "%var% =|+ 0|NULL|nullptr )|]|,|;|+")) {
                ovar = tok->variable();
                tokNull = tok->tokAt(2);
            }
            if (ovar && !ovar->isPointer() && !ovar->isArray() && ovar->isStlStringType() && tokNull && tokNull->originalName() != "'\\0'")
                nullPointerError(tokNull);
        }
    }
}
示例#18
0
SourceLocation TypeConstructorExpr::getLocEnd() const {
  if(getArguments().empty())
    return getLocation();
  return getArguments().back()->getLocEnd();
}
示例#19
0
SourceLocation IntrinsicCallExpr::getLocEnd() const {
  return getArguments().back()->getLocEnd();
}
示例#20
0
SourceLocation CallExpr::getLocEnd() const {
  return getArguments().empty()? getLocation() :
                                 getArguments().back()->getLocEnd();
}
示例#21
0
SourceLocation ArraySectionExpr::getLocEnd() const {
  return getArguments().back()->getLocEnd();
}
示例#22
0
void DiamondClassifyTask::prepare() {
    ExternalToolRunTask *classifyTask = new ExternalToolRunTask(DiamondSupport::TOOL_NAME, getArguments(), new ExternalToolLogParser());
    setListenerForTask(classifyTask);
    addSubTask(classifyTask);
}
示例#23
0
文件: uid.c 项目: ohamada/389ds
/*
 * preop_add - pre-operation plug-in for add
 */
static int
preop_add(Slapi_PBlock *pb)
{
  int result;
  char *errtext = NULL;
  char *attrName = NULL;

#ifdef DEBUG
  slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name, "ADD begin\n");
#endif

  result = LDAP_SUCCESS;

  /*
   * Do constraint check on the added entry.  Set result.
   */

 BEGIN
    int err;
    char *markerObjectClass = NULL;
    char *requiredObjectClass = NULL;
    Slapi_DN *sdn = NULL;
    int isupdatedn;
    Slapi_Entry *e;
    Slapi_Attr *attr;
    int argc;
    char **argv = NULL;

        /*
         * If this is a replication update, just be a noop.
         */
        err = slapi_pblock_get(pb, SLAPI_IS_REPLICATED_OPERATION, &isupdatedn);
    if (err) { result = uid_op_error(50); break; }
        if (isupdatedn)
        {
          break;
        }

    /*
     * Get the arguments
     */
        result = getArguments(pb, &attrName, &markerObjectClass,
                                                  &requiredObjectClass);
        if (UNTAGGED_PARAMETER == result)
        {
          slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name, 
                          "ADD parameter untagged: %s\n", attrName);
          result = LDAP_SUCCESS;
          /* Statically defined subtrees to monitor */
          err = slapi_pblock_get(pb, SLAPI_PLUGIN_ARGC, &argc);
          if (err) { result = uid_op_error(53); break; }

          err = slapi_pblock_get(pb, SLAPI_PLUGIN_ARGV, &argv);
          if (err) { result = uid_op_error(54); break; }
          argc--; argv++; /* First argument was attribute name */
        } else if (0 != result)
        {
          break;
        }

    /*
     * Get the target DN for this add operation
     */
    err = slapi_pblock_get(pb, SLAPI_ADD_TARGET_SDN, &sdn);
    if (err) { result = uid_op_error(51); break; }

#ifdef DEBUG
    slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name, "ADD target=%s\n", slapi_sdn_get_dn(sdn));
#endif

       /*
         * Get the entry data for this add. Check whether it
         * contains a value for the unique attribute
         */
        err = slapi_pblock_get(pb, SLAPI_ADD_ENTRY, &e);
        if (err) { result = uid_op_error(52); break; }

        err = slapi_entry_attr_find(e, attrName, &attr);
        if (err) break;  /* no unique attribute */

        /*
         * Check if it contains the required object class
         */
        if (NULL != requiredObjectClass)
        {
          if (!entryHasObjectClass(pb, e, requiredObjectClass))
          {
                /* No, so we don't have to do anything */
                break;
          }
        }

        /*
         * Passed all the requirements - this is an operation we
         * need to enforce uniqueness on. Now find all parent entries
         * with the marker object class, and do a search for each one.
         */
        if (NULL != markerObjectClass)
        {
          /* Subtree defined by location of marker object class */
                result = findSubtreeAndSearch(sdn, attrName, attr, NULL,
                                              requiredObjectClass, sdn,
                                              markerObjectClass);
        } else
        {
          /* Subtrees listed on invocation line */
          result = searchAllSubtrees(argc, argv, attrName, attr, NULL,
                                     requiredObjectClass, sdn);
        }
  END

  if (result)
  {
    slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name,
      "ADD result %d\n", result);

    if (result == LDAP_CONSTRAINT_VIOLATION) {
      errtext = slapi_ch_smprintf(moreInfo, attrName);
    } else {
      errtext = slapi_ch_strdup("Error checking for attribute uniqueness.");
    }

    /* Send failure to the client */
    slapi_send_ldap_result(pb, result, 0, errtext, 0, 0);

    slapi_ch_free_string(&errtext);
  }

  return (result==LDAP_SUCCESS)?0:-1;
}
示例#24
0
文件: NEModule.cpp 项目: kniz/World
	//	---------------------------------------------------------------------------------
	//	히스토리:	2011-07-07	이태훈	개발 완료
	//	---------------------------------------------------------------------------------
	NEBinaryFileLoader NE_DLL &NEModule::serialize(NEBinaryFileLoader& loader)
	{
		NENamedUnit::serialize(loader);

		return loader >> getArguments();
	}
示例#25
0
/* pretty much the main loop */
static TCHAR* replaceDynVars(TCHAR* szTemplate, FORMATINFO* fi)
{
	TCHAR
		*string,
		*cur,   // current position (pnt only)
		*tcur,  // temp cur			(pnt only)
		*scur,  // start of variable(pnt only)
		*parsedToken,   // parsed result (dyn alloc)
		**argv, // arguments (dyn alloc)
		**pargv, //  dyn alloc
		*token; // variable name (pnt only)
 	int argc = 0, i, scurPos, curPos, tmpVarPos;
	size_t pos;
	FORMATINFO afi;
	TOKENREGISTEREX *tr;
	ARGUMENTSINFO ai = { 0 };

	string = mir_tstrdup(szTemplate);
	if (string == NULL)
		return NULL;

	cur = tcur = scur = token = parsedToken = NULL;
	pargv = argv = NULL;
	//fi->pCount = 0;
	memcpy(&afi, fi, sizeof(afi));
	for (pos = 0; pos < mir_tstrlen(string); pos++) {
		// string may move in memory, iterate by remembering the position in the string
		cur = string+pos;
		// mir_free memory from last iteration, this way we can bail out at any time in the loop
		mir_free(parsedToken);

		for (i = 0; i < argc; i ++)
			mir_free(argv[i]);
		mir_free(argv);
		argc = 0;
		tcur = scur = token = parsedToken = NULL;
		pargv = argv = NULL;
		// new round
		if (*cur == DONTPARSE_CHAR) {
			memmove(cur, cur+1, (mir_tstrlen(cur+1)+1)*sizeof(TCHAR));
			if (*cur == DONTPARSE_CHAR)
				continue;

			while ( (*cur != DONTPARSE_CHAR) && (*cur != 0))
				cur++;

			memmove(cur, cur+1, (mir_tstrlen(cur+1)+1)*sizeof(TCHAR));
			pos = cur-string-1;
			continue;
		}
		// remove end of lines
		else if ((!_tcsncmp(cur, _T("\r\n"), 2)) && (gParseOpts.bStripEOL)) {
			memmove(cur, cur+2, (mir_tstrlen(cur+2)+1)*sizeof(TCHAR));
			pos = cur-string-1;
			continue;
		}
		else if ((*cur == '\n' && gParseOpts.bStripEOL) || (*cur == ' ' && gParseOpts.bStripWS)) {
			memmove(cur, cur+1, (mir_tstrlen(cur+1)+1)*sizeof(TCHAR));
			pos = cur - string - 1;
			continue;
		}
		// remove comments
		else if (!_tcsncmp(cur, _T(COMMENT_STRING), mir_tstrlen(_T(COMMENT_STRING)))) {
			scur = cur;
			while ( _tcsncmp(cur, _T("\r\n"), 2) && *cur != '\n' && *cur != 0)
				cur++;

			if (*cur == 0) {
				*scur = 0;
				string = (TCHAR*)mir_realloc(string, (mir_tstrlen(string)+1)*sizeof(TCHAR));
				continue;
			}
			memmove(scur, cur, (mir_tstrlen(cur)+1)*sizeof(TCHAR));
			pos = scur-string-1;
			continue;
		}
		else if ((*cur != FIELD_CHAR) && (*cur != FUNC_CHAR) && (*cur != FUNC_ONCE_CHAR)) {
			if (gParseOpts.bStripAll) {
				memmove(cur, cur+1, (mir_tstrlen(cur+1)+1)*sizeof(TCHAR));
				pos = cur - string - 1;
			}
			continue;
		}
		scur = tcur = cur+1;
		while (isValidTokenChar(*tcur))
			tcur++;

		if (tcur == cur) {
			fi->eCount++;
			continue;
		}
		token = (TCHAR*)mir_alloc((tcur-scur+1)*sizeof(TCHAR));
		if (token == NULL) {
			fi->eCount++;
			return NULL;
		}
		memset(token, '\0', (tcur-scur+1)*sizeof(TCHAR));
		_tcsncpy(token, cur+1, tcur-scur);
		// cur points to FIELD_CHAR or FUNC_CHAR
 		tmpVarPos = -1;
 		tr = NULL;
 		if (*cur==FIELD_CHAR) {
 			for(i = 0; i < fi->cbTemporaryVarsSize; i += 2) {
 				if (mir_tstrcmp(fi->tszaTemporaryVars[i], token) == 0) {
 					tmpVarPos = i;
 					break;
 				}
 			}
 		}
 		if (tmpVarPos < 0)
 			tr = searchRegister(token, (*cur==FIELD_CHAR)?TRF_FIELD:TRF_FUNCTION);
 		mir_free(token);
 		if (tmpVarPos < 0 && tr == NULL) {
			fi->eCount++;
			// token not found, continue
			continue;
		}
		scur = cur; // store this pointer for later use
		if (*cur == FIELD_CHAR) {
 			size_t len = mir_tstrlen(tr != NULL ? tr->tszTokenString : fi->tszaTemporaryVars[tmpVarPos]);
			cur++;
 			if (*(cur + len) != FIELD_CHAR) { // the next char after the token should be %
				fi->eCount++;
				continue;
			}
 			cur += len+1;
		}
		else if ((*cur == FUNC_CHAR) || (*cur == FUNC_ONCE_CHAR)) {
			TCHAR *argcur;

			cur += mir_tstrlen(tr->tszTokenString)+1;
			argcur = getArguments(cur, &argv, &argc);
			if ((argcur == cur) || (argcur == NULL)) {
				fi->eCount++;
				// error getting arguments
				continue;
			}
			cur = argcur;
			// arguments
			for (i=0;i<argc;i++) {
				if (argv[i] != NULL) {
					if (!(tr->flags&TRF_UNPARSEDARGS)) {
						afi.tszFormat = argv[i];
						afi.eCount = afi.pCount = 0;
						argv[i] = formatString(&afi);
						fi->eCount += afi.eCount;
						fi->pCount += afi.pCount;
						mir_free(afi.szFormat);
					}
				}
				if (argv[i] == NULL)
					argv[i] = mir_tstrdup(_T(""));
			}
		}
		// cur should now point at the character after FIELD_CHAR or after the last ')'
 		if (tr != NULL) {
 			pargv = ( TCHAR** )mir_alloc((argc+1)*sizeof(TCHAR*));
 			if (pargv == NULL) {
 				fi->eCount++;
 				return NULL;
 			}
 			for (i=0;i<argc;i++)
 				pargv[i+1] = argv[i];

 			pargv[0] = tr->tszTokenString;
 			memset(&ai, 0, sizeof(ai));
 			ai.cbSize = sizeof(ai);
 			ai.argc = argc+1;
 			ai.targv = pargv;
 			ai.fi = fi;
 			if ((*scur == FUNC_ONCE_CHAR) || (*scur == FIELD_CHAR))
 				ai.flags |= AIF_DONTPARSE;

 			parsedToken = parseFromRegister(&ai);
 			mir_free(pargv);
 		}
 		else parsedToken = fi->tszaTemporaryVars[tmpVarPos + 1];

		if (parsedToken == NULL) {
			fi->eCount++;
			continue;
		}

		//replaced a var
		if (ai.flags & AIF_FALSE )
			fi->eCount++;
		else
			fi->pCount++;

		// 'special' chars need to be taken care of (DONTPARSE, TRYPARSE, \r\n)
		// if the var contains the escape character, this character must be doubled, we don't want it to act as an esacpe char
		/*for (tcur=parsedToken;*tcur != '\0';tcur++) {
			if (*tcur == DONTPARSE_CHAR) {//|| (*(var+pos) == ')')) {
				parsedToken = mir_realloc(parsedToken, mir_strlen(parsedToken) + 2);
				if (parsedToken == NULL) {
					fi->err = EMEM;
					return NULL;
				}
				memcpy(tcur+1, tcur, mir_strlen(tcur)+1);
				tcur++;
			}
		}*/

		size_t parsedTokenLen = mir_tstrlen(parsedToken);
		size_t initStrLen = mir_tstrlen(string);
		size_t tokenLen = cur-scur;
		scurPos = scur-string;
		curPos = cur-string;
		if (tokenLen < parsedTokenLen) {
			// string needs more memory
			string = (TCHAR*)mir_realloc(string, (initStrLen-tokenLen+parsedTokenLen+1)*sizeof(TCHAR));
			if (string == NULL) {
				fi->eCount++;
				return NULL;
			}
		}
		scur = string+scurPos;
		cur = string+curPos;
		memmove(scur + parsedTokenLen, cur, (mir_tstrlen(cur)+1)*sizeof(TCHAR));
		memcpy(scur, parsedToken, parsedTokenLen*sizeof(TCHAR));
		{
			size_t len = mir_tstrlen(string);
			string = (TCHAR*)mir_realloc(string, (len+1)*sizeof(TCHAR));
		}
		if (( ai.flags & AIF_DONTPARSE ) || tmpVarPos >= 0)
			pos += parsedTokenLen;

		pos--; // parse the same pos again, it changed

 		if (tr == NULL)
 			parsedToken = NULL; // To avoid mir_free
	}
	if (parsedToken != NULL)
		mir_free(parsedToken);

	for (i = 0; i < argc; i ++)
		mir_free(argv[i]);
	mir_free(argv);

	return (TCHAR*)mir_realloc(string, (mir_tstrlen(string)+1)*sizeof(TCHAR));
}
示例#26
0
// Dispatch.
as_value
Function::call(const fn_call& fn)
{
    // Extract caller before pushing ourself on the call stack
    VM& vm = getVM(fn); 

    as_object* caller = vm.calling() ? &vm.currentCall().function() : 0;

	// Set up local stack frame, for parameters and locals.
	FrameGuard guard(getVM(fn), *this);
    CallFrame& cf = guard.callFrame();

	DisplayObject* target = _env.target();
	DisplayObject* orig_target = _env.get_original_target();

	// Some features are version-dependant.
	const int swfversion = getSWFVersion(fn);

	if (swfversion < 6) {
		// In SWF5, when 'this' is a DisplayObject it becomes
		// the target for this function call.
		// See actionscript.all/setProperty.as
        DisplayObject* ch = get<DisplayObject>(fn.this_ptr);
        if (ch) {
            target = ch;
            orig_target = ch;
        }
	}

	/// This is only needed for SWF5 (temp switch of target)
	/// We do always and base 'target' value on SWF version.
	/// TODO: simplify code by maybe using a custom as_environment
	///       instead, so to get an "original" target being 
	///       the one set now (rather then the really original one)
	/// TODO: test scope when calling functions defined in another timeline
	///       (target, in particular).
	TargetGuard targetGuard(_env, target, orig_target);

    // Push the arguments onto the local frame.
    for (size_t i = 0, n = _args.size(); i < n; ++i) {

        assert(_args[i].reg == 0);
        if (i < fn.nargs) {
            setLocal(cf, _args[i].name, fn.arg(i));
        }
        else {
            // Still declare named arguments, even if
            // they are not passed from caller
            // See bug #22203
            declareLocal(cf, _args[i].name);
        }
    }

    // Add 'this'
    setLocal(cf, NSV::PROP_THIS, fn.this_ptr ? fn.this_ptr : as_value());

    as_object* super = fn.super ? fn.super :
        fn.this_ptr ? fn.this_ptr->get_super() : 0;

    // Add 'super' (SWF6+ only)
    if (super && swfversion > 5) {
        setLocal(cf, NSV::PROP_SUPER, super);
    }

    // Add 'arguments'
    as_object* args = getGlobal(fn).createArray();

    // Put 'arguments' in a local var.
    setLocal(cf, NSV::PROP_ARGUMENTS, getArguments(*this, *args, fn, caller));

	// Execute the actions.
    as_value result;
    ActionExec(*this, _env, &result, fn.this_ptr)();
    return result;
}
示例#27
0
文件: uid.c 项目: ohamada/389ds
/*
 * preop_modrdn - Pre-operation call for modify RDN
 *
 * Check that the new RDN does not include attributes that
 * cause a constraint violation
 */
static int
preop_modrdn(Slapi_PBlock *pb)
{
  int result = LDAP_SUCCESS;
  Slapi_Entry *e = NULL;
  Slapi_Value *sv_requiredObjectClass = NULL;
  char *errtext = NULL;
  char *attrName = NULL;

#ifdef DEBUG
    slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name,
      "MODRDN begin\n");
#endif

  BEGIN
    int err;
    char *markerObjectClass=NULL;
    char *requiredObjectClass=NULL;
    Slapi_DN *sdn = NULL;
    Slapi_DN *superior;
    char *rdn;
    int deloldrdn = 0;
    int isupdatedn;
    Slapi_Attr *attr;
    int argc;
    char **argv = NULL;

        /*
         * If this is a replication update, just be a noop.
         */
        err = slapi_pblock_get(pb, SLAPI_IS_REPLICATED_OPERATION, &isupdatedn);
    if (err) { result = uid_op_error(30); break; }
        if (isupdatedn)
        {
          break;
        }

    /*
     * Get the arguments
     */
        result = getArguments(pb, &attrName, &markerObjectClass,
                                                  &requiredObjectClass);
        if (UNTAGGED_PARAMETER == result)
        {
          result = LDAP_SUCCESS;
          /* Statically defined subtrees to monitor */
          err = slapi_pblock_get(pb, SLAPI_PLUGIN_ARGC, &argc);
          if (err) { result = uid_op_error(53); break; }

          err = slapi_pblock_get(pb, SLAPI_PLUGIN_ARGV, &argv);
          if (err) { result = uid_op_error(54); break; }
          argc--; /* First argument was attribute name */
          argv++; 
        } else if (0 != result)
        {
          break;
        }

    /* Create a Slapi_Value for the requiredObjectClass to use
     * for checking the entry. */
    if (requiredObjectClass) {
        sv_requiredObjectClass = slapi_value_new_string(requiredObjectClass);
    }

    /* Get the DN of the entry being renamed */
    err = slapi_pblock_get(pb, SLAPI_MODRDN_TARGET_SDN, &sdn);
    if (err) { result = uid_op_error(31); break; }

    /* Get superior value - unimplemented in 3.0/4.0/5.0 DS */
    err = slapi_pblock_get(pb, SLAPI_MODRDN_NEWSUPERIOR_SDN, &superior);
    if (err) { result = uid_op_error(32); break; }

    /*
     * No superior means the entry is just renamed at
     * its current level in the tree.  Use the target DN for
     * determining which managed tree this belongs to
     */
    if (!superior) superior = sdn;

    /* Get the new RDN - this has the attribute values */
    err = slapi_pblock_get(pb, SLAPI_MODRDN_NEWRDN, &rdn);
    if (err) { result = uid_op_error(33); break; }
#ifdef DEBUG
    slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name,
      "MODRDN newrdn=%s\n", rdn);
#endif

    /* See if the old RDN value is being deleted. */
    err = slapi_pblock_get(pb, SLAPI_MODRDN_DELOLDRDN, &deloldrdn);
    if (err) { result = uid_op_error(34); break; }

    /* Get the entry that is being renamed so we can make a dummy copy
     * of what it will look like after the rename. */
    err = slapi_search_internal_get_entry(sdn, NULL, &e, plugin_identity);
    if (err != LDAP_SUCCESS) {
        result = uid_op_error(35);
        /* We want to return a no such object error if the target doesn't exist. */
        if (err == LDAP_NO_SUCH_OBJECT) {
            result = err;
        }
        break;
    }

    /* Apply the rename operation to the dummy entry. */
    /* slapi_entry_rename does not expect rdn normalized */
    err = slapi_entry_rename(e, rdn, deloldrdn, superior);
    if (err != LDAP_SUCCESS) { result = uid_op_error(36); break; }

        /*
         * Find any unique attribute data in the new RDN
         */
        err = slapi_entry_attr_find(e, attrName, &attr);
        if (err) break;  /* no UID attribute */

        /*
         * Check if it has the required object class
         */
        if (requiredObjectClass &&
            !slapi_entry_attr_has_syntax_value(e, SLAPI_ATTR_OBJECTCLASS, sv_requiredObjectClass)) { break; }

        /*
         * Passed all the requirements - this is an operation we
         * need to enforce uniqueness on. Now find all parent entries
         * with the marker object class, and do a search for each one.
         */
        if (NULL != markerObjectClass)
        {
          /* Subtree defined by location of marker object class */
                result = findSubtreeAndSearch(slapi_entry_get_sdn(e), attrName, attr, NULL,
                                              requiredObjectClass, sdn,
                                              markerObjectClass);
        } else
        {
          /* Subtrees listed on invocation line */
          result = searchAllSubtrees(argc, argv, attrName, attr, NULL,
                                     requiredObjectClass, sdn);
        }
  END
  /* Clean-up */
  slapi_value_free(&sv_requiredObjectClass);
  if (e) slapi_entry_free(e);

  if (result)
  {
    slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name,
      "MODRDN result %d\n", result);

    if (result == LDAP_CONSTRAINT_VIOLATION) {
      errtext = slapi_ch_smprintf(moreInfo, attrName);
    } else {
      errtext = slapi_ch_strdup("Error checking for attribute uniqueness.");
    }

    slapi_send_ldap_result(pb, result, 0, errtext, 0, 0);

    slapi_ch_free_string(&errtext);
  }

  return (result==LDAP_SUCCESS)?0:-1;

}
示例#28
0
文件: uid.c 项目: ohamada/389ds
/*
 * preop_modify - pre-operation plug-in for modify
 */
static int
preop_modify(Slapi_PBlock *pb)
{

  int result = LDAP_SUCCESS;
  Slapi_PBlock *spb = NULL;
  LDAPMod **checkmods = NULL;
  int checkmodsCapacity = 0;
  char *errtext = NULL;
  char *attrName = NULL;

#ifdef DEBUG
    slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name,
      "MODIFY begin\n");
#endif

  BEGIN
    int err;
    char *markerObjectClass=NULL;
    char *requiredObjectClass=NULL;
    LDAPMod **mods;
    int modcount = 0;
    int ii;
    LDAPMod *mod;
    Slapi_DN *sdn = NULL;
    int isupdatedn;
    int argc;
    char **argv = NULL;

    /*
     * If this is a replication update, just be a noop.
     */
    err = slapi_pblock_get(pb, SLAPI_IS_REPLICATED_OPERATION, &isupdatedn);
    if (err) { result = uid_op_error(60); break; }
    if (isupdatedn)
    {
      break;
    }

    /*
     * Get the arguments
     */
        result = getArguments(pb, &attrName, &markerObjectClass,
                                                  &requiredObjectClass);
        if (UNTAGGED_PARAMETER == result)
        {
          result = LDAP_SUCCESS;
          /* Statically defined subtrees to monitor */
          err = slapi_pblock_get(pb, SLAPI_PLUGIN_ARGC, &argc);
          if (err) { result = uid_op_error(53); break; }

          err = slapi_pblock_get(pb, SLAPI_PLUGIN_ARGV, &argv);
          if (err) { result = uid_op_error(54); break; }
          argc--; /* First argument was attribute name */
          argv++;
        } else if (0 != result)
        {
          break;
        }

    err = slapi_pblock_get(pb, SLAPI_MODIFY_MODS, &mods);
    if (err) { result = uid_op_error(61); break; }

    /* There may be more than one mod that matches e.g.
       changetype: modify
       delete: uid
       uid: balster1950
       -
       add: uid
       uid: scottg
       
       So, we need to first find all mods that contain the attribute
       which are add or replace ops and are bvalue encoded
    */
    /* find out how many mods meet this criteria */
    for(;*mods;mods++)
    {
        mod = *mods;
        if ((slapi_attr_type_cmp(mod->mod_type, attrName, 1) == 0) && /* mod contains target attr */
            (mod->mod_op & LDAP_MOD_BVALUES) && /* mod is bval encoded (not string val) */
            (mod->mod_bvalues && mod->mod_bvalues[0]) && /* mod actually contains some values */
            (SLAPI_IS_MOD_ADD(mod->mod_op) || /* mod is add */
             SLAPI_IS_MOD_REPLACE(mod->mod_op))) /* mod is replace */
        {
          addMod(&checkmods, &checkmodsCapacity, &modcount, mod);
        }
    }
    if (modcount == 0) {
        break; /* no mods to check, we are done */
    }

    /* Get the target DN */
    err = slapi_pblock_get(pb, SLAPI_MODIFY_TARGET_SDN, &sdn);
    if (err) { result = uid_op_error(11); break; }

    /*
     * Check if it has the required object class
     */
    if (requiredObjectClass &&
        !(spb = dnHasObjectClass(sdn, requiredObjectClass))) {
        break;
    }

    /*
     * Passed all the requirements - this is an operation we
     * need to enforce uniqueness on. Now find all parent entries
     * with the marker object class, and do a search for each one.
     */
    /*
     * stop checking at first mod that fails the check
     */
    for (ii = 0; (result == 0) && (ii < modcount); ++ii)
    {
        mod = checkmods[ii];
        if (NULL != markerObjectClass)
        {
            /* Subtree defined by location of marker object class */
            result = findSubtreeAndSearch(sdn, attrName, NULL, 
                                          mod->mod_bvalues, requiredObjectClass,
                                          sdn, markerObjectClass);
        } else
        {
            /* Subtrees listed on invocation line */
            result = searchAllSubtrees(argc, argv, attrName, NULL,
                                       mod->mod_bvalues, requiredObjectClass, sdn);
        }
    }
  END

  slapi_ch_free((void **)&checkmods);
  freePblock(spb);
 if (result)
  {
    slapi_log_error(SLAPI_LOG_PLUGIN, plugin_name,
      "MODIFY result %d\n", result);

    if (result == LDAP_CONSTRAINT_VIOLATION) {
      errtext = slapi_ch_smprintf(moreInfo, attrName);
    } else {
      errtext = slapi_ch_strdup("Error checking for attribute uniqueness.");
    }

    slapi_send_ldap_result(pb, result, 0, errtext, 0, 0);

    slapi_ch_free_string(&errtext);
  }

  return (result==LDAP_SUCCESS)?0:-1;

}
示例#29
0
void Parser::start() {
	while(buffer->getSize()) {
		Token* token = buffer->peek(0);
		
		switch(token->type) {
			case IN: {
				match(IN);
				Token* tokType = match(TYPE);
				Token* tokName = match(VARIABLE);
				match(END);
				
				Variable* variable = variables->find(variables->root, tokName->data, &currentFunction);
				if(variable == NULL) {
					Variable *variable = (Variable*) malloc(sizeof(Variable));
					variable->name = (char*)malloc(sizeof(tokName->data));
					strncpy(variable->name, tokName->data, strlen(tokName->data));
					variable->type = VariableType(variabletypes->find(variabletypes->root, tokType->data)->type);
					variable->function = currentFunction;
					in->push(variables->insert(variables->root, variable));
				}
				else {
					printf("[Parser Error] Redefinition of variable %s\n", variable->name);
					free(variable);
				}
				
				break;
			}
			case OUT: {
				match(OUT);
				Token* tokType = match(TYPE);
				Token* tokName = match(VARIABLE);
				match(END);
				
				Variable* variable = variables->find(variables->root, tokName->data, &currentFunction);
				if(variable == NULL) {
					Variable *variable = (Variable*) malloc(sizeof(Variable));
					variable->name = (char*)malloc(sizeof(tokName->data));
					strncpy(variable->name, tokName->data, strlen(tokName->data));
					variable->type = VariableType(variabletypes->find(variabletypes->root, tokType->data)->type);
					variable->function = currentFunction;
					out->push(variables->insert(variables->root, variable));
				}
				else {
					printf("[Parser Error] Redefinition of variable %s\n", variable->name);
					free(variable);
				}
				
				break;
			}
			case UNIFORM: {
				match(UNIFORM);
				Token* tokType = match(TYPE);
				Token* tokName = match(VARIABLE);
				match(END);
				
				Variable* variable = variables->find(variables->root, tokName->data, &currentFunction);
				if(variable == NULL) {
					Variable *variable = (Variable*) malloc(sizeof(Variable));
					variable->name = (char*)malloc(sizeof(tokName->data));
					strncpy(variable->name, tokName->data, strlen(tokName->data));
					variable->type = VariableType(variabletypes->find(variabletypes->root, tokType->data)->type);
					variable->function = currentFunction;
					uniform->push(variables->insert(variables->root, variable));
				}
				else {
					printf("[Parser Error] Redefinition of variable %s\n", variable->name);
					free(variable);
				}
				
				break;
			}
			case TYPE: {
				Token* tokType = match(TYPE);
				Token* tokName = match(VARIABLE);
				
				if(buffer->peek(0)->type == LPAR) {
					match(LPAR);
					
					Function* function = functions->findFunction(functions->root, tokName->data);
					if(function != NULL) {
						printf("[Parser Error] Redefinition of function %s\n", function->name);
						free(function);
						break;
					}
					
					Block* block = new Block();
					blockList->push(block);
					int blockId = blockList->getSize();
					
					Function* function = (Function*) malloc(sizeof(Function));
					strncpy(function->name, tokName->data, strlen(tokName->data));
					function->ret = VariableType(variabletypes->find(variabletypes->root, tokType->data)->type);
					function->arguments = getArguments();
					function->block = blockId;
					currentFunction = functions->addFunction(functions->root, function);
					
					processBlock(block);
					
					currentFunction = 0;
					
					break;
				}
				
				Variable* variable = variables->find(variables->root, tokName->data, &currentFunction);
				if(variable == NULL) {
					Variable *variable = (Variable*) malloc(sizeof(Variable));
					variable->name = (char*)malloc(sizeof(tokName->data));
					strncpy(variable->name, tokName->data, strlen(tokName->data));
					variable->type = VariableType(variabletypes->find(variabletypes->root, tokType->data)->type);
					variable->function = currentFunction;
					variables->insert(variables->root, variable);
				}
				else {
					printf("[Parser Error] Redefinition of variable %s\n", variable->name);
					free(variable);
				}
				
				break;
			}
			default: {
				printf("[Parser Error] Invalid token %s(%d) detected!\n", token->data, token->type);
				return;
			}
		}
	}
}
示例#30
0
文件: NEModule.cpp 项目: kniz/World
	//	인스턴스가 indexedModuleSet에 추가될때 1번 호출된다.
	type_result NEModule::initialize()
	{
		getArguments();	//	Argument 등록을 위해서 호출한다.

		return _onInitialize();
	}