예제 #1
0
/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
/// being passed to this variadic function, and set the MachineModuleInfo's
/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
/// reference to _fltused on Windows, which will link in MSVCRT's
/// floating-point support.
void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
                                      MachineModuleInfo *MMI)
{
  FunctionType *FT = cast<FunctionType>(
    I.getCalledValue()->getType()->getContainedType(0));
  if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
    for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
      Type* T = I.getArgOperand(i)->getType();
      for (auto i : post_order(T)) {
        if (i->isFloatingPointTy()) {
          MMI->setUsesVAFloatArgument(true);
          return;
        }
      }
    }
  }
}
예제 #2
0
파일: PlatQt.cpp 프로젝트: boq/PlasmaShop
PRectangle Window::GetPosition()
{
    QWidget *w = PWindow(wid);

    // Before any size allocated pretend its big enough not to be scrolled.
    PRectangle rc(0,0,5000,5000);

    if (w)
    {
        const QRect &r = w->geometry();

        rc.right = r.right() - r.left() + 1;
        rc.bottom = r.bottom() - r.top() + 1;
    }

    return rc;
}
// Emits code to decode the singleton.  Return true if we have matched all the
// well-known bits.
bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
                                         unsigned Opc) {
  std::vector<unsigned> StartBits;
  std::vector<unsigned> EndBits;
  std::vector<uint64_t> FieldVals;
  insn_t Insn;
  insnWithID(Insn, Opc);

  // Look for islands of undecoded bits of the singleton.
  getIslands(StartBits, EndBits, FieldVals, Insn);

  unsigned Size = StartBits.size();
  unsigned I, NumBits;

  // If we have matched all the well-known bits, just issue a return.
  if (Size == 0) {
    o.indent(Indentation) << "if (";
    if (!emitPredicateMatch(o, Indentation, Opc))
      o << "1";
    o << ") {\n";
    o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
    std::vector<OperandInfo>& InsnOperands = Operands[Opc];
    for (std::vector<OperandInfo>::iterator
         I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
      // If a custom instruction decoder was specified, use that.
      if (I->numFields() == 0 && I->Decoder.size()) {
        o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
                              << "(MI, insn, Address, Decoder)" << Emitter->GuardPostfix << "\n";
        break;
      }

      emitBinaryParser(o, Indentation, *I);
    }

    o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // " << nameWithID(Opc)
                          << '\n';
    o.indent(Indentation) << "}\n"; // Closing predicate block.
    return true;
  }

  // Otherwise, there are more decodings to be done!

  // Emit code to match the island(s) for the singleton.
  o.indent(Indentation) << "// Check ";

  for (I = Size; I != 0; --I) {
    o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
    if (I > 1)
      o << " && ";
    else
      o << "for singleton decoding...\n";
  }

  o.indent(Indentation) << "if (";
  if (emitPredicateMatch(o, Indentation, Opc)) {
    o << " &&\n";
    o.indent(Indentation+4);
  }

  for (I = Size; I != 0; --I) {
    NumBits = EndBits[I-1] - StartBits[I-1] + 1;
    o << "fieldFromInstruction" << BitWidth << "(insn, "
      << StartBits[I-1] << ", " << NumBits
      << ") == " << FieldVals[I-1];
    if (I > 1)
      o << " && ";
    else
      o << ") {\n";
  }
  o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
  std::vector<OperandInfo>& InsnOperands = Operands[Opc];
  for (std::vector<OperandInfo>::iterator
       I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
    // If a custom instruction decoder was specified, use that.
    if (I->numFields() == 0 && I->Decoder.size()) {
      o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
                            << "(MI, insn, Address, Decoder)" << Emitter->GuardPostfix << "\n";
      break;
    }

    emitBinaryParser(o, Indentation, *I);
  }
  o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // " << nameWithID(Opc)
                        << '\n';
  o.indent(Indentation) << "}\n";

  return false;
}
예제 #4
0
파일: llvm-size.cpp 프로젝트: SDkie/llvm
/// @brief Print the section sizes for @p file. If @p file is an archive, print
///        the section sizes for each archive member.
static void PrintFileSectionSizes(StringRef file) {
  // If file is not stdin, check that it exists.
  if (file != "-") {
    if (!sys::fs::exists(file)) {
      errs() << ToolName << ": '" << file << "': "
             << "No such file\n";
      return;
    }
  }

  // Attempt to open the binary.
  ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
  if (std::error_code EC = BinaryOrErr.getError()) {
    errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
    return;
  }
  Binary &Bin = *BinaryOrErr.get().getBinary();

  if (Archive *a = dyn_cast<Archive>(&Bin)) {
    // This is an archive. Iterate over each member and display its sizes.
    for (object::Archive::child_iterator i = a->child_begin(),
                                         e = a->child_end();
         i != e; ++i) {
      ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
      if (std::error_code EC = ChildOrErr.getError()) {
        errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
        continue;
      }
      if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
        MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
        if (!checkMachOAndArchFlags(o, file))
          return;
        if (OutputFormat == sysv)
          outs() << o->getFileName() << "   (ex " << a->getFileName() << "):\n";
        else if (MachO && OutputFormat == darwin)
          outs() << a->getFileName() << "(" << o->getFileName() << "):\n";
        PrintObjectSectionSizes(o);
        if (OutputFormat == berkeley) {
          if (MachO)
            outs() << a->getFileName() << "(" << o->getFileName() << ")\n";
          else
            outs() << o->getFileName() << " (ex " << a->getFileName() << ")\n";
        }
      }
    }
  } else if (MachOUniversalBinary *UB =
                 dyn_cast<MachOUniversalBinary>(&Bin)) {
    // If we have a list of architecture flags specified dump only those.
    if (!ArchAll && ArchFlags.size() != 0) {
      // Look for a slice in the universal binary that matches each ArchFlag.
      bool ArchFound;
      for (unsigned i = 0; i < ArchFlags.size(); ++i) {
        ArchFound = false;
        for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
                                                   E = UB->end_objects();
             I != E; ++I) {
          if (ArchFlags[i] == I->getArchTypeName()) {
            ArchFound = true;
            ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
            if (UO) {
              if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
                MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
                if (OutputFormat == sysv)
                  outs() << o->getFileName() << "  :\n";
                else if (MachO && OutputFormat == darwin) {
                  if (moreThanOneFile || ArchFlags.size() > 1)
                    outs() << o->getFileName() << " (for architecture "
                           << I->getArchTypeName() << "): \n";
                }
                PrintObjectSectionSizes(o);
                if (OutputFormat == berkeley) {
                  if (!MachO || moreThanOneFile || ArchFlags.size() > 1)
                    outs() << o->getFileName() << " (for architecture "
                           << I->getArchTypeName() << ")";
                  outs() << "\n";
                }
              }
            } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
                           I->getAsArchive()) {
              std::unique_ptr<Archive> &UA = *AOrErr;
              // This is an archive. Iterate over each member and display its
              // sizes.
              for (object::Archive::child_iterator i = UA->child_begin(),
                                                   e = UA->child_end();
                   i != e; ++i) {
                ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
                if (std::error_code EC = ChildOrErr.getError()) {
                  errs() << ToolName << ": " << file << ": " << EC.message()
                         << ".\n";
                  continue;
                }
                if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
                  MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
                  if (OutputFormat == sysv)
                    outs() << o->getFileName() << "   (ex " << UA->getFileName()
                           << "):\n";
                  else if (MachO && OutputFormat == darwin)
                    outs() << UA->getFileName() << "(" << o->getFileName()
                           << ")"
                           << " (for architecture " << I->getArchTypeName()
                           << "):\n";
                  PrintObjectSectionSizes(o);
                  if (OutputFormat == berkeley) {
                    if (MachO) {
                      outs() << UA->getFileName() << "(" << o->getFileName()
                             << ")";
                      if (ArchFlags.size() > 1)
                        outs() << " (for architecture " << I->getArchTypeName()
                               << ")";
                      outs() << "\n";
                    } else
                      outs() << o->getFileName() << " (ex " << UA->getFileName()
                             << ")\n";
                  }
                }
              }
            }
          }
        }
        if (!ArchFound) {
          errs() << ToolName << ": file: " << file
                 << " does not contain architecture" << ArchFlags[i] << ".\n";
          return;
        }
      }
      return;
    }
    // No architecture flags were specified so if this contains a slice that
    // matches the host architecture dump only that.
    if (!ArchAll) {
      StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
      for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
                                                 E = UB->end_objects();
           I != E; ++I) {
        if (HostArchName == I->getArchTypeName()) {
          ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
          if (UO) {
            if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
              MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
              if (OutputFormat == sysv)
                outs() << o->getFileName() << "  :\n";
              else if (MachO && OutputFormat == darwin) {
                if (moreThanOneFile)
                  outs() << o->getFileName() << " (for architecture "
                         << I->getArchTypeName() << "):\n";
              }
              PrintObjectSectionSizes(o);
              if (OutputFormat == berkeley) {
                if (!MachO || moreThanOneFile)
                  outs() << o->getFileName() << " (for architecture "
                         << I->getArchTypeName() << ")";
                outs() << "\n";
              }
            }
          } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
                         I->getAsArchive()) {
            std::unique_ptr<Archive> &UA = *AOrErr;
            // This is an archive. Iterate over each member and display its
            // sizes.
            for (object::Archive::child_iterator i = UA->child_begin(),
                                                 e = UA->child_end();
                 i != e; ++i) {
              ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
              if (std::error_code EC = ChildOrErr.getError()) {
                errs() << ToolName << ": " << file << ": " << EC.message()
                       << ".\n";
                continue;
              }
              if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
                MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
                if (OutputFormat == sysv)
                  outs() << o->getFileName() << "   (ex " << UA->getFileName()
                         << "):\n";
                else if (MachO && OutputFormat == darwin)
                  outs() << UA->getFileName() << "(" << o->getFileName() << ")"
                         << " (for architecture " << I->getArchTypeName()
                         << "):\n";
                PrintObjectSectionSizes(o);
                if (OutputFormat == berkeley) {
                  if (MachO)
                    outs() << UA->getFileName() << "(" << o->getFileName()
                           << ")\n";
                  else
                    outs() << o->getFileName() << " (ex " << UA->getFileName()
                           << ")\n";
                }
              }
            }
          }
          return;
        }
      }
    }
    // Either all architectures have been specified or none have been specified
    // and this does not contain the host architecture so dump all the slices.
    bool moreThanOneArch = UB->getNumberOfObjects() > 1;
    for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
                                               E = UB->end_objects();
         I != E; ++I) {
      ErrorOr<std::unique_ptr<ObjectFile>> UO = I->getAsObjectFile();
      if (UO) {
        if (ObjectFile *o = dyn_cast<ObjectFile>(&*UO.get())) {
          MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
          if (OutputFormat == sysv)
            outs() << o->getFileName() << "  :\n";
          else if (MachO && OutputFormat == darwin) {
            if (moreThanOneFile || moreThanOneArch)
              outs() << o->getFileName() << " (for architecture "
                     << I->getArchTypeName() << "):";
            outs() << "\n";
          }
          PrintObjectSectionSizes(o);
          if (OutputFormat == berkeley) {
            if (!MachO || moreThanOneFile || moreThanOneArch)
              outs() << o->getFileName() << " (for architecture "
                     << I->getArchTypeName() << ")";
            outs() << "\n";
          }
        }
      } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
                         I->getAsArchive()) {
        std::unique_ptr<Archive> &UA = *AOrErr;
        // This is an archive. Iterate over each member and display its sizes.
        for (object::Archive::child_iterator i = UA->child_begin(),
                                             e = UA->child_end();
             i != e; ++i) {
          ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
          if (std::error_code EC = ChildOrErr.getError()) {
            errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
            continue;
          }
          if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) {
            MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
            if (OutputFormat == sysv)
              outs() << o->getFileName() << "   (ex " << UA->getFileName()
                     << "):\n";
            else if (MachO && OutputFormat == darwin)
              outs() << UA->getFileName() << "(" << o->getFileName() << ")"
                     << " (for architecture " << I->getArchTypeName() << "):\n";
            PrintObjectSectionSizes(o);
            if (OutputFormat == berkeley) {
              if (MachO)
                outs() << UA->getFileName() << "(" << o->getFileName() << ")"
                       << " (for architecture " << I->getArchTypeName()
                       << ")\n";
              else
                outs() << o->getFileName() << " (ex " << UA->getFileName()
                       << ")\n";
            }
          }
        }
      }
    }
  } else if (ObjectFile *o = dyn_cast<ObjectFile>(&Bin)) {
    if (!checkMachOAndArchFlags(o, file))
      return;
    if (OutputFormat == sysv)
      outs() << o->getFileName() << "  :\n";
    PrintObjectSectionSizes(o);
    if (OutputFormat == berkeley) {
      MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o);
      if (!MachO || moreThanOneFile)
        outs() << o->getFileName();
      outs() << "\n";
    }
  } else {
    errs() << ToolName << ": " << file << ": "
           << "Unrecognized file type.\n";
  }
  // System V adds an extra newline at the end of each file.
  if (OutputFormat == sysv)
    outs() << "\n";
}
예제 #5
0
bool Smiles::load(const QString &file)
{
    clear();
    for (unsigned i = 0;; i++){
        const smile *s = defaultSmiles(i);
        if (s == NULL)
            break;
        SmileDef sd;
        sd.paste = s->paste;
        sd.icon  = NULL;
        m_smiles.push_back(sd);
    }
    QString fname = file;
    QFile f(fname);
    if (!f.open(IO_ReadOnly))
        return false;
#ifdef USE_EXPAT
    int pdot = fname.findRev(".");
    if ((pdot > 0) && (fname.mid(pdot + 1).lower() == "xep")){
        XepParser p;
        if (!p.parse(f))
            return false;
        for (list<xepRecord>::iterator it = p.m_rec.begin(); it != p.m_rec.end(); ++it){
            xepRecord &r = *it;
            QPixmap pict = p.pict(r.index);
            if (pict.isNull())
                continue;
            SmileDef sd;
            sd.title = getValue(r.title.c_str());
            sd.paste = sd.title;
            string exp   = getValue(r.smiles.c_str());
            for (const char *p = exp.c_str(); *p; p++){
                if (*p == '\\'){
                    if (*(++p) == 0)
                        break;
                    sd.exp += '\\';
                    sd.exp += *p;
                    continue;
                }
                if ((*p == '{') || (*p == '}'))
                    sd.exp += '\\';
                sd.exp += *p;
            }
            QIconSet *is = new QIconSet(pict);
            m_icons.push_back(is);
            sd.icon	 = is;
            unsigned index = (unsigned)(-1);
            for (index = 0;; index++){
                const smile *s = defaultSmiles(index);
                if (s == NULL)
                    break;
#if QT_VERSION < 300
                QString exp = s->exp;
                bool bMatch = false;
                while (!exp.isEmpty()){
                    QString e = getToken(exp, '|', false);
                    QRegExp re(e);
                    int len;
                    if ((re.match(sd.paste.c_str(), 0, &len) == 0) && (len == (int)(sd.paste.length()))){
                        bMatch = true;
                        break;
                    }
                }
                if (bMatch){
                    sd.title = s->title;
                    break;
                }
#else
                QRegExp re(s->exp);
                int len;
                if ((re.match(sd.paste.c_str(), 0, &len) == 0) && ((unsigned)len == sd.paste.length())){
                    sd.title = s->title;
                    break;
                }
#endif
            }
            if (index < 16){
                m_smiles[index] = sd;
            }else{
                m_smiles.push_back(sd);
            }
        }
        return true;
    }
#endif
#ifdef WIN32
    fname = fname.replace(QRegExp("\\"), "/");
#endif
    int pos = fname.findRev("/");
    if (pos >= 0){
        fname = fname.left(pos + 1);
    }else{
        fname = "";
    }
    string s;
    QRegExp start("^ *Smiley *= *");
    QRegExp num("^ *, *-[0-9]+ *, *");
    QRegExp nn("[0-9]+");
    QRegExp re("\\[\\]\\|\\(\\)\\{\\}\\.\\?\\*\\+");
    while (getLine(f, s)){
        QString line = QString::fromLocal8Bit(s.c_str());
        if (line[0] == ';')
            continue;
        int size;
        int pos = start.match(line, 0, &size);
        if (pos < 0)
            continue;
        line = line.mid(size);
        getToken(line, '\"');
        QString dll = getToken(line, '\"', false);
        if (dll.isEmpty())
            continue;
        dll = dll.replace(QRegExp("\\\\"), "/");
        pos = num.match(line, 0, &size);
        if (pos < 0)
            continue;
        QString num = line.left(size);
        line = line.mid(size);
        pos = nn.match(num, 0, &size);
        unsigned nIcon = num.mid(pos, size).toUInt();
        getToken(line, '\"');
        QString pattern = getToken(line, '\"', false);
        getToken(line, '\"');
        QString tip = getToken(line, '\"', false);
        QString dllName = fname + dll;
        dllName = dllName.replace(QRegExp("/\\./"), "/");
        string fn;
        fn = dllName.utf8();
        ICONS_MAP::iterator it = icons.find(fn.c_str());
        IconDLL *icon_dll = NULL;
        if (it == icons.end()){
            icon_dll = new IconDLL;
            if (!icon_dll->load(fn.c_str())){
                delete icon_dll;
                icon_dll = NULL;
            }
            icons.insert(ICONS_MAP::value_type(fn.c_str(), icon_dll));
        }else{
            icon_dll = (*it).second;
        }
        if (icon_dll == NULL)
            continue;
        const QIconSet *icon = icon_dll->get(nIcon);
        if (icon == NULL){
            log(L_DEBUG, "Icon empty %u", nIcon);
            continue;
        }
        QString p;
        QString paste;
        unsigned index = (unsigned)(-1);
        while (!pattern.isEmpty()){
            QString pat = getToken(pattern, ' ', false);
            if (index == (unsigned)(-1)){
                for (index = 0; index < 16; index++){
                    const smile *s = defaultSmiles(index);
                    if (pat == s->paste)
                        break;
                }
            }
            if (paste.isEmpty())
                paste = pat;
            QString res;
            while (!pat.isEmpty()){
                int pos = re.match(pat);
                if (pos < 0)
                    break;
                res += pat.left(pos);
                res += "\\";
                res += pat.mid(pos, 1);
                pat = pat.mid(pos + 1);
            }
            res += pat;
            if (!p.isEmpty())
                p += "|";
            p += res;
        }
        if (tip.isEmpty())
            tip = paste;
        SmileDef sd;
        sd.exp     = p.latin1();
        sd.paste   = paste.latin1();
        sd.title   = tip.latin1();
        sd.icon    = icon;
        if (index < 16){
            m_smiles[index] = sd;
        }else{
            m_smiles.push_back(sd);
        }
    }
    return true;
}
예제 #6
0
        bool handleSpecialNamespaces( Request& r , QueryMessage& q ) {
            const char * ns = r.getns();
            ns = strstr( r.getns() , ".$cmd.sys." );
            if ( ! ns )
                return false;
            ns += 10;

            r.checkAuth( Auth::WRITE );

            BSONObjBuilder b;
            vector<Shard> shards;

            if ( strcmp( ns , "inprog" ) == 0 ) {
                Shard::getAllShards( shards );

                BSONArrayBuilder arr( b.subarrayStart( "inprog" ) );

                for ( unsigned i=0; i<shards.size(); i++ ) {
                    Shard shard = shards[i];
                    ScopedDbConnection conn( shard );
                    BSONObj temp = conn->findOne( r.getns() , BSONObj() );
                    if ( temp["inprog"].isABSONObj() ) {
                        BSONObjIterator i( temp["inprog"].Obj() );
                        while ( i.more() ) {
                            BSONObjBuilder x;

                            BSONObjIterator j( i.next().Obj() );
                            while( j.more() ) {
                                BSONElement e = j.next();
                                if ( str::equals( e.fieldName() , "opid" ) ) {
                                    stringstream ss;
                                    ss << shard.getName() << ':' << e.numberInt();
                                    x.append( "opid" , ss.str() );
                                }
                                else if ( str::equals( e.fieldName() , "client" ) ) {
                                    x.appendAs( e , "client_s" );
                                }
                                else {
                                    x.append( e );
                                }
                            }
                            arr.append( x.obj() );
                        }
                    }
                    conn.done();
                }

                arr.done();
            }
            else if ( strcmp( ns , "killop" ) == 0 ) {
                BSONElement e = q.query["op"];
                if ( strstr( r.getns() , "admin." ) == 0 ) {
                    b.append( "err" , "unauthorized" );
                }
                else if ( e.type() != String ) {
                    b.append( "err" , "bad op" );
                    b.append( e );
                }
                else {
                    b.append( e );
                    string s = e.String();
                    string::size_type i = s.find( ':' );
                    if ( i == string::npos ) {
                        b.append( "err" , "bad opid" );
                    }
                    else {
                        string shard = s.substr( 0 , i );
                        int opid = atoi( s.substr( i + 1 ).c_str() );
                        b.append( "shard" , shard );
                        b.append( "shardid" , opid );

                        log() << "want to kill op: " << e << endl;
                        Shard s(shard);

                        ScopedDbConnection conn( s );
                        conn->findOne( r.getns() , BSON( "op" << opid ) );
                        conn.done();
                    }
                }
            }
            else if ( strcmp( ns , "unlock" ) == 0 ) {
                b.append( "err" , "can't do unlock through mongos" );
            }
            else {
                log( LL_WARNING ) << "unknown sys command [" << ns << "]" << endl;
                return false;
            }

            BSONObj x = b.done();
            replyToQuery(0, r.p(), r.m(), x);
            return true;
        }
예제 #7
0
ExecutionContext::ExecutionResult
ExecutionContext::runStaticInitializersOnce(llvm::Module* m) {
  assert(m && "Module must not be null");
  assert(m_engine && "Code generation did not create an engine!");

  if (m_RunningStaticInits)
     return kExeSuccess;

  llvm::GlobalVariable* GV
     = m->getGlobalVariable("llvm.global_ctors", true);
  // Nothing to do is good, too.
  if (!GV) return kExeSuccess;

  // Close similarity to
  // m_engine->runStaticConstructorsDestructors(false) aka
  // llvm::ExecutionEngine::runStaticConstructorsDestructors()
  // is intentional; we do an extra pass to check whether the JIT
  // managed to collect all the symbols needed by the niitializers.
  // Should be an array of '{ i32, void ()* }' structs.  The first value is
  // the init priority, which we ignore.
  llvm::ConstantArray *InitList
    = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer());
  if (InitList == 0)
    return kExeSuccess;

  m_RunningStaticInits = true;

  // We don't care whether something was unresolved before.
  m_unresolvedSymbols.clear();

  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
    llvm::ConstantStruct *CS
      = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i));
    if (CS == 0) continue;

    llvm::Constant *FP = CS->getOperand(1);
    if (FP->isNullValue())
      continue;  // Found a sentinal value, ignore.

    // Strip off constant expression casts.
    if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP))
      if (CE->isCast())
        FP = CE->getOperand(0);

    // Execute the ctor/dtor function!
    if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) {
      m_engine->getPointerToFunction(F);
      // check if there is any unresolved symbol in the list
      if (!m_unresolvedSymbols.empty()) {
        llvm::SmallVector<llvm::Function*, 100> funcsToFree;
        for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),
               e = m_unresolvedSymbols.end(); i != e; ++i) {
          llvm::errs() << "ExecutionContext::runStaticInitializersOnce: symbol '" << *i
                       << "' unresolved while linking static initializer '"
                       << F->getName() << "'!\n";
          llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());
          assert(ff && "cannot find function to free");
          funcsToFree.push_back(ff);
        }
        freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());
        m_unresolvedSymbols.clear();
        m_RunningStaticInits = false;
        return kExeUnresolvedSymbols;
      }
      m_engine->runFunction(F, std::vector<llvm::GenericValue>());
    }
  }

  GV->eraseFromParent();

  m_RunningStaticInits = false;
  return kExeSuccess;
}
예제 #8
0
IncrementalExecutor::ExecutionResult
IncrementalExecutor::runStaticInitializersOnce(llvm::Module* m) {
  assert(m && "Module must not be null");
  assert(m_engine && "Code generation did not create an engine!");

  llvm::GlobalVariable* GV
     = m->getGlobalVariable("llvm.global_ctors", true);
  // Nothing to do is good, too.
  if (!GV) return kExeSuccess;

  // Close similarity to
  // m_engine->runStaticConstructorsDestructors(false) aka
  // llvm::ExecutionEngine::runStaticConstructorsDestructors()
  // is intentional; we do an extra pass to check whether the JIT
  // managed to collect all the symbols needed by the niitializers.
  // Should be an array of '{ i32, void ()* }' structs.  The first value is
  // the init priority, which we ignore.
  llvm::ConstantArray *InitList
    = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer());

  // We need to delete it here just in case we have recursive inits, otherwise
  // it will call inits multiple times.
  GV->eraseFromParent();

  if (InitList == 0)
    return kExeSuccess;

  // We don't care whether something was unresolved before.
  m_unresolvedSymbols.clear();

  SmallVector<Function*, 2> initFuncs;

  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
    llvm::ConstantStruct *CS
      = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i));
    if (CS == 0) continue;

    llvm::Constant *FP = CS->getOperand(1);
    if (FP->isNullValue())
      continue;  // Found a sentinal value, ignore.

    // Strip off constant expression casts.
    if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP))
      if (CE->isCast())
        FP = CE->getOperand(0);

    // Execute the ctor/dtor function!
    if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) {
      remapSymbols();
      m_engine->getPointerToFunction(F);
      // check if there is any unresolved symbol in the list
      if (!m_unresolvedSymbols.empty()) {
        llvm::SmallVector<llvm::Function*, 100> funcsToFree;
        for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),
               e = m_unresolvedSymbols.end(); i != e; ++i) {
          llvm::errs() << "IncrementalExecutor::runStaticInitializersOnce: symbol '" << *i
                       << "' unresolved while linking static initializer '"
                       << F->getName() << "'!\n";
          llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());
          assert(ff && "cannot find function to free");
          funcsToFree.push_back(ff);
        }
        freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());
        m_unresolvedSymbols.clear();
        return kExeUnresolvedSymbols;
      }
      //executeFunction(F->getName());
      m_engine->runFunction(F, std::vector<llvm::GenericValue>());
      initFuncs.push_back(F);
      if (F->getName().startswith("_GLOBAL__sub_I__")) {
        BasicBlock& BB = F->getEntryBlock();
        for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
          if (CallInst* call = dyn_cast<CallInst>(I))
            initFuncs.push_back(call->getCalledFunction());
      }
    }
  }

  for (SmallVector<Function*,2>::iterator I = initFuncs.begin(),
         E = initFuncs.end(); I != E; ++I) {
    // Cleanup also the dangling init functions. They are in the form:
    // define internal void @_GLOBAL__I_aN() section "..."{
    // entry:
    //   call void @__cxx_global_var_init(N-1)()
    //   call void @__cxx_global_var_initM()
    //   ret void
    // }
    //
    // define internal void @__cxx_global_var_init(N-1)() section "..." {
    // entry:
    //   call void @_ZN7MyClassC1Ev(%struct.MyClass* @n)
    //   ret void
    // }

    // Erase __cxx_global_var_init(N-1)() first.
    (*I)->removeDeadConstantUsers();
    (*I)->eraseFromParent();
  }

  return kExeSuccess;
}
예제 #9
0
        bool handleSpecialNamespaces( Request& r , QueryMessage& q ) {
            const char * ns = strstr( r.getns() , ".$cmd.sys." );
            if ( ! ns )
                return false;
            ns += 10;

            BSONObjBuilder b;
            vector<Shard> shards;

            ClientBasic* client = ClientBasic::getCurrent();
            AuthorizationSession* authSession = client->getAuthorizationSession();
            if ( strcmp( ns , "inprog" ) == 0 ) {
                const bool isAuthorized = authSession->isAuthorizedForActionsOnResource(
                        ResourcePattern::forClusterResource(), ActionType::inprog);
                audit::logInProgAuthzCheck(
                        client, q.query, isAuthorized ? ErrorCodes::OK : ErrorCodes::Unauthorized);
                uassert(ErrorCodes::Unauthorized, "not authorized to run inprog", isAuthorized);

                Shard::getAllShards( shards );

                BSONArrayBuilder arr( b.subarrayStart( "inprog" ) );

                for ( unsigned i=0; i<shards.size(); i++ ) {
                    Shard shard = shards[i];
                    ScopedDbConnection conn(shard.getConnString());
                    BSONObj temp = conn->findOne( r.getns() , q.query );
                    if ( temp["inprog"].isABSONObj() ) {
                        BSONObjIterator i( temp["inprog"].Obj() );
                        while ( i.more() ) {
                            BSONObjBuilder x;

                            BSONObjIterator j( i.next().Obj() );
                            while( j.more() ) {
                                BSONElement e = j.next();
                                if ( str::equals( e.fieldName() , "opid" ) ) {
                                    stringstream ss;
                                    ss << shard.getName() << ':' << e.numberInt();
                                    x.append( "opid" , ss.str() );
                                }
                                else if ( str::equals( e.fieldName() , "client" ) ) {
                                    x.appendAs( e , "client_s" );
                                }
                                else {
                                    x.append( e );
                                }
                            }
                            arr.append( x.obj() );
                        }
                    }
                    conn.done();
                }

                arr.done();
            }
            else if ( strcmp( ns , "killop" ) == 0 ) {
                const bool isAuthorized = authSession->isAuthorizedForActionsOnResource(
                        ResourcePattern::forClusterResource(), ActionType::killop);
                audit::logKillOpAuthzCheck(
                        client,
                        q.query,
                        isAuthorized ? ErrorCodes::OK : ErrorCodes::Unauthorized);
                uassert(ErrorCodes::Unauthorized, "not authorized to run killop", isAuthorized);

                BSONElement e = q.query["op"];
                if ( e.type() != String ) {
                    b.append( "err" , "bad op" );
                    b.append( e );
                }
                else {
                    b.append( e );
                    string s = e.String();
                    string::size_type i = s.find( ':' );
                    if ( i == string::npos ) {
                        b.append( "err" , "bad opid" );
                    }
                    else {
                        string shard = s.substr( 0 , i );
                        int opid = atoi( s.substr( i + 1 ).c_str() );
                        b.append( "shard" , shard );
                        b.append( "shardid" , opid );

                        log() << "want to kill op: " << e << endl;
                        Shard s(shard);

                        ScopedDbConnection conn(s.getConnString());
                        conn->findOne( r.getns() , BSON( "op" << opid ) );
                        conn.done();
                    }
                }
            }
            else if ( strcmp( ns , "unlock" ) == 0 ) {
                b.append( "err" , "can't do unlock through mongos" );
            }
            else {
                warning() << "unknown sys command [" << ns << "]" << endl;
                return false;
            }

            BSONObj x = b.done();
            replyToQuery(0, r.p(), r.m(), x);
            return true;
        }
예제 #10
0
u256 State::enact(bytesConstRef _block, BlockChain const& _bc, bool _checkNonce)
{
	// m_currentBlock is assumed to be prepopulated and reset.

#if !ETH_RELEASE
	BlockInfo bi(_block, _checkNonce);
	assert(m_previousBlock.hash == bi.parentHash);
	assert(m_currentBlock.parentHash == bi.parentHash);
	assert(rootHash() == m_previousBlock.stateRoot);
#endif

	if (m_currentBlock.parentHash != m_previousBlock.hash)
		BOOST_THROW_EXCEPTION(InvalidParentHash());

	// Populate m_currentBlock with the correct values.
	m_currentBlock.populate(_block, _checkNonce);
	m_currentBlock.verifyInternals(_block);

//	cnote << "playback begins:" << m_state.root();
//	cnote << m_state;

	MemoryDB tm;
	GenericTrieDB<MemoryDB> transactionsTrie(&tm);
	transactionsTrie.init();

	MemoryDB rm;
	GenericTrieDB<MemoryDB> receiptsTrie(&rm);
	receiptsTrie.init();

	LastHashes lh = getLastHashes(_bc, (unsigned)m_previousBlock.number);

	// All ok with the block generally. Play back the transactions now...
	unsigned i = 0;
	for (auto const& tr: RLP(_block)[1])
	{
		RLPStream k;
		k << i;

		transactionsTrie.insert(&k.out(), tr.data());
		execute(lh, tr.data());

		RLPStream receiptrlp;
		m_receipts.back().streamRLP(receiptrlp);
		receiptsTrie.insert(&k.out(), &receiptrlp.out());
		++i;
	}

	if (transactionsTrie.root() != m_currentBlock.transactionsRoot)
	{
		cwarn << "Bad transactions state root!";
		BOOST_THROW_EXCEPTION(InvalidTransactionsStateRoot());
	}

	if (receiptsTrie.root() != m_currentBlock.receiptsRoot)
	{
		cwarn << "Bad receipts state root.";
		cwarn << "Block:" << toHex(_block);
		cwarn << "Block RLP:" << RLP(_block);
		cwarn << "Calculated: " << receiptsTrie.root();
		for (unsigned j = 0; j < i; ++j)
		{
			RLPStream k;
			k << j;
			auto b = asBytes(receiptsTrie.at(&k.out()));
			cwarn << j << ": ";
			cwarn << "RLP: " << RLP(b);
			cwarn << "Hex: " << toHex(b);
			cwarn << TransactionReceipt(&b);
		}
		cwarn << "Recorded: " << m_currentBlock.receiptsRoot;
		auto rs = _bc.receipts(m_currentBlock.hash);
		for (unsigned j = 0; j < rs.receipts.size(); ++j)
		{
			auto b = rs.receipts[j].rlp();
			cwarn << j << ": ";
			cwarn << "RLP: " << RLP(b);
			cwarn << "Hex: " << toHex(b);
			cwarn << rs.receipts[j];
		}
		BOOST_THROW_EXCEPTION(InvalidReceiptsStateRoot());
	}

	if (m_currentBlock.logBloom != logBloom())
	{
		cwarn << "Bad log bloom!";
		BOOST_THROW_EXCEPTION(InvalidLogBloom());
	}

	// Initialise total difficulty calculation.
	u256 tdIncrease = m_currentBlock.difficulty;

	// Check uncles & apply their rewards to state.
	set<h256> nonces = { m_currentBlock.nonce };
	Addresses rewarded;
	set<h256> knownUncles = _bc.allUnclesFrom(m_currentBlock.parentHash);
	for (auto const& i: RLP(_block)[2])
	{
		if (knownUncles.count(sha3(i.data())))
			BOOST_THROW_EXCEPTION(UncleInChain(knownUncles, sha3(i.data()) ));

		BlockInfo uncle = BlockInfo::fromHeader(i.data());
		if (nonces.count(uncle.nonce))
			BOOST_THROW_EXCEPTION(DuplicateUncleNonce());

		BlockInfo uncleParent(_bc.block(uncle.parentHash));
		if ((bigint)uncleParent.number < (bigint)m_currentBlock.number - 7)
			BOOST_THROW_EXCEPTION(UncleTooOld());
		uncle.verifyParent(uncleParent);

		nonces.insert(uncle.nonce);
		tdIncrease += uncle.difficulty;
		rewarded.push_back(uncle.coinbaseAddress);
	}
	applyRewards(rewarded);

	// Commit all cached state changes to the state trie.
	commit();

	// Hash the state trie and check against the state_root hash in m_currentBlock.
	if (m_currentBlock.stateRoot != m_previousBlock.stateRoot && m_currentBlock.stateRoot != rootHash())
	{
		cwarn << "Bad state root!";
		cnote << "Given to be:" << m_currentBlock.stateRoot;
		cnote << TrieDB<Address, OverlayDB>(&m_db, m_currentBlock.stateRoot);
		cnote << "Calculated to be:" << rootHash();
		cnote << m_state;
		cnote << *this;
		// Rollback the trie.
		m_db.rollback();
		BOOST_THROW_EXCEPTION(InvalidStateRoot());
	}

	if (m_currentBlock.gasUsed != gasUsed())
	{
		// Rollback the trie.
		m_db.rollback();
		BOOST_THROW_EXCEPTION(InvalidGasUsed() << RequirementError(bigint(gasUsed()), bigint(m_currentBlock.gasUsed)));
	}

	return tdIncrease;
}
예제 #11
0
int SubmitFile::MessageEnd(unsigned rcptnum, int iswhitelisted,
			   int filter_enabled)
{
int	is8bit=0, dorewrite=0, rwmode=0;
const	char *mime=getenv("MIME");
unsigned	n;
struct	stat	stat_buf;

	if (sizelimit && bytecount > sizelimit)
	{
		std::cout << "523 Message length (" <<
			bytecount << " bytes) exceeds administrative limit(" << sizelimit << ")."
			<< std::endl << std::flush;
		return (1);
	}

	if (diskfull)
	{
		std::cout << "431 Mail system full." << std::endl << std::flush;
		return (1);
	}

	if (spamtrap_flag)
	{
		std::cout << "550 Spam refused." << std::endl << std::flush;
		return (1);
	}

	if (rwrfcptr->rfcviolation & RFC2045_ERR2COMPLEX)
	{
                std::cout <<
                   "550 Message MIME complexity exceeds the policy maximum."
		     << std::endl << std::flush;
		return (1);
	}

	datfile << std::flush;
	if (datfile.fail())	clog_msg_errno();

	ctlfile << std::flush;
	if (ctlfile.fail())	clog_msg_errno();

	/* Run global filters for this message */

	std::string dfile=namefile("D", 0);

	if (!mime || strcmp(mime, "none"))
	{
		if (mime && strcmp(mime, "7bit") == 0)
		{
			rwmode=RFC2045_RW_7BIT;
			is8bit=0;
		}
		if (mime && strcmp(mime, "8bit") == 0)
			rwmode=RFC2045_RW_8BIT;
		if (rfc2045_ac_check(rwrfcptr, rwmode))
			dorewrite=1;
	}
	else
		(void)rfc2045_ac_check(rwrfcptr, 0);

	if (rwrfcptr->has8bitchars)
		is8bit=1;

	unlink(namefile("D", 1).c_str());	// Might be the GDBM file
					// if receipients read from headers.
	if (dorewrite)
	{
		int	fd1=dup(datfile.fd());
		int	fd2;

		if (fd1 < 0)	clog_msg_errno();
		datfile.close();
		if (datfile.fail())	clog_msg_errno();

		if ((fd2=open(namefile("D", 1).c_str(),
			O_RDWR|O_CREAT|O_TRUNC, PERMISSION)) < 0)
			clog_msg_errno();

		if (call_rfc2045_rewrite(rwrfcptr, fd1, fd2,
					 PACKAGE " " VERSION))
		{
			clog_msg_errno();
			std::cout << "431 Mail system full." << std::endl << std::flush;
			return (1);
		}
		close(fd1);

#if	EXPLICITSYNC
		fsync(fd2);
#endif
		fstat(fd2, &stat_buf);
		close(fd2);

		std::string p=namefile("D", 0);

		unlink(p.c_str());
		if (rename(namefile("D", 1).c_str(), p.c_str()) != 0)
			clog_msg_errno();
	}
	else
	{
		datfile.sync();
#if EXPLICITSYNC
		fsync(datfile.fd());
#endif
		fstat(datfile.fd(), &stat_buf);
		datfile.close();
		if (datfile.fail())	clog_msg_errno();
	}

	if (rwrfcptr->rfcviolation & RFC2045_ERR8BITHEADER)
	{
		/*
		** One control file: add a COMCTLFILE_SMTPUTF8 record.
		** When there are multiple control files, this is
		** handled below.
		*/

		if (num_control_files_created == 1)
			ctlfile << COMCTLFILE_SMTPUTF8 << std::endl;
	}

	if (is8bit)
	{
		ctlfile << COMCTLFILE_8BIT << "\n" << std::flush;
		closectl();

		if (num_control_files_created > 1)
		{
			for (n=1; n < num_control_files_created; n++)
			{
				std::string p=namefile("C", n);

				int nfd=open(p.c_str(), O_WRONLY | O_APPEND);

				if (nfd < 0)	clog_msg_errno();
				ctlfile.fd(nfd);
				ctlfile << COMCTLFILE_8BIT << "\n" << std::flush;
				if (ctlfile.fail())	clog_msg_errno();
#if EXPLICITSYNC
				ctlfile.sync();
				fsync(ctlfile.fd());
#endif
				ctlfile.close();
				if (ctlfile.fail())	clog_msg_errno();
			}
		}
	}
	else
	{
		closectl();
	}

	if (rwrfcptr->rfcviolation & RFC2045_ERR8BITHEADER)
	{
		/*
		** Multiple control files, add a COMCTLFILE_SMTPUTF8
		** record to each one.
		*/

		if (num_control_files_created > 1)
		{
			unsigned i;

			for (i=1; i <= num_control_files_created; i++)
			{
				std::string n=namefile("C", i);

				int fd=open(n.c_str(), O_WRONLY | O_APPEND,
					    0666);

				if (fd < 0)
				{
					clog_msg_errno();
				}
				else
				{
					char c[2];

					c[0]=COMCTLFILE_SMTPUTF8;
					c[1]='\n';

					if (write(fd, c, 2) != 2 ||
					    close(fd) < 0)
					{
						clog_msg_errno();
					}
				}
			}
		}
	}

	SubmitFile *voidp=this;

	if (filter_enabled &&
	    run_filter(dfile.c_str(), num_control_files_created,
		       iswhitelisted,
		       &SubmitFile::get_msgid_for_filtering, &voidp))
		return (1);

	std::string cfile=namefile("C", 0);

	for (n=2; n <= num_control_files_created; n++)
	{
		if (link(dfile.c_str(), namefile("D", n).c_str()) != 0)
			clog_msg_errno();
	}

	std::string okmsg("250 Ok. ");

	okmsg += basemsgid;

	int	hasxerror=datafilter(dfile.c_str(), rcptnum, okmsg.c_str());

	current_submit_file=0;
	if (num_control_files_created == 1)
	{
		if (rename(name1stctlfile().c_str(), cfile.c_str()) != 0)
			clog_msg_errno();
	}
	else
	{
		if (rename(namefile("C", 1).c_str(), cfile.c_str()) != 0)
			clog_msg_errno();
	}

	if (!hasxerror)
	{
#if EXPLICITDIRSYNC
		size_t p=cfile.rfind('/');

		if (p != std::string::npos)
		{
			std::string dir=cfile.substr(0, p);

			int fd=open(dir.c_str(), O_RDONLY);

			if (fd >= 0)
			{
				fsync(fd);
				close(fd);
			}
		}
#endif

		std::cout << okmsg << std::endl << std::flush;
	}

	trigger(TRIGGER_NEWMSG);
	return (0);
}