void CModel::SaveRelevant(FILE* file) { double maxprob; int nrelmodels; Diagnostics(maxprob,nrelmodels); fprintf(file,"%d\n",nrelmodels); CModel* p = Next; while(NULL!=p) { if(exp(p->laplace-maxprob)>=mdCutoffMax) { fprintf(file,"%d",p->vars[0]); for(int i=1;i<p->Length;i++) { fprintf(file,"\t%d",p->vars[i]); } fprintf(file,"\t%.10lf\n",p->laplace); } p = p->Next; } return; }
// Returns true on error. static bool format(std::string FileName) { FileManager Files((FileSystemOptions())); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), new DiagnosticOptions); SourceManager Sources(Diagnostics, Files); OwningPtr<MemoryBuffer> Code; if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) { llvm::errs() << ec.message() << "\n"; return true; } FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files); Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts()); if (Offsets.empty()) Offsets.push_back(0); if (Offsets.size() != Lengths.size() && !(Offsets.size() == 1 && Lengths.empty())) { llvm::errs() << "error: number of -offset and -length arguments must match.\n"; return true; } std::vector<CharSourceRange> Ranges; for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { if (Offsets[i] >= Code->getBufferSize()) { llvm::errs() << "error: offset " << Offsets[i] << " is outside the file\n"; return true; } SourceLocation Start = Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]); SourceLocation End; if (i < Lengths.size()) { if (Offsets[i] + Lengths[i] > Code->getBufferSize()) { llvm::errs() << "error: invalid length " << Lengths[i] << ", offset + length (" << Offsets[i] + Lengths[i] << ") is outside the file.\n"; return true; } End = Start.getLocWithOffset(Lengths[i]); } else { End = Sources.getLocForEndOfFile(ID); } Ranges.push_back(CharSourceRange::getCharRange(Start, End)); } tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges); if (OutputXML) { llvm::outs() << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n"; for (tooling::Replacements::const_iterator I = Replaces.begin(), E = Replaces.end(); I != E; ++I) { llvm::outs() << "<replacement " << "offset='" << I->getOffset() << "' " << "length='" << I->getLength() << "'>" << I->getReplacementText() << "</replacement>\n"; } llvm::outs() << "</replacements>\n"; } else { Rewriter Rewrite(Sources, LangOptions()); tooling::applyAllReplacements(Replaces, Rewrite); if (Inplace) { if (Replaces.size() == 0) return false; // Nothing changed, don't touch the file. std::string ErrorInfo; llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo, llvm::raw_fd_ostream::F_Binary); if (!ErrorInfo.empty()) { llvm::errs() << "Error while writing file: " << ErrorInfo << "\n"; return true; } Rewrite.getEditBuffer(ID).write(FileStream); FileStream.flush(); } else { Rewrite.getEditBuffer(ID).write(outs()); } } return false; }
int main (int argc, char const * argv []) { extern struct channel channel; static char const * optv [] = { "cCef:ri:qvz:", "device [device] [...] [> stdout]", "Qualcomm Atheros INT6x00 Log Retrieval Utility", "c\tclear watchdog and checkpoint reports", "C\tcustom watchdog report", "e\tredirect stderr to stdout", "f s\tprint Watchdog Report in format (s) [xml]", #if defined (WINPCAP) || defined (LIBPCAP) "i n\thost interface is (n) [" LITERAL (CHANNEL_ETHNUMBER) "]", #else "i s\thost interface is (s) [" LITERAL (CHANNEL_ETHDEVICE) "]", #endif "q\tquiet mode", "r\tread ", "v\tverbose mode", (char const *) (0) }; #include "../plc/plc.c" signed c; if (getenv (PLCDEVICE)) { #if defined (WINPCAP) || defined (LIBPCAP) channel.ifindex = atoi (getenv (PLCDEVICE)); #else channel.ifname = strdup (getenv (PLCDEVICE)); #endif } optind = 1; plc.readaction = 0; plc.action = INT6KLOG_FMT_XML; while ((c = getoptv (argc, argv, optv)) != -1) { switch (c) { case 'C': _setbits (plc.readaction, WD_ACTION_CUSTOM); break; case 'c': _setbits (plc.readaction, WD_ACTION_CLEAR); break; case 'e': dup2 (STDOUT_FILENO, STDERR_FILENO); break; case 'f': if ((c = lookup (optarg, formats, SIZEOF (formats))) == -1) { assist (optarg, "format", formats, SIZEOF (formats)); } plc.action = (uint8_t)(c); break; case 'i': #if defined (WINPCAP) || defined (LIBPCAP) channel.ifindex = atoi (optarg); #else channel.ifname = optarg; #endif break; case 'q': _setbits (channel.flags, CHANNEL_SILENCE); _setbits (plc.flags, PLC_SILENCE); break; case 'r': _setbits (plc.readaction, WD_ACTION_READ); break; case 'v': _setbits (channel.flags, CHANNEL_VERBOSE); _setbits (plc.flags, PLC_VERBOSE); break; case 'z': plc.readaction = (uint8_t)(uintspec (optarg, 0, 255)); break; default: break; } } argc -= optind; argv += optind; if (argc != 1) { if (plc.rpt.file != -1) { error (1, ECANCELED, PLC_NODEVICE); } } openchannel (&channel); if (!(plc.message = malloc (sizeof (* plc.message)))) { error (1, errno, PLC_NOMEMORY); } #ifdef WIN32 if (plc.action == INT6KLOG_FMT_RAW) { setmode (STDOUT_FILENO, O_BINARY); } #endif if (!argc) { Diagnostics (&plc); } while ((argc) && (* argv)) { if (!hexencode (channel.peer, sizeof (channel.peer), synonym (* argv, devices, SIZEOF (devices)))) { error (1, errno, PLC_BAD_MAC, * argv); } Diagnostics (&plc); argc--; argv++; } free (plc.message); closechannel (&channel); exit (0); }
/// \brief Strips any positional args and possible argv[0] from a command-line /// provided by the user to construct a FixedCompilationDatabase. /// /// FixedCompilationDatabase requires a command line to be in this format as it /// constructs the command line for each file by appending the name of the file /// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the /// start of the command line although its value is not important as it's just /// ignored by the Driver invoked by the ClangTool using the /// FixedCompilationDatabase. /// /// FIXME: This functionality should probably be made available by /// clang::driver::Driver although what the interface should look like is not /// clear. /// /// \param[in] Args Args as provided by the user. /// \return Resulting stripped command line. /// \li true if successful. /// \li false if \c Args cannot be used for compilation jobs (e.g. /// contains an option like -E or -version). static bool stripPositionalArgs(std::vector<const char *> Args, std::vector<std::string> &Result) { IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); UnusedInputDiagConsumer DiagClient; DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &DiagClient, false); // The clang executable path isn't required since the jobs the driver builds // will not be executed. std::unique_ptr<driver::Driver> NewDriver(new driver::Driver( /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(), Diagnostics)); NewDriver->setCheckInputsExist(false); // This becomes the new argv[0]. The value is actually not important as it // isn't used for invoking Tools. Args.insert(Args.begin(), "clang-tool"); // By adding -c, we force the driver to treat compilation as the last phase. // It will then issue warnings via Diagnostics about un-used options that // would have been used for linking. If the user provided a compiler name as // the original argv[0], this will be treated as a linker input thanks to // insertng a new argv[0] above. All un-used options get collected by // UnusedInputdiagConsumer and get stripped out later. Args.push_back("-c"); // Put a dummy C++ file on to ensure there's at least one compile job for the // driver to construct. If the user specified some other argument that // prevents compilation, e.g. -E or something like -version, we may still end // up with no jobs but then this is the user's fault. Args.push_back("placeholder.cpp"); // Remove -no-integrated-as; it's not used for syntax checking, // and it confuses targets which don't support this option. Args.erase(std::remove_if(Args.begin(), Args.end(), MatchesAny(std::string("-no-integrated-as"))), Args.end()); const std::unique_ptr<driver::Compilation> Compilation( NewDriver->BuildCompilation(Args)); const driver::JobList &Jobs = Compilation->getJobs(); CompileJobAnalyzer CompileAnalyzer; for (driver::JobList::const_iterator I = Jobs.begin(), E = Jobs.end(); I != E; ++I) { if ((*I)->getKind() == driver::Job::CommandClass) { const driver::Command *Cmd = cast<driver::Command>(*I); // Collect only for Assemble jobs. If we do all jobs we get duplicates // since Link jobs point to Assemble jobs as inputs. if (Cmd->getSource().getKind() == driver::Action::AssembleJobClass) CompileAnalyzer.run(&Cmd->getSource()); } } if (CompileAnalyzer.Inputs.empty()) { // No compile jobs found. // FIXME: Emit a warning of some kind? return false; } // Remove all compilation input files from the command line. This is // necessary so that getCompileCommands() can construct a command line for // each file. std::vector<const char *>::iterator End = std::remove_if( Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs)); // Remove all inputs deemed unused for compilation. End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs)); // Remove the -c add above as well. It will be at the end right now. assert(strcmp(*(End - 1), "-c") == 0); --End; Result = std::vector<std::string>(Args.begin() + 1, End); return true; }
// Returns true on error. static bool format(StringRef FileName) { ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr = MemoryBuffer::getFileOrSTDIN(FileName); if (std::error_code EC = CodeOrErr.getError()) { errs() << EC.message() << "\n"; return true; } std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get()); if (Code->getBufferSize() == 0) return false; // Empty files are formatted correctly. std::vector<tooling::Range> Ranges; if (fillRanges(Code.get(), Ranges)) return true; StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName; FormatStyle FormatStyle = getStyle(Style, AssumedFileName, FallbackStyle); if (SortIncludes.getNumOccurrences() != 0) FormatStyle.SortIncludes = SortIncludes; unsigned CursorPosition = Cursor; Replacements Replaces = sortIncludes(FormatStyle, Code->getBuffer(), Ranges, AssumedFileName, &CursorPosition); auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces); if (!ChangedCode) { llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n"; return true; } for (const auto &R : Replaces) Ranges.push_back({R.getOffset(), R.getLength()}); bool IncompleteFormat = false; Replacements FormatChanges = reformat(FormatStyle, *ChangedCode, Ranges, AssumedFileName, &IncompleteFormat); Replaces = tooling::mergeReplacements(Replaces, FormatChanges); if (OutputXML) { outs() << "<?xml version='1.0'?>\n<replacements " "xml:space='preserve' incomplete_format='" << (IncompleteFormat ? "true" : "false") << "'>\n"; if (Cursor.getNumOccurrences() != 0) outs() << "<cursor>" << tooling::shiftedCodePosition(FormatChanges, CursorPosition) << "</cursor>\n"; outputReplacementsXML(Replaces); outs() << "</replacements>\n"; } else { IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem( new vfs::InMemoryFileSystem); FileManager Files(FileSystemOptions(), InMemoryFileSystem); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), new DiagnosticOptions); SourceManager Sources(Diagnostics, Files); FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files, InMemoryFileSystem.get()); Rewriter Rewrite(Sources, LangOptions()); tooling::applyAllReplacements(Replaces, Rewrite); if (Inplace) { if (FileName == "-") errs() << "error: cannot use -i when reading from stdin.\n"; else if (Rewrite.overwriteChangedFiles()) return true; } else { if (Cursor.getNumOccurrences() != 0) outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(FormatChanges, CursorPosition) << ", \"IncompleteFormat\": " << (IncompleteFormat ? "true" : "false") << " }\n"; Rewrite.getEditBuffer(ID).write(outs()); } } return false; }
static bool fillRanges(MemoryBuffer *Code, std::vector<tooling::Range> &Ranges) { IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem( new vfs::InMemoryFileSystem); FileManager Files(FileSystemOptions(), InMemoryFileSystem); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), new DiagnosticOptions); SourceManager Sources(Diagnostics, Files); FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files, InMemoryFileSystem.get()); if (!LineRanges.empty()) { if (!Offsets.empty() || !Lengths.empty()) { errs() << "error: cannot use -lines with -offset/-length\n"; return true; } for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) { unsigned FromLine, ToLine; if (parseLineRange(LineRanges[i], FromLine, ToLine)) { errs() << "error: invalid <start line>:<end line> pair\n"; return true; } if (FromLine > ToLine) { errs() << "error: start line should be less than end line\n"; return true; } SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1); SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX); if (Start.isInvalid() || End.isInvalid()) return true; unsigned Offset = Sources.getFileOffset(Start); unsigned Length = Sources.getFileOffset(End) - Offset; Ranges.push_back(tooling::Range(Offset, Length)); } return false; } if (Offsets.empty()) Offsets.push_back(0); if (Offsets.size() != Lengths.size() && !(Offsets.size() == 1 && Lengths.empty())) { errs() << "error: number of -offset and -length arguments must match.\n"; return true; } for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { if (Offsets[i] >= Code->getBufferSize()) { errs() << "error: offset " << Offsets[i] << " is outside the file\n"; return true; } SourceLocation Start = Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]); SourceLocation End; if (i < Lengths.size()) { if (Offsets[i] + Lengths[i] > Code->getBufferSize()) { errs() << "error: invalid length " << Lengths[i] << ", offset + length (" << Offsets[i] + Lengths[i] << ") is outside the file.\n"; return true; } End = Start.getLocWithOffset(Lengths[i]); } else { End = Sources.getLocForEndOfFile(ID); } unsigned Offset = Sources.getFileOffset(Start); unsigned Length = Sources.getFileOffset(End) - Offset; Ranges.push_back(tooling::Range(Offset, Length)); } return false; }
// Returns true on error. static bool format(StringRef FileName) { if (!OutputXML && Inplace && FileName == "-") { errs() << "error: cannot use -i when reading from stdin.\n"; return false; } // On Windows, overwriting a file with an open file mapping doesn't work, // so read the whole file into memory when formatting in-place. ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr = !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) : MemoryBuffer::getFileOrSTDIN(FileName); if (std::error_code EC = CodeOrErr.getError()) { errs() << EC.message() << "\n"; return true; } std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get()); if (Code->getBufferSize() == 0) return false; // Empty files are formatted correctly. std::vector<tooling::Range> Ranges; if (fillRanges(Code.get(), Ranges)) return true; StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName; llvm::Expected<FormatStyle> FormatStyle = getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer()); if (!FormatStyle) { llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n"; return true; } if (SortIncludes.getNumOccurrences() != 0) FormatStyle->SortIncludes = SortIncludes; unsigned CursorPosition = Cursor; Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges, AssumedFileName, &CursorPosition); auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces); if (!ChangedCode) { llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n"; return true; } // Get new affected ranges after sorting `#includes`. Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges); FormattingAttemptStatus Status; Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status); Replaces = Replaces.merge(FormatChanges); if (OutputXML) { outs() << "<?xml version='1.0'?>\n<replacements " "xml:space='preserve' incomplete_format='" << (Status.FormatComplete ? "false" : "true") << "'"; if (!Status.FormatComplete) outs() << " line='" << Status.Line << "'"; outs() << ">\n"; if (Cursor.getNumOccurrences() != 0) outs() << "<cursor>" << FormatChanges.getShiftedCodePosition(CursorPosition) << "</cursor>\n"; outputReplacementsXML(Replaces); outs() << "</replacements>\n"; } else { IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem( new vfs::InMemoryFileSystem); FileManager Files(FileSystemOptions(), InMemoryFileSystem); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), new DiagnosticOptions); SourceManager Sources(Diagnostics, Files); FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files, InMemoryFileSystem.get()); Rewriter Rewrite(Sources, LangOptions()); tooling::applyAllReplacements(Replaces, Rewrite); if (Inplace) { if (Rewrite.overwriteChangedFiles()) return true; } else { if (Cursor.getNumOccurrences() != 0) { outs() << "{ \"Cursor\": " << FormatChanges.getShiftedCodePosition(CursorPosition) << ", \"IncompleteFormat\": " << (Status.FormatComplete ? "false" : "true"); if (!Status.FormatComplete) outs() << ", \"Line\": " << Status.Line; outs() << " }\n"; } Rewrite.getEditBuffer(ID).write(outs()); } } return false; }
InflatedHeaders() : allocator_(new Allocator<InflatedHeader>()) , diagnostics_(Diagnostics()) {}